pi-gemini-app 0.1.11 → 0.1.13
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.
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-gemini-app",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.13",
|
|
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": [
|
|
@@ -87,6 +87,7 @@ export function safeNativeEvidence(value) {
|
|
|
87
87
|
const emptyResponseReason = ['no_text', 'whitespace_only', 'thoughts_only', 'post_parse_empty'].includes(value.emptyResponseReason) ? value.emptyResponseReason : null;
|
|
88
88
|
const nativeTextBytes = bounded(value.nativeTextBytes, 0, 8 * 1024 * 1024);
|
|
89
89
|
const nativeShareableTextBytes = bounded(value.nativeShareableTextBytes, 0, 8 * 1024 * 1024);
|
|
90
|
+
const nativeThoughtBytes = bounded(value.nativeThoughtBytes, 0, 8 * 1024 * 1024);
|
|
90
91
|
const nativeResponseRevisions = bounded(value.nativeResponseRevisions, 0, 4096);
|
|
91
92
|
const nativeCompletenessState = bounded(value.nativeCompletenessState, 0, 0x7fffffff);
|
|
92
93
|
return {
|
|
@@ -111,6 +112,7 @@ export function safeNativeEvidence(value) {
|
|
|
111
112
|
...(emptyResponseReason ? { emptyResponseReason } : {}),
|
|
112
113
|
...(nativeTextBytes !== null ? { nativeTextBytes } : {}),
|
|
113
114
|
...(nativeShareableTextBytes !== null ? { nativeShareableTextBytes } : {}),
|
|
115
|
+
...(nativeThoughtBytes !== null ? { nativeThoughtBytes } : {}),
|
|
114
116
|
...(nativeResponseRevisions !== null ? { nativeResponseRevisions } : {}),
|
|
115
117
|
...(typeof value.nativeResponseIdentityVerified === 'boolean' ? { nativeResponseIdentityVerified: value.nativeResponseIdentityVerified } : {}),
|
|
116
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
|
-
|
|
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
|
}
|
package/src/native-provider.mjs
CHANGED
|
@@ -73,6 +73,20 @@ export function selectIdleDeadline(facts, now = Date.now()) {
|
|
|
73
73
|
};
|
|
74
74
|
}
|
|
75
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
|
+
}
|
|
76
90
|
return {
|
|
77
91
|
kind: 'post_output',
|
|
78
92
|
ms: facts.postOutputIdleMs === null ? null : Math.max(0, facts.postOutputIdleMs - elapsed(facts.lastTextProgressAt)),
|
|
@@ -150,7 +164,7 @@ const validateIdleMs = (value, name) => {
|
|
|
150
164
|
const IDLE_TIMEOUT_SENTINEL = Symbol('IDLE_TIMEOUT_SENTINEL');
|
|
151
165
|
|
|
152
166
|
export class NativeDirectProvider {
|
|
153
|
-
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 } = {}) {
|
|
154
168
|
if (!authManager || typeof authManager.getValidAccessToken !== 'function') throw new TypeError('authManager.getValidAccessToken required');
|
|
155
169
|
if (typeof openTurn !== 'function') throw new TypeError('openTurn required');
|
|
156
170
|
if (typeof uploadImages !== 'function') throw new TypeError('uploadImages required');
|
|
@@ -159,6 +173,12 @@ export class NativeDirectProvider {
|
|
|
159
173
|
const resolvedPostCompleteGraceMs = validateIdleMs(postCompleteGraceMs, 'postCompleteGraceMs');
|
|
160
174
|
const resolvedPostToolIdleMs = validateIdleMs(postToolIdleMs, 'postToolIdleMs');
|
|
161
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');
|
|
162
182
|
if (continuation !== false) throw protocolError('UNSUPPORTED_CONTINUATION', 400);
|
|
163
183
|
if (typeof allowAutoModel !== 'boolean') throw new TypeError('invalid auto model policy');
|
|
164
184
|
const resolvedAlias = canonicalModel(modelAlias);
|
|
@@ -168,6 +188,8 @@ export class NativeDirectProvider {
|
|
|
168
188
|
this.postCompleteGraceMs = resolvedPostCompleteGraceMs;
|
|
169
189
|
this.postToolIdleMs = resolvedPostToolIdleMs;
|
|
170
190
|
this.postOutputIdleMs = resolvedPostOutputIdleMs;
|
|
191
|
+
this.postOutputToolIdleMs = resolvedPostOutputToolIdleMs;
|
|
192
|
+
this.maxPostOutputThoughtHoldMs = resolvedMaxPostOutputThoughtHoldMs;
|
|
171
193
|
this.downloadImages = downloadImages;
|
|
172
194
|
this.blobCache = blobCache ?? null;
|
|
173
195
|
if (typeof allowTextSnapshotReplacement !== 'boolean') throw new TypeError('invalid snapshot policy');
|
|
@@ -322,6 +344,17 @@ export class NativeDirectProvider {
|
|
|
322
344
|
const postOutputIdleMs = context.postOutputIdleMs === undefined
|
|
323
345
|
? this.postOutputIdleMs
|
|
324
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));
|
|
325
358
|
const body = normalizeChatRequest(canonicalChatBody, { allowAutoModel: this.allowAutoModel });
|
|
326
359
|
if (body.native_search) return this.runNativeSearch(accountId, body, onDelta, { ...context, timeoutMs });
|
|
327
360
|
const recoveryInstruction = toolRecoveryInstruction(context.recoveryCode, context.recoveryReason);
|
|
@@ -363,23 +396,34 @@ export class NativeDirectProvider {
|
|
|
363
396
|
const requiresHydrogen = body.model === 'gemini-hydrogen';
|
|
364
397
|
const requiresNeon = body.model === 'gemini-neon';
|
|
365
398
|
let rawText = '', frames = 0, received = 0, observedMode = null, observedThinking = null;
|
|
366
|
-
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;
|
|
367
401
|
let observedFallback = null, downgradeReason = null, observedAttribution = null;
|
|
368
402
|
const attributionMatches = value => (!requiresHydrogen || HYDROGEN_ATTRIBUTION.test(value ?? '')) && (!requiresNeon || NEON_ATTRIBUTION.test(value ?? ''));
|
|
369
403
|
const attributionVerified = () => attributionMatches(observedAttribution);
|
|
370
404
|
let snapshotId = null, revisionCount = 0, quotaObservation = null, quotaFrames = 0;
|
|
371
405
|
let emptyResponseReason = null, outputObserved = false, responseLimitReason = null, outputFailureReason = null;
|
|
372
|
-
const outputShape = { nativeShareableTextBytes: 0, nativeThoughtsPresent: false, nativeStructuredOutputPresent: false, nativeRefusalPresent: false };
|
|
406
|
+
const outputShape = { nativeShareableTextBytes: 0, nativeThoughtsPresent: false, nativeThoughtBytes: 0, nativeStructuredOutputPresent: false, nativeRefusalPresent: false };
|
|
373
407
|
const incremental = context.incrementalOutput === true && !body.response_format;
|
|
374
408
|
const identity = { id: 'chatcmpl-' + crypto.randomBytes(16).toString('hex'), created: Math.floor(Date.now() / 1000), model: body.model,
|
|
375
409
|
[RESPONSE_TOOL_IDENTITIES]: body[RESPONSE_TOOL_IDENTITIES],
|
|
376
410
|
requestedThinkingLevel: body.thinking_level, ignoredTokenParameters: ['max_tokens', 'max_completion_tokens'].filter(key => body[key] !== undefined),
|
|
377
411
|
...((body.reasoning_effort ?? body.reasoning?.effort) === undefined ? {} : { requestedReasoningEffort: body.reasoning_effort ?? body.reasoning?.effort }) };
|
|
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;
|
|
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;
|
|
379
413
|
const deliver = async event => {
|
|
380
414
|
try { await onDelta(event); }
|
|
381
415
|
catch (error) { sinkFailed = true; throw error; }
|
|
382
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
|
+
};
|
|
383
427
|
// The sink owns the commit boundary: provider-published text may still be held.
|
|
384
428
|
// Missing/invalid feedback is conservative for streaming callers.
|
|
385
429
|
const committedOutput = () => {
|
|
@@ -463,13 +507,13 @@ export class NativeDirectProvider {
|
|
|
463
507
|
if (liveCalls.length > 0) return (cachedFallbackResult = { kind: 'none' });
|
|
464
508
|
try {
|
|
465
509
|
const probeCalls = probeItems.filter(it => it.type === 'call').map(it => it.call);
|
|
466
|
-
|
|
510
|
+
let probeContent = probeItems.filter(it => it.type === 'content').map(it => it.text).join('');
|
|
467
511
|
if (!outputShape.nativeStructuredOutputPresent && softErrorReason(probeContent, body, probeCalls.length)) return (cachedFallbackResult = { kind: 'none' });
|
|
468
512
|
if (body.parallel_tool_calls === false && probeCalls.length > 1) return (cachedFallbackResult = { kind: 'none' });
|
|
469
513
|
validateToolCompletion(probeCalls, policy);
|
|
470
514
|
if (!probeCalls.length && !probeContent.trim()) return (cachedFallbackResult = { kind: 'none' });
|
|
471
|
-
if (body.response_format && !probeCalls.length) validateStructuredOutputText(probeContent, body.response_format);
|
|
472
|
-
return (cachedFallbackResult = { kind: 'clean_output' });
|
|
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 });
|
|
473
517
|
} catch {
|
|
474
518
|
return (cachedFallbackResult = { kind: 'none' });
|
|
475
519
|
}
|
|
@@ -494,26 +538,32 @@ export class NativeDirectProvider {
|
|
|
494
538
|
const candidateText = liveContent + liveSplitter.preview();
|
|
495
539
|
if (!candidateText.trim()) return { kind: 'none' };
|
|
496
540
|
if (!outputShape.nativeStructuredOutputPresent && softErrorReason(candidateText, body, 0)) return { kind: 'none' };
|
|
497
|
-
return { kind: 'clean_output' };
|
|
541
|
+
return { kind: 'clean_output', hasCalls: false };
|
|
498
542
|
};
|
|
499
543
|
const nextEventWithIdle = async () => {
|
|
500
544
|
const verified = !downgrade && !outputShape.nativeRefusalPresent && modeMatches(observedMode) && attributionVerified();
|
|
501
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;
|
|
502
548
|
const { kind: idleKind, ms: idleMs } = selectIdleDeadline({
|
|
503
549
|
verified,
|
|
504
550
|
hasText: rawText.trim().length > 0,
|
|
505
551
|
hasLiveToolError: Boolean(liveToolError),
|
|
506
552
|
hasClosedToolError: snap.kind === 'closed_tool_error',
|
|
507
553
|
modelComplete,
|
|
508
|
-
hasLiveCalls:
|
|
554
|
+
hasLiveCalls: hasParsedCalls,
|
|
509
555
|
streamingTool: snap.kind === 'streaming_tool',
|
|
510
|
-
cleanOutput: snap.kind === 'clean_output',
|
|
556
|
+
cleanOutput: snap.kind === 'clean_output' && !hasParsedCalls,
|
|
557
|
+
awaitingOptionalTool,
|
|
511
558
|
liveToolErrorDeadline,
|
|
512
559
|
lastTextProgressAt,
|
|
560
|
+
lastGenerationProgressAt,
|
|
513
561
|
modelCompleteAt,
|
|
514
562
|
postCompleteGraceMs,
|
|
515
563
|
postToolIdleMs,
|
|
516
564
|
postOutputIdleMs,
|
|
565
|
+
postOutputToolIdleMs,
|
|
566
|
+
maxPostOutputThoughtHoldMs,
|
|
517
567
|
});
|
|
518
568
|
const nextPromise = iterator.next();
|
|
519
569
|
if (idleMs === null) return bounded(nextPromise);
|
|
@@ -552,18 +602,21 @@ export class NativeDirectProvider {
|
|
|
552
602
|
readExit = 'deferred_tool_error';
|
|
553
603
|
break;
|
|
554
604
|
}
|
|
605
|
+
const finalSnap = item.verified ? classifyIdleSnapshot() : { kind: 'none' };
|
|
555
606
|
note(`${idleKind}_idle_timeout`, {
|
|
556
607
|
frames,
|
|
557
|
-
calls: liveCalls.length,
|
|
608
|
+
calls: liveCalls.length || (finalSnap.calls?.length ?? 0),
|
|
558
609
|
textBytes: Buffer.byteLength(rawText),
|
|
559
610
|
});
|
|
560
611
|
try { turn?.cancel(); } catch {}
|
|
561
612
|
const idleError = protocolError('NATIVE_TURN_TIMEOUT', 504);
|
|
562
|
-
if (idleKind === 'post_tool' && item.verified && liveCalls.length > 0) {
|
|
613
|
+
if (idleKind === 'post_tool' && item.verified && (liveCalls.length > 0 || finalSnap.hasCalls === true)) {
|
|
563
614
|
idleError.postToolIdleStall = true;
|
|
615
|
+
if (!incremental && finalSnap.kind === 'clean_output') validatedIdleOutput = finalSnap;
|
|
564
616
|
}
|
|
565
|
-
if (idleKind === 'post_output' && item.verified &&
|
|
617
|
+
if (idleKind === 'post_output' && item.verified && finalSnap.kind === 'clean_output' && !finalSnap.hasCalls && liveCalls.length === 0) {
|
|
566
618
|
idleError.postOutputIdleStall = true;
|
|
619
|
+
if (!incremental) validatedIdleOutput = finalSnap;
|
|
567
620
|
}
|
|
568
621
|
throw idleError;
|
|
569
622
|
}
|
|
@@ -582,6 +635,7 @@ export class NativeDirectProvider {
|
|
|
582
635
|
if (info?.outputShape) {
|
|
583
636
|
outputObserved = true;
|
|
584
637
|
outputShape.nativeShareableTextBytes = Math.max(outputShape.nativeShareableTextBytes, info.outputShape.nativeShareableTextBytes);
|
|
638
|
+
outputShape.nativeThoughtBytes = Math.max(outputShape.nativeThoughtBytes, info.outputShape.nativeThoughtBytes ?? 0);
|
|
585
639
|
for (const key of ['nativeThoughtsPresent', 'nativeStructuredOutputPresent', 'nativeRefusalPresent']) outputShape[key] ||= info.outputShape[key];
|
|
586
640
|
if (info.outputShape.nativeCompletenessState !== undefined) outputShape.nativeCompletenessState = info.outputShape.nativeCompletenessState;
|
|
587
641
|
}
|
|
@@ -619,6 +673,7 @@ export class NativeDirectProvider {
|
|
|
619
673
|
fail('MODEL_DOWNGRADE_REJECTED');
|
|
620
674
|
}
|
|
621
675
|
if (outputShape.nativeRefusalPresent) fail('NATIVE_RESPONSE_REFUSED', 422);
|
|
676
|
+
let textProgressed = false;
|
|
622
677
|
if (info.text !== null) {
|
|
623
678
|
const id = info.responseId || null;
|
|
624
679
|
if (this.allowTextSnapshotReplacement && !id) fail('INVALID_NATIVE_RESPONSE');
|
|
@@ -641,16 +696,45 @@ export class NativeDirectProvider {
|
|
|
641
696
|
}
|
|
642
697
|
}
|
|
643
698
|
if (id) snapshotId = id;
|
|
644
|
-
if (!extendsPrior)
|
|
699
|
+
if (!extendsPrior) {
|
|
700
|
+
revisionCount++;
|
|
701
|
+
thoughtHighWaterBytes = 0;
|
|
702
|
+
allowThoughtRebase = false;
|
|
703
|
+
}
|
|
645
704
|
if (info.text !== rawText) {
|
|
705
|
+
const progressAt = Date.now();
|
|
646
706
|
modelComplete = info.completed;
|
|
647
|
-
modelCompleteAt = modelComplete ?
|
|
648
|
-
lastTextProgressAt =
|
|
707
|
+
modelCompleteAt = modelComplete ? progressAt : null;
|
|
708
|
+
lastTextProgressAt = progressAt;
|
|
709
|
+
lastGenerationProgressAt = progressAt;
|
|
710
|
+
allowThoughtRebase = true;
|
|
711
|
+
textProgressed = true;
|
|
649
712
|
}
|
|
650
713
|
rawText = info.text;
|
|
651
714
|
} else if (snapshotId !== null && info.responseId && info.responseId !== snapshotId) {
|
|
652
715
|
fail('INVALID_NATIVE_RESPONSE');
|
|
653
716
|
}
|
|
717
|
+
const frameThoughtBytes = info.outputShape?.nativeThoughtBytes ?? 0;
|
|
718
|
+
if (textProgressed) {
|
|
719
|
+
// Keep allowThoughtRebase armed if this text-progress frame also carried the tail
|
|
720
|
+
// of pre-text thoughts; if a smaller post-text block already started here, rebase now.
|
|
721
|
+
if (frameThoughtBytes > thoughtHighWaterBytes) thoughtHighWaterBytes = frameThoughtBytes;
|
|
722
|
+
else if (frameThoughtBytes > 0 && frameThoughtBytes < thoughtHighWaterBytes) {
|
|
723
|
+
thoughtHighWaterBytes = frameThoughtBytes;
|
|
724
|
+
allowThoughtRebase = false;
|
|
725
|
+
}
|
|
726
|
+
} else if (frameThoughtBytes > 0) {
|
|
727
|
+
if (frameThoughtBytes > thoughtHighWaterBytes) {
|
|
728
|
+
thoughtHighWaterBytes = frameThoughtBytes;
|
|
729
|
+
allowThoughtRebase = false;
|
|
730
|
+
if (lastTextProgressAt !== null) lastGenerationProgressAt = Date.now();
|
|
731
|
+
} else if (frameThoughtBytes < thoughtHighWaterBytes && allowThoughtRebase) {
|
|
732
|
+
// Post-text new thought block restarted at a smaller byte count: rebase once
|
|
733
|
+
// without advancing the clock; a subsequent strictly larger frame must prove progress.
|
|
734
|
+
thoughtHighWaterBytes = frameThoughtBytes;
|
|
735
|
+
allowThoughtRebase = false;
|
|
736
|
+
}
|
|
737
|
+
}
|
|
654
738
|
if (incremental && !liveToolError && modeMatches(observedMode) && attributionVerified() && liveSyncedLength < rawText.length) {
|
|
655
739
|
const delta = rawText.slice(liveSyncedLength);
|
|
656
740
|
liveSyncedLength = rawText.length;
|
|
@@ -784,20 +868,30 @@ export class NativeDirectProvider {
|
|
|
784
868
|
nativeTextBytes: Buffer.byteLength(rawText), ...outputShape,
|
|
785
869
|
nativeResponseRevisions: revisionCount, nativeResponseIdentityVerified: snapshotId !== null });
|
|
786
870
|
phase = 'output';
|
|
787
|
-
if (!incremental)
|
|
788
|
-
if (body.response_format && !calls.length) {
|
|
789
|
-
if (content) await onDelta({ content });
|
|
790
|
-
} else {
|
|
791
|
-
for (const item of items) await onDelta(item.type === 'call' ? { call: item.call } : { content: item.text });
|
|
792
|
-
}
|
|
793
|
-
}
|
|
871
|
+
if (!incremental) await deliverNonIncremental(items, content, calls);
|
|
794
872
|
note('provider_success');
|
|
795
873
|
return result;
|
|
796
874
|
} catch (error) {
|
|
797
875
|
const modeVerified = !downgrade && !outputShape.nativeRefusalPresent && modeMatches(observedMode) && attributionVerified();
|
|
798
876
|
if (incremental && !liveToolError && modeVerified && !sinkFailed) {
|
|
799
877
|
try { await publish(liveSplitter.flush()); }
|
|
800
|
-
catch {
|
|
878
|
+
catch (flushError) {
|
|
879
|
+
if (sinkFailed) error = flushError;
|
|
880
|
+
/* Otherwise (e.g. TRUNCATED_TOOL_CALL / parse error): retain already-published text without releasing an invalid/incomplete tool body. */
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
if (incremental && error?.postToolIdleStall && publishedCalls === 0) delete error.postToolIdleStall;
|
|
884
|
+
if (incremental && error?.postOutputIdleStall && !publishedContent.trim().length) delete error.postOutputIdleStall;
|
|
885
|
+
let nonIncrementalDelivered = null;
|
|
886
|
+
if (!incremental && !liveToolError && modeVerified && !sinkFailed &&
|
|
887
|
+
(error?.postOutputIdleStall || error?.postToolIdleStall) &&
|
|
888
|
+
validatedIdleOutput && (validatedIdleOutput.content.length || validatedIdleOutput.calls.length)) {
|
|
889
|
+
try {
|
|
890
|
+
await deliverNonIncremental(validatedIdleOutput.items, validatedIdleOutput.content, validatedIdleOutput.calls, { includeMeta: true });
|
|
891
|
+
nonIncrementalDelivered = validatedIdleOutput;
|
|
892
|
+
} catch (sinkError) {
|
|
893
|
+
error = sinkError;
|
|
894
|
+
}
|
|
801
895
|
}
|
|
802
896
|
const safe = safeFailure(error);
|
|
803
897
|
if (!modeVerified) safe.unverifiedOutput = true;
|
|
@@ -829,6 +923,8 @@ export class NativeDirectProvider {
|
|
|
829
923
|
});
|
|
830
924
|
if (incremental && modeVerified && (publishedContent.length || publishedCalls)) safe.partialResult = { ...identity, content: publishedContent, calls: liveCalls.slice(0, publishedCalls),
|
|
831
925
|
thinkingLevel: observedThinking, resolvedModeCategory: observedMode, ...(observedAttribution !== null ? { attribution: observedAttribution } : {}), nativeEvidence: safe.nativeEvidence };
|
|
926
|
+
else if (nonIncrementalDelivered) safe.partialResult = { ...identity, content: nonIncrementalDelivered.content, calls: nonIncrementalDelivered.calls,
|
|
927
|
+
thinkingLevel: observedThinking, resolvedModeCategory: observedMode, ...(observedAttribution !== null ? { attribution: observedAttribution } : {}), nativeEvidence: safe.nativeEvidence };
|
|
832
928
|
throw safe;
|
|
833
929
|
}
|
|
834
930
|
finally {
|
package/src/openai-contract.mjs
CHANGED
|
@@ -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
|
|
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,
|
|
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) {
|
|
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')
|
|
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
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
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
|
-
|
|
455
|
-
|
|
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
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
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
|
-
|
|
475
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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) => {
|