opencode-gemini-app 0.0.0-stage → 0.1.0
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/DISCLAIMER.md +17 -0
- package/LICENSE +21 -0
- package/README.md +44 -2
- package/extensions/opencode/auth.js +324 -0
- package/extensions/opencode/fetch.js +494 -0
- package/extensions/opencode/index.js +27 -0
- package/extensions/opencode/models.js +84 -0
- package/extensions/pi/auth.js +215 -0
- package/native-wire/consumer-tool-codec.mjs +239 -0
- package/native-wire/oauth-loopback.mjs +175 -0
- package/native-wire/protobuf.mjs +133 -0
- package/native-wire/robin-current.mjs +172 -0
- package/package.json +75 -4
- package/src/gateway/automatic-recovery.mjs +64 -0
- package/src/gateway/image-download.mjs +110 -0
- package/src/gateway/image-upload.mjs +219 -0
- package/src/gateway/native-diagnostic.mjs +189 -0
- package/src/gateway/native-evidence.mjs +113 -0
- package/src/gateway/native-response-limits.mjs +8 -0
- package/src/gateway/native-search-citations.mjs +196 -0
- package/src/gateway/native-search-diagnostic.mjs +282 -0
- package/src/gateway/native-search-metadata.mjs +749 -0
- package/src/gateway/native-transport.mjs +375 -0
- package/src/gateway/oauth-client-defaults.mjs +12 -0
- package/src/gateway/oauth-identity.mjs +67 -0
- package/src/gateway/outbound-proxy.mjs +320 -0
- package/src/gateway/output-recovery.mjs +48 -0
- package/src/gateway/quota-failover.mjs +14 -0
- package/src/gateway/quota-transport.mjs +37 -0
- package/src/gateway/quota.mjs +181 -0
- package/src/gateway/soft-error.mjs +25 -0
- package/src/gateway/structured-output.mjs +157 -0
- package/src/gateway/subscription.mjs +51 -0
- package/src/gateway/terms.mjs +126 -0
- package/src/image-input.mjs +137 -0
- package/src/image-url.mjs +21 -0
- package/src/native-provider.mjs +681 -0
- package/src/openai-contract.mjs +576 -0
- package/src/openai-usage.mjs +66 -0
- package/src/prompt-tool-schema.mjs +391 -0
- package/src/responses-tool-namespaces.mjs +84 -0
- package/src/tool-protocol.mjs +348 -0
|
@@ -0,0 +1,681 @@
|
|
|
1
|
+
/** Product direct provider: one bounded native turn, no retries, execution or
|
|
2
|
+
* unverified output. Full history replay only: continuation is intentionally OFF
|
|
3
|
+
* and continuation:true is rejected until an owner/session-bound design exists.
|
|
4
|
+
* This does not change the legacy provider, shared codecs or research transport.
|
|
5
|
+
*/
|
|
6
|
+
import crypto from 'node:crypto';
|
|
7
|
+
import { parse } from '../native-wire/protobuf.mjs';
|
|
8
|
+
import { decodeClientGenerateResponse } from '../native-wire/robin-current.mjs';
|
|
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';
|
|
11
|
+
import { RESPONSE_TOOL_IDENTITIES } from './responses-tool-namespaces.mjs';
|
|
12
|
+
import { safeNativeEvidence } from './gateway/native-evidence.mjs';
|
|
13
|
+
import { decodePassiveQuota, mergeQuotaObservation } from './gateway/quota.mjs';
|
|
14
|
+
import { uploadNativeImages, createImageBlobCache } from './gateway/image-upload.mjs';
|
|
15
|
+
import { downloadRemoteImages } from './gateway/image-download.mjs';
|
|
16
|
+
import { quotaDowngradeCode } from './gateway/quota-failover.mjs';
|
|
17
|
+
import { inspectNativeOutput } from './gateway/output-recovery.mjs';
|
|
18
|
+
import { toolRecoveryInstruction } from './gateway/automatic-recovery.mjs';
|
|
19
|
+
import { validateStructuredOutputText } from './gateway/structured-output.mjs';
|
|
20
|
+
import { mapNativeSearchAnnotations, extractNativeSearchSources } from './gateway/native-search-citations.mjs';
|
|
21
|
+
import { softErrorReason } from './gateway/soft-error.mjs';
|
|
22
|
+
import { observeNative } from './gateway/native-diagnostic.mjs';
|
|
23
|
+
export { MODEL_ALIASES, MODEL_SPECS, NATIVE_MODELS, canonicalModel, normalizeChatRequest, normalizeResponsesRequest, writeChatResponse, writeResponsesResponse };
|
|
24
|
+
|
|
25
|
+
import { NATIVE_RESPONSE_LIMITS as RESPONSE_LIMITS } from './gateway/native-response-limits.mjs';
|
|
26
|
+
const fail = (code, status = 502) => { throw protocolError(code, status); };
|
|
27
|
+
// Diagnosis only: identifies which guard produced a non-monotonic failure. Byte counts
|
|
28
|
+
// and booleans travel with the error; no text and no identifiers.
|
|
29
|
+
const commonPrefixBytes = (prior, next) => {
|
|
30
|
+
const limit = Math.min(prior.length, next.length);
|
|
31
|
+
let i = 0;
|
|
32
|
+
while (i < limit && prior.charCodeAt(i) === next.charCodeAt(i)) i++;
|
|
33
|
+
return Buffer.byteLength(prior.slice(0, i));
|
|
34
|
+
};
|
|
35
|
+
const failWithEvidence = (code, evidence) => {
|
|
36
|
+
throw Object.assign(protocolError(code, 502), { nativeEvidence: evidence });
|
|
37
|
+
};
|
|
38
|
+
const utf8 = new TextDecoder('utf-8', { fatal: true });
|
|
39
|
+
const HYDROGEN_ATTRIBUTION = /\bhydrogen\b/i;
|
|
40
|
+
const NEON_ATTRIBUTION = /\bneon\b/i;
|
|
41
|
+
function one(fields, number) {
|
|
42
|
+
const found = fields.filter(field => field.number === number);
|
|
43
|
+
if (found.length > 1) fail('INVALID_NATIVE_RESPONSE');
|
|
44
|
+
return found[0];
|
|
45
|
+
}
|
|
46
|
+
function frameInfo(bytes) {
|
|
47
|
+
if (!Buffer.isBuffer(bytes) || bytes.length > RESPONSE_LIMITS.frameBytes) fail('INVALID_NATIVE_RESPONSE');
|
|
48
|
+
const wrapper = one(parse(bytes), 1003);
|
|
49
|
+
if (!wrapper) return null; // Opaque continuation handles deliberately ignored.
|
|
50
|
+
const client = one(parse(wrapper.payload), 1);
|
|
51
|
+
if (!client) return null;
|
|
52
|
+
const fields = parse(client.payload);
|
|
53
|
+
// Ambiguous evidence must not be resolved by a decoder's first/last field rule.
|
|
54
|
+
for (const n of [1, 9, 11, 30, 31, 41, 42]) one(fields, n);
|
|
55
|
+
const attribution = one(fields, 30);
|
|
56
|
+
if (attribution) {
|
|
57
|
+
if (attribution.wire !== 2 || attribution.payload.length > 4096) fail('INVALID_NATIVE_RESPONSE');
|
|
58
|
+
try { utf8.decode(attribution.payload); } catch { fail('INVALID_NATIVE_RESPONSE'); }
|
|
59
|
+
}
|
|
60
|
+
const info = decodeClientGenerateResponse(client.payload);
|
|
61
|
+
if (info.hasToolOperations) fail('UNSUPPORTED_NATIVE_TOOL_EVENT');
|
|
62
|
+
for (const n of [9, 11]) {
|
|
63
|
+
const flag = one(fields, n);
|
|
64
|
+
if (flag && (flag.wire !== 0 || flag.payload.length !== 1 || flag.payload[0] > 1)) fail('INVALID_NATIVE_RESPONSE');
|
|
65
|
+
}
|
|
66
|
+
info.text = null;
|
|
67
|
+
info.responseId = null;
|
|
68
|
+
const model = one(fields, 1);
|
|
69
|
+
if (model) {
|
|
70
|
+
const modelFields = parse(model.payload);
|
|
71
|
+
const responseId = one(modelFields, 1);
|
|
72
|
+
if (responseId) {
|
|
73
|
+
if (responseId.wire !== 2 || responseId.payload.length > 4096) fail('INVALID_NATIVE_RESPONSE');
|
|
74
|
+
info.responseId = utf8.decode(responseId.payload);
|
|
75
|
+
}
|
|
76
|
+
const display = one(modelFields, 2);
|
|
77
|
+
if (display) {
|
|
78
|
+
const text = one(parse(display.payload), 1);
|
|
79
|
+
if (text) info.text = utf8.decode(text.payload);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
info.outputShape = inspectNativeOutput(fields);
|
|
83
|
+
info.quotaObservation = decodePassiveQuota(client.payload);
|
|
84
|
+
return info;
|
|
85
|
+
}
|
|
86
|
+
const TRANSPORT_ERRORS = new Set(['NATIVE_CONNECTION_FAILED', 'NATIVE_STREAM_FAILED', 'NATIVE_STREAM_RESET', 'NATIVE_STREAM_CLOSED_EARLY', 'NATIVE_HTTP_REJECTED', 'NATIVE_INVALID_STATUS', 'NATIVE_RECEIVE_LIMIT', 'NATIVE_FRAME_REJECTED', 'NATIVE_READER_BUSY']);
|
|
87
|
+
function safeFailure(error) {
|
|
88
|
+
if (error instanceof ProtocolError) return error;
|
|
89
|
+
if (error?.code === 'NATIVE_QUOTA_EXHAUSTED') return protocolError('NATIVE_QUOTA_EXHAUSTED', 429);
|
|
90
|
+
if (error?.code === 'NATIVE_PERMISSION_OR_AUTH') return protocolError('NATIVE_PERMISSION_OR_AUTH', 403);
|
|
91
|
+
if (error?.code === 'NATIVE_CREDENTIAL_REQUIRED') return protocolError('NATIVE_CREDENTIAL_REQUIRED', 503);
|
|
92
|
+
if (error?.code === 'NATIVE_UPSTREAM_UNAVAILABLE') return protocolError('NATIVE_UPSTREAM_UNAVAILABLE', 503);
|
|
93
|
+
if (error?.code === 'ACCOUNT_LOGIN_REQUIRED') return protocolError('ACCOUNT_LOGIN_REQUIRED', 401);
|
|
94
|
+
if (error?.code === 'OAUTH_REFRESH_FAILED') return protocolError('OAUTH_REFRESH_FAILED', 502);
|
|
95
|
+
if (error?.code === 'REQUEST_CANCELLED') return protocolError('NATIVE_TURN_ABORTED', 499);
|
|
96
|
+
if (error?.code === 'NATIVE_TRANSPORT_ABORTED' || error?.name === 'AbortError') return protocolError('NATIVE_TURN_ABORTED', 499);
|
|
97
|
+
if (error?.code === 'NATIVE_TRANSPORT_TIMEOUT' || error?.code === 'NATIVE_TURN_TIMEOUT') return protocolError('NATIVE_TURN_TIMEOUT', 504);
|
|
98
|
+
if (error?.code === 'RESPONSE_TOO_LARGE') return protocolError('RESPONSE_TOO_LARGE', 502);
|
|
99
|
+
return protocolError(TRANSPORT_ERRORS.has(error?.code) ? error.code : 'NATIVE_TURN_FAILED', 502);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
const validateIdleMs = (value, name) => {
|
|
104
|
+
if (value === null || value === undefined) return null;
|
|
105
|
+
if (!Number.isInteger(value) || value < 1 || value > 600_000) throw new TypeError(`invalid ${name}`);
|
|
106
|
+
return value;
|
|
107
|
+
};
|
|
108
|
+
const IDLE_TIMEOUT_SENTINEL = Symbol('IDLE_TIMEOUT_SENTINEL');
|
|
109
|
+
|
|
110
|
+
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 } = {}) {
|
|
112
|
+
if (!authManager || typeof authManager.getValidAccessToken !== 'function') throw new TypeError('authManager.getValidAccessToken required');
|
|
113
|
+
if (typeof openTurn !== 'function') throw new TypeError('openTurn required');
|
|
114
|
+
if (typeof uploadImages !== 'function') throw new TypeError('uploadImages required');
|
|
115
|
+
if (typeof downloadImages !== 'function') throw new TypeError('downloadImages required');
|
|
116
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 600_000) throw new TypeError('invalid timeout');
|
|
117
|
+
const resolvedPostCompleteGraceMs = validateIdleMs(postCompleteGraceMs, 'postCompleteGraceMs');
|
|
118
|
+
const resolvedPostToolIdleMs = validateIdleMs(postToolIdleMs, 'postToolIdleMs');
|
|
119
|
+
const resolvedPostOutputIdleMs = validateIdleMs(postOutputIdleMs, 'postOutputIdleMs');
|
|
120
|
+
if (continuation !== false) throw protocolError('UNSUPPORTED_CONTINUATION', 400);
|
|
121
|
+
if (typeof allowAutoModel !== 'boolean') throw new TypeError('invalid auto model policy');
|
|
122
|
+
const resolvedAlias = canonicalModel(modelAlias);
|
|
123
|
+
const allowedModels = allowAutoModel ? [...NATIVE_MODELS, 'gemini-auto'] : NATIVE_MODELS;
|
|
124
|
+
if (!allowedModels.includes(resolvedAlias)) throw protocolError('UNSUPPORTED_MODEL', 400);
|
|
125
|
+
this.authManager = authManager; this.openTurn = openTurn; this.uploadImages = uploadImages; this.timeoutMs = timeoutMs;
|
|
126
|
+
this.postCompleteGraceMs = resolvedPostCompleteGraceMs;
|
|
127
|
+
this.postToolIdleMs = resolvedPostToolIdleMs;
|
|
128
|
+
this.postOutputIdleMs = resolvedPostOutputIdleMs;
|
|
129
|
+
this.downloadImages = downloadImages;
|
|
130
|
+
this.blobCache = blobCache ?? null;
|
|
131
|
+
if (typeof allowTextSnapshotReplacement !== 'boolean') throw new TypeError('invalid snapshot policy');
|
|
132
|
+
this.allowTextSnapshotReplacement = allowTextSnapshotReplacement;
|
|
133
|
+
this.allowAutoModel = allowAutoModel;
|
|
134
|
+
this.modelAlias = resolvedAlias; this.continuationEnabled = false;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async #resolveImageAttachments(accountId, token, images, { signal, timeoutMs, bypassCache = false } = {}) {
|
|
138
|
+
if (!images.length) return { attachments: [], usedCachedKeys: [] };
|
|
139
|
+
const uploadTimeoutMs = Math.min(timeoutMs, 180000);
|
|
140
|
+
const cache = !bypassCache ? this.blobCache : null;
|
|
141
|
+
const scope = `${accountId}:${crypto.createHash('sha256').update(String(token)).digest('hex').slice(0, 16)}`;
|
|
142
|
+
const keys = images.map(img => (this.blobCache && Buffer.isBuffer(img.data) ? this.blobCache.keyOf(scope, img.mimeType, img.data) : null));
|
|
143
|
+
const attachments = new Array(images.length);
|
|
144
|
+
const usedCachedKeys = [];
|
|
145
|
+
const missImages = [];
|
|
146
|
+
const missKeyToSlot = new Map();
|
|
147
|
+
const missSlotIndices = [];
|
|
148
|
+
for (let i = 0; i < images.length; i++) {
|
|
149
|
+
const key = keys[i];
|
|
150
|
+
const cached = cache && key ? cache.get(key) : null;
|
|
151
|
+
if (cached && cached.mimeType === images[i].mimeType) {
|
|
152
|
+
attachments[i] = cached;
|
|
153
|
+
usedCachedKeys.push(key);
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
if (key && missKeyToSlot.has(key)) {
|
|
157
|
+
missSlotIndices[missKeyToSlot.get(key)].push(i);
|
|
158
|
+
} else {
|
|
159
|
+
const slot = missImages.length;
|
|
160
|
+
if (key) missKeyToSlot.set(key, slot);
|
|
161
|
+
missImages.push(images[i]);
|
|
162
|
+
missSlotIndices.push([i]);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
if (missImages.length) {
|
|
166
|
+
const uploaded = await this.uploadImages(token, missImages, { signal, timeoutMs: uploadTimeoutMs });
|
|
167
|
+
if (
|
|
168
|
+
!Array.isArray(uploaded) ||
|
|
169
|
+
uploaded.length !== missImages.length ||
|
|
170
|
+
uploaded.some((attachment, index) => attachment?.mimeType !== missImages[index].mimeType || typeof attachment.blobId !== 'string' || !attachment.blobId.length)
|
|
171
|
+
) {
|
|
172
|
+
fail('INVALID_NATIVE_IMAGE_UPLOAD');
|
|
173
|
+
}
|
|
174
|
+
for (let slot = 0; slot < uploaded.length; slot++) {
|
|
175
|
+
const item = uploaded[slot];
|
|
176
|
+
for (const targetIndex of missSlotIndices[slot]) {
|
|
177
|
+
attachments[targetIndex] = item;
|
|
178
|
+
const key = keys[targetIndex];
|
|
179
|
+
if (this.blobCache && key) this.blobCache.set(key, item);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return { attachments, usedCachedKeys };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
buildTurn(body) { return buildCanonicalPrompt(normalizeChatRequest(body, { allowAutoModel: this.allowAutoModel })); }
|
|
187
|
+
|
|
188
|
+
async runNativeSearch(accountId, body, onDelta, context) {
|
|
189
|
+
const timeoutMs = context.timeoutMs ?? this.timeoutMs;
|
|
190
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 600000) fail('INVALID_TIMEOUT', 400);
|
|
191
|
+
// Dynamic import avoids initialization recursion; diagnostic's inner turn has no native_search flag.
|
|
192
|
+
const { runNativeSearchDiagnostic } = await import('./gateway/native-search-diagnostic.mjs');
|
|
193
|
+
const { messages } = buildCanonicalPrompt(body);
|
|
194
|
+
const report = await runNativeSearchDiagnostic({
|
|
195
|
+
getAccessToken: () => this.authManager.getValidAccessToken(accountId),
|
|
196
|
+
openTurn: this.openTurn, query: messages[0].content,
|
|
197
|
+
allowNativeTools: true, timeoutMs: Math.min(timeoutMs, 180000), signal: context.signal,
|
|
198
|
+
});
|
|
199
|
+
if (!report.ok) {
|
|
200
|
+
const status = ['NATIVE_RATE_LIMITED','NATIVE_QUOTA_EXHAUSTED'].includes(report.errorCode) ? 429
|
|
201
|
+
: ['NATIVE_CREDENTIAL_REQUIRED', 'NATIVE_UPSTREAM_UNAVAILABLE'].includes(report.errorCode) ? 503
|
|
202
|
+
: report.errorCode === 'NATIVE_TURN_TIMEOUT' ? 504
|
|
203
|
+
: report.errorCode === 'NATIVE_TURN_ABORTED' ? 499
|
|
204
|
+
: report.errorCode === 'ACCOUNT_LOGIN_REQUIRED' ? 401
|
|
205
|
+
: report.errorCode === 'NATIVE_PERMISSION_OR_AUTH' ? 403 : 502;
|
|
206
|
+
const error = protocolError(report.errorCode, status);
|
|
207
|
+
if (report.nativeEvidence) error.nativeEvidence = report.nativeEvidence;
|
|
208
|
+
throw error;
|
|
209
|
+
}
|
|
210
|
+
if (report.otherToolStatusCount) fail('UNSUPPORTED_NATIVE_TOOL_REPORT');
|
|
211
|
+
if (!report.googleToolReported) fail('NATIVE_SEARCH_NOT_OBSERVED');
|
|
212
|
+
const annotations = mapNativeSearchAnnotations(report.answer, report);
|
|
213
|
+
const sources = extractNativeSearchSources(report);
|
|
214
|
+
const result = {
|
|
215
|
+
id: 'chatcmpl-' + crypto.randomBytes(16).toString('hex'), created: Math.floor(Date.now()/1000),
|
|
216
|
+
model: body.model, resolvedModeCategory: report.resolvedModeCategory,
|
|
217
|
+
content: report.answer, calls: [],
|
|
218
|
+
...(annotations.length ? { annotations } : {}),
|
|
219
|
+
thinkingLevel: report.thinkingLevel,
|
|
220
|
+
requestedThinkingLevel: body.thinking_level, continued: false,
|
|
221
|
+
nativeSearch: {
|
|
222
|
+
provider: 'gemini', evidence: 'upstream_final_tool_invocation', googleToolReported: true,
|
|
223
|
+
googleToolStatusCount: report.googleToolStatusCount,
|
|
224
|
+
googleFinalInvocationCount: report.googleFinalInvocationCount,
|
|
225
|
+
revisionCount: report.revisionCount, structuredCitationCount: report.citationCount,
|
|
226
|
+
structuredSourceCount: report.webSourceCount,
|
|
227
|
+
mappedAnnotationCount: annotations.length,
|
|
228
|
+
sources,
|
|
229
|
+
sourceFormat: annotations.length ? 'url_citation_annotations' : 'answer_text; no_public_web_annotations',
|
|
230
|
+
},
|
|
231
|
+
};
|
|
232
|
+
const effort = body.reasoning_effort ?? body.reasoning?.effort;
|
|
233
|
+
if (effort !== undefined) result.requestedReasoningEffort = effort;
|
|
234
|
+
result.ignoredTokenParameters = ['max_tokens', 'max_completion_tokens'].filter(key => body[key] !== undefined);
|
|
235
|
+
if (report.quotaObservation) result.quotaObservation = report.quotaObservation;
|
|
236
|
+
await onDelta({ content: result.content, response: result });
|
|
237
|
+
return result;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** Product callers opt into incremental output; terminal validation still determines completion. */
|
|
241
|
+
async runTurn(accountId, canonicalChatBody, onDelta = () => {}, context = {}) {
|
|
242
|
+
const timeoutMs = context.timeoutMs ?? this.timeoutMs;
|
|
243
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 600000) fail('INVALID_TIMEOUT', 400);
|
|
244
|
+
const postCompleteGraceMs = context.postCompleteGraceMs === undefined
|
|
245
|
+
? this.postCompleteGraceMs
|
|
246
|
+
: validateIdleMs(context.postCompleteGraceMs, 'postCompleteGraceMs');
|
|
247
|
+
const postToolIdleMs = context.postToolIdleMs === undefined
|
|
248
|
+
? this.postToolIdleMs
|
|
249
|
+
: validateIdleMs(context.postToolIdleMs, 'postToolIdleMs');
|
|
250
|
+
const postOutputIdleMs = context.postOutputIdleMs === undefined
|
|
251
|
+
? this.postOutputIdleMs
|
|
252
|
+
: validateIdleMs(context.postOutputIdleMs, 'postOutputIdleMs');
|
|
253
|
+
const body = normalizeChatRequest(canonicalChatBody, { allowAutoModel: this.allowAutoModel });
|
|
254
|
+
if (body.native_search) return this.runNativeSearch(accountId, body, onDelta, { ...context, timeoutMs });
|
|
255
|
+
const recoveryInstruction = toolRecoveryInstruction(context.recoveryCode);
|
|
256
|
+
if (recoveryInstruction) body.messages = [...body.messages, { role: 'system', content: recoveryInstruction }];
|
|
257
|
+
if (this.allowTextSnapshotReplacement && body.tools.length) fail('NATIVE_TEXT_SNAPSHOT_TOOLS_FORBIDDEN', 400);
|
|
258
|
+
const policy = compileToolPolicy(body.tools, body.tool_choice);
|
|
259
|
+
let { messages, images } = buildCanonicalPrompt(body);
|
|
260
|
+
const isAutoModel = this.allowAutoModel && body.model === 'gemini-auto';
|
|
261
|
+
const modeCategory = isAutoModel ? null : MODEL_MODES[body.model];
|
|
262
|
+
const modeMatches = mode => isAutoModel
|
|
263
|
+
? (mode === null || (Number.isSafeInteger(mode) && mode >= 0 && mode <= 64))
|
|
264
|
+
: mode === modeCategory;
|
|
265
|
+
if (context.signal?.aborted) fail('NATIVE_TURN_ABORTED', 499);
|
|
266
|
+
const controller = new AbortController();
|
|
267
|
+
const note = (name, values) => observeNative(context.nativeDiagnostic, 'event', name, values);
|
|
268
|
+
let turn, iterator, timer, rejectDeadline;
|
|
269
|
+
const deadline = new Promise((_, reject) => { rejectDeadline = reject; });
|
|
270
|
+
const stop = error => {
|
|
271
|
+
note('provider_stop', { code: error?.code });
|
|
272
|
+
rejectDeadline(error);
|
|
273
|
+
controller.abort();
|
|
274
|
+
try { turn?.cancel(); } catch {}
|
|
275
|
+
};
|
|
276
|
+
const abort = () => stop(context.signal?.reason?.code === 'REQUEST_DEADLINE'
|
|
277
|
+
? protocolError('NATIVE_TURN_TIMEOUT', 504) : protocolError('NATIVE_TURN_ABORTED', 499));
|
|
278
|
+
context.signal?.addEventListener('abort', abort, { once: true });
|
|
279
|
+
timer = setTimeout(() => stop(protocolError('NATIVE_TURN_TIMEOUT', 504)), timeoutMs);
|
|
280
|
+
const bounded = promise => Promise.race([promise, deadline]);
|
|
281
|
+
const requiresHydrogen = body.model === 'gemini-hydrogen';
|
|
282
|
+
const requiresNeon = body.model === 'gemini-neon';
|
|
283
|
+
let rawText = '', frames = 0, received = 0, observedMode = null, observedThinking = null;
|
|
284
|
+
let modelComplete = false, ended = false, grpc = null, httpStatus = null, downgrade = false, phase = 'auth';
|
|
285
|
+
let observedFallback = null, downgradeReason = null, observedAttribution = null;
|
|
286
|
+
const attributionMatches = value => (!requiresHydrogen || HYDROGEN_ATTRIBUTION.test(value ?? '')) && (!requiresNeon || NEON_ATTRIBUTION.test(value ?? ''));
|
|
287
|
+
const attributionVerified = () => attributionMatches(observedAttribution);
|
|
288
|
+
let snapshotId = null, revisionCount = 0, quotaObservation = null, quotaFrames = 0;
|
|
289
|
+
let emptyResponseReason = null, outputObserved = false, responseLimitReason = null, outputFailureReason = null;
|
|
290
|
+
const outputShape = { nativeShareableTextBytes: 0, nativeThoughtsPresent: false, nativeStructuredOutputPresent: false, nativeRefusalPresent: false };
|
|
291
|
+
const incremental = context.incrementalOutput === true && !body.response_format;
|
|
292
|
+
const identity = { id: 'chatcmpl-' + crypto.randomBytes(16).toString('hex'), created: Math.floor(Date.now() / 1000), model: body.model,
|
|
293
|
+
[RESPONSE_TOOL_IDENTITIES]: body[RESPONSE_TOOL_IDENTITIES],
|
|
294
|
+
requestedThinkingLevel: body.thinking_level, ignoredTokenParameters: ['max_tokens', 'max_completion_tokens'].filter(key => body[key] !== undefined),
|
|
295
|
+
...((body.reasoning_effort ?? body.reasoning?.effort) === undefined ? {} : { requestedReasoningEffort: body.reasoning_effort ?? body.reasoning?.effort }) };
|
|
296
|
+
let liveSplitter = incremental ? createToolCallSplitter({ policy }) : null, liveItems = [], liveContent = '', liveCalls = [], publishedContent = '', publishedCalls = 0, liveSyncedLength = 0, sinkFailed = false;
|
|
297
|
+
const deliver = async event => {
|
|
298
|
+
try { await onDelta(event); }
|
|
299
|
+
catch (error) { sinkFailed = true; throw error; }
|
|
300
|
+
};
|
|
301
|
+
// The sink owns the commit boundary: provider-published text may still be held.
|
|
302
|
+
// Missing/invalid feedback is conservative for streaming callers.
|
|
303
|
+
const committedOutput = () => {
|
|
304
|
+
if (typeof context.getOutputCommitState === 'function') try {
|
|
305
|
+
const state = context.getOutputCommitState();
|
|
306
|
+
if (Number.isSafeInteger(state?.publishedBytes) && state.publishedBytes >= 0 &&
|
|
307
|
+
Number.isSafeInteger(state?.toolCallCount) && state.toolCallCount >= 0) return state;
|
|
308
|
+
} catch { /* Fall back to the stricter provider-published boundary. */ }
|
|
309
|
+
return context.outputMode === 'buffered' ? { publishedBytes: 0, toolCallCount: 0 }
|
|
310
|
+
: { publishedBytes: Buffer.byteLength(publishedContent), toolCallCount: publishedCalls };
|
|
311
|
+
};
|
|
312
|
+
const publish = async items => {
|
|
313
|
+
for (const item of items) { liveItems.push(item); if (item.type === 'content') liveContent += item.text; else liveCalls.push(item.call); }
|
|
314
|
+
const text = liveContent + liveSplitter.preview();
|
|
315
|
+
if (!text.startsWith(publishedContent)) {
|
|
316
|
+
const committed = committedOutput();
|
|
317
|
+
if (snapshotId === null || committed.publishedBytes || committed.toolCallCount) failWithEvidence('NON_MONOTONIC_NATIVE_RESPONSE', {
|
|
318
|
+
phase: 'output', nonMonotonicSite: 'provider_publish', sameResponseIdentity: snapshotId !== null,
|
|
319
|
+
snapshotPriorBytes: Buffer.byteLength(publishedContent), snapshotNextBytes: Buffer.byteLength(text),
|
|
320
|
+
snapshotCommonPrefixBytes: commonPrefixBytes(publishedContent, text), ...committed });
|
|
321
|
+
await deliver({ reset: true, sameResponseIdentity: true, response: identity });
|
|
322
|
+
publishedContent = ''; publishedCalls = 0;
|
|
323
|
+
}
|
|
324
|
+
if (text.length > publishedContent.length) {
|
|
325
|
+
const content = text.slice(publishedContent.length);
|
|
326
|
+
await deliver({ content, response: { ...identity, thinkingLevel: observedThinking } });
|
|
327
|
+
publishedContent = text;
|
|
328
|
+
}
|
|
329
|
+
while (publishedCalls < liveCalls.length) {
|
|
330
|
+
if (body.parallel_tool_calls === false && publishedCalls >= 1) fail('PARALLEL_TOOL_CALLS_DISABLED');
|
|
331
|
+
const call = liveCalls[publishedCalls];
|
|
332
|
+
await deliver({ call, response: { ...identity, thinkingLevel: observedThinking } });
|
|
333
|
+
publishedCalls++;
|
|
334
|
+
}
|
|
335
|
+
};
|
|
336
|
+
try {
|
|
337
|
+
if (images.some(image => image.url)) {
|
|
338
|
+
phase = 'upload';
|
|
339
|
+
images = await bounded(this.downloadImages(images, { signal: controller.signal, timeoutMs: Math.min(timeoutMs, 30000) }));
|
|
340
|
+
({ messages, images } = buildCanonicalPrompt(body, images));
|
|
341
|
+
}
|
|
342
|
+
phase = 'auth';
|
|
343
|
+
let token;
|
|
344
|
+
try { token = await bounded(this.authManager.getValidAccessToken(accountId, { accountTest: context.accountTest === true })); }
|
|
345
|
+
catch (error) { if (error instanceof ProtocolError || ['NATIVE_PERMISSION_OR_AUTH','NATIVE_CREDENTIAL_REQUIRED','OAUTH_REFRESH_FAILED','ACCOUNT_LOGIN_REQUIRED'].includes(error?.code)) throw safeFailure(error); fail('NATIVE_AUTH_FAILED', 503); }
|
|
346
|
+
if (controller.signal.aborted) await deadline;
|
|
347
|
+
phase = 'upload';
|
|
348
|
+
let { attachments, usedCachedKeys } = await bounded(this.#resolveImageAttachments(accountId, token, images, { signal: controller.signal, timeoutMs }));
|
|
349
|
+
if (controller.signal.aborted) await deadline;
|
|
350
|
+
// The product injects its independent transport; historical research ledgers are untouched.
|
|
351
|
+
const STALE_BLOB_CODES = new Set(['NATIVE_HTTP_REJECTED', 'NATIVE_INVALID_STATUS', 'NATIVE_PRECONDITION_REQUIRED', 'NATIVE_TURN_FAILED']);
|
|
352
|
+
for (let blobAttempt = 0; ; blobAttempt++) {
|
|
353
|
+
phase = 'open';
|
|
354
|
+
turn = this.openTurn(token, { messages, images: attachments, temporaryChat: true,
|
|
355
|
+
modeCategory: isAutoModel ? null : modeCategory,
|
|
356
|
+
thinkingLevel: isAutoModel ? null : body.thinking_level,
|
|
357
|
+
...(isAutoModel ? { smartModelSelection: true } : {}),
|
|
358
|
+
timeoutMs, signal: controller.signal,
|
|
359
|
+
emitHeaders: incremental,
|
|
360
|
+
...(context.nativeDiagnostic ? { diagnostic: context.nativeDiagnostic } : {}) });
|
|
361
|
+
iterator = turn.events[Symbol.asyncIterator]();
|
|
362
|
+
try {
|
|
363
|
+
const isCleanPostOutputIdleStall = () => {
|
|
364
|
+
if (!rawText.trim()) return false;
|
|
365
|
+
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)) return false;
|
|
366
|
+
try {
|
|
367
|
+
const probe = createToolCallSplitter({ policy });
|
|
368
|
+
const probeItems = [...probe.push(rawText), ...probe.flush()];
|
|
369
|
+
const probeCalls = probeItems.filter(it => it.type === 'call').map(it => it.call);
|
|
370
|
+
const probeContent = probeItems.filter(it => it.type === 'content').map(it => it.text).join('');
|
|
371
|
+
if (!outputShape.nativeStructuredOutputPresent && softErrorReason(probeContent, body, probeCalls.length)) return false;
|
|
372
|
+
if (body.parallel_tool_calls === false && probeCalls.length > 1) return false;
|
|
373
|
+
validateToolCompletion(probeCalls, policy);
|
|
374
|
+
if (!probeCalls.length && !probeContent.trim()) return false;
|
|
375
|
+
if (body.response_format && !probeCalls.length) validateStructuredOutputText(probeContent, body.response_format);
|
|
376
|
+
return true;
|
|
377
|
+
} catch {
|
|
378
|
+
return false;
|
|
379
|
+
}
|
|
380
|
+
};
|
|
381
|
+
const nextEventWithIdle = async () => {
|
|
382
|
+
const verified = !downgrade && !outputShape.nativeRefusalPresent && modeMatches(observedMode) && attributionVerified();
|
|
383
|
+
// Never arm an idle timer unless we already have verified, complete, deliverable output;
|
|
384
|
+
// otherwise a slow mid-tool-call or mid-JSON pause would be falsely killed with 504 -> 422.
|
|
385
|
+
const idleKind = (modelComplete && verified && rawText.trim().length > 0) ? 'post_complete'
|
|
386
|
+
: (verified && liveCalls.length > 0 ? 'post_tool'
|
|
387
|
+
: (verified && liveCalls.length === 0 && isCleanPostOutputIdleStall() ? 'post_output' : null));
|
|
388
|
+
const idleMs = idleKind === 'post_complete' ? postCompleteGraceMs
|
|
389
|
+
: idleKind === 'post_tool' ? postToolIdleMs
|
|
390
|
+
: idleKind === 'post_output' ? postOutputIdleMs
|
|
391
|
+
: null;
|
|
392
|
+
const nextPromise = iterator.next();
|
|
393
|
+
if (idleMs === null) return bounded(nextPromise);
|
|
394
|
+
nextPromise.catch(() => {});
|
|
395
|
+
let idleTimer = null;
|
|
396
|
+
try {
|
|
397
|
+
return await Promise.race([
|
|
398
|
+
bounded(nextPromise),
|
|
399
|
+
new Promise(resolve => {
|
|
400
|
+
idleTimer = setTimeout(() => resolve({ [IDLE_TIMEOUT_SENTINEL]: idleKind, verified }), idleMs);
|
|
401
|
+
idleTimer.unref?.();
|
|
402
|
+
}),
|
|
403
|
+
]);
|
|
404
|
+
} finally {
|
|
405
|
+
if (idleTimer !== null) clearTimeout(idleTimer);
|
|
406
|
+
}
|
|
407
|
+
};
|
|
408
|
+
for (;;) {
|
|
409
|
+
phase = 'read';
|
|
410
|
+
const item = await nextEventWithIdle();
|
|
411
|
+
if (item && item[IDLE_TIMEOUT_SENTINEL]) {
|
|
412
|
+
const idleKind = item[IDLE_TIMEOUT_SENTINEL];
|
|
413
|
+
if (idleKind === 'post_complete' && item.verified && rawText.trim().length > 0) {
|
|
414
|
+
note('post_complete_idle_finish', { frames, textBytes: Buffer.byteLength(rawText) });
|
|
415
|
+
try { turn?.cancel(); } catch {}
|
|
416
|
+
ended = true;
|
|
417
|
+
httpStatus = httpStatus ?? 200;
|
|
418
|
+
grpc = grpc ?? 0;
|
|
419
|
+
break;
|
|
420
|
+
}
|
|
421
|
+
note(`${idleKind}_idle_timeout`, {
|
|
422
|
+
frames,
|
|
423
|
+
calls: liveCalls.length,
|
|
424
|
+
textBytes: Buffer.byteLength(rawText),
|
|
425
|
+
});
|
|
426
|
+
try { turn?.cancel(); } catch {}
|
|
427
|
+
const idleError = protocolError('NATIVE_TURN_TIMEOUT', 504);
|
|
428
|
+
if (idleKind === 'post_output' && item.verified && isCleanPostOutputIdleStall()) {
|
|
429
|
+
idleError.postOutputIdleStall = true;
|
|
430
|
+
}
|
|
431
|
+
throw idleError;
|
|
432
|
+
}
|
|
433
|
+
if (item.done) break;
|
|
434
|
+
const event = item.value;
|
|
435
|
+
if (incremental && event.type === 'headers') { await deliver({ start: true, response: identity }); continue; }
|
|
436
|
+
if (event.type === 'frame') {
|
|
437
|
+
frames++;
|
|
438
|
+
received += event.bytes?.length ?? RESPONSE_LIMITS.wireBytes + 1;
|
|
439
|
+
if (frames > RESPONSE_LIMITS.frames || received > RESPONSE_LIMITS.wireBytes) {
|
|
440
|
+
responseLimitReason = frames > RESPONSE_LIMITS.frames ? 'frame_count' : 'wire_bytes';
|
|
441
|
+
fail('NATIVE_RESPONSE_LIMIT');
|
|
442
|
+
}
|
|
443
|
+
phase = 'decode';
|
|
444
|
+
const info = frameInfo(event.bytes);
|
|
445
|
+
if (info?.outputShape) {
|
|
446
|
+
outputObserved = true;
|
|
447
|
+
outputShape.nativeShareableTextBytes = Math.max(outputShape.nativeShareableTextBytes, info.outputShape.nativeShareableTextBytes);
|
|
448
|
+
for (const key of ['nativeThoughtsPresent', 'nativeStructuredOutputPresent', 'nativeRefusalPresent']) outputShape[key] ||= info.outputShape[key];
|
|
449
|
+
if (info.outputShape.nativeCompletenessState !== undefined) outputShape.nativeCompletenessState = info.outputShape.nativeCompletenessState;
|
|
450
|
+
}
|
|
451
|
+
if (!info) continue;
|
|
452
|
+
observedFallback = info.fallback ?? observedFallback;
|
|
453
|
+
downgradeReason = info.downgradeReason ?? downgradeReason;
|
|
454
|
+
const frameMode = info.resolvedModeCategory;
|
|
455
|
+
const hasContentOrComplete = (info.text !== null && info.text.length > 0) || info.completed === true;
|
|
456
|
+
const frameResolved = (frameMode !== null && frameMode !== undefined && frameMode !== 0) || hasContentOrComplete;
|
|
457
|
+
if (frameMode !== null && frameMode !== undefined && (frameMode !== 0 || hasContentOrComplete || observedMode === null)) {
|
|
458
|
+
observedMode = frameMode;
|
|
459
|
+
}
|
|
460
|
+
if (frameResolved && info.attribution !== null && info.attribution.length > 0) {
|
|
461
|
+
observedAttribution = info.attribution;
|
|
462
|
+
if (!attributionMatches(info.attribution)) downgrade = true;
|
|
463
|
+
}
|
|
464
|
+
// Final generate evidence must name the requested mode unless auto selection is enabled.
|
|
465
|
+
// Prior proven rejection is sticky; an unresolved zero is not a proven downgrade.
|
|
466
|
+
if (!isAutoModel) {
|
|
467
|
+
if (observedMode !== null && observedMode !== 0 && observedMode !== modeCategory) downgrade = true;
|
|
468
|
+
if (info.fallback === 1 || (info.downgradeReason !== null && info.downgradeReason !== undefined && info.downgradeReason !== 0)) downgrade = true;
|
|
469
|
+
}
|
|
470
|
+
if (info.thinkingLevel !== null && info.thinkingLevel !== undefined) {
|
|
471
|
+
if (!Number.isSafeInteger(info.thinkingLevel) || info.thinkingLevel < 0 || info.thinkingLevel > 4) fail('INVALID_NATIVE_THINKING_LEVEL');
|
|
472
|
+
observedThinking = info.thinkingLevel;
|
|
473
|
+
}
|
|
474
|
+
modelComplete ||= info.completed;
|
|
475
|
+
// Stop as soon as a wrong model is proven; do not pay for a full
|
|
476
|
+
// downgraded answer that this gateway can never return as success.
|
|
477
|
+
if (downgrade) {
|
|
478
|
+
const quotaCode = quotaDowngradeCode(downgradeReason);
|
|
479
|
+
if (quotaCode) fail(quotaCode, 429);
|
|
480
|
+
fail('MODEL_DOWNGRADE_REJECTED');
|
|
481
|
+
}
|
|
482
|
+
if (outputShape.nativeRefusalPresent) fail('NATIVE_RESPONSE_REFUSED', 422);
|
|
483
|
+
if (info.text !== null) {
|
|
484
|
+
const id = info.responseId || null;
|
|
485
|
+
if (this.allowTextSnapshotReplacement && !id) fail('INVALID_NATIVE_RESPONSE');
|
|
486
|
+
if (snapshotId !== null && id !== snapshotId) fail('INVALID_NATIVE_RESPONSE');
|
|
487
|
+
const extendsPrior = info.text.startsWith(rawText);
|
|
488
|
+
if (!extendsPrior) {
|
|
489
|
+
const committed = committedOutput();
|
|
490
|
+
// Validate identity BEFORE asking the sink to discard any buffered data.
|
|
491
|
+
if (!id || snapshotId !== id) failWithEvidence('NON_MONOTONIC_NATIVE_RESPONSE', {
|
|
492
|
+
phase: 'decode', nonMonotonicSite: 'snapshot_identity', sameResponseIdentity: false,
|
|
493
|
+
snapshotPriorBytes: Buffer.byteLength(rawText), snapshotNextBytes: Buffer.byteLength(info.text),
|
|
494
|
+
snapshotCommonPrefixBytes: commonPrefixBytes(rawText, info.text), ...committed });
|
|
495
|
+
if (incremental) {
|
|
496
|
+
if (committed.publishedBytes || committed.toolCallCount) failWithEvidence('NON_MONOTONIC_NATIVE_RESPONSE', {
|
|
497
|
+
phase: 'decode', nonMonotonicSite: 'snapshot_stream', sameResponseIdentity: true,
|
|
498
|
+
snapshotPriorBytes: Buffer.byteLength(rawText), snapshotNextBytes: Buffer.byteLength(info.text),
|
|
499
|
+
snapshotCommonPrefixBytes: commonPrefixBytes(rawText, info.text), ...committed });
|
|
500
|
+
if (liveSyncedLength > 0) await deliver({ reset: true, sameResponseIdentity: true, response: identity });
|
|
501
|
+
liveSplitter = createToolCallSplitter({ policy }); liveItems = []; liveContent = ''; liveCalls = []; publishedContent = ''; publishedCalls = 0; liveSyncedLength = 0;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
if (id) snapshotId = id;
|
|
505
|
+
if (!extendsPrior) revisionCount++;
|
|
506
|
+
if (info.text !== rawText) modelComplete = info.completed;
|
|
507
|
+
rawText = info.text;
|
|
508
|
+
} else if (snapshotId !== null && info.responseId && info.responseId !== snapshotId) {
|
|
509
|
+
fail('INVALID_NATIVE_RESPONSE');
|
|
510
|
+
}
|
|
511
|
+
if (incremental && modeMatches(observedMode) && attributionVerified() && liveSyncedLength < rawText.length) {
|
|
512
|
+
const delta = rawText.slice(liveSyncedLength);
|
|
513
|
+
liveSyncedLength = rawText.length;
|
|
514
|
+
await publish(liveSplitter.push(delta));
|
|
515
|
+
// Once valid tool_call(s) have been parsed and the model begins hallucinating
|
|
516
|
+
// a fake [Caller tool result], stop upstream immediately instead of waiting
|
|
517
|
+
// minutes for the model to finish generating discarded text.
|
|
518
|
+
if (liveSplitter.suppressed && liveCalls.length > 0 && !downgrade && !outputShape.nativeRefusalPresent) {
|
|
519
|
+
note('early_stop_post_tool_hallucination', { calls: liveCalls.length });
|
|
520
|
+
try { turn?.cancel(); } catch {}
|
|
521
|
+
ended = true;
|
|
522
|
+
modelComplete = true;
|
|
523
|
+
httpStatus = httpStatus ?? 200;
|
|
524
|
+
grpc = grpc ?? 0;
|
|
525
|
+
break;
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
if (info.quotaObservation) {
|
|
529
|
+
quotaFrames++;
|
|
530
|
+
if (quotaFrames > 16) quotaObservation = null;
|
|
531
|
+
else if (info.quotaObservation.source === 'official') quotaObservation = mergeQuotaObservation(quotaObservation, info.quotaObservation);
|
|
532
|
+
}
|
|
533
|
+
} else if (event.type === 'end') {
|
|
534
|
+
phase = 'end'; ended = true; grpc = event.grpcStatus; httpStatus = event.httpStatus;
|
|
535
|
+
if (event.httpStatus === 429 || grpc === 8) fail('NATIVE_RATE_LIMITED', 429);
|
|
536
|
+
if (event.httpStatus === 401 || grpc === 16) fail('NATIVE_AUTH_REJECTED');
|
|
537
|
+
if (event.httpStatus === 403 || grpc === 7) fail('NATIVE_PERMISSION_REJECTED');
|
|
538
|
+
if (event.httpStatus === 200 && grpc === 9) fail('NATIVE_PRECONDITION_REQUIRED');
|
|
539
|
+
if (event.httpStatus === 503 || grpc === 14) fail('NATIVE_UPSTREAM_UNAVAILABLE', 503);
|
|
540
|
+
if (event.httpStatus !== 200 || (grpc !== null && grpc !== undefined && grpc !== 0)) fail('NATIVE_TURN_FAILED');
|
|
541
|
+
break;
|
|
542
|
+
} else fail('INVALID_NATIVE_EVENT');
|
|
543
|
+
}
|
|
544
|
+
break;
|
|
545
|
+
} catch (turnErr) {
|
|
546
|
+
const safeErr = safeFailure(turnErr);
|
|
547
|
+
const canRetryFreshBlobs =
|
|
548
|
+
blobAttempt === 0 &&
|
|
549
|
+
usedCachedKeys.length > 0 &&
|
|
550
|
+
frames === 0 &&
|
|
551
|
+
!outputObserved &&
|
|
552
|
+
!controller.signal.aborted &&
|
|
553
|
+
STALE_BLOB_CODES.has(safeErr.code);
|
|
554
|
+
if (!canRetryFreshBlobs) throw turnErr;
|
|
555
|
+
for (const key of usedCachedKeys) this.blobCache?.delete(key);
|
|
556
|
+
try { turn?.cancel(); } catch {}
|
|
557
|
+
turn = null; iterator = null; ended = false; grpc = null; httpStatus = null;
|
|
558
|
+
phase = 'upload';
|
|
559
|
+
({ attachments, usedCachedKeys } = await bounded(this.#resolveImageAttachments(accountId, token, images, { signal: controller.signal, timeoutMs, bypassCache: true })));
|
|
560
|
+
if (controller.signal.aborted) await deadline;
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
phase = 'validate';
|
|
564
|
+
if (downgrade) fail('MODEL_DOWNGRADE_REJECTED');
|
|
565
|
+
if (!ended) fail('INCOMPLETE_NATIVE_RESPONSE');
|
|
566
|
+
// An ordinary RPC close is not model completion. Async UI placeholders
|
|
567
|
+
// must be non-retryable or PI will repeatedly submit fresh generations.
|
|
568
|
+
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);
|
|
569
|
+
if (!modelComplete) fail('INCOMPLETE_NATIVE_RESPONSE');
|
|
570
|
+
if (!modeMatches(observedMode)) fail('MISSING_NATIVE_MODE_EVIDENCE');
|
|
571
|
+
if (!attributionVerified()) fail('MODEL_DOWNGRADE_REJECTED');
|
|
572
|
+
if (outputShape.nativeRefusalPresent) fail('NATIVE_RESPONSE_REFUSED', 422);
|
|
573
|
+
if (!rawText.trim()) {
|
|
574
|
+
if (outputShape.nativeShareableTextBytes || outputShape.nativeStructuredOutputPresent) fail('NATIVE_OUTPUT_NOT_TEXT', 422);
|
|
575
|
+
emptyResponseReason = rawText.length ? 'whitespace_only' : outputShape.nativeThoughtsPresent ? 'thoughts_only' : 'no_text';
|
|
576
|
+
fail('EMPTY_NATIVE_RESPONSE');
|
|
577
|
+
}
|
|
578
|
+
let items;
|
|
579
|
+
if (incremental) {
|
|
580
|
+
if (liveSyncedLength < rawText.length) {
|
|
581
|
+
const delta = rawText.slice(liveSyncedLength);
|
|
582
|
+
liveSyncedLength = rawText.length;
|
|
583
|
+
await publish(liveSplitter.push(delta));
|
|
584
|
+
}
|
|
585
|
+
await publish(liveSplitter.flush());
|
|
586
|
+
items = liveItems;
|
|
587
|
+
}
|
|
588
|
+
else { const splitter = createToolCallSplitter({ policy }); items = [...splitter.push(rawText), ...splitter.flush()]; }
|
|
589
|
+
const calls = items.filter(item => item.type === 'call').map(item => item.call);
|
|
590
|
+
let content = items.filter(item => item.type === 'content').map(item => item.text).join('');
|
|
591
|
+
if (!outputShape.nativeStructuredOutputPresent) {
|
|
592
|
+
outputFailureReason = softErrorReason(content, body, calls.length);
|
|
593
|
+
if (outputFailureReason) fail('NATIVE_SOFT_ERROR_RESPONSE');
|
|
594
|
+
}
|
|
595
|
+
if (body.parallel_tool_calls === false && calls.length > 1) fail('PARALLEL_TOOL_CALLS_DISABLED');
|
|
596
|
+
validateToolCompletion(calls, policy);
|
|
597
|
+
if (!calls.length && !content.trim()) { emptyResponseReason = 'post_parse_empty'; fail('EMPTY_NATIVE_RESPONSE'); }
|
|
598
|
+
if (body.response_format && !calls.length) {
|
|
599
|
+
content = validateStructuredOutputText(content, body.response_format);
|
|
600
|
+
}
|
|
601
|
+
const result = { ...identity, resolvedModeCategory: observedMode, ...(observedAttribution !== null ? { attribution: observedAttribution } : {}), content, calls, frames, thinkingLevel: observedThinking, continued: false };
|
|
602
|
+
const effort = body.reasoning_effort ?? body.reasoning?.effort;
|
|
603
|
+
if (effort !== undefined) result.requestedReasoningEffort = effort;
|
|
604
|
+
result.ignoredTokenParameters = ['max_tokens', 'max_completion_tokens'].filter(key => body[key] !== undefined);
|
|
605
|
+
if (quotaObservation) result.quotaObservation = { ...quotaObservation, observedModel: body.model };
|
|
606
|
+
if (snapshotId !== null) { result.revisionCount = revisionCount; result.textSnapshotPolicy = 'same-id-whole-text-replacement'; }
|
|
607
|
+
result.nativeEvidence = safeNativeEvidence({ phase: 'validate', upstreamHttpStatus: httpStatus, grpcStatus: grpc,
|
|
608
|
+
wireEnded: ended, modelCompleted: modelComplete, frameCount: frames, receivedBytes: received,
|
|
609
|
+
observedMode, observedThinking, fallback: observedFallback, downgradeReason,
|
|
610
|
+
nativeTextBytes: Buffer.byteLength(rawText), ...outputShape,
|
|
611
|
+
nativeResponseRevisions: revisionCount, nativeResponseIdentityVerified: snapshotId !== null });
|
|
612
|
+
phase = 'output';
|
|
613
|
+
if (!incremental) {
|
|
614
|
+
if (body.response_format && !calls.length) {
|
|
615
|
+
if (content) await onDelta({ content });
|
|
616
|
+
} else {
|
|
617
|
+
for (const item of items) await onDelta(item.type === 'call' ? { call: item.call } : { content: item.text });
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
note('provider_success');
|
|
621
|
+
return result;
|
|
622
|
+
} catch (error) {
|
|
623
|
+
const modeVerified = !downgrade && !outputShape.nativeRefusalPresent && modeMatches(observedMode) && attributionVerified();
|
|
624
|
+
if (incremental && modeVerified && !sinkFailed) {
|
|
625
|
+
try { await publish(liveSplitter.flush()); }
|
|
626
|
+
catch { /* Retain already-published text; never release an invalid/incomplete tool body. */ }
|
|
627
|
+
}
|
|
628
|
+
const safe = safeFailure(error);
|
|
629
|
+
if (!modeVerified) safe.unverifiedOutput = true;
|
|
630
|
+
note('provider_failure', { code: safe.code });
|
|
631
|
+
let transport = {};
|
|
632
|
+
try { transport = turn?.getSafeStatus?.() ?? {}; } catch {}
|
|
633
|
+
safe.nativeEvidence = safeNativeEvidence({
|
|
634
|
+
// Keep guard-site diagnostics raised deeper in this turn; they are byte counts only.
|
|
635
|
+
...(error.nativeEvidence ?? {}),
|
|
636
|
+
phase, upstreamHttpStatus: transport.httpStatus ?? httpStatus,
|
|
637
|
+
grpcStatus: transport.grpcStatus ?? grpc,
|
|
638
|
+
http2ResetCode: transport.http2ResetCode,
|
|
639
|
+
connectionEndObserved: transport.connectionEndObserved,
|
|
640
|
+
streamCloseCode: transport.streamCloseCode,
|
|
641
|
+
upstreamMessage: transport.grpcMessage,
|
|
642
|
+
wireEnded: transport.ended ?? ended, modelCompleted: modelComplete,
|
|
643
|
+
frameCount: frames, receivedBytes: transport.receivedBytes ?? received,
|
|
644
|
+
observedMode, observedThinking,
|
|
645
|
+
fallback: observedFallback, downgradeReason,
|
|
646
|
+
toolProtocolReason: safe.toolProtocolReason,
|
|
647
|
+
...(outputObserved ? { nativeTextBytes: Buffer.byteLength(rawText), ...outputShape,
|
|
648
|
+
nativeResponseRevisions: revisionCount, nativeResponseIdentityVerified: snapshotId !== null } : {}),
|
|
649
|
+
...(responseLimitReason ? { nativeResponseLimitReason: responseLimitReason } : {}),
|
|
650
|
+
...(outputFailureReason ? { outputFailureReason, outputFailureSource: 'exact_text_signature', outputToolCalls: 0 } : {}),
|
|
651
|
+
...(emptyResponseReason ? { emptyResponseReason } : {}),
|
|
652
|
+
});
|
|
653
|
+
if (incremental && modeVerified && (publishedContent.length || publishedCalls)) safe.partialResult = { ...identity, content: publishedContent, calls: liveCalls.slice(0, publishedCalls),
|
|
654
|
+
thinkingLevel: observedThinking, resolvedModeCategory: observedMode, ...(observedAttribution !== null ? { attribution: observedAttribution } : {}), nativeEvidence: safe.nativeEvidence };
|
|
655
|
+
throw safe;
|
|
656
|
+
}
|
|
657
|
+
finally {
|
|
658
|
+
note('provider_cleanup');
|
|
659
|
+
clearTimeout(timer);
|
|
660
|
+
context.signal?.removeEventListener('abort', abort);
|
|
661
|
+
try { turn?.cancel(); } catch {}
|
|
662
|
+
controller.abort();
|
|
663
|
+
// Do not wait for a stuck async generator on timeout/cancellation.
|
|
664
|
+
try { Promise.resolve(iterator?.return?.()).catch(() => {}); } catch {}
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/** Legacy method retained, but even SSE headers wait for verification. New
|
|
669
|
+
* gateway calls normalizer -> runTurn -> writer itself. */
|
|
670
|
+
async executeChatCompletion(accountId, payload, res, context = {}) {
|
|
671
|
+
try {
|
|
672
|
+
const body = normalizeChatRequest(payload);
|
|
673
|
+
const result = await this.runTurn(accountId, body, () => {}, context);
|
|
674
|
+
writeChatResponse(res, result, { stream: body.stream, includeUsage: body.stream_options?.include_usage ?? false });
|
|
675
|
+
} catch (error) {
|
|
676
|
+
const safe = safeFailure(error);
|
|
677
|
+
res.writeHead(safe.status, { 'Content-Type': 'application/json' });
|
|
678
|
+
res.end(JSON.stringify({ error: { code: safe.code, type: safe.type, message: safe.message } }));
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
}
|