pi-gemini-app 0.1.10 → 0.1.12

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.12",
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,10 +83,11 @@ 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);
90
+ const nativeThoughtBytes = bounded(value.nativeThoughtBytes, 0, 8 * 1024 * 1024);
74
91
  const nativeResponseRevisions = bounded(value.nativeResponseRevisions, 0, 4096);
75
92
  const nativeCompletenessState = bounded(value.nativeCompletenessState, 0, 0x7fffffff);
76
93
  return {
@@ -95,6 +112,7 @@ export function safeNativeEvidence(value) {
95
112
  ...(emptyResponseReason ? { emptyResponseReason } : {}),
96
113
  ...(nativeTextBytes !== null ? { nativeTextBytes } : {}),
97
114
  ...(nativeShareableTextBytes !== null ? { nativeShareableTextBytes } : {}),
115
+ ...(nativeThoughtBytes !== null ? { nativeThoughtBytes } : {}),
98
116
  ...(nativeResponseRevisions !== null ? { nativeResponseRevisions } : {}),
99
117
  ...(typeof value.nativeResponseIdentityVerified === 'boolean' ? { nativeResponseIdentityVerified: value.nativeResponseIdentityVerified } : {}),
100
118
  ...(['provider_publish', 'snapshot_stream', 'snapshot_identity', 'delivery_reset', 'delivery_final'].includes(value.nonMonotonicSite) ? { nonMonotonicSite: value.nonMonotonicSite } : {}),
@@ -15,7 +15,17 @@ export function inspectNativeOutput(fields) {
15
15
  const shareable = singular(mf, 7), thoughts = singular(mf, 12);
16
16
  const tf = thoughts ? parse(thoughts.payload) : [];
17
17
  const thoughtText = singular(tf, 1);
18
- const thoughtsPresent = !!thoughtText?.payload.length || tf.some(field => field.number === 3 && field.wire === 2 && field.payload.length > 0);
18
+ let thoughtBytes = thoughtText?.payload.length ?? 0;
19
+ for (const field of tf) {
20
+ if (field.number === 3 && field.wire === 2 && field.payload.length > 0) thoughtBytes += field.payload.length;
21
+ }
22
+ // Structured thought headers (ModelResponse field 16) can repeat; sum wire===2 payloads without singular().
23
+ let structuredThoughtHeaderBytes = 0;
24
+ for (const field of mf) {
25
+ if (field.number === 16 && field.wire === 2 && field.payload.length > 0) structuredThoughtHeaderBytes += field.payload.length;
26
+ }
27
+ const nativeThoughtBytes = thoughtBytes + structuredThoughtHeaderBytes;
28
+ const thoughtsPresent = thoughtBytes > 0;
19
29
  // Descriptor model field19 is completenessState. Retain only the bounded raw
20
30
  // enum for diagnostics; its values are not established as acceptance rules.
21
31
  const completeness = mf.filter(field => field.number === 19);
@@ -25,6 +35,7 @@ export function inspectNativeOutput(fields) {
25
35
  // Native media/tree/artifact/goal channels are not caller-owned prompt tools.
26
36
  const structured = [4, 5, 13, 21, 23, 24, 25].some(number => mf.some(field => field.number === number && field.payload.length > 0));
27
37
  return { nativeShareableTextBytes: shareable?.payload.length ?? 0, nativeThoughtsPresent: thoughtsPresent,
38
+ nativeThoughtBytes,
28
39
  nativeStructuredOutputPresent: structured, nativeRefusalPresent: refusal,
29
40
  ...(Number.isSafeInteger(completenessState) && completenessState >= 0 && completenessState <= 0x7fffffff ? { nativeCompletenessState: completenessState } : {}) };
30
41
  }
@@ -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,62 @@ 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) {
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
+ if (facts.awaitingOptionalTool) {
77
+ const toolBudgetMs = facts.postOutputToolIdleMs === undefined ? facts.postOutputIdleMs : facts.postOutputToolIdleMs;
78
+ if (toolBudgetMs === null) return { kind: 'post_output', ms: null };
79
+ const progressAnchor = facts.lastGenerationProgressAt ?? facts.lastTextProgressAt;
80
+ const idleRemaining = Math.max(0, toolBudgetMs - elapsed(progressAnchor));
81
+ const maxHoldMs = facts.maxPostOutputThoughtHoldMs;
82
+ const capRemaining = (maxHoldMs !== null && maxHoldMs !== undefined && facts.lastTextProgressAt !== null && facts.lastTextProgressAt !== undefined)
83
+ ? Math.max(0, maxHoldMs - elapsed(facts.lastTextProgressAt))
84
+ : null;
85
+ return {
86
+ kind: 'post_output',
87
+ ms: capRemaining === null ? idleRemaining : Math.min(idleRemaining, capRemaining),
88
+ };
89
+ }
90
+ return {
91
+ kind: 'post_output',
92
+ ms: facts.postOutputIdleMs === null ? null : Math.max(0, facts.postOutputIdleMs - elapsed(facts.lastTextProgressAt)),
93
+ };
94
+ }
95
+ return { kind: null, ms: null };
96
+ }
41
97
  function one(fields, number) {
42
98
  const found = fields.filter(field => field.number === number);
43
99
  if (found.length > 1) fail('INVALID_NATIVE_RESPONSE');
@@ -108,7 +164,7 @@ const validateIdleMs = (value, name) => {
108
164
  const IDLE_TIMEOUT_SENTINEL = Symbol('IDLE_TIMEOUT_SENTINEL');
109
165
 
110
166
  export class NativeDirectProvider {
111
- constructor(authManager, { openTurn, uploadImages = uploadNativeImages, downloadImages = downloadRemoteImages, blobCache = createImageBlobCache(), timeoutMs = 600_000, postCompleteGraceMs = 2_000, postToolIdleMs = 6_000, postOutputIdleMs = 15_000, modelAlias = 'gemini-neon', continuation = false, allowTextSnapshotReplacement = false, allowAutoModel = false } = {}) {
167
+ constructor(authManager, { openTurn, uploadImages = uploadNativeImages, downloadImages = downloadRemoteImages, blobCache = createImageBlobCache(), timeoutMs = 600_000, postCompleteGraceMs = 2_000, postToolIdleMs = 6_000, postOutputIdleMs = 15_000, postOutputToolIdleMs = undefined, maxPostOutputThoughtHoldMs = undefined, modelAlias = 'gemini-neon', continuation = false, allowTextSnapshotReplacement = false, allowAutoModel = false } = {}) {
112
168
  if (!authManager || typeof authManager.getValidAccessToken !== 'function') throw new TypeError('authManager.getValidAccessToken required');
113
169
  if (typeof openTurn !== 'function') throw new TypeError('openTurn required');
114
170
  if (typeof uploadImages !== 'function') throw new TypeError('uploadImages required');
@@ -117,6 +173,12 @@ export class NativeDirectProvider {
117
173
  const resolvedPostCompleteGraceMs = validateIdleMs(postCompleteGraceMs, 'postCompleteGraceMs');
118
174
  const resolvedPostToolIdleMs = validateIdleMs(postToolIdleMs, 'postToolIdleMs');
119
175
  const resolvedPostOutputIdleMs = validateIdleMs(postOutputIdleMs, 'postOutputIdleMs');
176
+ const resolvedPostOutputToolIdleMs = postOutputToolIdleMs === undefined
177
+ ? undefined
178
+ : validateIdleMs(postOutputToolIdleMs, 'postOutputToolIdleMs');
179
+ const resolvedMaxPostOutputThoughtHoldMs = maxPostOutputThoughtHoldMs === undefined
180
+ ? undefined
181
+ : validateIdleMs(maxPostOutputThoughtHoldMs, 'maxPostOutputThoughtHoldMs');
120
182
  if (continuation !== false) throw protocolError('UNSUPPORTED_CONTINUATION', 400);
121
183
  if (typeof allowAutoModel !== 'boolean') throw new TypeError('invalid auto model policy');
122
184
  const resolvedAlias = canonicalModel(modelAlias);
@@ -126,6 +188,8 @@ export class NativeDirectProvider {
126
188
  this.postCompleteGraceMs = resolvedPostCompleteGraceMs;
127
189
  this.postToolIdleMs = resolvedPostToolIdleMs;
128
190
  this.postOutputIdleMs = resolvedPostOutputIdleMs;
191
+ this.postOutputToolIdleMs = resolvedPostOutputToolIdleMs;
192
+ this.maxPostOutputThoughtHoldMs = resolvedMaxPostOutputThoughtHoldMs;
129
193
  this.downloadImages = downloadImages;
130
194
  this.blobCache = blobCache ?? null;
131
195
  if (typeof allowTextSnapshotReplacement !== 'boolean') throw new TypeError('invalid snapshot policy');
@@ -280,13 +344,34 @@ export class NativeDirectProvider {
280
344
  const postOutputIdleMs = context.postOutputIdleMs === undefined
281
345
  ? this.postOutputIdleMs
282
346
  : validateIdleMs(context.postOutputIdleMs, 'postOutputIdleMs');
347
+ const configuredPostOutputToolIdleMs = context.postOutputToolIdleMs !== undefined
348
+ ? validateIdleMs(context.postOutputToolIdleMs, 'postOutputToolIdleMs')
349
+ : this.postOutputToolIdleMs;
350
+ const postOutputToolIdleMs = configuredPostOutputToolIdleMs !== undefined
351
+ ? configuredPostOutputToolIdleMs
352
+ : (postOutputIdleMs === null ? null : Math.max(postOutputIdleMs, 45_000));
353
+ const maxPostOutputThoughtHoldMs = context.maxPostOutputThoughtHoldMs !== undefined
354
+ ? validateIdleMs(context.maxPostOutputThoughtHoldMs, 'maxPostOutputThoughtHoldMs')
355
+ : this.maxPostOutputThoughtHoldMs !== undefined
356
+ ? this.maxPostOutputThoughtHoldMs
357
+ : (postOutputToolIdleMs === null ? null : Math.min(600_000, postOutputToolIdleMs * 3));
283
358
  const body = normalizeChatRequest(canonicalChatBody, { allowAutoModel: this.allowAutoModel });
284
359
  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 }];
360
+ const recoveryInstruction = toolRecoveryInstruction(context.recoveryCode, context.recoveryReason);
361
+ const appendRecovery = promptMessages => {
362
+ if (!recoveryInstruction || !promptMessages?.length) return promptMessages;
363
+ const next = promptMessages.map(msg => ({ ...msg }));
364
+ const last = next[next.length - 1];
365
+ const suffix = `\n\n${recoveryInstruction}`;
366
+ if (typeof last?.content === 'string' && Buffer.byteLength(last.content + suffix) <= PROMPT_MAX_BYTES) {
367
+ last.content += suffix;
368
+ }
369
+ return next;
370
+ };
287
371
  if (this.allowTextSnapshotReplacement && body.tools.length) fail('NATIVE_TEXT_SNAPSHOT_TOOLS_FORBIDDEN', 400);
288
372
  const policy = compileToolPolicy(body.tools, body.tool_choice);
289
373
  let { messages, images } = buildCanonicalPrompt(body);
374
+ messages = appendRecovery(messages);
290
375
  const isAutoModel = this.allowAutoModel && body.model === 'gemini-auto';
291
376
  const modeCategory = isAutoModel ? null : MODEL_MODES[body.model];
292
377
  const modeMatches = mode => isAutoModel
@@ -311,23 +396,34 @@ export class NativeDirectProvider {
311
396
  const requiresHydrogen = body.model === 'gemini-hydrogen';
312
397
  const requiresNeon = body.model === 'gemini-neon';
313
398
  let rawText = '', frames = 0, received = 0, observedMode = null, observedThinking = null;
314
- let modelComplete = false, modelCompleteAt = null, lastTextProgressAt = null, ended = false, grpc = null, httpStatus = null, downgrade = false, phase = 'auth';
399
+ let modelComplete = false, modelCompleteAt = null, lastTextProgressAt = null, lastGenerationProgressAt = null, ended = false, grpc = null, httpStatus = null, downgrade = false, phase = 'auth';
400
+ let thoughtHighWaterBytes = 0, allowThoughtRebase = false;
315
401
  let observedFallback = null, downgradeReason = null, observedAttribution = null;
316
402
  const attributionMatches = value => (!requiresHydrogen || HYDROGEN_ATTRIBUTION.test(value ?? '')) && (!requiresNeon || NEON_ATTRIBUTION.test(value ?? ''));
317
403
  const attributionVerified = () => attributionMatches(observedAttribution);
318
404
  let snapshotId = null, revisionCount = 0, quotaObservation = null, quotaFrames = 0;
319
405
  let emptyResponseReason = null, outputObserved = false, responseLimitReason = null, outputFailureReason = null;
320
- const outputShape = { nativeShareableTextBytes: 0, nativeThoughtsPresent: false, nativeStructuredOutputPresent: false, nativeRefusalPresent: false };
406
+ const outputShape = { nativeShareableTextBytes: 0, nativeThoughtsPresent: false, nativeThoughtBytes: 0, nativeStructuredOutputPresent: false, nativeRefusalPresent: false };
321
407
  const incremental = context.incrementalOutput === true && !body.response_format;
322
408
  const identity = { id: 'chatcmpl-' + crypto.randomBytes(16).toString('hex'), created: Math.floor(Date.now() / 1000), model: body.model,
323
409
  [RESPONSE_TOOL_IDENTITIES]: body[RESPONSE_TOOL_IDENTITIES],
324
410
  requestedThinkingLevel: body.thinking_level, ignoredTokenParameters: ['max_tokens', 'max_completion_tokens'].filter(key => body[key] !== undefined),
325
411
  ...((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;
412
+ let liveSplitter = incremental ? createToolCallSplitter({ policy }) : null, liveItems = [], liveContent = '', liveCalls = [], publishedContent = '', publishedCalls = 0, liveSyncedLength = 0, liveToolError = null, liveToolErrorTailStart = 0, liveToolErrorDeadline = null, validatedIdleOutput = null, readExit = 'none', sinkFailed = false;
327
413
  const deliver = async event => {
328
414
  try { await onDelta(event); }
329
415
  catch (error) { sinkFailed = true; throw error; }
330
416
  };
417
+ const deliverNonIncremental = async (items, content, calls, { includeMeta = false } = {}) => {
418
+ const extra = includeMeta ? { response: { ...identity, thinkingLevel: observedThinking } } : {};
419
+ if (body.response_format && !calls.length) {
420
+ if (content) await deliver({ content, ...extra });
421
+ } else {
422
+ for (const item of items) {
423
+ await deliver(item.type === 'call' ? { call: item.call, ...extra } : { content: item.text, ...extra });
424
+ }
425
+ }
426
+ };
331
427
  // The sink owns the commit boundary: provider-published text may still be held.
332
428
  // Missing/invalid feedback is conservative for streaming callers.
333
429
  const committedOutput = () => {
@@ -368,6 +464,7 @@ export class NativeDirectProvider {
368
464
  phase = 'upload';
369
465
  images = await bounded(this.downloadImages(images, { signal: controller.signal, timeoutMs: Math.min(timeoutMs, 30000) }));
370
466
  ({ messages, images } = buildCanonicalPrompt(body, images));
467
+ messages = appendRecovery(messages);
371
468
  }
372
469
  phase = 'auth';
373
470
  let token;
@@ -390,85 +487,84 @@ export class NativeDirectProvider {
390
487
  ...(context.nativeDiagnostic ? { diagnostic: context.nativeDiagnostic } : {}) });
391
488
  iterator = turn.events[Symbol.asyncIterator]();
392
489
  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' });
490
+ let cachedFallbackText = null, cachedFallbackRevision = -1, cachedFallbackResult = { kind: 'none' };
491
+ const probeFullRawText = () => {
492
+ if (cachedFallbackText === rawText && cachedFallbackRevision === revisionCount) return cachedFallbackResult;
493
+ cachedFallbackText = rawText;
494
+ cachedFallbackRevision = revisionCount;
495
+ if (!rawText.trim() || ASYNC_DEEP_THINK_PLACEHOLDER_RE.test(rawText)) {
496
+ return (cachedFallbackResult = { kind: 'none' });
405
497
  }
406
498
  let probeItems;
407
499
  try {
408
500
  const probe = createToolCallSplitter({ policy });
409
501
  probeItems = [...probe.push(rawText), ...probe.flush()];
410
502
  } 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' });
503
+ if (probeError?.code === 'TRUNCATED_TOOL_CALL') return (cachedFallbackResult = { kind: 'streaming_tool' });
504
+ if (TOOL_ERRORS.has(probeError?.code)) return (cachedFallbackResult = { kind: 'closed_tool_error', error: probeError });
505
+ return (cachedFallbackResult = { kind: 'none' });
422
506
  }
423
- if (liveCalls.length > 0) return (cachedProbeResult = { kind: 'none' });
507
+ if (liveCalls.length > 0) return (cachedFallbackResult = { kind: 'none' });
424
508
  try {
425
509
  const probeCalls = probeItems.filter(it => it.type === 'call').map(it => it.call);
426
- 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' });
510
+ 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' });
429
513
  validateToolCompletion(probeCalls, policy);
430
- if (!probeCalls.length && !probeContent.trim()) return (cachedProbeResult = { kind: 'none' });
431
- if (body.response_format && !probeCalls.length) validateStructuredOutputText(probeContent, body.response_format);
432
- return (cachedProbeResult = { kind: 'clean_output' });
514
+ if (!probeCalls.length && !probeContent.trim()) return (cachedFallbackResult = { kind: 'none' });
515
+ 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 });
433
517
  } catch {
434
- return (cachedProbeResult = { kind: 'none' });
518
+ return (cachedFallbackResult = { kind: 'none' });
519
+ }
520
+ };
521
+ // O(1) incremental idle classification for streaming turns via liveSplitter.state;
522
+ // only falls back to full probe when a pending closing fence lacks trailing LF or !incremental.
523
+ const classifyIdleSnapshot = () => {
524
+ if (!rawText.trim() || ASYNC_DEEP_THINK_PLACEHOLDER_RE.test(rawText)) return { kind: 'none' };
525
+ if (!liveSplitter) return probeFullRawText();
526
+ const state = liveSplitter.state;
527
+ const lastLf = rawText.lastIndexOf('\n');
528
+ const trailingLine = lastLf < 0 ? rawText : rawText.slice(lastLf + 1);
529
+ if (state === 'tool_fence') {
530
+ if (trailingLine && CLOSING_FENCE_LINE_RE.test(trailingLine)) return probeFullRawText();
531
+ return { kind: 'streaming_tool' };
532
+ }
533
+ if (state === 'text' && trailingLine && PENDING_TOOL_OPEN_RE.test(trailingLine)) {
534
+ return { kind: 'streaming_tool' };
435
535
  }
536
+ if (liveCalls.length > 0) return { kind: 'none' };
537
+ if (policy.choice === 'required' || policy.forced) return { kind: 'none' };
538
+ const candidateText = liveContent + liveSplitter.preview();
539
+ if (!candidateText.trim()) return { kind: 'none' };
540
+ if (!outputShape.nativeStructuredOutputPresent && softErrorReason(candidateText, body, 0)) return { kind: 'none' };
541
+ return { kind: 'clean_output', hasCalls: false };
436
542
  };
437
- const isCleanPostOutputIdleStall = () => probeIdleState().kind === 'clean_output';
438
543
  const nextEventWithIdle = async () => {
439
544
  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
- }
545
+ const snap = (verified && !liveToolError) ? classifyIdleSnapshot() : { kind: 'none' };
546
+ const hasParsedCalls = liveCalls.length > 0 || snap.hasCalls === true;
547
+ const awaitingOptionalTool = policy.enabled && policy.choice === 'auto' && !hasParsedCalls;
548
+ const { kind: idleKind, ms: idleMs } = selectIdleDeadline({
549
+ verified,
550
+ hasText: rawText.trim().length > 0,
551
+ hasLiveToolError: Boolean(liveToolError),
552
+ hasClosedToolError: snap.kind === 'closed_tool_error',
553
+ modelComplete,
554
+ hasLiveCalls: hasParsedCalls,
555
+ streamingTool: snap.kind === 'streaming_tool',
556
+ cleanOutput: snap.kind === 'clean_output' && !hasParsedCalls,
557
+ awaitingOptionalTool,
558
+ liveToolErrorDeadline,
559
+ lastTextProgressAt,
560
+ lastGenerationProgressAt,
561
+ modelCompleteAt,
562
+ postCompleteGraceMs,
563
+ postToolIdleMs,
564
+ postOutputIdleMs,
565
+ postOutputToolIdleMs,
566
+ maxPostOutputThoughtHoldMs,
567
+ });
472
568
  const nextPromise = iterator.next();
473
569
  if (idleMs === null) return bounded(nextPromise);
474
570
  nextPromise.catch(() => {});
@@ -477,7 +573,7 @@ export class NativeDirectProvider {
477
573
  return await Promise.race([
478
574
  bounded(nextPromise),
479
575
  new Promise(resolve => {
480
- idleTimer = setTimeout(() => resolve({ [IDLE_TIMEOUT_SENTINEL]: idleKind, verified, probeError: probeState.error ?? null }), idleMs);
576
+ idleTimer = setTimeout(() => resolve({ [IDLE_TIMEOUT_SENTINEL]: idleKind, verified, probeError: snap.error ?? null }), idleMs);
481
577
  idleTimer.unref?.();
482
578
  }),
483
579
  ]);
@@ -490,31 +586,45 @@ export class NativeDirectProvider {
490
586
  const item = await nextEventWithIdle();
491
587
  if (item && item[IDLE_TIMEOUT_SENTINEL]) {
492
588
  const idleKind = item[IDLE_TIMEOUT_SENTINEL];
493
- if (idleKind === 'post_complete' && item.verified && rawText.trim().length > 0) {
494
- note('post_complete_idle_finish', { bytes: Buffer.byteLength(rawText) });
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 });
495
602
  try { turn?.cancel(); } catch {}
496
- postCompleteIdleFinished = true;
497
- ended = true;
498
- httpStatus = httpStatus ?? 200;
499
- grpc = grpc ?? 0;
603
+ readExit = 'complete_empty_grace';
500
604
  break;
501
605
  }
502
606
  if (idleKind === 'post_tool_error' && item.verified && (liveToolError || item.probeError)) {
503
607
  if (!liveToolError) liveToolError = item.probeError;
504
608
  note('post_tool_error_idle_finish', { code: liveToolError.code, bytes: Buffer.byteLength(rawText) });
505
609
  try { turn?.cancel(); } catch {}
506
- toolErrorEarlyStop = true;
610
+ readExit = 'deferred_tool_error';
507
611
  break;
508
612
  }
613
+ const finalSnap = item.verified ? classifyIdleSnapshot() : { kind: 'none' };
509
614
  note(`${idleKind}_idle_timeout`, {
510
615
  frames,
511
- calls: liveCalls.length,
616
+ calls: liveCalls.length || (finalSnap.calls?.length ?? 0),
512
617
  textBytes: Buffer.byteLength(rawText),
513
618
  });
514
619
  try { turn?.cancel(); } catch {}
515
620
  const idleError = protocolError('NATIVE_TURN_TIMEOUT', 504);
516
- if (idleKind === 'post_output' && item.verified && isCleanPostOutputIdleStall()) {
621
+ if (idleKind === 'post_tool' && item.verified && (liveCalls.length > 0 || finalSnap.hasCalls === true)) {
622
+ idleError.postToolIdleStall = true;
623
+ if (!incremental && finalSnap.kind === 'clean_output') validatedIdleOutput = finalSnap;
624
+ }
625
+ if (idleKind === 'post_output' && item.verified && finalSnap.kind === 'clean_output' && !finalSnap.hasCalls && liveCalls.length === 0) {
517
626
  idleError.postOutputIdleStall = true;
627
+ if (!incremental) validatedIdleOutput = finalSnap;
518
628
  }
519
629
  throw idleError;
520
630
  }
@@ -533,6 +643,7 @@ export class NativeDirectProvider {
533
643
  if (info?.outputShape) {
534
644
  outputObserved = true;
535
645
  outputShape.nativeShareableTextBytes = Math.max(outputShape.nativeShareableTextBytes, info.outputShape.nativeShareableTextBytes);
646
+ outputShape.nativeThoughtBytes = Math.max(outputShape.nativeThoughtBytes, info.outputShape.nativeThoughtBytes ?? 0);
536
647
  for (const key of ['nativeThoughtsPresent', 'nativeStructuredOutputPresent', 'nativeRefusalPresent']) outputShape[key] ||= info.outputShape[key];
537
648
  if (info.outputShape.nativeCompletenessState !== undefined) outputShape.nativeCompletenessState = info.outputShape.nativeCompletenessState;
538
649
  }
@@ -570,6 +681,7 @@ export class NativeDirectProvider {
570
681
  fail('MODEL_DOWNGRADE_REJECTED');
571
682
  }
572
683
  if (outputShape.nativeRefusalPresent) fail('NATIVE_RESPONSE_REFUSED', 422);
684
+ let textProgressed = false;
573
685
  if (info.text !== null) {
574
686
  const id = info.responseId || null;
575
687
  if (this.allowTextSnapshotReplacement && !id) fail('INVALID_NATIVE_RESPONSE');
@@ -592,16 +704,45 @@ export class NativeDirectProvider {
592
704
  }
593
705
  }
594
706
  if (id) snapshotId = id;
595
- if (!extendsPrior) revisionCount++;
707
+ if (!extendsPrior) {
708
+ revisionCount++;
709
+ thoughtHighWaterBytes = 0;
710
+ allowThoughtRebase = false;
711
+ }
596
712
  if (info.text !== rawText) {
713
+ const progressAt = Date.now();
597
714
  modelComplete = info.completed;
598
- modelCompleteAt = modelComplete ? Date.now() : null;
599
- lastTextProgressAt = Date.now();
715
+ modelCompleteAt = modelComplete ? progressAt : null;
716
+ lastTextProgressAt = progressAt;
717
+ lastGenerationProgressAt = progressAt;
718
+ allowThoughtRebase = true;
719
+ textProgressed = true;
600
720
  }
601
721
  rawText = info.text;
602
722
  } else if (snapshotId !== null && info.responseId && info.responseId !== snapshotId) {
603
723
  fail('INVALID_NATIVE_RESPONSE');
604
724
  }
725
+ const frameThoughtBytes = info.outputShape?.nativeThoughtBytes ?? 0;
726
+ if (textProgressed) {
727
+ // Keep allowThoughtRebase armed if this text-progress frame also carried the tail
728
+ // of pre-text thoughts; if a smaller post-text block already started here, rebase now.
729
+ if (frameThoughtBytes > thoughtHighWaterBytes) thoughtHighWaterBytes = frameThoughtBytes;
730
+ else if (frameThoughtBytes > 0 && frameThoughtBytes < thoughtHighWaterBytes) {
731
+ thoughtHighWaterBytes = frameThoughtBytes;
732
+ allowThoughtRebase = false;
733
+ }
734
+ } else if (frameThoughtBytes > 0) {
735
+ if (frameThoughtBytes > thoughtHighWaterBytes) {
736
+ thoughtHighWaterBytes = frameThoughtBytes;
737
+ allowThoughtRebase = false;
738
+ if (lastTextProgressAt !== null) lastGenerationProgressAt = Date.now();
739
+ } else if (frameThoughtBytes < thoughtHighWaterBytes && allowThoughtRebase) {
740
+ // Post-text new thought block restarted at a smaller byte count: rebase once
741
+ // without advancing the clock; a subsequent strictly larger frame must prove progress.
742
+ thoughtHighWaterBytes = frameThoughtBytes;
743
+ allowThoughtRebase = false;
744
+ }
745
+ }
605
746
  if (incremental && !liveToolError && modeMatches(observedMode) && attributionVerified() && liveSyncedLength < rawText.length) {
606
747
  const delta = rawText.slice(liveSyncedLength);
607
748
  liveSyncedLength = rawText.length;
@@ -625,6 +766,7 @@ export class NativeDirectProvider {
625
766
  if (!liveToolError && liveSplitter.suppressed && liveCalls.length > 0 && !downgrade && !outputShape.nativeRefusalPresent) {
626
767
  note('early_stop_post_tool_hallucination', { calls: liveCalls.length });
627
768
  try { turn?.cancel(); } catch {}
769
+ readExit = 'suppressed_after_valid_call';
628
770
  ended = true;
629
771
  modelComplete = true;
630
772
  httpStatus = httpStatus ?? 200;
@@ -639,7 +781,7 @@ export class NativeDirectProvider {
639
781
  if (postErrorTail.includes('[Caller tool result]') || postErrorTailBytes > 4096 || graceExpired) {
640
782
  note('early_stop_post_tool_error', { code: liveToolError.code, bytes: postErrorTailBytes });
641
783
  try { turn?.cancel(); } catch {}
642
- toolErrorEarlyStop = true;
784
+ readExit = 'deferred_tool_error';
643
785
  break;
644
786
  }
645
787
  }
@@ -649,7 +791,7 @@ export class NativeDirectProvider {
649
791
  else if (info.quotaObservation.source === 'official') quotaObservation = mergeQuotaObservation(quotaObservation, info.quotaObservation);
650
792
  }
651
793
  } else if (event.type === 'end') {
652
- phase = 'end'; ended = true; grpc = event.grpcStatus; httpStatus = event.httpStatus;
794
+ phase = 'end'; readExit = 'wire_end'; ended = true; grpc = event.grpcStatus; httpStatus = event.httpStatus;
653
795
  if (event.httpStatus === 429 || grpc === 8) fail('NATIVE_RATE_LIMITED', 429);
654
796
  if (event.httpStatus === 401 || grpc === 16) fail('NATIVE_AUTH_REJECTED');
655
797
  if (event.httpStatus === 403 || grpc === 7) fail('NATIVE_PERMISSION_REJECTED');
@@ -681,7 +823,7 @@ export class NativeDirectProvider {
681
823
  phase = 'validate';
682
824
  if (downgrade) fail('MODEL_DOWNGRADE_REJECTED');
683
825
  if (outputShape.nativeRefusalPresent) fail('NATIVE_RESPONSE_REFUSED', 422);
684
- if (toolErrorEarlyStop && liveToolError) {
826
+ if (readExit === 'deferred_tool_error' && liveToolError) {
685
827
  if (!modeMatches(observedMode)) fail('MISSING_NATIVE_MODE_EVIDENCE');
686
828
  if (!attributionVerified()) fail('MODEL_DOWNGRADE_REJECTED');
687
829
  throw liveToolError;
@@ -689,7 +831,7 @@ export class NativeDirectProvider {
689
831
  if (!ended) fail('INCOMPLETE_NATIVE_RESPONSE');
690
832
  // An ordinary RPC close is not model completion. Async UI placeholders
691
833
  // 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);
834
+ if (ASYNC_DEEP_THINK_PLACEHOLDER_RE.test(rawText)) fail('NATIVE_ASYNC_RESPONSE_UNSUPPORTED', 422);
693
835
  if (!modelComplete) fail('INCOMPLETE_NATIVE_RESPONSE');
694
836
  if (!modeMatches(observedMode)) fail('MISSING_NATIVE_MODE_EVIDENCE');
695
837
  if (!attributionVerified()) fail('MODEL_DOWNGRADE_REJECTED');
@@ -734,28 +876,40 @@ export class NativeDirectProvider {
734
876
  nativeTextBytes: Buffer.byteLength(rawText), ...outputShape,
735
877
  nativeResponseRevisions: revisionCount, nativeResponseIdentityVerified: snapshotId !== null });
736
878
  phase = 'output';
737
- if (!incremental) {
738
- if (body.response_format && !calls.length) {
739
- if (content) await onDelta({ content });
740
- } else {
741
- for (const item of items) await onDelta(item.type === 'call' ? { call: item.call } : { content: item.text });
742
- }
743
- }
879
+ if (!incremental) await deliverNonIncremental(items, content, calls);
744
880
  note('provider_success');
745
881
  return result;
746
882
  } catch (error) {
747
883
  const modeVerified = !downgrade && !outputShape.nativeRefusalPresent && modeMatches(observedMode) && attributionVerified();
748
884
  if (incremental && !liveToolError && modeVerified && !sinkFailed) {
749
885
  try { await publish(liveSplitter.flush()); }
750
- catch { /* Retain already-published text; never release an invalid/incomplete tool body. */ }
886
+ catch (flushError) {
887
+ if (sinkFailed) error = flushError;
888
+ /* Otherwise (e.g. TRUNCATED_TOOL_CALL / parse error): retain already-published text without releasing an invalid/incomplete tool body. */
889
+ }
890
+ }
891
+ if (incremental && error?.postToolIdleStall && publishedCalls === 0) delete error.postToolIdleStall;
892
+ if (incremental && error?.postOutputIdleStall && !publishedContent.trim().length) delete error.postOutputIdleStall;
893
+ let nonIncrementalDelivered = null;
894
+ if (!incremental && !liveToolError && modeVerified && !sinkFailed &&
895
+ (error?.postOutputIdleStall || error?.postToolIdleStall) &&
896
+ validatedIdleOutput && (validatedIdleOutput.content.length || validatedIdleOutput.calls.length)) {
897
+ try {
898
+ await deliverNonIncremental(validatedIdleOutput.items, validatedIdleOutput.content, validatedIdleOutput.calls, { includeMeta: true });
899
+ nonIncrementalDelivered = validatedIdleOutput;
900
+ } catch (sinkError) {
901
+ error = sinkError;
902
+ }
751
903
  }
752
904
  const safe = safeFailure(error);
753
905
  if (!modeVerified) safe.unverifiedOutput = true;
754
906
  note('provider_failure', { code: safe.code });
755
907
  let transport = {};
756
908
  try { transport = turn?.getSafeStatus?.() ?? {}; } catch {}
909
+ const committedOnFailure = committedOutput();
757
910
  safe.nativeEvidence = safeNativeEvidence({
758
911
  // Keep guard-site diagnostics raised deeper in this turn; they are byte counts only.
912
+ ...((committedOnFailure.publishedBytes > 0 || committedOnFailure.toolCallCount > 0 || TOOL_ERRORS.has(safe.code)) ? committedOnFailure : {}),
759
913
  ...(error.nativeEvidence ?? {}),
760
914
  phase, upstreamHttpStatus: transport.httpStatus ?? httpStatus,
761
915
  grpcStatus: transport.grpcStatus ?? grpc,
@@ -768,7 +922,7 @@ export class NativeDirectProvider {
768
922
  observedMode, observedThinking,
769
923
  fallback: observedFallback, downgradeReason,
770
924
  toolProtocolReason: safe.toolProtocolReason,
771
- ...((toolErrorEarlyStop || (postCompleteIdleFinished && phase === 'validate' && TOOL_ERRORS.has(safe.code))) ? { toolErrorEarlyStop: true } : {}),
925
+ ...((readExit === 'deferred_tool_error' || (readExit === 'complete_grace' && phase === 'validate' && TOOL_ERRORS.has(safe.code))) ? { toolErrorEarlyStop: true } : {}),
772
926
  ...(outputObserved ? { nativeTextBytes: Buffer.byteLength(rawText), ...outputShape,
773
927
  nativeResponseRevisions: revisionCount, nativeResponseIdentityVerified: snapshotId !== null } : {}),
774
928
  ...(responseLimitReason ? { nativeResponseLimitReason: responseLimitReason } : {}),
@@ -777,6 +931,8 @@ export class NativeDirectProvider {
777
931
  });
778
932
  if (incremental && modeVerified && (publishedContent.length || publishedCalls)) safe.partialResult = { ...identity, content: publishedContent, calls: liveCalls.slice(0, publishedCalls),
779
933
  thinkingLevel: observedThinking, resolvedModeCategory: observedMode, ...(observedAttribution !== null ? { attribution: observedAttribution } : {}), nativeEvidence: safe.nativeEvidence };
934
+ else if (nonIncrementalDelivered) safe.partialResult = { ...identity, content: nonIncrementalDelivered.content, calls: nonIncrementalDelivered.calls,
935
+ thinkingLevel: observedThinking, resolvedModeCategory: observedMode, ...(observedAttribution !== null ? { attribution: observedAttribution } : {}), nativeEvidence: safe.nativeEvidence };
780
936
  throw safe;
781
937
  }
782
938
  finally {
@@ -5,6 +5,7 @@
5
5
  * `native_search` is a documented Gemini-native opt-in, not OpenAI web_search.
6
6
  */
7
7
  import crypto from 'node:crypto';
8
+ import { TOOL_LIMITS } from '../native-wire/consumer-tool-codec.mjs';
8
9
  import { plainObject, protocolError, parseBoundedJson, compileToolPolicy, validateToolCall, flattenMessages, buildToolInstruction } from './tool-protocol.mjs';
9
10
  import { stripSchemaAnnotations } from './prompt-tool-schema.mjs';
10
11
  import { normalizeChatResponseFormat, normalizeResponsesText, buildStructuredOutputInstruction } from './gateway/structured-output.mjs';
@@ -52,7 +53,10 @@ function thinkingSettings(body) {
52
53
  }
53
54
  export const PROMPT_MAX_BYTES = 4 * 1024 * 1024;
54
55
  export const REQUEST_MAX_NON_IMAGE_BYTES = PROMPT_MAX_BYTES;
56
+ export const MAX_STRIPPED_REASONING_BYTES = 16 * 1024 * 1024;
55
57
  export const MAX_MESSAGES = 8192;
58
+ export const CANONICAL_PROMPT_CHARS = Symbol('canonicalPromptChars');
59
+ export const CANONICAL_IMAGE_COUNT = Symbol('canonicalImageCount');
56
60
  const REQUEST_MAX_NODES = 131072;
57
61
  const configured = Number(process.env.GEMINI_PROMPT_MAX_CHARS);
58
62
  const MAX_CHARS = Number.isSafeInteger(configured) && configured > 0 ? Math.min(configured, PROMPT_MAX_BYTES) : PROMPT_MAX_BYTES;
@@ -69,9 +73,10 @@ function keys(value, allowed, prefix = '') {
69
73
  // Bound work before compiling schemas, cloning tools or joining text blocks.
70
74
  // This is independent of the gateway's raw HTTP body limit.
71
75
  function requestBudget(root) {
72
- let nodes = 0, bytes = 0, imageBytes = 0, imageCount = 0;
73
- // Only declared user-image URL slots get a separate budget, never arbitrary strings.
76
+ let nodes = 0, bytes = 0, imageBytes = 0, strippedReasoningBytes = 0, imageCount = 0;
77
+ // Only declared user-image URL slots and stripped reasoning ciphertext get separate budgets.
74
78
  const imageSlots = new WeakMap();
79
+ const strippedSlots = new WeakMap();
75
80
  const mark = (part, responses = false) => {
76
81
  if (!plainObject(part)) return;
77
82
  if ((responses && part.type === 'input_image') || (!responses && part.type === 'image_url')) {
@@ -86,16 +91,19 @@ function requestBudget(root) {
86
91
  for (const item of Array.isArray(root.input) ? root.input.slice(0, MAX_MESSAGES) : []) {
87
92
  if (item?.type === 'input_image') mark(item, true);
88
93
  if (item?.role === 'user' && Array.isArray(item.content) && item.content.length <= 1024) for (const part of item.content) mark(part, true);
89
- if (item?.type === 'function_call_output' && Array.isArray(item.output) && item.output.length <= 1024) for (const part of item.output) mark(part, true);
94
+ if ((item?.type === 'function_call_output' || item?.type === 'custom_tool_call_output') && Array.isArray(item.output) && item.output.length <= 1024) for (const part of item.output) mark(part, true);
95
+ if (plainObject(item) && item.type === 'reasoning') strippedSlots.set(item, 'encrypted_content');
90
96
  }
91
97
  const ancestors = new Set();
92
- const visit = (value, depth, image = false) => {
98
+ const visit = (value, depth, slot = null) => {
93
99
  if (++nodes > REQUEST_MAX_NODES || depth > 32) fail('REQUEST_TOO_LARGE', 413);
94
100
  if (typeof value === 'string') {
95
- if (image) {
101
+ if (slot === 'image') {
96
102
  const len = Buffer.byteLength(value);
97
103
  if (len > MAX_IMAGE_URL_BYTES) fail('IMAGE_TOO_LARGE', 413);
98
104
  imageBytes += len;
105
+ } else if (slot === 'stripped') {
106
+ strippedReasoningBytes += Buffer.byteLength(value);
99
107
  } else bytes += Buffer.byteLength(value);
100
108
  }
101
109
  else if (value === null || value === undefined || typeof value === 'boolean') bytes += 4;
@@ -113,11 +121,15 @@ function requestBudget(root) {
113
121
  } else {
114
122
  const entries = Object.entries(value);
115
123
  if (entries.length > 4096) fail('REQUEST_TOO_LARGE', 413);
116
- for (const [key, child] of entries) { bytes += Buffer.byteLength(key); visit(child, depth + 1, imageSlots.get(value) === key); }
124
+ for (const [key, child] of entries) {
125
+ bytes += Buffer.byteLength(key);
126
+ const childSlot = imageSlots.get(value) === key ? 'image' : strippedSlots.get(value) === key ? 'stripped' : null;
127
+ visit(child, depth + 1, childSlot);
128
+ }
117
129
  }
118
130
  ancestors.delete(value);
119
131
  }
120
- if (bytes > REQUEST_MAX_NON_IMAGE_BYTES || imageBytes > MAX_TOTAL_IMAGE_URL_BYTES) fail('REQUEST_TOO_LARGE', 413);
132
+ if (bytes > REQUEST_MAX_NON_IMAGE_BYTES || imageBytes > MAX_TOTAL_IMAGE_URL_BYTES || strippedReasoningBytes > MAX_STRIPPED_REASONING_BYTES) fail('REQUEST_TOO_LARGE', 413);
121
133
  };
122
134
  visit(root, 0);
123
135
  }
@@ -127,6 +139,14 @@ function text(value, { nullable = false } = {}) {
127
139
  if (value.length > MAX_CHARS || Buffer.byteLength(value) > PROMPT_MAX_BYTES) fail('PROMPT_TOO_LARGE', 413);
128
140
  return value;
129
141
  }
142
+ // Validate UTF-8 and hard byte bounds for stripped replay scratchpad fields
143
+ // without enforcing GEMINI_PROMPT_MAX_CHARS (which bounds rendered prompt text).
144
+ function strippedText(value, param = null) {
145
+ if (typeof value !== 'string') fail('INVALID_TEXT', 400, param);
146
+ if (Buffer.byteLength(value) > PROMPT_MAX_BYTES) fail('REQUEST_TOO_LARGE', 413, param);
147
+ if (Buffer.from(value).toString('utf8') !== value) fail('INVALID_TEXT', 400, param);
148
+ return value;
149
+ }
130
150
  function id(value) {
131
151
  if (typeof value !== 'string' || !/^[A-Za-z0-9_-]{1,256}$/.test(value)) fail('INVALID_TOOL_CALL_ID');
132
152
  return value;
@@ -373,7 +393,7 @@ export function normalizeChatRequest(payload, { allowAutoModel = false, _imageCa
373
393
  if (role !== 'assistant' || (message[key] !== null && typeof message[key] !== 'string')) {
374
394
  fail('UNSUPPORTED_PARAMETER', 400, `messages.${key}`);
375
395
  }
376
- if (typeof message[key] === 'string') text(message[key]);
396
+ if (typeof message[key] === 'string') strippedText(message[key], `messages.${key}`);
377
397
  }
378
398
  }
379
399
  if (message.annotations !== undefined) {
@@ -415,10 +435,60 @@ export function normalizeChatRequest(payload, { allowAutoModel = false, _imageCa
415
435
  body.stream_options = { include_usage: payload.stream_options.include_usage };
416
436
  }
417
437
  }
418
- buildCanonicalPrompt(body, undefined, imageCache); // Validate budgets BEFORE any account reservation.
438
+ const built = buildCanonicalPrompt(body, undefined, imageCache); // Validate budgets BEFORE any account reservation.
439
+ body[CANONICAL_PROMPT_CHARS] = built.messages.reduce((sum, m) => sum + (typeof m?.content === 'string' ? m.content.length : 0), 0);
440
+ body[CANONICAL_IMAGE_COUNT] = built.images.length;
419
441
  return body;
420
442
  }
421
443
 
444
+ // Unified OpenAI Responses SDK replay metadata validator (aligned with openai/lib/responses/ResponseInputItems).
445
+ // Keeps inert wire metadata consistent across message, reasoning, tool calls, and tool outputs.
446
+ const MAX_REASONING_PARTS = 256;
447
+ const TOOL_IDENTIFIER_RE = /^[A-Za-z0-9_-]{1,64}$/;
448
+ function validateReplayItemId(value) {
449
+ if (value === undefined || value === null) return;
450
+ if (!validBoundedChars(value, 256, 256) || /[\u0000-\u001f\u007f]/.test(value)) {
451
+ fail('INVALID_INPUT_ITEM', 400, 'input.id');
452
+ }
453
+ }
454
+ function validateReplayItemMeta(item, { allowCaller = false, allowAsync = false } = {}) {
455
+ validateReplayItemId(item.id);
456
+ if (item.status !== undefined && item.status !== null && item.status !== 'completed') {
457
+ fail('INVALID_INPUT_STATUS', 400, 'input.status');
458
+ }
459
+ if (allowCaller && item.caller !== undefined && item.caller !== null) {
460
+ if (!plainObject(item.caller) || Object.keys(item.caller).some(k => k !== 'type') || item.caller.type !== 'direct') {
461
+ fail('UNSUPPORTED_PARAMETER', 400, 'input.caller');
462
+ }
463
+ }
464
+ if (allowAsync && item.async !== undefined && item.async !== null && item.async !== false) {
465
+ fail('UNSUPPORTED_PARAMETER', 400, 'input.async');
466
+ }
467
+ }
468
+ function validateReasoningItem(item) {
469
+ keys(item, ['type', 'id', 'status', 'summary', 'content', 'encrypted_content'], 'input');
470
+ validateReplayItemMeta(item);
471
+ if (item.summary !== undefined && item.summary !== null) {
472
+ if (!Array.isArray(item.summary) || item.summary.length > MAX_REASONING_PARTS) fail('INVALID_REASONING_ITEM', 400, 'input.summary');
473
+ for (const part of item.summary) {
474
+ keys(part, ['type', 'text'], 'input.summary');
475
+ if (part.type !== 'summary_text') fail('UNSUPPORTED_CONTENT_TYPE', 400, 'input.summary');
476
+ strippedText(part.text, 'input.summary');
477
+ }
478
+ }
479
+ if (item.content !== undefined && item.content !== null) {
480
+ if (!Array.isArray(item.content) || item.content.length > MAX_REASONING_PARTS) fail('INVALID_REASONING_ITEM', 400, 'input.content');
481
+ for (const part of item.content) {
482
+ keys(part, ['type', 'text'], 'input.content');
483
+ if (part.type !== 'reasoning_text') fail('UNSUPPORTED_CONTENT_TYPE', 400, 'input.content');
484
+ strippedText(part.text, 'input.content');
485
+ }
486
+ }
487
+ if (item.encrypted_content !== undefined && item.encrypted_content !== null) {
488
+ strippedText(item.encrypted_content, 'input.encrypted_content');
489
+ }
490
+ }
491
+
422
492
  export function normalizeResponsesRequest(payload, { allowAutoModel = false } = {}) {
423
493
  const imageCache = new Map();
424
494
  keys(payload, ['model', 'input', 'instructions', 'tools', 'tool_choice', 'thinking_level', 'reasoning_effort', 'stream', 'store', 'parallel_tool_calls', 'reasoning', 'include', 'prompt_cache_key', 'client_metadata', 'native_search', 'temperature', 'top_p', 'max_output_tokens', 'text', 'user', 'metadata', 'service_tier', 'truncation']);
@@ -435,58 +505,149 @@ export function normalizeResponsesRequest(payload, { allowAutoModel = false } =
435
505
  const { tools, choice, callName, identities } = normalizeResponsesTools(payload);
436
506
  const deferredToolImages = [];
437
507
  let toolImageSeq = 0;
508
+ const openCalls = new Map();
509
+ const seenCalls = new Set();
510
+ let hasNormalizedInput = false;
438
511
  const flushToolImages = () => {
439
512
  if (deferredToolImages.length) messages.push({ role: 'user', content: deferredToolImages.splice(0) });
440
513
  };
514
+ const pushToolOutput = (callId, output) => {
515
+ if (Array.isArray(output)) {
516
+ const normalized = content(output, { user: true, responses: true, toolOutput: true, prefix: 'input.output', imageCache });
517
+ if (Array.isArray(normalized)) {
518
+ const toolTextParts = [];
519
+ for (const part of normalized) {
520
+ if (part.type === 'text') {
521
+ toolTextParts.push(part.text);
522
+ } else {
523
+ const label = `[Tool image ${++toolImageSeq} for ${callId}]`;
524
+ toolTextParts.push(toolTextParts.length ? `\n${label}\n` : label);
525
+ deferredToolImages.push({ type: 'text', text: `${label}:` }, part);
526
+ }
527
+ }
528
+ messages.push({ role: 'tool', tool_call_id: callId, content: toolTextParts.join('') });
529
+ } else {
530
+ messages.push({ role: 'tool', tool_call_id: callId, content: normalized });
531
+ }
532
+ } else {
533
+ messages.push({ role: 'tool', tool_call_id: callId, content: text(output) });
534
+ }
535
+ };
441
536
  for (const item of input) {
442
537
  if (!plainObject(item)) fail('INVALID_INPUT_ITEM');
443
- if (item.type !== 'function_call_output') flushToolImages();
444
- if (item.type === 'function_call') {
445
- keys(item, ['type', 'id', 'status', 'call_id', 'namespace', 'name', 'arguments', 'parsed_arguments'], 'input');
446
- if (item.parsed_arguments !== undefined && item.parsed_arguments !== null) fail('UNSUPPORTED_PARAMETER', 400, 'input.parsed_arguments');
447
- if (item.id !== undefined) id(item.id);
448
- if (item.status !== undefined && item.status !== 'completed') fail('INVALID_INPUT_STATUS');
449
- const call = { id: id(item.call_id), type: 'function', function: { name: callName(item.name, item.namespace), arguments: item.arguments } };
538
+ // Replayed reasoning scratchpad items are validated and stripped transparently
539
+ // without flushing deferred tool images or creating empty assistant messages.
540
+ if (item.type === 'reasoning') {
541
+ validateReasoningItem(item);
542
+ continue;
543
+ }
544
+ if (item.type === 'function_call' || item.type === 'custom_tool_call') {
545
+ flushToolImages();
546
+ hasNormalizedInput = true;
547
+ let call;
548
+ if (item.type === 'function_call') {
549
+ keys(item, ['type', 'id', 'status', 'call_id', 'namespace', 'name', 'arguments', 'parsed_arguments', 'caller', 'async'], 'input');
550
+ if (item.parsed_arguments !== undefined && item.parsed_arguments !== null) fail('UNSUPPORTED_PARAMETER', 400, 'input.parsed_arguments');
551
+ validateReplayItemMeta(item, { allowCaller: true, allowAsync: true });
552
+ const callId = id(item.call_id);
553
+ if (seenCalls.has(callId)) fail('INVALID_TOOL_CALL');
554
+ const resolvedName = callName(item.name, item.namespace);
555
+ seenCalls.add(callId);
556
+ openCalls.set(callId, { kind: 'function_call', name: item.name, namespace: item.namespace ?? null });
557
+ call = { id: callId, type: 'function', function: { name: resolvedName, arguments: item.arguments } };
558
+ } else {
559
+ keys(item, ['type', 'id', 'status', 'call_id', 'namespace', 'name', 'input', 'caller', 'async'], 'input');
560
+ validateReplayItemMeta(item, { allowCaller: true, allowAsync: true });
561
+ const callId = id(item.call_id);
562
+ if (seenCalls.has(callId)) fail('INVALID_TOOL_CALL');
563
+ const rawInput = text(item.input);
564
+ if (Buffer.byteLength(rawInput, 'utf8') > TOOL_LIMITS.bytes) fail('INVALID_TOOL_ARGUMENTS', 400, 'input.input');
565
+ const wrapped = JSON.stringify({ input: rawInput });
566
+ if (Buffer.byteLength(wrapped, 'utf8') > TOOL_LIMITS.bytes) fail('INVALID_TOOL_ARGUMENTS', 400, 'input.input');
567
+ const resolvedName = callName(item.name, item.namespace);
568
+ seenCalls.add(callId);
569
+ openCalls.set(callId, { kind: 'custom_tool_call', name: item.name, namespace: item.namespace ?? null });
570
+ call = { id: callId, type: 'function', function: { name: resolvedName, arguments: wrapped } };
571
+ }
450
572
  const previous = messages.at(-1);
451
573
  if (previous?.role === 'assistant') (previous.tool_calls ??= []).push(call);
452
574
  else messages.push({ role: 'assistant', content: null, tool_calls: [call] });
453
- } else if (item.type === 'function_call_output') {
454
- keys(item, ['type', 'id', 'call_id', 'output'], 'input');
455
- if (item.id !== undefined) id(item.id);
575
+ } else if (item.type === 'function_call_output' || item.type === 'custom_tool_call_output') {
576
+ hasNormalizedInput = true;
577
+ const isFunctionOutput = item.type === 'function_call_output';
578
+ keys(
579
+ item,
580
+ isFunctionOutput
581
+ ? ['type', 'id', 'status', 'call_id', 'output', 'caller', 'name', 'namespace']
582
+ : ['type', 'id', 'status', 'call_id', 'output', 'caller'],
583
+ 'input',
584
+ );
585
+ validateReplayItemMeta(item, { allowCaller: true });
586
+ if (isFunctionOutput) {
587
+ if (item.name !== undefined && item.name !== null && (typeof item.name !== 'string' || !TOOL_IDENTIFIER_RE.test(item.name))) {
588
+ fail('INVALID_TOOL_RESULT', 400, 'input.name');
589
+ }
590
+ if (item.namespace !== undefined && item.namespace !== null && (typeof item.namespace !== 'string' || !TOOL_IDENTIFIER_RE.test(item.namespace))) {
591
+ fail('INVALID_TOOL_RESULT', 400, 'input.namespace');
592
+ }
593
+ }
456
594
  const callId = id(item.call_id);
457
- if (Array.isArray(item.output)) {
458
- const normalized = content(item.output, { user: true, responses: true, toolOutput: true, prefix: 'input.output', imageCache });
459
- if (Array.isArray(normalized)) {
460
- const toolTextParts = [];
461
- for (const part of normalized) {
462
- if (part.type === 'text') {
463
- toolTextParts.push(part.text);
464
- } else {
465
- const label = `[Tool image ${++toolImageSeq} for ${callId}]`;
466
- toolTextParts.push(toolTextParts.length ? `\n${label}\n` : label);
467
- deferredToolImages.push({ type: 'text', text: `${label}:` }, part);
468
- }
595
+ const expectedKind = isFunctionOutput ? 'function_call' : 'custom_tool_call';
596
+ const openCall = openCalls.get(callId);
597
+ if (openCall !== undefined && openCall.kind !== expectedKind) fail('INVALID_TOOL_RESULT');
598
+ if (openCall === undefined) {
599
+ // Avoid decoding base64/PNG images on unlinked outputs; normalizeChatRequest will reject
600
+ // the orphan call_id with INVALID_TOOL_RESULT after validating earlier call arguments.
601
+ messages.push({ role: 'tool', tool_call_id: callId, content: '' });
602
+ } else {
603
+ if (isFunctionOutput) {
604
+ if (item.name !== undefined && item.name !== null && item.name !== openCall.name) {
605
+ fail('INVALID_TOOL_RESULT', 400, 'input.name');
606
+ }
607
+ if (item.namespace !== undefined && item.namespace !== null && item.namespace !== openCall.namespace) {
608
+ fail('INVALID_TOOL_RESULT', 400, 'input.namespace');
469
609
  }
470
- messages.push({ role: 'tool', tool_call_id: callId, content: toolTextParts.join('') });
471
- } else {
472
- messages.push({ role: 'tool', tool_call_id: callId, content: normalized });
473
610
  }
474
- } else {
475
- messages.push({ role: 'tool', tool_call_id: callId, content: text(item.output) });
611
+ openCalls.delete(callId);
612
+ pushToolOutput(callId, item.output);
476
613
  }
477
614
  } else if (item.type === 'input_text') {
615
+ flushToolImages();
616
+ hasNormalizedInput = true;
478
617
  keys(item, ['type', 'text'], 'input'); messages.push({ role: 'user', content: text(item.text) });
479
618
  } else if (item.type === 'input_image') {
619
+ flushToolImages();
620
+ hasNormalizedInput = true;
480
621
  messages.push({ role: 'user', content: content([item], { user: true, responses: true, prefix: 'input', imageCache }) });
622
+ } else if (item.type === undefined || item.type === 'message') {
623
+ flushToolImages();
624
+ hasNormalizedInput = true;
625
+ keys(item, ['type', 'id', 'status', 'role', 'content', 'phase'], 'input');
626
+ validateReplayItemMeta(item);
627
+ if (item.phase !== undefined && item.phase !== null) {
628
+ if (item.role !== 'assistant' || !['commentary', 'final_answer'].includes(item.phase)) {
629
+ fail('UNSUPPORTED_PARAMETER', 400, 'input.phase');
630
+ }
631
+ }
632
+ const normalizedContent = content(item.content, { assistant: item.role === 'assistant', user: item.role === 'user', responses: true, prefix: 'input.content', imageCache });
633
+ const previous = messages.at(-1);
634
+ // A single OpenAI Responses turn can interleave assistant commentary messages
635
+ // with parallel tool calls before tool outputs arrive; coalesce assistant text
636
+ // onto the open assistant turn so sibling calls stay in one tool batch.
637
+ if (openCalls.size > 0 && item.role === 'assistant' && previous?.role === 'assistant') {
638
+ if (typeof normalizedContent === 'string' && normalizedContent.length) {
639
+ previous.content = previous.content ? `${previous.content}\n${normalizedContent}` : normalizedContent;
640
+ }
641
+ } else {
642
+ messages.push({ role: item.role, content: normalizedContent });
643
+ }
481
644
  } else {
482
- keys(item, ['type', 'id', 'status', 'role', 'content'], 'input');
483
- if (item.type !== undefined && item.type !== 'message') fail('UNSUPPORTED_INPUT_TYPE');
484
- if (item.id !== undefined) id(item.id);
485
- if (item.status !== undefined && (item.role !== 'assistant' || item.status !== 'completed')) fail('INVALID_INPUT_STATUS');
486
- messages.push({ role: item.role, content: content(item.content, { assistant: item.role === 'assistant', user: item.role === 'user', responses: true, prefix: 'input.content', imageCache }) });
645
+ fail('UNSUPPORTED_INPUT_TYPE', 400, 'input.type');
487
646
  }
488
647
  }
489
648
  flushToolImages();
649
+ if (!hasNormalizedInput) fail('INPUT_REQUIRED', 400, 'input');
650
+ if (messages.length > MAX_MESSAGES) fail('REQUEST_TOO_LARGE', 413, 'input');
490
651
  const { include: _include, ...inertCompat } = compat;
491
652
  const body = normalizeChatRequest({ ...resolved, ...inertCompat, ...(response_format ? { response_format } : {}), messages, tools, tool_choice: choice, [RESPONSE_TOOL_IDENTITIES]: identities }, { allowAutoModel, _imageCache: imageCache });
492
653
  const projected = collectImageInputs(body.messages, undefined, imageCache).messages;
@@ -22,8 +22,9 @@ export function normalizeResponsesTools(payload) {
22
22
  if (Buffer.byteLength(JSON.stringify(source)) > PROMPT_TOOL_LIMITS.declarationBytes) fail('TOOL_SIZE_LIMIT', 'tools.bytes');
23
23
  const declarations = [], namespaces = new Set(), reserved = new Set(), identities = new Map(), aliases = new Map();
24
24
  const add = (tool, namespace, description) => {
25
- keys(tool, ['type', 'name', 'description', 'parameters', 'strict']);
25
+ if (!plainObject(tool)) fail('INVALID_TOOL_DECLARATION');
26
26
  if (tool.type !== 'function') fail('UNSUPPORTED_TOOL_TYPE');
27
+ keys(tool, ['type', 'name', 'description', 'parameters', 'strict']);
27
28
  name(tool.name);
28
29
  if (tool.description !== undefined && typeof tool.description !== 'string') fail('INVALID_TOOL_DECLARATION');
29
30
  if (declarations.length >= PROMPT_TOOL_LIMITS.tools) fail('TOOL_SIZE_LIMIT', 'tools.count');
@@ -42,7 +43,7 @@ export function normalizeResponsesTools(payload) {
42
43
  // Reserve historical flat names too: an undeclared old call must not alias a
43
44
  // currently declared namespace tool. History is not current authorization.
44
45
  for (const item of Array.isArray(payload.input) ? payload.input : []) {
45
- if (item?.type === 'function_call' && item.namespace == null && typeof item.name === 'string') reserved.add(item.name);
46
+ if ((item?.type === 'function_call' || item?.type === 'custom_tool_call') && item.namespace == null && typeof item.name === 'string') reserved.add(item.name);
46
47
  }
47
48
  let nextAlias = 0;
48
49
  const callName = (toolName, namespace) => {
@@ -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
  }