pi-gemini-app 0.1.13 → 0.1.15
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/extensions/pi/auth.js +11 -7
- package/extensions/pi/provider.js +17 -5
- package/extensions/pi/stream.js +14 -5
- package/native-wire/robin-current.mjs +51 -14
- package/package.json +2 -1
- package/src/gateway/automatic-recovery.mjs +3 -1
- package/src/gateway/native-evidence.mjs +1 -0
- package/src/gateway/output-recovery.mjs +33 -0
- package/src/gateway/subscription-transport.mjs +78 -0
- package/src/gateway/subscription.mjs +36 -19
- package/src/native-provider.mjs +170 -41
- package/src/openai-contract.mjs +11 -1
- package/src/tool-protocol.mjs +306 -53
package/src/native-provider.mjs
CHANGED
|
@@ -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, PROMPT_MAX_BYTES, canonicalModel, normalizeChatRequest, normalizeResponsesRequest, buildCanonicalPrompt, writeChatResponse, writeResponsesResponse } from './openai-contract.mjs';
|
|
10
|
+
import { MODEL_ALIASES, MODEL_MODES, MODEL_SPECS, NATIVE_MODELS, PROMPT_MAX_BYTES, CANONICAL_BUILT, 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';
|
|
@@ -355,7 +355,11 @@ export class NativeDirectProvider {
|
|
|
355
355
|
: this.maxPostOutputThoughtHoldMs !== undefined
|
|
356
356
|
? this.maxPostOutputThoughtHoldMs
|
|
357
357
|
: (postOutputToolIdleMs === null ? null : Math.min(600_000, postOutputToolIdleMs * 3));
|
|
358
|
-
const body =
|
|
358
|
+
const body =
|
|
359
|
+
context.preNormalized === true &&
|
|
360
|
+
canonicalChatBody?.[CANONICAL_BUILT]?.allowAutoModel === this.allowAutoModel
|
|
361
|
+
? canonicalChatBody
|
|
362
|
+
: normalizeChatRequest(canonicalChatBody, { allowAutoModel: this.allowAutoModel });
|
|
359
363
|
if (body.native_search) return this.runNativeSearch(accountId, body, onDelta, { ...context, timeoutMs });
|
|
360
364
|
const recoveryInstruction = toolRecoveryInstruction(context.recoveryCode, context.recoveryReason);
|
|
361
365
|
const appendRecovery = promptMessages => {
|
|
@@ -370,7 +374,7 @@ export class NativeDirectProvider {
|
|
|
370
374
|
};
|
|
371
375
|
if (this.allowTextSnapshotReplacement && body.tools.length) fail('NATIVE_TEXT_SNAPSHOT_TOOLS_FORBIDDEN', 400);
|
|
372
376
|
const policy = compileToolPolicy(body.tools, body.tool_choice);
|
|
373
|
-
let { messages, images } = buildCanonicalPrompt(body);
|
|
377
|
+
let { messages, images } = body[CANONICAL_BUILT] ?? buildCanonicalPrompt(body);
|
|
374
378
|
messages = appendRecovery(messages);
|
|
375
379
|
const isAutoModel = this.allowAutoModel && body.model === 'gemini-auto';
|
|
376
380
|
const modeCategory = isAutoModel ? null : MODEL_MODES[body.model];
|
|
@@ -435,9 +439,87 @@ export class NativeDirectProvider {
|
|
|
435
439
|
return context.outputMode === 'buffered' ? { publishedBytes: 0, toolCallCount: 0 }
|
|
436
440
|
: { publishedBytes: Buffer.byteLength(publishedContent), toolCallCount: publishedCalls };
|
|
437
441
|
};
|
|
438
|
-
|
|
442
|
+
// Gemini App may revise a same-id snapshot mid-stream, including inside tool_call
|
|
443
|
+
// bodies. With deferToolCalls, calls (and any text after the first call) are held
|
|
444
|
+
// until the turn is final so callers never receive draft calls that upstream rewrites.
|
|
445
|
+
const deferCalls = incremental && context.deferToolCalls === true;
|
|
446
|
+
const visibleText = (items, content, splitter, final) => {
|
|
447
|
+
if (!deferCalls || final) return content + splitter.preview();
|
|
448
|
+
let text = '';
|
|
449
|
+
for (const item of items) {
|
|
450
|
+
if (item.type === 'call') return text;
|
|
451
|
+
text += item.text;
|
|
452
|
+
}
|
|
453
|
+
return text + splitter.preview();
|
|
454
|
+
};
|
|
455
|
+
// Same-id revision after output was committed: accept it only if replaying the new
|
|
456
|
+
// snapshot reproduces everything already delivered (visible text prefix + identical calls).
|
|
457
|
+
// A recoverable TOOL_ERRORS failure in an unpublished tail is deferred so a subsequent
|
|
458
|
+
// same-id revision can still repair the draft without leaking old held calls.
|
|
459
|
+
const tryRebaseLive = nextText => {
|
|
460
|
+
let splitter = createToolCallSplitter({ policy });
|
|
461
|
+
let items;
|
|
462
|
+
let rebaseToolError = null;
|
|
463
|
+
try {
|
|
464
|
+
items = splitter.push(nextText);
|
|
465
|
+
} catch (splitError) {
|
|
466
|
+
if (!TOOL_ERRORS.has(splitError?.code)) return false;
|
|
467
|
+
const replay = createToolCallSplitter({ policy });
|
|
468
|
+
items = [];
|
|
469
|
+
for (let pos = 0; pos < nextText.length;) {
|
|
470
|
+
const nl = nextText.indexOf('\n', pos);
|
|
471
|
+
const end = nl < 0 ? nextText.length : nl + 1;
|
|
472
|
+
try {
|
|
473
|
+
items.push(...replay.push(nextText.slice(pos, end)));
|
|
474
|
+
} catch (lineErr) {
|
|
475
|
+
if (!TOOL_ERRORS.has(lineErr?.code)) return false;
|
|
476
|
+
rebaseToolError = lineErr;
|
|
477
|
+
break;
|
|
478
|
+
}
|
|
479
|
+
pos = end;
|
|
480
|
+
}
|
|
481
|
+
if (!rebaseToolError) return false;
|
|
482
|
+
splitter = replay;
|
|
483
|
+
}
|
|
484
|
+
let content = '';
|
|
485
|
+
const calls = [];
|
|
486
|
+
for (const item of items) {
|
|
487
|
+
if (item.type === 'content') content += item.text;
|
|
488
|
+
else calls.push(item.call);
|
|
489
|
+
}
|
|
490
|
+
if (calls.length < publishedCalls) return false;
|
|
491
|
+
for (let i = 0; i < publishedCalls; i++) {
|
|
492
|
+
if (calls[i].function.name !== liveCalls[i].function.name || calls[i].function.arguments !== liveCalls[i].function.arguments) return false;
|
|
493
|
+
}
|
|
494
|
+
if (!visibleText(items, content, splitter, false).startsWith(publishedContent)) return false;
|
|
495
|
+
// Preserve IDs of calls that were already delivered.
|
|
496
|
+
let callIndex = 0;
|
|
497
|
+
for (const item of items) {
|
|
498
|
+
if (item.type === 'call') {
|
|
499
|
+
if (callIndex < publishedCalls) item.call = liveCalls[callIndex];
|
|
500
|
+
calls[callIndex] = item.call;
|
|
501
|
+
callIndex++;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
liveSplitter = splitter;
|
|
505
|
+
liveItems = items;
|
|
506
|
+
liveContent = content;
|
|
507
|
+
liveCalls = calls;
|
|
508
|
+
liveSyncedLength = nextText.length;
|
|
509
|
+
if (rebaseToolError) {
|
|
510
|
+
liveToolError = rebaseToolError;
|
|
511
|
+
liveToolErrorTailStart = Number.isInteger(rebaseToolError.postFenceOffset) ? rebaseToolError.postFenceOffset : nextText.length;
|
|
512
|
+
liveToolErrorDeadline = postToolIdleMs === null ? null : Date.now() + postToolIdleMs;
|
|
513
|
+
} else {
|
|
514
|
+
liveToolError = null;
|
|
515
|
+
liveToolErrorTailStart = 0;
|
|
516
|
+
liveToolErrorDeadline = null;
|
|
517
|
+
}
|
|
518
|
+
return true;
|
|
519
|
+
};
|
|
520
|
+
const publish = async (items, { final = false } = {}) => {
|
|
439
521
|
for (const item of items) { liveItems.push(item); if (item.type === 'content') liveContent += item.text; else liveCalls.push(item.call); }
|
|
440
|
-
const text = liveContent
|
|
522
|
+
const text = visibleText(liveItems, liveContent, liveSplitter, final);
|
|
441
523
|
if (!text.startsWith(publishedContent)) {
|
|
442
524
|
const committed = committedOutput();
|
|
443
525
|
if (snapshotId === null || committed.publishedBytes || committed.toolCallCount) failWithEvidence('NON_MONOTONIC_NATIVE_RESPONSE', {
|
|
@@ -452,7 +534,7 @@ export class NativeDirectProvider {
|
|
|
452
534
|
await deliver({ content, response: { ...identity, thinkingLevel: observedThinking } });
|
|
453
535
|
publishedContent = text;
|
|
454
536
|
}
|
|
455
|
-
while (publishedCalls < liveCalls.length) {
|
|
537
|
+
while ((!deferCalls || final) && publishedCalls < liveCalls.length) {
|
|
456
538
|
if (body.parallel_tool_calls === false && publishedCalls >= 1) fail('PARALLEL_TOOL_CALLS_DISABLED');
|
|
457
539
|
const call = liveCalls[publishedCalls];
|
|
458
540
|
await deliver({ call, response: { ...identity, thinkingLevel: observedThinking } });
|
|
@@ -487,35 +569,38 @@ export class NativeDirectProvider {
|
|
|
487
569
|
...(context.nativeDiagnostic ? { diagnostic: context.nativeDiagnostic } : {}) });
|
|
488
570
|
iterator = turn.events[Symbol.asyncIterator]();
|
|
489
571
|
try {
|
|
490
|
-
let cachedFallbackText = null, cachedFallbackRevision = -1, cachedFallbackResult = { kind: 'none' };
|
|
572
|
+
let cachedFallbackText = null, cachedFallbackRevision = -1, cachedFallbackComplete = null, cachedFallbackResult = { kind: 'none' };
|
|
491
573
|
const probeFullRawText = () => {
|
|
492
|
-
if (cachedFallbackText === rawText && cachedFallbackRevision === revisionCount) return cachedFallbackResult;
|
|
574
|
+
if (cachedFallbackText === rawText && cachedFallbackRevision === revisionCount && cachedFallbackComplete === modelComplete) return cachedFallbackResult;
|
|
493
575
|
cachedFallbackText = rawText;
|
|
494
576
|
cachedFallbackRevision = revisionCount;
|
|
577
|
+
cachedFallbackComplete = modelComplete;
|
|
495
578
|
if (!rawText.trim() || ASYNC_DEEP_THINK_PLACEHOLDER_RE.test(rawText)) {
|
|
496
579
|
return (cachedFallbackResult = { kind: 'none' });
|
|
497
580
|
}
|
|
498
581
|
let probeItems;
|
|
582
|
+
let probeSuppressed = false;
|
|
499
583
|
try {
|
|
500
584
|
const probe = createToolCallSplitter({ policy });
|
|
501
|
-
probeItems = [...probe.push(rawText), ...probe.flush()];
|
|
585
|
+
probeItems = [...probe.push(rawText), ...probe.flush({ interrupted: !modelComplete })];
|
|
586
|
+
probeSuppressed = probe.suppressed;
|
|
502
587
|
} catch (probeError) {
|
|
503
588
|
if (probeError?.code === 'TRUNCATED_TOOL_CALL') return (cachedFallbackResult = { kind: 'streaming_tool' });
|
|
504
589
|
if (TOOL_ERRORS.has(probeError?.code)) return (cachedFallbackResult = { kind: 'closed_tool_error', error: probeError });
|
|
505
590
|
return (cachedFallbackResult = { kind: 'none' });
|
|
506
591
|
}
|
|
507
|
-
if (liveCalls.length > 0) return (cachedFallbackResult = { kind: 'none' });
|
|
592
|
+
if (liveCalls.length > 0) return (cachedFallbackResult = { kind: 'none', suppressed: probeSuppressed });
|
|
508
593
|
try {
|
|
509
594
|
const probeCalls = probeItems.filter(it => it.type === 'call').map(it => it.call);
|
|
510
595
|
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' });
|
|
596
|
+
if (!outputShape.nativeStructuredOutputPresent && softErrorReason(probeContent, body, probeCalls.length)) return (cachedFallbackResult = { kind: 'none', suppressed: probeSuppressed });
|
|
597
|
+
if (body.parallel_tool_calls === false && probeCalls.length > 1) return (cachedFallbackResult = { kind: 'none', suppressed: probeSuppressed });
|
|
513
598
|
validateToolCompletion(probeCalls, policy);
|
|
514
|
-
if (!probeCalls.length && !probeContent.trim()) return (cachedFallbackResult = { kind: 'none' });
|
|
599
|
+
if (!probeCalls.length && !probeContent.trim()) return (cachedFallbackResult = { kind: 'none', suppressed: probeSuppressed });
|
|
515
600
|
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 });
|
|
601
|
+
return (cachedFallbackResult = { kind: 'clean_output', hasCalls: probeCalls.length > 0, suppressed: probeSuppressed, content: probeContent, calls: probeCalls, items: probeItems });
|
|
517
602
|
} catch {
|
|
518
|
-
return (cachedFallbackResult = { kind: 'none' });
|
|
603
|
+
return (cachedFallbackResult = { kind: 'none', suppressed: probeSuppressed });
|
|
519
604
|
}
|
|
520
605
|
};
|
|
521
606
|
// O(1) incremental idle classification for streaming turns via liveSplitter.state;
|
|
@@ -662,9 +747,6 @@ export class NativeDirectProvider {
|
|
|
662
747
|
if (!Number.isSafeInteger(info.thinkingLevel) || info.thinkingLevel < 0 || info.thinkingLevel > 4) fail('INVALID_NATIVE_THINKING_LEVEL');
|
|
663
748
|
observedThinking = info.thinkingLevel;
|
|
664
749
|
}
|
|
665
|
-
const wasComplete = modelComplete;
|
|
666
|
-
modelComplete ||= info.completed;
|
|
667
|
-
if (!wasComplete && modelComplete) modelCompleteAt = Date.now();
|
|
668
750
|
// Stop as soon as a wrong model is proven; do not pay for a full
|
|
669
751
|
// downgraded answer that this gateway can never return as success.
|
|
670
752
|
if (downgrade) {
|
|
@@ -674,6 +756,7 @@ export class NativeDirectProvider {
|
|
|
674
756
|
}
|
|
675
757
|
if (outputShape.nativeRefusalPresent) fail('NATIVE_RESPONSE_REFUSED', 422);
|
|
676
758
|
let textProgressed = false;
|
|
759
|
+
let rebased = false;
|
|
677
760
|
if (info.text !== null) {
|
|
678
761
|
const id = info.responseId || null;
|
|
679
762
|
if (this.allowTextSnapshotReplacement && !id) fail('INVALID_NATIVE_RESPONSE');
|
|
@@ -686,11 +769,14 @@ export class NativeDirectProvider {
|
|
|
686
769
|
phase: 'decode', nonMonotonicSite: 'snapshot_identity', sameResponseIdentity: false,
|
|
687
770
|
snapshotPriorBytes: Buffer.byteLength(rawText), snapshotNextBytes: Buffer.byteLength(info.text),
|
|
688
771
|
snapshotCommonPrefixBytes: commonPrefixBytes(rawText, info.text), ...committed });
|
|
689
|
-
if (incremental) {
|
|
690
|
-
if (
|
|
772
|
+
if (incremental && (committed.publishedBytes || committed.toolCallCount)) {
|
|
773
|
+
if (!tryRebaseLive(info.text)) failWithEvidence('NON_MONOTONIC_NATIVE_RESPONSE', {
|
|
691
774
|
phase: 'decode', nonMonotonicSite: 'snapshot_stream', sameResponseIdentity: true,
|
|
692
775
|
snapshotPriorBytes: Buffer.byteLength(rawText), snapshotNextBytes: Buffer.byteLength(info.text),
|
|
693
776
|
snapshotCommonPrefixBytes: commonPrefixBytes(rawText, info.text), ...committed });
|
|
777
|
+
note('snapshot_rebase', { priorBytes: Buffer.byteLength(rawText), nextBytes: Buffer.byteLength(info.text) });
|
|
778
|
+
rebased = true;
|
|
779
|
+
} else if (incremental) {
|
|
694
780
|
if (liveSyncedLength > 0) await deliver({ reset: true, sameResponseIdentity: true, response: identity });
|
|
695
781
|
liveSplitter = createToolCallSplitter({ policy }); liveItems = []; liveContent = ''; liveCalls = []; publishedContent = ''; publishedCalls = 0; liveSyncedLength = 0; liveToolError = null; liveToolErrorTailStart = 0; liveToolErrorDeadline = null;
|
|
696
782
|
}
|
|
@@ -714,6 +800,12 @@ export class NativeDirectProvider {
|
|
|
714
800
|
} else if (snapshotId !== null && info.responseId && info.responseId !== snapshotId) {
|
|
715
801
|
fail('INVALID_NATIVE_RESPONSE');
|
|
716
802
|
}
|
|
803
|
+
// Completion evidence applies ONLY after frame identity and monotonicity checks succeed.
|
|
804
|
+
if (!textProgressed) {
|
|
805
|
+
const wasComplete = modelComplete;
|
|
806
|
+
modelComplete ||= info.completed;
|
|
807
|
+
if (!wasComplete && modelComplete) modelCompleteAt = Date.now();
|
|
808
|
+
}
|
|
717
809
|
const frameThoughtBytes = info.outputShape?.nativeThoughtBytes ?? 0;
|
|
718
810
|
if (textProgressed) {
|
|
719
811
|
// Keep allowThoughtRebase armed if this text-progress frame also carried the tail
|
|
@@ -735,30 +827,54 @@ export class NativeDirectProvider {
|
|
|
735
827
|
allowThoughtRebase = false;
|
|
736
828
|
}
|
|
737
829
|
}
|
|
738
|
-
if (incremental && !liveToolError && modeMatches(observedMode) && attributionVerified() && liveSyncedLength < rawText.length) {
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
830
|
+
if (incremental && !liveToolError && modeMatches(observedMode) && attributionVerified() && (rebased || liveSyncedLength < rawText.length)) {
|
|
831
|
+
if (rebased) {
|
|
832
|
+
await publish([]);
|
|
833
|
+
} else {
|
|
834
|
+
const delta = rawText.slice(liveSyncedLength);
|
|
835
|
+
liveSyncedLength = rawText.length;
|
|
836
|
+
try {
|
|
837
|
+
await publish(liveSplitter.push(delta));
|
|
838
|
+
} catch (splitError) {
|
|
839
|
+
// Defer recoverable tool-protocol errors briefly until stream completion so
|
|
840
|
+
// upstream completion/downgrade/refusal evidence is fully verified and
|
|
841
|
+
// automatic tool_protocol recovery (or same-ID revision) can run cleanly.
|
|
842
|
+
if (!sinkFailed && TOOL_ERRORS.has(splitError?.code)) {
|
|
843
|
+
liveToolError = splitError;
|
|
844
|
+
liveToolErrorTailStart = Number.isInteger(splitError.postFenceOffset) ? splitError.postFenceOffset : rawText.length;
|
|
845
|
+
liveToolErrorDeadline = postToolIdleMs === null ? null : Date.now() + postToolIdleMs;
|
|
846
|
+
} else {
|
|
847
|
+
throw splitError;
|
|
848
|
+
}
|
|
753
849
|
}
|
|
754
850
|
}
|
|
755
|
-
// Once valid tool_call(s) have been parsed and the model begins hallucinating
|
|
851
|
+
// Once valid output or tool_call(s) have been parsed and the model begins hallucinating
|
|
756
852
|
// a fake [Caller tool result], stop upstream immediately instead of waiting
|
|
757
853
|
// minutes for the model to finish generating discarded text.
|
|
758
|
-
if (!liveToolError && liveSplitter.suppressed && liveCalls.length > 0 && !downgrade && !outputShape.nativeRefusalPresent) {
|
|
854
|
+
if (!liveToolError && liveSplitter.suppressed && (liveCalls.length > 0 || liveContent.trim().length > 0) && !downgrade && !outputShape.nativeRefusalPresent) {
|
|
759
855
|
note('early_stop_post_tool_hallucination', { calls: liveCalls.length });
|
|
760
856
|
try { turn?.cancel(); } catch {}
|
|
761
|
-
readExit = 'suppressed_after_valid_call';
|
|
857
|
+
readExit = liveCalls.length > 0 ? 'suppressed_after_valid_call' : 'suppressed_after_valid_text';
|
|
858
|
+
ended = true;
|
|
859
|
+
modelComplete = true;
|
|
860
|
+
httpStatus = httpStatus ?? 200;
|
|
861
|
+
grpc = grpc ?? 0;
|
|
862
|
+
break;
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
if (!incremental && rawText.length > 0 && !downgrade && !outputShape.nativeRefusalPresent && modeMatches(observedMode) && attributionVerified()) {
|
|
866
|
+
const snap = probeFullRawText();
|
|
867
|
+
if (snap.kind === 'closed_tool_error' && snap.error?.toolProtocolReason === 'hallucinated_caller_result') {
|
|
868
|
+
liveToolError = snap.error;
|
|
869
|
+
note('early_stop_post_tool_error', { code: liveToolError.code, bytes: Buffer.byteLength(rawText) });
|
|
870
|
+
try { turn?.cancel(); } catch {}
|
|
871
|
+
readExit = 'deferred_tool_error';
|
|
872
|
+
break;
|
|
873
|
+
}
|
|
874
|
+
if (snap.suppressed) {
|
|
875
|
+
note('early_stop_post_tool_hallucination', { calls: snap.calls?.length ?? 0 });
|
|
876
|
+
try { turn?.cancel(); } catch {}
|
|
877
|
+
readExit = snap.hasCalls ? 'suppressed_after_valid_call' : 'suppressed_after_valid_text';
|
|
762
878
|
ended = true;
|
|
763
879
|
modelComplete = true;
|
|
764
880
|
httpStatus = httpStatus ?? 200;
|
|
@@ -840,7 +956,7 @@ export class NativeDirectProvider {
|
|
|
840
956
|
liveSyncedLength = rawText.length;
|
|
841
957
|
await publish(liveSplitter.push(delta));
|
|
842
958
|
}
|
|
843
|
-
await publish(liveSplitter.flush());
|
|
959
|
+
await publish(liveSplitter.flush(), { final: true });
|
|
844
960
|
items = liveItems;
|
|
845
961
|
}
|
|
846
962
|
else { const splitter = createToolCallSplitter({ policy }); items = [...splitter.push(rawText), ...splitter.flush()]; }
|
|
@@ -868,18 +984,31 @@ export class NativeDirectProvider {
|
|
|
868
984
|
nativeTextBytes: Buffer.byteLength(rawText), ...outputShape,
|
|
869
985
|
nativeResponseRevisions: revisionCount, nativeResponseIdentityVerified: snapshotId !== null });
|
|
870
986
|
phase = 'output';
|
|
871
|
-
if (!incremental) await deliverNonIncremental(items, content, calls);
|
|
987
|
+
if (!incremental) await deliverNonIncremental(items, content, calls, { includeMeta: context.incrementalOutput === true || calls.length > 0 });
|
|
872
988
|
note('provider_success');
|
|
873
989
|
return result;
|
|
874
990
|
} catch (error) {
|
|
875
991
|
const modeVerified = !downgrade && !outputShape.nativeRefusalPresent && modeMatches(observedMode) && attributionVerified();
|
|
992
|
+
// Only an accepted snapshot may authorize releasing held tool calls; a rejected
|
|
993
|
+
// frame (wrong identity or failed rebase) must never promote old draft calls.
|
|
994
|
+
const snapshotAccepted = !['NON_MONOTONIC_NATIVE_RESPONSE', 'INVALID_NATIVE_RESPONSE'].includes(error?.code);
|
|
995
|
+
const releaseHeld = snapshotAccepted && (error?.postToolIdleStall === true || modelComplete || error?.code === 'NATIVE_TURN_TIMEOUT');
|
|
876
996
|
if (incremental && !liveToolError && modeVerified && !sinkFailed) {
|
|
877
|
-
try { await publish(liveSplitter.flush()); }
|
|
997
|
+
try { await publish(liveSplitter.flush({ interrupted: true }), { final: releaseHeld }); }
|
|
878
998
|
catch (flushError) {
|
|
879
999
|
if (sinkFailed) error = flushError;
|
|
1000
|
+
else if (releaseHeld && deferCalls) {
|
|
1001
|
+
try { await publish([], { final: true }); } catch (releaseError) { if (sinkFailed) error = releaseError; }
|
|
1002
|
+
}
|
|
880
1003
|
/* Otherwise (e.g. TRUNCATED_TOOL_CALL / parse error): retain already-published text without releasing an invalid/incomplete tool body. */
|
|
881
1004
|
}
|
|
882
1005
|
}
|
|
1006
|
+
// Deferred tool-protocol errors (or transport reset/timeout after a bad tail) leave
|
|
1007
|
+
// earlier validated calls from the same accepted snapshot eligible for salvage.
|
|
1008
|
+
if (deferCalls && modeVerified && !sinkFailed && snapshotAccepted && publishedCalls < liveCalls.length &&
|
|
1009
|
+
(TOOL_ERRORS.has(error?.code) || releaseHeld)) {
|
|
1010
|
+
try { await publish([], { final: true }); } catch (releaseError) { if (sinkFailed) error = releaseError; }
|
|
1011
|
+
}
|
|
883
1012
|
if (incremental && error?.postToolIdleStall && publishedCalls === 0) delete error.postToolIdleStall;
|
|
884
1013
|
if (incremental && error?.postOutputIdleStall && !publishedContent.trim().length) delete error.postOutputIdleStall;
|
|
885
1014
|
let nonIncrementalDelivered = null;
|
package/src/openai-contract.mjs
CHANGED
|
@@ -14,6 +14,7 @@ import { MAX_IMAGES, MAX_IMAGE_URL_BYTES, MAX_TOTAL_IMAGE_URL_BYTES, normalizeIm
|
|
|
14
14
|
import { RESPONSE_TOOL_IDENTITIES, normalizeResponsesTools, responsesCallFields } from './responses-tool-namespaces.mjs';
|
|
15
15
|
import { toResponsesUsage } from './openai-usage.mjs';
|
|
16
16
|
|
|
17
|
+
export const CANONICAL_BUILT = Symbol('canonicalBuilt');
|
|
17
18
|
const fail = (code, status = 400, param = null) => { throw protocolError(code, status, param); };
|
|
18
19
|
export const NATIVE_MODELS = Object.freeze(['gemini-neon', 'gemini-hydrogen', 'gemini-flash-lite']);
|
|
19
20
|
// Temporary compatibility alias while clients migrate from retired gemini-argon (mode 8) to gemini-neon (mode 3).
|
|
@@ -438,6 +439,15 @@ export function normalizeChatRequest(payload, { allowAutoModel = false, _imageCa
|
|
|
438
439
|
const built = buildCanonicalPrompt(body, undefined, imageCache); // Validate budgets BEFORE any account reservation.
|
|
439
440
|
body[CANONICAL_PROMPT_CHARS] = built.messages.reduce((sum, m) => sum + (typeof m?.content === 'string' ? m.content.length : 0), 0);
|
|
440
441
|
body[CANONICAL_IMAGE_COUNT] = built.images.length;
|
|
442
|
+
Object.defineProperty(body, CANONICAL_BUILT, {
|
|
443
|
+
value: Object.freeze({
|
|
444
|
+
messages: built.messages,
|
|
445
|
+
images: built.images,
|
|
446
|
+
toolCount: built.toolCount,
|
|
447
|
+
allowAutoModel,
|
|
448
|
+
}),
|
|
449
|
+
enumerable: false,
|
|
450
|
+
});
|
|
441
451
|
return body;
|
|
442
452
|
}
|
|
443
453
|
|
|
@@ -688,7 +698,7 @@ export function writeChatResponse(res, result, { stream = false, includeUsage =
|
|
|
688
698
|
return;
|
|
689
699
|
}
|
|
690
700
|
res.writeHead(200, { ...streamHeaders, ...thinkingHeaders(result) });
|
|
691
|
-
const send = (delta, finish_reason = null) => res.write('data: ' + JSON.stringify({ ...base, ...(finish_reason && result.nativeSearch ? {native_search: result.nativeSearch} : {}), choices: [{ index: 0, delta, finish_reason }], ...(includeUsage ? { usage:
|
|
701
|
+
const send = (delta, finish_reason = null) => res.write('data: ' + JSON.stringify({ ...base, ...(finish_reason && result.nativeSearch ? {native_search: result.nativeSearch} : {}), choices: [{ index: 0, delta, finish_reason }], ...(includeUsage ? { usage: null } : {}) }) + '\n\n');
|
|
692
702
|
send({ role: 'assistant' });
|
|
693
703
|
if (result.content) send({ content: result.content });
|
|
694
704
|
result.calls.forEach((call, index) => send({ tool_calls: [{ index, ...call }] }));
|