Optimize think tag parser with early-exit lastIndexOf and cursor indexing - #1219
Open
nordicnode wants to merge 1 commit into
Open
Optimize think tag parser with early-exit lastIndexOf and cursor indexing#1219nordicnode wants to merge 1 commit into
nordicnode wants to merge 1 commit into
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Optimize think tag parser with early-exit lastIndexOf and cursor indexing
Summary
• In$O(1)$ check using
cli/src/utils/think-tag-parser.ts, optimize streaming think-tag detection and segment parsing.• Previously,
getPartialTagLengthwas called on every streamed token chunk and sequentially tested 12 hardcoded prefix strings acrossPARTIAL_CLOSE_PREFIXESandPARTIAL_OPEN_PREFIXESwithtext.endsWith(prefix). Replaced this with antext.lastIndexOf('<'). If<does not appear within the last 7 characters of the string (since the longest partial prefix is'</think', length 7), it returns 0 immediately without evaluating prefix arrays. If<is found in the trailing window, it verifies the prefix against the constant tags.• Measured
getPartialTagLength:• In
parseThinkTags, replaced continuousremaining = remaining.slice(...)string allocations with an index cursorlet cursor = 0to scan tags directly on the source string without allocating intermediate substrings.• Removed unused
PARTIAL_OPEN_PREFIXESandPARTIAL_CLOSE_PREFIXESarrays.• Verified 100% behavioral and edge-case parity against all 22 existing unit tests.
Test plan
[✓]
bun test --config=/dev/null src/utils/__tests__/think-tag-parser.test.ts— 22 pass, 0 fail[✓]
bun run --cwd cli typecheck— 0 errors[✓] PR hygiene check passed