pi-gemini-app 0.1.10 → 0.1.11

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.
@@ -1,7 +1,7 @@
1
1
  import { openDirectTurn as defaultOpenDirectTurn } from '../../src/gateway/native-transport.mjs';
2
2
  import { createImageBlobCache } from '../../src/gateway/image-upload.mjs';
3
3
  import { NativeDirectProvider as DefaultNativeDirectProvider } from '../../src/native-provider.mjs';
4
- import { automaticRecoveryKind as defaultAutomaticRecoveryKind } from '../../src/gateway/automatic-recovery.mjs';
4
+ import { TOOL_ERRORS, automaticRecoveryKind as defaultAutomaticRecoveryKind } from '../../src/gateway/automatic-recovery.mjs';
5
5
  import { buildChatPayload as defaultBuildChatPayload } from './transcript.js';
6
6
  import { estimateUsage as defaultEstimateUsage, measurePromptImagePayload } from '../../src/openai-usage.mjs';
7
7
 
@@ -365,6 +365,7 @@ export function createGeminiStreamHandler({
365
365
 
366
366
  let attempts = 0;
367
367
  let recoveryCode;
368
+ let recoveryReason;
368
369
 
369
370
  while (true) {
370
371
  try {
@@ -439,6 +440,7 @@ export function createGeminiStreamHandler({
439
440
  incrementalOutput: true,
440
441
  signal: options?.signal,
441
442
  recoveryCode,
443
+ recoveryReason,
442
444
  getOutputCommitState,
443
445
  });
444
446
  if (turnResult?.thinkingLevel !== undefined && turnResult.thinkingLevel !== null) {
@@ -449,25 +451,25 @@ export function createGeminiStreamHandler({
449
451
  }
450
452
  break;
451
453
  } catch (turnError) {
452
- if (
453
- !options?.signal?.aborted &&
454
+ const usableTimeout =
454
455
  turnError?.code === 'NATIVE_TURN_TIMEOUT' &&
455
- turnError?.unverifiedOutput !== true &&
456
- (hasToolCalls || turnError?.postOutputIdleStall === true || publishedBytes >= PREFIX_BYTES)
457
- ) {
456
+ (hasToolCalls || turnError?.postOutputIdleStall === true || publishedBytes >= PREFIX_BYTES);
457
+ const salvageValidatedCalls = hasToolCalls && TOOL_ERRORS.has(turnError?.code);
458
+ if (!options?.signal?.aborted && turnError?.unverifiedOutput !== true && (usableTimeout || salvageValidatedCalls)) {
458
459
  break;
459
460
  }
460
461
  if (
461
462
  !started &&
462
- attempts === 0 &&
463
463
  !options?.signal?.aborted &&
464
464
  turnError?.code !== 'NATIVE_TURN_ABORTED' &&
465
465
  turnError?.code !== 'REQUEST_CANCELLED'
466
466
  ) {
467
467
  const kind = automaticRecoveryKind(turnError, model.id, { allowAutoModel: true });
468
- if (ALLOWED_RECOVERY_KINDS.has(kind)) {
468
+ const maxRetries = kind === 'tool_protocol' || kind === 'structured_output' ? 2 : 1;
469
+ if (ALLOWED_RECOVERY_KINDS.has(kind) && attempts < maxRetries) {
469
470
  attempts++;
470
471
  recoveryCode = turnError.code;
472
+ recoveryReason = turnError.toolProtocolReason ?? turnError.nativeEvidence?.toolProtocolReason ?? null;
471
473
  textBuffer = '';
472
474
  pendingSurrogate = '';
473
475
  observedThinking = null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-gemini-app",
3
- "version": "0.1.10",
3
+ "version": "0.1.11",
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": [
@@ -7,10 +7,26 @@ export const TOOL_ERRORS = new Set(['MALFORMED_TOOL_CALL', 'INVALID_TOOL_JSON',
7
7
  'TOOL_CHOICE_MISMATCH', 'TOOL_CALL_NOT_ALLOWED', 'PARALLEL_TOOL_CALLS_DISABLED']);
8
8
  const STRUCTURED_OUTPUT_ERRORS = new Set(['INVALID_STRUCTURED_OUTPUT_JSON', 'STRUCTURED_OUTPUT_SCHEMA_MISMATCH']);
9
9
  const TRANSPORT_ERRORS = new Set(['NATIVE_STREAM_RESET', 'NATIVE_CONNECTION_FAILED', 'NATIVE_STREAM_FAILED', 'NATIVE_STREAM_CLOSED_EARLY']);
10
- export function toolRecoveryInstruction(code) {
10
+ const JSON_REASON_HINTS = Object.freeze({
11
+ multiple_root_values: ' The previous tool_call block failed JSON parsing (multiple_root_values): never put multiple JSON objects inside one tool_call fence; open a separate ```tool_call block for each call.',
12
+ raw_newline_in_string: ' The previous tool_call block failed JSON parsing (raw_newline_in_string): encode all newlines inside JSON string values as \\n, never raw line breaks.',
13
+ control_char_in_string: ' The previous tool_call block failed JSON parsing (control_char_in_string): escape control characters (such as \\t and \\n) inside JSON strings.',
14
+ invalid_escape: ' The previous tool_call block failed JSON parsing (invalid_escape): double-escape backslashes (\\\\) in regexes, paths, and shell commands.',
15
+ unexpected_token_after_string: ' The previous tool_call block failed JSON parsing (unexpected_token_after_string): escape all inner double quotes as \\" inside shell/code strings.',
16
+ trailing_comma: ' The previous tool_call block failed JSON parsing (trailing_comma): remove trailing commas before } or ].',
17
+ unterminated_json: ' The previous tool_call block was truncated or missing a closing quote/brace (unterminated_json): emit the complete JSON object before closing the ``` fence.',
18
+ duplicate_key: ' The previous tool_call block contained duplicate JSON object keys (duplicate_key): emit each key only once.',
19
+ limit_exceeded: ' The previous tool_call block exceeded JSON size/depth limits (limit_exceeded): split large edits into smaller calls.',
20
+ });
21
+ export function toolRecoveryInstruction(code, reason = null) {
11
22
  if (TOOL_ERRORS.has(code)) {
23
+ const jsonHint = code === 'INVALID_TOOL_JSON'
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
+ : '';
12
26
  return '[Gateway automatic recovery: regenerate this turn; the previous response was not delivered and no caller tool was executed.]\n' +
13
- '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). Use only declared names and actual JSON-object arguments matching the original schema. Respect the selected tool choice and parallel-call restriction. Put both fences on separate lines. Do not invent tool results, duplicate already completed work, or discuss this recovery instruction. If tools are prohibited, answer normally without tool_call blocks.';
27
+ '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
+ jsonHint +
29
+ ' Use only declared names and actual JSON-object arguments matching the original schema. Respect the selected tool choice and parallel-call restriction. Put both fences on separate lines. Do not invent tool results, duplicate already completed work, or discuss this recovery instruction. If tools are prohibited, answer normally without tool_call blocks.';
14
30
  }
15
31
  if (STRUCTURED_OUTPUT_ERRORS.has(code)) {
16
32
  return '[Gateway automatic recovery: regenerate this turn; the previous response was not delivered because it did not satisfy the required JSON output format.]\n' +
@@ -103,6 +103,7 @@ export class NativeDiagnostic {
103
103
  this.now = now; this.monotonic = monotonic;
104
104
  }
105
105
  claim(requestId) {
106
+ if (process.platform === 'win32') return null;
106
107
  let fd;
107
108
  try {
108
109
  if (!this.directory || !/^req_[a-f0-9-]{36}$/.test(requestId)) return null;
@@ -3,6 +3,22 @@ import { NATIVE_RESPONSE_LIMITS } from './native-response-limits.mjs';
3
3
  import { NATIVE_MODELS } from '../openai-contract.mjs';
4
4
  const bounded = (value, min, max) =>
5
5
  Number.isSafeInteger(value) && value >= min && value <= max ? value : null;
6
+ const TOOL_PROTOCOL_REASONS = new Set([
7
+ 'opening_fence',
8
+ 'closing_fence',
9
+ 'multiple_root_values',
10
+ 'raw_newline_in_string',
11
+ 'control_char_in_string',
12
+ 'invalid_escape',
13
+ 'unexpected_token_after_string',
14
+ 'trailing_comma',
15
+ 'unterminated_json',
16
+ 'duplicate_key',
17
+ 'nonfinite_number',
18
+ 'invalid_surrogate',
19
+ 'limit_exceeded',
20
+ 'invalid_syntax',
21
+ ]);
6
22
  const phases = new Set([
7
23
  "auth",
8
24
  "upload",
@@ -67,7 +83,7 @@ export function safeNativeEvidence(value) {
67
83
  const streamCloseCode = bounded(value.streamCloseCode, 1, 0xffffffff);
68
84
  const fallback = bounded(value.fallback, 0, 1);
69
85
  const downgradeReason = bounded(value.downgradeReason, 0, 0x7fffffff);
70
- const toolProtocolReason = ['opening_fence', 'closing_fence'].includes(value.toolProtocolReason) ? value.toolProtocolReason : null;
86
+ const toolProtocolReason = TOOL_PROTOCOL_REASONS.has(value.toolProtocolReason) ? value.toolProtocolReason : null;
71
87
  const emptyResponseReason = ['no_text', 'whitespace_only', 'thoughts_only', 'post_parse_empty'].includes(value.emptyResponseReason) ? value.emptyResponseReason : null;
72
88
  const nativeTextBytes = bounded(value.nativeTextBytes, 0, 8 * 1024 * 1024);
73
89
  const nativeShareableTextBytes = bounded(value.nativeShareableTextBytes, 0, 8 * 1024 * 1024);
@@ -7,7 +7,7 @@ import crypto from 'node:crypto';
7
7
  import { parse } from '../native-wire/protobuf.mjs';
8
8
  import { decodeClientGenerateResponse } from '../native-wire/robin-current.mjs';
9
9
  import { ProtocolError, protocolError, compileToolPolicy, createToolCallSplitter, validateToolCompletion } from './tool-protocol.mjs';
10
- import { MODEL_ALIASES, MODEL_MODES, MODEL_SPECS, NATIVE_MODELS, canonicalModel, normalizeChatRequest, normalizeResponsesRequest, buildCanonicalPrompt, writeChatResponse, writeResponsesResponse } from './openai-contract.mjs';
10
+ import { MODEL_ALIASES, MODEL_MODES, MODEL_SPECS, NATIVE_MODELS, PROMPT_MAX_BYTES, canonicalModel, normalizeChatRequest, normalizeResponsesRequest, buildCanonicalPrompt, writeChatResponse, writeResponsesResponse } from './openai-contract.mjs';
11
11
  import { RESPONSE_TOOL_IDENTITIES } from './responses-tool-namespaces.mjs';
12
12
  import { safeNativeEvidence } from './gateway/native-evidence.mjs';
13
13
  import { decodePassiveQuota, mergeQuotaObservation } from './gateway/quota.mjs';
@@ -38,6 +38,48 @@ const failWithEvidence = (code, evidence) => {
38
38
  const utf8 = new TextDecoder('utf-8', { fatal: true });
39
39
  const HYDROGEN_ATTRIBUTION = /\bhydrogen\b/i;
40
40
  const NEON_ATTRIBUTION = /\bneon\b/i;
41
+ const ASYNC_DEEP_THINK_PLACEHOLDER_RE = /^\s*I'm on it\.\s*Responses with Deep Think can take some time, so check back in a bit\.\s*https?:\/\/googleusercontent\.com\/agentic_processing_chip\/\d+\s*$/i;
42
+ const CLOSING_FENCE_LINE_RE = /^ {0,3}`{3,}/;
43
+ const PENDING_TOOL_OPEN_RE = /^ {0,3}`{3,}[ \t]*t(?:o(?:o(?:l(?:_(?:c(?:a(?:l(?:l)?)?)?)?)?)?)?)?[ \t]*$/;
44
+
45
+ /** Pure idle deadline selector for NativeDirectProvider.runTurn().
46
+ * Preserves strict priority: an enabled lower-priority timer never runs while
47
+ * a higher-priority condition matches with its own deadline disabled (null). */
48
+ export function selectIdleDeadline(facts, now = Date.now()) {
49
+ if (!facts?.verified) return { kind: null, ms: null };
50
+ const elapsed = anchor => (anchor !== null && anchor !== undefined ? Math.max(0, now - anchor) : 0);
51
+ const completeRemaining = (facts.modelComplete && facts.postCompleteGraceMs !== null)
52
+ ? Math.max(0, facts.postCompleteGraceMs - elapsed(facts.modelCompleteAt))
53
+ : null;
54
+ if (facts.hasLiveToolError || facts.hasClosedToolError) {
55
+ const toolErrorRemaining = facts.hasLiveToolError
56
+ ? (facts.postToolIdleMs === null ? null : Math.max(0, (facts.liveToolErrorDeadline ?? now) - now))
57
+ : (facts.postToolIdleMs === null ? null : Math.max(0, facts.postToolIdleMs - elapsed(facts.lastTextProgressAt)));
58
+ if (toolErrorRemaining !== null && (completeRemaining === null || toolErrorRemaining <= completeRemaining)) {
59
+ return { kind: 'post_tool_error', ms: toolErrorRemaining };
60
+ }
61
+ if (completeRemaining !== null) {
62
+ return { kind: 'post_tool_error', ms: completeRemaining };
63
+ }
64
+ return { kind: null, ms: null };
65
+ }
66
+ if (facts.modelComplete && facts.hasText) {
67
+ return { kind: 'post_complete', ms: completeRemaining };
68
+ }
69
+ if (facts.hasLiveCalls && !facts.streamingTool) {
70
+ return {
71
+ kind: 'post_tool',
72
+ ms: facts.postToolIdleMs === null ? null : Math.max(0, facts.postToolIdleMs - elapsed(facts.lastTextProgressAt)),
73
+ };
74
+ }
75
+ if (facts.cleanOutput) {
76
+ return {
77
+ kind: 'post_output',
78
+ ms: facts.postOutputIdleMs === null ? null : Math.max(0, facts.postOutputIdleMs - elapsed(facts.lastTextProgressAt)),
79
+ };
80
+ }
81
+ return { kind: null, ms: null };
82
+ }
41
83
  function one(fields, number) {
42
84
  const found = fields.filter(field => field.number === number);
43
85
  if (found.length > 1) fail('INVALID_NATIVE_RESPONSE');
@@ -282,11 +324,21 @@ export class NativeDirectProvider {
282
324
  : validateIdleMs(context.postOutputIdleMs, 'postOutputIdleMs');
283
325
  const body = normalizeChatRequest(canonicalChatBody, { allowAutoModel: this.allowAutoModel });
284
326
  if (body.native_search) return this.runNativeSearch(accountId, body, onDelta, { ...context, timeoutMs });
285
- const recoveryInstruction = toolRecoveryInstruction(context.recoveryCode);
286
- if (recoveryInstruction) body.messages = [...body.messages, { role: 'system', content: recoveryInstruction }];
327
+ const recoveryInstruction = toolRecoveryInstruction(context.recoveryCode, context.recoveryReason);
328
+ const appendRecovery = promptMessages => {
329
+ if (!recoveryInstruction || !promptMessages?.length) return promptMessages;
330
+ const next = promptMessages.map(msg => ({ ...msg }));
331
+ const last = next[next.length - 1];
332
+ const suffix = `\n\n${recoveryInstruction}`;
333
+ if (typeof last?.content === 'string' && Buffer.byteLength(last.content + suffix) <= PROMPT_MAX_BYTES) {
334
+ last.content += suffix;
335
+ }
336
+ return next;
337
+ };
287
338
  if (this.allowTextSnapshotReplacement && body.tools.length) fail('NATIVE_TEXT_SNAPSHOT_TOOLS_FORBIDDEN', 400);
288
339
  const policy = compileToolPolicy(body.tools, body.tool_choice);
289
340
  let { messages, images } = buildCanonicalPrompt(body);
341
+ messages = appendRecovery(messages);
290
342
  const isAutoModel = this.allowAutoModel && body.model === 'gemini-auto';
291
343
  const modeCategory = isAutoModel ? null : MODEL_MODES[body.model];
292
344
  const modeMatches = mode => isAutoModel
@@ -323,7 +375,7 @@ export class NativeDirectProvider {
323
375
  [RESPONSE_TOOL_IDENTITIES]: body[RESPONSE_TOOL_IDENTITIES],
324
376
  requestedThinkingLevel: body.thinking_level, ignoredTokenParameters: ['max_tokens', 'max_completion_tokens'].filter(key => body[key] !== undefined),
325
377
  ...((body.reasoning_effort ?? body.reasoning?.effort) === undefined ? {} : { requestedReasoningEffort: body.reasoning_effort ?? body.reasoning?.effort }) };
326
- let liveSplitter = incremental ? createToolCallSplitter({ policy }) : null, liveItems = [], liveContent = '', liveCalls = [], publishedContent = '', publishedCalls = 0, liveSyncedLength = 0, liveToolError = null, liveToolErrorTailStart = 0, liveToolErrorDeadline = null, toolErrorEarlyStop = false, postCompleteIdleFinished = false, sinkFailed = false;
378
+ let liveSplitter = incremental ? createToolCallSplitter({ policy }) : null, liveItems = [], liveContent = '', liveCalls = [], publishedContent = '', publishedCalls = 0, liveSyncedLength = 0, liveToolError = null, liveToolErrorTailStart = 0, liveToolErrorDeadline = null, readExit = 'none', sinkFailed = false;
327
379
  const deliver = async event => {
328
380
  try { await onDelta(event); }
329
381
  catch (error) { sinkFailed = true; throw error; }
@@ -368,6 +420,7 @@ export class NativeDirectProvider {
368
420
  phase = 'upload';
369
421
  images = await bounded(this.downloadImages(images, { signal: controller.signal, timeoutMs: Math.min(timeoutMs, 30000) }));
370
422
  ({ messages, images } = buildCanonicalPrompt(body, images));
423
+ messages = appendRecovery(messages);
371
424
  }
372
425
  phase = 'auth';
373
426
  let token;
@@ -390,85 +443,78 @@ export class NativeDirectProvider {
390
443
  ...(context.nativeDiagnostic ? { diagnostic: context.nativeDiagnostic } : {}) });
391
444
  iterator = turn.events[Symbol.asyncIterator]();
392
445
  try {
393
- let cachedProbeText = null, cachedProbeRevision = -1, cachedProbeLiveCalls = -1, cachedProbeStructured = false, cachedProbeResult = { kind: 'none' };
394
- const probeIdleState = () => {
395
- if (cachedProbeText === rawText && cachedProbeRevision === revisionCount && cachedProbeLiveCalls === liveCalls.length && cachedProbeStructured === outputShape.nativeStructuredOutputPresent) {
396
- return cachedProbeResult;
397
- }
398
- cachedProbeText = rawText;
399
- cachedProbeRevision = revisionCount;
400
- cachedProbeLiveCalls = liveCalls.length;
401
- cachedProbeStructured = outputShape.nativeStructuredOutputPresent;
402
- if (!rawText.trim()) return (cachedProbeResult = { kind: 'none' });
403
- if (/^\s*I'm on it\.\s*Responses with Deep Think can take some time, so check back in a bit\.\s*https?:\/\/googleusercontent\.com\/agentic_processing_chip\/\d+\s*$/i.test(rawText)) {
404
- return (cachedProbeResult = { kind: 'none' });
446
+ let cachedFallbackText = null, cachedFallbackRevision = -1, cachedFallbackResult = { kind: 'none' };
447
+ const probeFullRawText = () => {
448
+ if (cachedFallbackText === rawText && cachedFallbackRevision === revisionCount) return cachedFallbackResult;
449
+ cachedFallbackText = rawText;
450
+ cachedFallbackRevision = revisionCount;
451
+ if (!rawText.trim() || ASYNC_DEEP_THINK_PLACEHOLDER_RE.test(rawText)) {
452
+ return (cachedFallbackResult = { kind: 'none' });
405
453
  }
406
454
  let probeItems;
407
455
  try {
408
456
  const probe = createToolCallSplitter({ policy });
409
457
  probeItems = [...probe.push(rawText), ...probe.flush()];
410
458
  } catch (probeError) {
411
- // Only a closed tool block (or malformed fence/call) failing parse/schema validation
412
- // is a closed_tool_error. TRUNCATED_TOOL_CALL means a tool block is still streaming,
413
- // and TOOL_CHOICE_NOT_SATISFIED is checked separately below so a valid preamble before
414
- // a required tool_choice call is never misclassified as a closed tool error.
415
- if (probeError?.code === 'TRUNCATED_TOOL_CALL') {
416
- return (cachedProbeResult = { kind: 'streaming_tool' });
417
- }
418
- if (TOOL_ERRORS.has(probeError?.code)) {
419
- return (cachedProbeResult = { kind: 'closed_tool_error', error: probeError });
420
- }
421
- return (cachedProbeResult = { kind: 'none' });
459
+ if (probeError?.code === 'TRUNCATED_TOOL_CALL') return (cachedFallbackResult = { kind: 'streaming_tool' });
460
+ if (TOOL_ERRORS.has(probeError?.code)) return (cachedFallbackResult = { kind: 'closed_tool_error', error: probeError });
461
+ return (cachedFallbackResult = { kind: 'none' });
422
462
  }
423
- if (liveCalls.length > 0) return (cachedProbeResult = { kind: 'none' });
463
+ if (liveCalls.length > 0) return (cachedFallbackResult = { kind: 'none' });
424
464
  try {
425
465
  const probeCalls = probeItems.filter(it => it.type === 'call').map(it => it.call);
426
466
  const probeContent = probeItems.filter(it => it.type === 'content').map(it => it.text).join('');
427
- if (!outputShape.nativeStructuredOutputPresent && softErrorReason(probeContent, body, probeCalls.length)) return (cachedProbeResult = { kind: 'none' });
428
- if (body.parallel_tool_calls === false && probeCalls.length > 1) return (cachedProbeResult = { kind: 'none' });
467
+ if (!outputShape.nativeStructuredOutputPresent && softErrorReason(probeContent, body, probeCalls.length)) return (cachedFallbackResult = { kind: 'none' });
468
+ if (body.parallel_tool_calls === false && probeCalls.length > 1) return (cachedFallbackResult = { kind: 'none' });
429
469
  validateToolCompletion(probeCalls, policy);
430
- if (!probeCalls.length && !probeContent.trim()) return (cachedProbeResult = { kind: 'none' });
470
+ if (!probeCalls.length && !probeContent.trim()) return (cachedFallbackResult = { kind: 'none' });
431
471
  if (body.response_format && !probeCalls.length) validateStructuredOutputText(probeContent, body.response_format);
432
- return (cachedProbeResult = { kind: 'clean_output' });
472
+ return (cachedFallbackResult = { kind: 'clean_output' });
433
473
  } catch {
434
- return (cachedProbeResult = { kind: 'none' });
474
+ return (cachedFallbackResult = { kind: 'none' });
475
+ }
476
+ };
477
+ // O(1) incremental idle classification for streaming turns via liveSplitter.state;
478
+ // only falls back to full probe when a pending closing fence lacks trailing LF or !incremental.
479
+ const classifyIdleSnapshot = () => {
480
+ if (!rawText.trim() || ASYNC_DEEP_THINK_PLACEHOLDER_RE.test(rawText)) return { kind: 'none' };
481
+ if (!liveSplitter) return probeFullRawText();
482
+ const state = liveSplitter.state;
483
+ const lastLf = rawText.lastIndexOf('\n');
484
+ const trailingLine = lastLf < 0 ? rawText : rawText.slice(lastLf + 1);
485
+ if (state === 'tool_fence') {
486
+ if (trailingLine && CLOSING_FENCE_LINE_RE.test(trailingLine)) return probeFullRawText();
487
+ return { kind: 'streaming_tool' };
488
+ }
489
+ if (state === 'text' && trailingLine && PENDING_TOOL_OPEN_RE.test(trailingLine)) {
490
+ return { kind: 'streaming_tool' };
435
491
  }
492
+ if (liveCalls.length > 0) return { kind: 'none' };
493
+ if (policy.choice === 'required' || policy.forced) return { kind: 'none' };
494
+ const candidateText = liveContent + liveSplitter.preview();
495
+ if (!candidateText.trim()) return { kind: 'none' };
496
+ if (!outputShape.nativeStructuredOutputPresent && softErrorReason(candidateText, body, 0)) return { kind: 'none' };
497
+ return { kind: 'clean_output' };
436
498
  };
437
- const isCleanPostOutputIdleStall = () => probeIdleState().kind === 'clean_output';
438
499
  const nextEventWithIdle = async () => {
439
500
  const verified = !downgrade && !outputShape.nativeRefusalPresent && modeMatches(observedMode) && attributionVerified();
440
- const probeState = (verified && !liveToolError) ? probeIdleState() : { kind: 'none' };
441
- // Never arm an idle timer unless we already have verified, complete, deliverable output
442
- // or a closed invalid tool block; never kill a slow still-streaming tool call (TRUNCATED_TOOL_CALL)
443
- // or a valid preamble preceding a required tool_choice call.
444
- const now = Date.now();
445
- const toolErrorRemaining = liveToolError
446
- ? (postToolIdleMs === null ? null : Math.max(0, (liveToolErrorDeadline ?? now) - now))
447
- : (postToolIdleMs === null ? null : Math.max(0, postToolIdleMs - (lastTextProgressAt !== null ? now - lastTextProgressAt : 0)));
448
- const completeRemaining = (modelComplete && postCompleteGraceMs !== null)
449
- ? Math.max(0, postCompleteGraceMs - (modelCompleteAt !== null ? now - modelCompleteAt : 0))
450
- : null;
451
- let idleKind = null;
452
- let idleMs = null;
453
- if (verified && (liveToolError || probeState.kind === 'closed_tool_error')) {
454
- // Take the shortest enabled deadline across post_tool_error and (when modelComplete) post_complete.
455
- if (toolErrorRemaining !== null && (completeRemaining === null || toolErrorRemaining <= completeRemaining)) {
456
- idleKind = 'post_tool_error';
457
- idleMs = toolErrorRemaining;
458
- } else if (completeRemaining !== null) {
459
- idleKind = 'post_tool_error';
460
- idleMs = completeRemaining;
461
- }
462
- } else if (modelComplete && verified && rawText.trim().length > 0) {
463
- idleKind = 'post_complete';
464
- idleMs = completeRemaining;
465
- } else if (verified && liveCalls.length > 0 && probeState.kind !== 'streaming_tool') {
466
- idleKind = 'post_tool';
467
- idleMs = postToolIdleMs === null ? null : Math.max(0, postToolIdleMs - (lastTextProgressAt !== null ? now - lastTextProgressAt : 0));
468
- } else if (probeState.kind === 'clean_output') {
469
- idleKind = 'post_output';
470
- idleMs = postOutputIdleMs === null ? null : Math.max(0, postOutputIdleMs - (lastTextProgressAt !== null ? now - lastTextProgressAt : 0));
471
- }
501
+ const snap = (verified && !liveToolError) ? classifyIdleSnapshot() : { kind: 'none' };
502
+ const { kind: idleKind, ms: idleMs } = selectIdleDeadline({
503
+ verified,
504
+ hasText: rawText.trim().length > 0,
505
+ hasLiveToolError: Boolean(liveToolError),
506
+ hasClosedToolError: snap.kind === 'closed_tool_error',
507
+ modelComplete,
508
+ hasLiveCalls: liveCalls.length > 0,
509
+ streamingTool: snap.kind === 'streaming_tool',
510
+ cleanOutput: snap.kind === 'clean_output',
511
+ liveToolErrorDeadline,
512
+ lastTextProgressAt,
513
+ modelCompleteAt,
514
+ postCompleteGraceMs,
515
+ postToolIdleMs,
516
+ postOutputIdleMs,
517
+ });
472
518
  const nextPromise = iterator.next();
473
519
  if (idleMs === null) return bounded(nextPromise);
474
520
  nextPromise.catch(() => {});
@@ -477,7 +523,7 @@ export class NativeDirectProvider {
477
523
  return await Promise.race([
478
524
  bounded(nextPromise),
479
525
  new Promise(resolve => {
480
- idleTimer = setTimeout(() => resolve({ [IDLE_TIMEOUT_SENTINEL]: idleKind, verified, probeError: probeState.error ?? null }), idleMs);
526
+ idleTimer = setTimeout(() => resolve({ [IDLE_TIMEOUT_SENTINEL]: idleKind, verified, probeError: snap.error ?? null }), idleMs);
481
527
  idleTimer.unref?.();
482
528
  }),
483
529
  ]);
@@ -493,7 +539,7 @@ export class NativeDirectProvider {
493
539
  if (idleKind === 'post_complete' && item.verified && rawText.trim().length > 0) {
494
540
  note('post_complete_idle_finish', { bytes: Buffer.byteLength(rawText) });
495
541
  try { turn?.cancel(); } catch {}
496
- postCompleteIdleFinished = true;
542
+ readExit = 'complete_grace';
497
543
  ended = true;
498
544
  httpStatus = httpStatus ?? 200;
499
545
  grpc = grpc ?? 0;
@@ -503,7 +549,7 @@ export class NativeDirectProvider {
503
549
  if (!liveToolError) liveToolError = item.probeError;
504
550
  note('post_tool_error_idle_finish', { code: liveToolError.code, bytes: Buffer.byteLength(rawText) });
505
551
  try { turn?.cancel(); } catch {}
506
- toolErrorEarlyStop = true;
552
+ readExit = 'deferred_tool_error';
507
553
  break;
508
554
  }
509
555
  note(`${idleKind}_idle_timeout`, {
@@ -513,7 +559,10 @@ export class NativeDirectProvider {
513
559
  });
514
560
  try { turn?.cancel(); } catch {}
515
561
  const idleError = protocolError('NATIVE_TURN_TIMEOUT', 504);
516
- if (idleKind === 'post_output' && item.verified && isCleanPostOutputIdleStall()) {
562
+ if (idleKind === 'post_tool' && item.verified && liveCalls.length > 0) {
563
+ idleError.postToolIdleStall = true;
564
+ }
565
+ if (idleKind === 'post_output' && item.verified && classifyIdleSnapshot().kind === 'clean_output') {
517
566
  idleError.postOutputIdleStall = true;
518
567
  }
519
568
  throw idleError;
@@ -625,6 +674,7 @@ export class NativeDirectProvider {
625
674
  if (!liveToolError && liveSplitter.suppressed && liveCalls.length > 0 && !downgrade && !outputShape.nativeRefusalPresent) {
626
675
  note('early_stop_post_tool_hallucination', { calls: liveCalls.length });
627
676
  try { turn?.cancel(); } catch {}
677
+ readExit = 'suppressed_after_valid_call';
628
678
  ended = true;
629
679
  modelComplete = true;
630
680
  httpStatus = httpStatus ?? 200;
@@ -639,7 +689,7 @@ export class NativeDirectProvider {
639
689
  if (postErrorTail.includes('[Caller tool result]') || postErrorTailBytes > 4096 || graceExpired) {
640
690
  note('early_stop_post_tool_error', { code: liveToolError.code, bytes: postErrorTailBytes });
641
691
  try { turn?.cancel(); } catch {}
642
- toolErrorEarlyStop = true;
692
+ readExit = 'deferred_tool_error';
643
693
  break;
644
694
  }
645
695
  }
@@ -649,7 +699,7 @@ export class NativeDirectProvider {
649
699
  else if (info.quotaObservation.source === 'official') quotaObservation = mergeQuotaObservation(quotaObservation, info.quotaObservation);
650
700
  }
651
701
  } else if (event.type === 'end') {
652
- phase = 'end'; ended = true; grpc = event.grpcStatus; httpStatus = event.httpStatus;
702
+ phase = 'end'; readExit = 'wire_end'; ended = true; grpc = event.grpcStatus; httpStatus = event.httpStatus;
653
703
  if (event.httpStatus === 429 || grpc === 8) fail('NATIVE_RATE_LIMITED', 429);
654
704
  if (event.httpStatus === 401 || grpc === 16) fail('NATIVE_AUTH_REJECTED');
655
705
  if (event.httpStatus === 403 || grpc === 7) fail('NATIVE_PERMISSION_REJECTED');
@@ -681,7 +731,7 @@ export class NativeDirectProvider {
681
731
  phase = 'validate';
682
732
  if (downgrade) fail('MODEL_DOWNGRADE_REJECTED');
683
733
  if (outputShape.nativeRefusalPresent) fail('NATIVE_RESPONSE_REFUSED', 422);
684
- if (toolErrorEarlyStop && liveToolError) {
734
+ if (readExit === 'deferred_tool_error' && liveToolError) {
685
735
  if (!modeMatches(observedMode)) fail('MISSING_NATIVE_MODE_EVIDENCE');
686
736
  if (!attributionVerified()) fail('MODEL_DOWNGRADE_REJECTED');
687
737
  throw liveToolError;
@@ -689,7 +739,7 @@ export class NativeDirectProvider {
689
739
  if (!ended) fail('INCOMPLETE_NATIVE_RESPONSE');
690
740
  // An ordinary RPC close is not model completion. Async UI placeholders
691
741
  // must be non-retryable or PI will repeatedly submit fresh generations.
692
- if (/^\s*I'm on it\.\s*Responses with Deep Think can take some time, so check back in a bit\.\s*https?:\/\/googleusercontent\.com\/agentic_processing_chip\/\d+\s*$/i.test(rawText)) fail('NATIVE_ASYNC_RESPONSE_UNSUPPORTED', 422);
742
+ if (ASYNC_DEEP_THINK_PLACEHOLDER_RE.test(rawText)) fail('NATIVE_ASYNC_RESPONSE_UNSUPPORTED', 422);
693
743
  if (!modelComplete) fail('INCOMPLETE_NATIVE_RESPONSE');
694
744
  if (!modeMatches(observedMode)) fail('MISSING_NATIVE_MODE_EVIDENCE');
695
745
  if (!attributionVerified()) fail('MODEL_DOWNGRADE_REJECTED');
@@ -754,8 +804,10 @@ export class NativeDirectProvider {
754
804
  note('provider_failure', { code: safe.code });
755
805
  let transport = {};
756
806
  try { transport = turn?.getSafeStatus?.() ?? {}; } catch {}
807
+ const committedOnFailure = committedOutput();
757
808
  safe.nativeEvidence = safeNativeEvidence({
758
809
  // Keep guard-site diagnostics raised deeper in this turn; they are byte counts only.
810
+ ...((committedOnFailure.publishedBytes > 0 || committedOnFailure.toolCallCount > 0 || TOOL_ERRORS.has(safe.code)) ? committedOnFailure : {}),
759
811
  ...(error.nativeEvidence ?? {}),
760
812
  phase, upstreamHttpStatus: transport.httpStatus ?? httpStatus,
761
813
  grpcStatus: transport.grpcStatus ?? grpc,
@@ -768,7 +820,7 @@ export class NativeDirectProvider {
768
820
  observedMode, observedThinking,
769
821
  fallback: observedFallback, downgradeReason,
770
822
  toolProtocolReason: safe.toolProtocolReason,
771
- ...((toolErrorEarlyStop || (postCompleteIdleFinished && phase === 'validate' && TOOL_ERRORS.has(safe.code))) ? { toolErrorEarlyStop: true } : {}),
823
+ ...((readExit === 'deferred_tool_error' || (readExit === 'complete_grace' && phase === 'validate' && TOOL_ERRORS.has(safe.code))) ? { toolErrorEarlyStop: true } : {}),
772
824
  ...(outputObserved ? { nativeTextBytes: Buffer.byteLength(rawText), ...outputShape,
773
825
  nativeResponseRevisions: revisionCount, nativeResponseIdentityVerified: snapshotId !== null } : {}),
774
826
  ...(responseLimitReason ? { nativeResponseLimitReason: responseLimitReason } : {}),
@@ -19,63 +19,104 @@ export class ProtocolError extends Error {
19
19
  export const protocolError = (code, status = 400, param = null) => new ProtocolError(code, status, param);
20
20
  const fail = (code, status = 400, param = null) => { throw protocolError(code, status, param); };
21
21
 
22
+ export const TOOL_JSON_REASONS = Object.freeze([
23
+ 'multiple_root_values',
24
+ 'raw_newline_in_string',
25
+ 'control_char_in_string',
26
+ 'invalid_escape',
27
+ 'unexpected_token_after_string',
28
+ 'trailing_comma',
29
+ 'unterminated_json',
30
+ 'duplicate_key',
31
+ 'nonfinite_number',
32
+ 'invalid_surrogate',
33
+ 'limit_exceeded',
34
+ 'invalid_syntax',
35
+ ]);
36
+
22
37
  /** Bounded JSON parser: rejects duplicate keys, non-finite numbers and deep or
23
38
  * oversized trees, rather than silently overwriting ambiguous arguments. */
24
39
  export function parseBoundedJson(text, { status = 400 } = {}) {
25
- if (typeof text !== 'string' || Buffer.byteLength(text) > TOOL_LIMITS.bytes) fail('INVALID_TOOL_JSON', status);
40
+ const bad = (reason = 'invalid_syntax') => {
41
+ const error = protocolError('INVALID_TOOL_JSON', status);
42
+ error.toolProtocolReason = reason;
43
+ throw error;
44
+ };
45
+ if (typeof text !== 'string') bad('invalid_syntax');
46
+ if (Buffer.byteLength(text) > TOOL_LIMITS.bytes) bad('limit_exceeded');
26
47
  let pos = 0, nodes = 0;
27
- const bad = () => fail('INVALID_TOOL_JSON', status);
28
48
  const ws = () => { while (/[\t\n\r ]/.test(text[pos] ?? '\0')) pos++; };
29
49
  const string = () => {
30
50
  const start = pos++;
31
51
  while (pos < text.length) {
32
52
  const ch = text[pos++];
33
53
  if (ch === '"') {
34
- try {
35
- const result = JSON.parse(text.slice(start, pos));
36
- if (Buffer.from(result).toString('utf8') !== result) bad();
37
- return result;
38
- } catch { bad(); }
54
+ let result;
55
+ try { result = JSON.parse(text.slice(start, pos)); } catch { bad('invalid_syntax'); }
56
+ if (Buffer.from(result).toString('utf8') !== result) bad('invalid_surrogate');
57
+ return result;
58
+ }
59
+ if (ch === '\n' || ch === '\r') bad('raw_newline_in_string');
60
+ if (ch.charCodeAt(0) < 0x20) bad('control_char_in_string');
61
+ if (ch === '\\') {
62
+ if (pos >= text.length) bad('unterminated_json');
63
+ const esc = text[pos++];
64
+ if (esc === 'u') {
65
+ if (!/^[0-9a-fA-F]{4}/.test(text.slice(pos, pos + 4))) bad('invalid_escape');
66
+ pos += 4;
67
+ } else if (!'"\\/bfnrt'.includes(esc)) {
68
+ bad('invalid_escape');
69
+ }
39
70
  }
40
- if (ch === '\\') pos++;
41
71
  }
42
- bad();
72
+ bad('unterminated_json');
43
73
  };
44
74
  const value = depth => {
45
- if (++nodes > TOOL_LIMITS.nodes || depth > TOOL_LIMITS.depth) bad();
75
+ if (++nodes > TOOL_LIMITS.nodes || depth > TOOL_LIMITS.depth) bad('limit_exceeded');
46
76
  ws();
77
+ if (pos >= text.length) bad('unterminated_json');
47
78
  if (text[pos] === '"') return string();
48
79
  if (text[pos] === '{' || text[pos] === '[') {
49
80
  const object = text[pos++] === '{', result = object ? Object.create(null) : [];
50
81
  const end = object ? '}' : ']';
51
82
  ws();
83
+ if (pos >= text.length) bad('unterminated_json');
52
84
  if (text[pos] === end) { pos++; return result; }
53
85
  for (;;) {
54
86
  ws();
87
+ if (pos >= text.length) bad('unterminated_json');
88
+ if (text[pos] === end) bad('trailing_comma');
55
89
  let key;
56
90
  if (object) {
57
- if (text[pos] !== '"') bad();
91
+ if (text[pos] !== '"') bad('invalid_syntax');
58
92
  key = string();
59
- if (Object.hasOwn(result, key)) bad();
60
- ws(); if (text[pos++] !== ':') bad();
93
+ if (Object.hasOwn(result, key)) bad('duplicate_key');
94
+ ws();
95
+ if (pos >= text.length) bad('unterminated_json');
96
+ if (text[pos++] !== ':') bad('unexpected_token_after_string');
61
97
  }
98
+ const childWasString = (() => { ws(); return text[pos] === '"'; })();
62
99
  const child = value(depth + 1);
63
100
  if (object) result[key] = child; else result.push(child);
64
101
  ws();
102
+ if (pos >= text.length) bad('unterminated_json');
65
103
  const separator = text[pos++];
66
104
  if (separator === end) return result;
67
- if (separator !== ',') bad();
105
+ if (separator !== ',') bad(childWasString ? 'unexpected_token_after_string' : 'invalid_syntax');
68
106
  }
69
107
  }
70
108
  const token = /^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(text.slice(pos));
71
- if (!token) bad();
109
+ if (!token) bad('invalid_syntax');
72
110
  pos += token[0].length;
73
111
  const result = JSON.parse(token[0]);
74
- if (typeof result === 'number' && !Number.isFinite(result)) bad();
112
+ if (typeof result === 'number' && !Number.isFinite(result)) bad('nonfinite_number');
75
113
  return result;
76
114
  };
77
115
  const result = value(0);
78
- ws(); if (pos !== text.length) bad();
116
+ ws();
117
+ if (pos !== text.length) {
118
+ bad(text[pos] === '{' || text[pos] === '[' || text[pos] === ',' ? 'multiple_root_values' : 'invalid_syntax');
119
+ }
79
120
  return result;
80
121
  }
81
122
 
@@ -362,5 +403,6 @@ export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBy
362
403
  },
363
404
  get toolCallCount() { return seen; },
364
405
  get suppressed() { return suppressed; },
406
+ get state() { return suppressed ? 'suppressed' : mode === 'tool' ? 'tool_fence' : mode === 'ordinary' ? 'ordinary_fence' : 'text'; },
365
407
  };
366
408
  }