pi-gemini-app 0.1.12 → 0.1.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -438,6 +438,7 @@ export function createGeminiStreamHandler({
438
438
 
439
439
  const turnResult = await provider.runTurn('pi-session', body, onDelta, {
440
440
  incrementalOutput: true,
441
+ deferToolCalls: true,
441
442
  signal: options?.signal,
442
443
  recoveryCode,
443
444
  recoveryReason,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-gemini-app",
3
- "version": "0.1.12",
3
+ "version": "0.1.14",
4
4
  "description": "In-process Google Gemini App provider extension for Pi (direct native HTTP/2, /login gemini-app, /gemini-quota, zero runtime dependencies).",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -22,7 +22,9 @@ export function toolRecoveryInstruction(code, reason = null) {
22
22
  if (TOOL_ERRORS.has(code)) {
23
23
  const jsonHint = code === 'INVALID_TOOL_JSON'
24
24
  ? (JSON_REASON_HINTS[reason] ?? ' The previous tool_call block failed strict JSON parsing: double-escape all backslashes (\\\\) and quotes (\\") inside shell/code strings, use \\n instead of raw newlines inside strings, avoid trailing commas, and never put multiple JSON objects inside one tool_call fence (use a separate ```tool_call block per call).')
25
- : '';
25
+ : (code === 'MALFORMED_TOOL_CALL' && reason === 'hallucinated_caller_result')
26
+ ? ' The previous attempt echoed a synthetic [Caller tool result] transcript block instead of answering or invoking a tool: never emit [Caller tool result]; either answer the user directly or emit a real ```tool_call block.'
27
+ : '';
26
28
  return '[Gateway automatic recovery: regenerate this turn; the previous response was not delivered and no caller tool was executed.]\n' +
27
29
  'Answer the latest user request using the complete history. If a tool is needed and permitted, emit a complete tool_call block with exactly the keys "name" and "arguments" as valid JSON. Emit one strict JSON object per tool_call block with properly escaped strings (no raw newlines, invalid escapes, or trailing commas).' +
28
30
  jsonHint +
@@ -6,6 +6,7 @@ const bounded = (value, min, max) =>
6
6
  const TOOL_PROTOCOL_REASONS = new Set([
7
7
  'opening_fence',
8
8
  'closing_fence',
9
+ 'hallucinated_caller_result',
9
10
  'multiple_root_values',
10
11
  'raw_newline_in_string',
11
12
  'control_char_in_string',
@@ -63,7 +63,7 @@ export function selectIdleDeadline(facts, now = Date.now()) {
63
63
  }
64
64
  return { kind: null, ms: null };
65
65
  }
66
- if (facts.modelComplete) {
66
+ if (facts.modelComplete && facts.hasText) {
67
67
  return { kind: 'post_complete', ms: completeRemaining };
68
68
  }
69
69
  if (facts.hasLiveCalls && !facts.streamingTool) {
@@ -435,9 +435,87 @@ export class NativeDirectProvider {
435
435
  return context.outputMode === 'buffered' ? { publishedBytes: 0, toolCallCount: 0 }
436
436
  : { publishedBytes: Buffer.byteLength(publishedContent), toolCallCount: publishedCalls };
437
437
  };
438
- const publish = async items => {
438
+ // Gemini App may revise a same-id snapshot mid-stream, including inside tool_call
439
+ // bodies. With deferToolCalls, calls (and any text after the first call) are held
440
+ // until the turn is final so callers never receive draft calls that upstream rewrites.
441
+ const deferCalls = incremental && context.deferToolCalls === true;
442
+ const visibleText = (items, content, splitter, final) => {
443
+ if (!deferCalls || final) return content + splitter.preview();
444
+ let text = '';
445
+ for (const item of items) {
446
+ if (item.type === 'call') return text;
447
+ text += item.text;
448
+ }
449
+ return text + splitter.preview();
450
+ };
451
+ // Same-id revision after output was committed: accept it only if replaying the new
452
+ // snapshot reproduces everything already delivered (visible text prefix + identical calls).
453
+ // A recoverable TOOL_ERRORS failure in an unpublished tail is deferred so a subsequent
454
+ // same-id revision can still repair the draft without leaking old held calls.
455
+ const tryRebaseLive = nextText => {
456
+ let splitter = createToolCallSplitter({ policy });
457
+ let items;
458
+ let rebaseToolError = null;
459
+ try {
460
+ items = splitter.push(nextText);
461
+ } catch (splitError) {
462
+ if (!TOOL_ERRORS.has(splitError?.code)) return false;
463
+ const replay = createToolCallSplitter({ policy });
464
+ items = [];
465
+ for (let pos = 0; pos < nextText.length;) {
466
+ const nl = nextText.indexOf('\n', pos);
467
+ const end = nl < 0 ? nextText.length : nl + 1;
468
+ try {
469
+ items.push(...replay.push(nextText.slice(pos, end)));
470
+ } catch (lineErr) {
471
+ if (!TOOL_ERRORS.has(lineErr?.code)) return false;
472
+ rebaseToolError = lineErr;
473
+ break;
474
+ }
475
+ pos = end;
476
+ }
477
+ if (!rebaseToolError) return false;
478
+ splitter = replay;
479
+ }
480
+ let content = '';
481
+ const calls = [];
482
+ for (const item of items) {
483
+ if (item.type === 'content') content += item.text;
484
+ else calls.push(item.call);
485
+ }
486
+ if (calls.length < publishedCalls) return false;
487
+ for (let i = 0; i < publishedCalls; i++) {
488
+ if (calls[i].function.name !== liveCalls[i].function.name || calls[i].function.arguments !== liveCalls[i].function.arguments) return false;
489
+ }
490
+ if (!visibleText(items, content, splitter, false).startsWith(publishedContent)) return false;
491
+ // Preserve IDs of calls that were already delivered.
492
+ let callIndex = 0;
493
+ for (const item of items) {
494
+ if (item.type === 'call') {
495
+ if (callIndex < publishedCalls) item.call = liveCalls[callIndex];
496
+ calls[callIndex] = item.call;
497
+ callIndex++;
498
+ }
499
+ }
500
+ liveSplitter = splitter;
501
+ liveItems = items;
502
+ liveContent = content;
503
+ liveCalls = calls;
504
+ liveSyncedLength = nextText.length;
505
+ if (rebaseToolError) {
506
+ liveToolError = rebaseToolError;
507
+ liveToolErrorTailStart = Number.isInteger(rebaseToolError.postFenceOffset) ? rebaseToolError.postFenceOffset : nextText.length;
508
+ liveToolErrorDeadline = postToolIdleMs === null ? null : Date.now() + postToolIdleMs;
509
+ } else {
510
+ liveToolError = null;
511
+ liveToolErrorTailStart = 0;
512
+ liveToolErrorDeadline = null;
513
+ }
514
+ return true;
515
+ };
516
+ const publish = async (items, { final = false } = {}) => {
439
517
  for (const item of items) { liveItems.push(item); if (item.type === 'content') liveContent += item.text; else liveCalls.push(item.call); }
440
- const text = liveContent + liveSplitter.preview();
518
+ const text = visibleText(liveItems, liveContent, liveSplitter, final);
441
519
  if (!text.startsWith(publishedContent)) {
442
520
  const committed = committedOutput();
443
521
  if (snapshotId === null || committed.publishedBytes || committed.toolCallCount) failWithEvidence('NON_MONOTONIC_NATIVE_RESPONSE', {
@@ -452,7 +530,7 @@ export class NativeDirectProvider {
452
530
  await deliver({ content, response: { ...identity, thinkingLevel: observedThinking } });
453
531
  publishedContent = text;
454
532
  }
455
- while (publishedCalls < liveCalls.length) {
533
+ while ((!deferCalls || final) && publishedCalls < liveCalls.length) {
456
534
  if (body.parallel_tool_calls === false && publishedCalls >= 1) fail('PARALLEL_TOOL_CALLS_DISABLED');
457
535
  const call = liveCalls[publishedCalls];
458
536
  await deliver({ call, response: { ...identity, thinkingLevel: observedThinking } });
@@ -487,35 +565,38 @@ export class NativeDirectProvider {
487
565
  ...(context.nativeDiagnostic ? { diagnostic: context.nativeDiagnostic } : {}) });
488
566
  iterator = turn.events[Symbol.asyncIterator]();
489
567
  try {
490
- let cachedFallbackText = null, cachedFallbackRevision = -1, cachedFallbackResult = { kind: 'none' };
568
+ let cachedFallbackText = null, cachedFallbackRevision = -1, cachedFallbackComplete = null, cachedFallbackResult = { kind: 'none' };
491
569
  const probeFullRawText = () => {
492
- if (cachedFallbackText === rawText && cachedFallbackRevision === revisionCount) return cachedFallbackResult;
570
+ if (cachedFallbackText === rawText && cachedFallbackRevision === revisionCount && cachedFallbackComplete === modelComplete) return cachedFallbackResult;
493
571
  cachedFallbackText = rawText;
494
572
  cachedFallbackRevision = revisionCount;
573
+ cachedFallbackComplete = modelComplete;
495
574
  if (!rawText.trim() || ASYNC_DEEP_THINK_PLACEHOLDER_RE.test(rawText)) {
496
575
  return (cachedFallbackResult = { kind: 'none' });
497
576
  }
498
577
  let probeItems;
578
+ let probeSuppressed = false;
499
579
  try {
500
580
  const probe = createToolCallSplitter({ policy });
501
- probeItems = [...probe.push(rawText), ...probe.flush()];
581
+ probeItems = [...probe.push(rawText), ...probe.flush({ interrupted: !modelComplete })];
582
+ probeSuppressed = probe.suppressed;
502
583
  } catch (probeError) {
503
584
  if (probeError?.code === 'TRUNCATED_TOOL_CALL') return (cachedFallbackResult = { kind: 'streaming_tool' });
504
585
  if (TOOL_ERRORS.has(probeError?.code)) return (cachedFallbackResult = { kind: 'closed_tool_error', error: probeError });
505
586
  return (cachedFallbackResult = { kind: 'none' });
506
587
  }
507
- if (liveCalls.length > 0) return (cachedFallbackResult = { kind: 'none' });
588
+ if (liveCalls.length > 0) return (cachedFallbackResult = { kind: 'none', suppressed: probeSuppressed });
508
589
  try {
509
590
  const probeCalls = probeItems.filter(it => it.type === 'call').map(it => it.call);
510
591
  let probeContent = probeItems.filter(it => it.type === 'content').map(it => it.text).join('');
511
- if (!outputShape.nativeStructuredOutputPresent && softErrorReason(probeContent, body, probeCalls.length)) return (cachedFallbackResult = { kind: 'none' });
512
- if (body.parallel_tool_calls === false && probeCalls.length > 1) return (cachedFallbackResult = { kind: 'none' });
592
+ if (!outputShape.nativeStructuredOutputPresent && softErrorReason(probeContent, body, probeCalls.length)) return (cachedFallbackResult = { kind: 'none', suppressed: probeSuppressed });
593
+ if (body.parallel_tool_calls === false && probeCalls.length > 1) return (cachedFallbackResult = { kind: 'none', suppressed: probeSuppressed });
513
594
  validateToolCompletion(probeCalls, policy);
514
- if (!probeCalls.length && !probeContent.trim()) return (cachedFallbackResult = { kind: 'none' });
595
+ if (!probeCalls.length && !probeContent.trim()) return (cachedFallbackResult = { kind: 'none', suppressed: probeSuppressed });
515
596
  if (body.response_format && !probeCalls.length) probeContent = validateStructuredOutputText(probeContent, body.response_format);
516
- return (cachedFallbackResult = { kind: 'clean_output', hasCalls: probeCalls.length > 0, content: probeContent, calls: probeCalls, items: probeItems });
597
+ return (cachedFallbackResult = { kind: 'clean_output', hasCalls: probeCalls.length > 0, suppressed: probeSuppressed, content: probeContent, calls: probeCalls, items: probeItems });
517
598
  } catch {
518
- return (cachedFallbackResult = { kind: 'none' });
599
+ return (cachedFallbackResult = { kind: 'none', suppressed: probeSuppressed });
519
600
  }
520
601
  };
521
602
  // O(1) incremental idle classification for streaming turns via liveSplitter.state;
@@ -586,21 +667,13 @@ export class NativeDirectProvider {
586
667
  const item = await nextEventWithIdle();
587
668
  if (item && item[IDLE_TIMEOUT_SENTINEL]) {
588
669
  const idleKind = item[IDLE_TIMEOUT_SENTINEL];
589
- if (idleKind === 'post_complete' && item.verified) {
590
- if (rawText.trim().length > 0) {
591
- note('post_complete_idle_finish', { bytes: Buffer.byteLength(rawText) });
592
- try { turn?.cancel(); } catch {}
593
- readExit = 'complete_grace';
594
- ended = true;
595
- httpStatus = httpStatus ?? 200;
596
- grpc = grpc ?? 0;
597
- break;
598
- }
599
- // Upstream marked modelComplete=true with empty/thoughts-only text and never closed the stream:
600
- // break promptly without forging wireEnded=true so validate rejects as INCOMPLETE_NATIVE_RESPONSE.
601
- note('post_complete_empty_idle_timeout', { frames, thoughtBytes: outputShape.nativeThoughtBytes });
670
+ if (idleKind === 'post_complete' && item.verified && rawText.trim().length > 0) {
671
+ note('post_complete_idle_finish', { bytes: Buffer.byteLength(rawText) });
602
672
  try { turn?.cancel(); } catch {}
603
- readExit = 'complete_empty_grace';
673
+ readExit = 'complete_grace';
674
+ ended = true;
675
+ httpStatus = httpStatus ?? 200;
676
+ grpc = grpc ?? 0;
604
677
  break;
605
678
  }
606
679
  if (idleKind === 'post_tool_error' && item.verified && (liveToolError || item.probeError)) {
@@ -670,9 +743,6 @@ export class NativeDirectProvider {
670
743
  if (!Number.isSafeInteger(info.thinkingLevel) || info.thinkingLevel < 0 || info.thinkingLevel > 4) fail('INVALID_NATIVE_THINKING_LEVEL');
671
744
  observedThinking = info.thinkingLevel;
672
745
  }
673
- const wasComplete = modelComplete;
674
- modelComplete ||= info.completed;
675
- if (!wasComplete && modelComplete) modelCompleteAt = Date.now();
676
746
  // Stop as soon as a wrong model is proven; do not pay for a full
677
747
  // downgraded answer that this gateway can never return as success.
678
748
  if (downgrade) {
@@ -682,6 +752,7 @@ export class NativeDirectProvider {
682
752
  }
683
753
  if (outputShape.nativeRefusalPresent) fail('NATIVE_RESPONSE_REFUSED', 422);
684
754
  let textProgressed = false;
755
+ let rebased = false;
685
756
  if (info.text !== null) {
686
757
  const id = info.responseId || null;
687
758
  if (this.allowTextSnapshotReplacement && !id) fail('INVALID_NATIVE_RESPONSE');
@@ -694,11 +765,14 @@ export class NativeDirectProvider {
694
765
  phase: 'decode', nonMonotonicSite: 'snapshot_identity', sameResponseIdentity: false,
695
766
  snapshotPriorBytes: Buffer.byteLength(rawText), snapshotNextBytes: Buffer.byteLength(info.text),
696
767
  snapshotCommonPrefixBytes: commonPrefixBytes(rawText, info.text), ...committed });
697
- if (incremental) {
698
- if (committed.publishedBytes || committed.toolCallCount) failWithEvidence('NON_MONOTONIC_NATIVE_RESPONSE', {
768
+ if (incremental && (committed.publishedBytes || committed.toolCallCount)) {
769
+ if (!tryRebaseLive(info.text)) failWithEvidence('NON_MONOTONIC_NATIVE_RESPONSE', {
699
770
  phase: 'decode', nonMonotonicSite: 'snapshot_stream', sameResponseIdentity: true,
700
771
  snapshotPriorBytes: Buffer.byteLength(rawText), snapshotNextBytes: Buffer.byteLength(info.text),
701
772
  snapshotCommonPrefixBytes: commonPrefixBytes(rawText, info.text), ...committed });
773
+ note('snapshot_rebase', { priorBytes: Buffer.byteLength(rawText), nextBytes: Buffer.byteLength(info.text) });
774
+ rebased = true;
775
+ } else if (incremental) {
702
776
  if (liveSyncedLength > 0) await deliver({ reset: true, sameResponseIdentity: true, response: identity });
703
777
  liveSplitter = createToolCallSplitter({ policy }); liveItems = []; liveContent = ''; liveCalls = []; publishedContent = ''; publishedCalls = 0; liveSyncedLength = 0; liveToolError = null; liveToolErrorTailStart = 0; liveToolErrorDeadline = null;
704
778
  }
@@ -722,6 +796,12 @@ export class NativeDirectProvider {
722
796
  } else if (snapshotId !== null && info.responseId && info.responseId !== snapshotId) {
723
797
  fail('INVALID_NATIVE_RESPONSE');
724
798
  }
799
+ // Completion evidence applies ONLY after frame identity and monotonicity checks succeed.
800
+ if (!textProgressed) {
801
+ const wasComplete = modelComplete;
802
+ modelComplete ||= info.completed;
803
+ if (!wasComplete && modelComplete) modelCompleteAt = Date.now();
804
+ }
725
805
  const frameThoughtBytes = info.outputShape?.nativeThoughtBytes ?? 0;
726
806
  if (textProgressed) {
727
807
  // Keep allowThoughtRebase armed if this text-progress frame also carried the tail
@@ -743,30 +823,54 @@ export class NativeDirectProvider {
743
823
  allowThoughtRebase = false;
744
824
  }
745
825
  }
746
- if (incremental && !liveToolError && modeMatches(observedMode) && attributionVerified() && liveSyncedLength < rawText.length) {
747
- const delta = rawText.slice(liveSyncedLength);
748
- liveSyncedLength = rawText.length;
749
- try {
750
- await publish(liveSplitter.push(delta));
751
- } catch (splitError) {
752
- // Defer recoverable tool-protocol errors briefly until stream completion so
753
- // upstream completion/downgrade/refusal evidence is fully verified and
754
- // automatic tool_protocol recovery (or same-ID revision) can run cleanly.
755
- if (!sinkFailed && TOOL_ERRORS.has(splitError?.code)) {
756
- liveToolError = splitError;
757
- liveToolErrorTailStart = Number.isInteger(splitError.postFenceOffset) ? splitError.postFenceOffset : rawText.length;
758
- liveToolErrorDeadline = postToolIdleMs === null ? null : Date.now() + postToolIdleMs;
759
- } else {
760
- throw splitError;
826
+ if (incremental && !liveToolError && modeMatches(observedMode) && attributionVerified() && (rebased || liveSyncedLength < rawText.length)) {
827
+ if (rebased) {
828
+ await publish([]);
829
+ } else {
830
+ const delta = rawText.slice(liveSyncedLength);
831
+ liveSyncedLength = rawText.length;
832
+ try {
833
+ await publish(liveSplitter.push(delta));
834
+ } catch (splitError) {
835
+ // Defer recoverable tool-protocol errors briefly until stream completion so
836
+ // upstream completion/downgrade/refusal evidence is fully verified and
837
+ // automatic tool_protocol recovery (or same-ID revision) can run cleanly.
838
+ if (!sinkFailed && TOOL_ERRORS.has(splitError?.code)) {
839
+ liveToolError = splitError;
840
+ liveToolErrorTailStart = Number.isInteger(splitError.postFenceOffset) ? splitError.postFenceOffset : rawText.length;
841
+ liveToolErrorDeadline = postToolIdleMs === null ? null : Date.now() + postToolIdleMs;
842
+ } else {
843
+ throw splitError;
844
+ }
761
845
  }
762
846
  }
763
- // Once valid tool_call(s) have been parsed and the model begins hallucinating
847
+ // Once valid output or tool_call(s) have been parsed and the model begins hallucinating
764
848
  // a fake [Caller tool result], stop upstream immediately instead of waiting
765
849
  // minutes for the model to finish generating discarded text.
766
- if (!liveToolError && liveSplitter.suppressed && liveCalls.length > 0 && !downgrade && !outputShape.nativeRefusalPresent) {
850
+ if (!liveToolError && liveSplitter.suppressed && (liveCalls.length > 0 || liveContent.trim().length > 0) && !downgrade && !outputShape.nativeRefusalPresent) {
767
851
  note('early_stop_post_tool_hallucination', { calls: liveCalls.length });
768
852
  try { turn?.cancel(); } catch {}
769
- readExit = 'suppressed_after_valid_call';
853
+ readExit = liveCalls.length > 0 ? 'suppressed_after_valid_call' : 'suppressed_after_valid_text';
854
+ ended = true;
855
+ modelComplete = true;
856
+ httpStatus = httpStatus ?? 200;
857
+ grpc = grpc ?? 0;
858
+ break;
859
+ }
860
+ }
861
+ if (!incremental && rawText.length > 0 && !downgrade && !outputShape.nativeRefusalPresent && modeMatches(observedMode) && attributionVerified()) {
862
+ const snap = probeFullRawText();
863
+ if (snap.kind === 'closed_tool_error' && snap.error?.toolProtocolReason === 'hallucinated_caller_result') {
864
+ liveToolError = snap.error;
865
+ note('early_stop_post_tool_error', { code: liveToolError.code, bytes: Buffer.byteLength(rawText) });
866
+ try { turn?.cancel(); } catch {}
867
+ readExit = 'deferred_tool_error';
868
+ break;
869
+ }
870
+ if (snap.suppressed) {
871
+ note('early_stop_post_tool_hallucination', { calls: snap.calls?.length ?? 0 });
872
+ try { turn?.cancel(); } catch {}
873
+ readExit = snap.hasCalls ? 'suppressed_after_valid_call' : 'suppressed_after_valid_text';
770
874
  ended = true;
771
875
  modelComplete = true;
772
876
  httpStatus = httpStatus ?? 200;
@@ -848,7 +952,7 @@ export class NativeDirectProvider {
848
952
  liveSyncedLength = rawText.length;
849
953
  await publish(liveSplitter.push(delta));
850
954
  }
851
- await publish(liveSplitter.flush());
955
+ await publish(liveSplitter.flush(), { final: true });
852
956
  items = liveItems;
853
957
  }
854
958
  else { const splitter = createToolCallSplitter({ policy }); items = [...splitter.push(rawText), ...splitter.flush()]; }
@@ -881,13 +985,26 @@ export class NativeDirectProvider {
881
985
  return result;
882
986
  } catch (error) {
883
987
  const modeVerified = !downgrade && !outputShape.nativeRefusalPresent && modeMatches(observedMode) && attributionVerified();
988
+ // Only an accepted snapshot may authorize releasing held tool calls; a rejected
989
+ // frame (wrong identity or failed rebase) must never promote old draft calls.
990
+ const snapshotAccepted = !['NON_MONOTONIC_NATIVE_RESPONSE', 'INVALID_NATIVE_RESPONSE'].includes(error?.code);
991
+ const releaseHeld = snapshotAccepted && (error?.postToolIdleStall === true || modelComplete || error?.code === 'NATIVE_TURN_TIMEOUT');
884
992
  if (incremental && !liveToolError && modeVerified && !sinkFailed) {
885
- try { await publish(liveSplitter.flush()); }
993
+ try { await publish(liveSplitter.flush({ interrupted: true }), { final: releaseHeld }); }
886
994
  catch (flushError) {
887
995
  if (sinkFailed) error = flushError;
996
+ else if (releaseHeld && deferCalls) {
997
+ try { await publish([], { final: true }); } catch (releaseError) { if (sinkFailed) error = releaseError; }
998
+ }
888
999
  /* Otherwise (e.g. TRUNCATED_TOOL_CALL / parse error): retain already-published text without releasing an invalid/incomplete tool body. */
889
1000
  }
890
1001
  }
1002
+ // Deferred tool-protocol errors (or transport reset/timeout after a bad tail) leave
1003
+ // earlier validated calls from the same accepted snapshot eligible for salvage.
1004
+ if (deferCalls && modeVerified && !sinkFailed && snapshotAccepted && publishedCalls < liveCalls.length &&
1005
+ (TOOL_ERRORS.has(error?.code) || releaseHeld)) {
1006
+ try { await publish([], { final: true }); } catch (releaseError) { if (sinkFailed) error = releaseError; }
1007
+ }
891
1008
  if (incremental && error?.postToolIdleStall && publishedCalls === 0) delete error.postToolIdleStall;
892
1009
  if (incremental && error?.postOutputIdleStall && !publishedContent.trim().length) delete error.postOutputIdleStall;
893
1010
  let nonIncrementalDelivered = null;
@@ -205,6 +205,58 @@ export function flattenMessages(messages = [], { maxChars = 3_500_000 } = {}) {
205
205
 
206
206
  const CALLER_RESULT_MARKER = '[Caller tool result]';
207
207
 
208
+ // Single source of truth for classifying an unquoted buffer against the internal
209
+ // `[Caller tool result]` + `{"tool_call_id":` wire format (supporting spaces, tabs, LF, and CRLF).
210
+ // Returns:
211
+ // - 'match' : confirmed synthetic wire block prefix
212
+ // - 'pending' : valid prefix that could still become a 'match' with more bytes
213
+ // - 'none' : definitely ordinary text (safe to stream immediately)
214
+ function classifyCallerResultWire(str, { jsonOnly = false } = {}) {
215
+ let i = 0;
216
+ const skipIndent = () => {
217
+ let spaces = 0;
218
+ while (i < str.length && spaces < 3 && str[i] === ' ') { i++; spaces++; }
219
+ };
220
+ const matchLiteral = literal => {
221
+ const rem = str.length - i;
222
+ if (rem <= 0) return 'pending';
223
+ if (rem < literal.length) return literal.startsWith(str.slice(i)) ? 'pending' : 'none';
224
+ if (!str.startsWith(literal, i)) return 'none';
225
+ i += literal.length;
226
+ return 'ok';
227
+ };
228
+ if (!jsonOnly) {
229
+ skipIndent();
230
+ if (i >= str.length) return 'pending';
231
+ const m = matchLiteral(CALLER_RESULT_MARKER);
232
+ if (m !== 'ok') return m;
233
+ let sawSep = false;
234
+ while (i < str.length && (str[i] === ' ' || str[i] === '\t')) { i++; sawSep = true; }
235
+ if (i < str.length && str[i] === '\r') {
236
+ i++;
237
+ if (i === str.length) return 'pending';
238
+ if (str[i] !== '\n') return 'none';
239
+ i++;
240
+ sawSep = true;
241
+ skipIndent();
242
+ } else if (i < str.length && str[i] === '\n') {
243
+ i++;
244
+ sawSep = true;
245
+ skipIndent();
246
+ }
247
+ if (i === str.length) return 'pending';
248
+ if (!sawSep) return 'none';
249
+ } else {
250
+ skipIndent();
251
+ if (i >= str.length) return 'pending';
252
+ }
253
+ const j = matchLiteral('{"tool_call_id"');
254
+ if (j !== 'ok') return j;
255
+ while (i < str.length && (str[i] === ' ' || str[i] === '\t')) i++;
256
+ if (i === str.length) return 'pending';
257
+ return str[i] === ':' ? 'match' : 'none';
258
+ }
259
+
208
260
  // Returns the safe prefix length before a full or trailing partial CALLER_RESULT_MARKER.
209
261
  // Because CALLER_RESULT_MARKER contains '[' only at index 0, any partial prefix at the end
210
262
  // of `str` must start at the last '[' within the trailing slice.
@@ -222,16 +274,45 @@ function callerResultPreviewCut(str) {
222
274
  * become call events; preview exposes ordinary pending text, never a tool body.
223
275
  * Once at least one real tool_call has been emitted, any unquoted hallucinated
224
276
  * `[Caller tool result]` continuation and everything after it is suppressed so
225
- * the caller receives only the real tool calls. */
277
+ * the caller receives only the real tool calls. Even before any tool_call, an
278
+ * unquoted wire-format `[Caller tool result]` + `{"tool_call_id":...}` block is
279
+ * rejected as recoverable MALFORMED_TOOL_CALL when leading (no prior visible
280
+ * text) or suppressed when trailing after real visible text. */
226
281
  export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBytes(12).toString('hex'), policy = compileToolPolicy([]) } = {}) {
227
282
  let pending = '', scanned = 0, seen = 0, closed = false, suppressed = false, bytes = 0, consumedChars = 0;
228
283
  let mode = 'text', marker = '`', fenceLength = 3, toolBody = '', toolBytes = 0, headerBytes = 0, inlineTicks = 0;
284
+ let hasVisibleContent = false, leadingWhitespace = '', heldMarkerLine = null, heldMarkerOffset = 0;
229
285
  const ids = new Set();
230
- const malformed = reason => {
286
+ const pushContent = (events, chunk) => {
287
+ if (!chunk) return;
288
+ if (!hasVisibleContent && seen === 0) {
289
+ if (!chunk.trim().length) {
290
+ leadingWhitespace += chunk;
291
+ return;
292
+ }
293
+ hasVisibleContent = true;
294
+ events.push({ type: 'content', text: leadingWhitespace + chunk });
295
+ leadingWhitespace = '';
296
+ return;
297
+ }
298
+ if (chunk.trim().length > 0) hasVisibleContent = true;
299
+ events.push({ type: 'content', text: chunk });
300
+ };
301
+ const malformed = (reason, offset = undefined) => {
231
302
  const error = protocolError('MALFORMED_TOOL_CALL', 502);
232
303
  error.toolProtocolReason = reason;
304
+ if (offset !== undefined) error.postFenceOffset = offset;
233
305
  throw error;
234
306
  };
307
+ const handleZeroCallHallucination = offset => {
308
+ heldMarkerLine = null;
309
+ heldMarkerOffset = 0;
310
+ if (!hasVisibleContent) {
311
+ leadingWhitespace = '';
312
+ malformed('hallucinated_caller_result', offset);
313
+ }
314
+ suppressed = true;
315
+ };
235
316
  const emitCall = events => {
236
317
  const parsed = parseBoundedJson(toolBody.trim(), { status: 502 });
237
318
  if (!plainObject(parsed) || Object.keys(parsed).some(k => !['name', 'arguments'].includes(k)) || typeof parsed.name !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(parsed.name) || !plainObject(parsed.arguments)) fail('INVALID_TOOL_CALL', 502);
@@ -240,30 +321,30 @@ export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBy
240
321
  const id = newId();
241
322
  if (typeof id !== 'string' || !/^call_[A-Za-z0-9_-]{1,200}$/.test(id) || ids.has(id)) fail('INVALID_TOOL_CALL_ID', 502);
242
323
  ids.add(id);
324
+ if (leadingWhitespace) {
325
+ events.push({ type: 'content', text: leadingWhitespace });
326
+ leadingWhitespace = '';
327
+ }
243
328
  events.push({ type: 'call', call: { id, type: 'function', function: { name: parsed.name, arguments: JSON.stringify(parsed.arguments) } } });
244
329
  };
245
- const inlineText = (text, raw, eol, events) => {
246
- if (/^(?: {4}|\t| {0,3}(?:>|[-+*][ \t]|\d+[.)][ \t]))/.test(text)) {
247
- inlineTicks = 0;
248
- if (seen > 0) {
249
- const idx = text.indexOf(CALLER_RESULT_MARKER);
250
- if (idx >= 0) {
251
- if (idx > 0) events.push({ type: 'content', text: text.slice(0, idx) });
330
+ const scanInlineText = (text, raw, eol, events, { interrupted = false, allowToolFence = true, persistTicks = true } = {}) => {
331
+ let ticks = persistTicks ? inlineTicks : 0;
332
+ let lastBacktickRun = null;
333
+ for (let i = 0; i < text.length;) {
334
+ if (seen > 0 && !ticks) {
335
+ if (text.startsWith(CALLER_RESULT_MARKER, i)) {
336
+ if (i) pushContent(events, text.slice(0, i));
252
337
  suppressed = true;
338
+ if (persistTicks) inlineTicks = 0;
339
+ return;
340
+ }
341
+ if (interrupted && text[i] === '[' && CALLER_RESULT_MARKER.startsWith(text.slice(i))) {
342
+ if (i) pushContent(events, text.slice(0, i));
343
+ if (persistTicks) inlineTicks = 0;
253
344
  return;
254
345
  }
255
346
  }
256
- events.push({ type: 'content', text: raw });
257
- return;
258
- }
259
- if (!text.trim()) inlineTicks = 0;
260
- for (let i = 0; i < text.length;) {
261
- if (seen > 0 && !inlineTicks && text.startsWith(CALLER_RESULT_MARKER, i)) {
262
- if (i) events.push({ type: 'content', text: text.slice(0, i) });
263
- suppressed = true;
264
- return;
265
- }
266
- if (text[i] === '\\' && !inlineTicks) {
347
+ if (text[i] === '\\' && !ticks) {
267
348
  i += 2;
268
349
  while (text[i] === '`' && text[i - 1] === '`') i++;
269
350
  continue;
@@ -273,21 +354,56 @@ export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBy
273
354
  const length = end - i;
274
355
  // Historical successful responses may append an actual block after prose.
275
356
  // It still needs an exact label/newline and cannot be inside inline code.
276
- if (!inlineTicks && length >= 3 && eol && /^[ \t]*tool_call[ \t]*$/.test(text.slice(end))) {
277
- if (i) events.push({ type: 'content', text: text.slice(0, i) });
357
+ if (allowToolFence && !ticks && length >= 3 && eol && /^[ \t]*tool_call[ \t]*$/.test(text.slice(end))) {
358
+ if (i) pushContent(events, text.slice(0, i));
278
359
  mode = 'tool'; fenceLength = length; headerBytes = Buffer.byteLength(text.slice(i) + eol);
360
+ if (persistTicks) inlineTicks = 0;
279
361
  return;
280
362
  }
281
- if (!inlineTicks) inlineTicks = length;
282
- else if (inlineTicks === length) inlineTicks = 0;
363
+ if (!ticks) {
364
+ if (!persistTicks) {
365
+ if (lastBacktickRun === null) {
366
+ lastBacktickRun = new Map();
367
+ for (let j = i; j < text.length;) {
368
+ if (text[j] !== '`') { j++; continue; }
369
+ let runEnd = j;
370
+ while (text[runEnd] === '`') runEnd++;
371
+ lastBacktickRun.set(runEnd - j, j);
372
+ j = runEnd;
373
+ }
374
+ }
375
+ if ((lastBacktickRun.get(length) ?? -1) >= end) ticks = length;
376
+ } else {
377
+ ticks = length;
378
+ }
379
+ } else if (ticks === length) ticks = 0;
283
380
  i = end;
284
381
  }
285
- events.push({ type: 'content', text: raw });
382
+ if (persistTicks) inlineTicks = ticks;
383
+ pushContent(events, raw);
384
+ };
385
+ const inlineText = (text, raw, eol, events, interrupted = false) => {
386
+ if (/^(?: {4}|\t| {0,3}(?:>|[-+*][ \t]|\d+[.)][ \t]))/.test(text)) {
387
+ inlineTicks = 0;
388
+ scanInlineText(text, raw, eol, events, { interrupted, allowToolFence: false, persistTicks: false });
389
+ return;
390
+ }
391
+ if (!text.trim()) inlineTicks = 0;
392
+ scanInlineText(text, raw, eol, events, { interrupted, allowToolFence: true, persistTicks: true });
286
393
  };
287
- const line = (raw, final, events, lineStartOffset = consumedChars) => {
394
+ const line = (raw, final, events, lineStartOffset = consumedChars, interrupted = false) => {
288
395
  if (suppressed) return;
289
396
  const eol = /\r?\n$/.exec(raw)?.[0] ?? '';
290
397
  const text = eol ? raw.slice(0, -eol.length) : raw;
398
+ if (heldMarkerLine !== null) {
399
+ if (mode === 'text' && !inlineTicks && seen === 0 && classifyCallerResultWire(text, { jsonOnly: true }) === 'match') {
400
+ handleZeroCallHallucination(heldMarkerOffset);
401
+ return;
402
+ }
403
+ pushContent(events, heldMarkerLine);
404
+ heldMarkerLine = null;
405
+ heldMarkerOffset = 0;
406
+ }
291
407
  // Prefix-only matching avoids backtracking across long untrusted lines.
292
408
  const opening = /^ {0,3}(`{3,}|~{3,})/.exec(text);
293
409
  const run = opening?.[1], info = opening ? text.slice(opening[0].length) : '';
@@ -303,14 +419,8 @@ export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBy
303
419
  }
304
420
  mode = 'text'; toolBody = ''; toolBytes = 0; inlineTicks = 0;
305
421
  if (info.trim()) {
306
- const markerIdx = info.indexOf(CALLER_RESULT_MARKER);
307
- if (markerIdx >= 0) {
308
- if (markerIdx > 0) events.push({ type: 'content', text: info.slice(0, markerIdx) });
309
- suppressed = true;
310
- return;
311
- }
312
- events.push({ type: 'content', text: info + eol });
313
- } else if (eol) events.push({ type: 'content', text: eol });
422
+ scanInlineText(info, info + eol, eol, events, { interrupted, allowToolFence: false, persistTicks: false });
423
+ } else if (eol) pushContent(events, eol);
314
424
  return;
315
425
  }
316
426
  if (run?.[0] === '`' && info.trim()) malformed('closing_fence');
@@ -319,12 +429,24 @@ export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBy
319
429
  return;
320
430
  }
321
431
  if (mode === 'ordinary') {
322
- events.push({ type: 'content', text: raw });
432
+ pushContent(events, raw);
323
433
  if (run?.[0] === marker && run.length >= fenceLength && /^[ \t]*$/.test(info)) mode = 'text';
324
434
  return;
325
435
  }
326
436
  if (!opening || (run[0] === '`' && info.includes('`'))) {
327
- inlineText(text, raw, eol, events); return;
437
+ if (seen === 0 && !inlineTicks) {
438
+ const wireState = classifyCallerResultWire(raw);
439
+ if (wireState === 'match') {
440
+ handleZeroCallHallucination(lineStartOffset);
441
+ return;
442
+ }
443
+ if (!final && wireState === 'pending' && eol) {
444
+ heldMarkerLine = raw;
445
+ heldMarkerOffset = lineStartOffset;
446
+ return;
447
+ }
448
+ }
449
+ inlineText(text, raw, eol, events, interrupted); return;
328
450
  }
329
451
  const label = info.trim();
330
452
  if (label === 'tool_call' && run[0] === '`') {
@@ -335,12 +457,12 @@ export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBy
335
457
  if (label.startsWith('tool_call')) malformed('opening_fence');
336
458
  if (final && !eol && label && 'tool_call'.startsWith(label)) fail('TRUNCATED_TOOL_CALL', 502);
337
459
  mode = 'ordinary'; inlineTicks = 0; marker = run[0]; fenceLength = run.length;
338
- events.push({ type: 'content', text: raw });
460
+ pushContent(events, raw);
339
461
  };
340
- const drain = final => {
462
+ const drain = (final, { interrupted = false } = {}) => {
341
463
  const events = []; let consumed = 0, from = scanned;
342
- const runLine = (raw, isFinal, lineStartOffset) => {
343
- try { line(raw, isFinal, events, lineStartOffset); }
464
+ const runLine = (raw, isFinal, lineStartOffset, isInterrupted = false) => {
465
+ try { line(raw, isFinal, events, lineStartOffset, isInterrupted); }
344
466
  catch (err) {
345
467
  if (err && typeof err === 'object' && err.postFenceOffset === undefined) {
346
468
  err.postFenceOffset = lineStartOffset + raw.length;
@@ -358,12 +480,64 @@ export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBy
358
480
  }
359
481
  if (consumed) { consumedChars += consumed; pending = pending.slice(consumed); }
360
482
  scanned = pending.length;
483
+ if (!final && !suppressed && mode === 'text' && !inlineTicks && seen === 0 && pending) {
484
+ if (heldMarkerLine !== null) {
485
+ if (classifyCallerResultWire(pending, { jsonOnly: true }) === 'match') {
486
+ handleZeroCallHallucination(heldMarkerOffset);
487
+ if (suppressed) { consumedChars += pending.length; pending = ''; scanned = 0; return events; }
488
+ } else if (classifyCallerResultWire(pending) === 'match') {
489
+ pushContent(events, heldMarkerLine);
490
+ heldMarkerLine = null;
491
+ heldMarkerOffset = 0;
492
+ handleZeroCallHallucination(consumedChars);
493
+ if (suppressed) { consumedChars += pending.length; pending = ''; scanned = 0; return events; }
494
+ }
495
+ } else if (classifyCallerResultWire(pending) === 'match') {
496
+ handleZeroCallHallucination(consumedChars);
497
+ if (suppressed) { consumedChars += pending.length; pending = ''; scanned = 0; return events; }
498
+ }
499
+ }
361
500
  if (final && pending) {
362
- const lineStartOffset = consumedChars;
363
- runLine(pending, true, lineStartOffset);
364
- consumedChars += pending.length;
365
- pending = ''; scanned = 0;
366
- if (suppressed) return events;
501
+ // On transport interruption (not a normal completed EOF), never release an unresolved
502
+ // `[Caller tool result]` wire prefix or held marker line as visible content.
503
+ // (For `seen > 0`, `inlineText()` handles per-character backtick-aware partial-marker trimming.)
504
+ if (interrupted && mode === 'text' && !inlineTicks && seen === 0) {
505
+ if (heldMarkerLine !== null) {
506
+ if (classifyCallerResultWire(pending, { jsonOnly: true }) !== 'none') {
507
+ heldMarkerLine = null;
508
+ heldMarkerOffset = 0;
509
+ pending = ''; scanned = 0;
510
+ return events;
511
+ }
512
+ // heldMarkerLine is confirmed prose; still guard pending if it starts a new wire prefix.
513
+ if (classifyCallerResultWire(pending) !== 'none') {
514
+ pushContent(events, heldMarkerLine);
515
+ heldMarkerLine = null;
516
+ heldMarkerOffset = 0;
517
+ pending = ''; scanned = 0;
518
+ return events;
519
+ }
520
+ } else if (classifyCallerResultWire(pending) !== 'none') {
521
+ pending = ''; scanned = 0;
522
+ return events;
523
+ }
524
+ }
525
+ if (pending) {
526
+ const lineStartOffset = consumedChars;
527
+ runLine(pending, true, lineStartOffset, interrupted);
528
+ consumedChars += pending.length;
529
+ pending = ''; scanned = 0;
530
+ if (suppressed) return events;
531
+ }
532
+ }
533
+ if (final && heldMarkerLine !== null) {
534
+ if (!interrupted) pushContent(events, heldMarkerLine);
535
+ heldMarkerLine = null;
536
+ heldMarkerOffset = 0;
537
+ }
538
+ if (final && leadingWhitespace) {
539
+ if (!interrupted) events.push({ type: 'content', text: leadingWhitespace });
540
+ leadingWhitespace = '';
367
541
  }
368
542
  if (mode === 'tool') {
369
543
  if (headerBytes + toolBytes + Buffer.byteLength(pending) > TOOL_LIMITS.bytes) fail('TOOL_SIZE_LIMIT', 502);
@@ -371,6 +545,78 @@ export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBy
371
545
  }
372
546
  return events;
373
547
  };
548
+ // Incremental O(n) preview scanner matching scanInlineText()'s backtick and escape rules.
549
+ // Resets automatically whenever pending advances to a new line (consumedChars changes).
550
+ let pLineOffset = -1, pIdx = 0, pTicks = 0, pHold = -1, pRunStart = -1, pEscTicks = false;
551
+ const safePendingPreview = str => {
552
+ if (pLineOffset !== consumedChars) {
553
+ pLineOffset = consumedChars;
554
+ pIdx = 0;
555
+ pTicks = inlineTicks;
556
+ pHold = -1;
557
+ pRunStart = -1;
558
+ pEscTicks = false;
559
+ }
560
+ if (pHold >= 0) return str.slice(0, pHold);
561
+ if (pEscTicks) {
562
+ while (pIdx < str.length && str[pIdx] === '`') pIdx++;
563
+ if (pIdx === str.length) return str;
564
+ pEscTicks = false;
565
+ }
566
+ if (pRunStart >= 0) {
567
+ while (pIdx < str.length && str[pIdx] === '`') pIdx++;
568
+ const length = pIdx - pRunStart;
569
+ const atLineOpen = pRunStart <= 3 && /^ *$/.test(str.slice(0, pRunStart));
570
+ if (length >= 3 && (atLineOpen || !pTicks)) {
571
+ pHold = atLineOpen ? 0 : pRunStart;
572
+ pRunStart = -1;
573
+ return str.slice(0, pHold);
574
+ }
575
+ if (pIdx === str.length) {
576
+ return (atLineOpen || !pTicks) ? (atLineOpen ? '' : str.slice(0, pRunStart)) : str;
577
+ }
578
+ if (!pTicks) pTicks = length;
579
+ else if (pTicks === length) pTicks = 0;
580
+ pRunStart = -1;
581
+ }
582
+ let i = pIdx;
583
+ while (i < str.length) {
584
+ if (str[i] === '\\' && !pTicks) {
585
+ if (i + 1 >= str.length) { pIdx = i; return str; }
586
+ let next = i + 2;
587
+ if (str[i + 1] === '`') {
588
+ while (next < str.length && str[next] === '`') next++;
589
+ pIdx = next;
590
+ if (next === str.length) { pEscTicks = true; return str; }
591
+ i = next;
592
+ continue;
593
+ }
594
+ i = next;
595
+ pIdx = i;
596
+ continue;
597
+ }
598
+ if (str[i] !== '`') { i++; pIdx = i; continue; }
599
+ let end = i;
600
+ while (end < str.length && str[end] === '`') end++;
601
+ const length = end - i;
602
+ const atLineOpen = i <= 3 && /^ *$/.test(str.slice(0, i));
603
+ if (length >= 3 && (atLineOpen || !pTicks)) {
604
+ pHold = atLineOpen ? 0 : i;
605
+ pIdx = end;
606
+ return str.slice(0, pHold);
607
+ }
608
+ if (end === str.length) {
609
+ pRunStart = i;
610
+ pIdx = end;
611
+ return (atLineOpen || !pTicks) ? (atLineOpen ? '' : str.slice(0, i)) : str;
612
+ }
613
+ if (!pTicks) pTicks = length;
614
+ else if (pTicks === length) pTicks = 0;
615
+ i = end;
616
+ pIdx = i;
617
+ }
618
+ return str;
619
+ };
374
620
  return {
375
621
  push(text) {
376
622
  if (closed) fail('SPLITTER_CLOSED', 502);
@@ -379,25 +625,32 @@ export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBy
379
625
  pending += text;
380
626
  return drain(false);
381
627
  },
382
- flush() {
628
+ flush({ interrupted = false } = {}) {
383
629
  if (closed) fail('SPLITTER_CLOSED', 502);
384
630
  closed = true;
385
631
  if (suppressed) return [];
386
- return drain(true);
632
+ return drain(true, { interrupted });
387
633
  },
388
634
  preview() {
389
635
  if (suppressed || mode === 'tool') return '';
390
636
  if (mode === 'ordinary') return pending;
391
- if (!pending.trim() && pending.length <= 3) return '';
392
- let safe = pending;
393
- const tick = safe.indexOf('`');
394
- if (tick >= 0) {
395
- if (tick <= 3 && /^ *$/.test(safe.slice(0, tick))) return '';
396
- safe = safe.slice(0, tick);
637
+ if (heldMarkerLine !== null) {
638
+ if (classifyCallerResultWire(pending, { jsonOnly: true }) !== 'none') return '';
639
+ const safe = (!inlineTicks && classifyCallerResultWire(pending) !== 'none') ? '' : safePendingPreview(pending);
640
+ return (!hasVisibleContent && seen === 0) ? (leadingWhitespace + heldMarkerLine + safe) : (heldMarkerLine + safe);
397
641
  }
642
+ if (!pending.trim() && pending.length <= 3) return '';
643
+ if (!hasVisibleContent && seen === 0 && !pending.trim()) return '';
644
+ let safe = safePendingPreview(pending);
398
645
  if (seen > 0) {
399
646
  const cut = callerResultPreviewCut(safe);
400
647
  if (cut >= 0) safe = safe.slice(0, cut);
648
+ } else if (!inlineTicks && classifyCallerResultWire(pending) !== 'none') {
649
+ return '';
650
+ }
651
+ if (!hasVisibleContent && seen === 0) {
652
+ if (!safe.trim()) return '';
653
+ return leadingWhitespace + safe;
401
654
  }
402
655
  return safe;
403
656
  },