opencode-gemini-app 0.1.0 → 0.1.1
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/README.md +2 -0
- package/package.json +1 -1
- package/src/gateway/automatic-recovery.mjs +9 -3
- package/src/gateway/image-upload.mjs +57 -14
- package/src/gateway/native-diagnostic.mjs +3 -2
- package/src/gateway/native-evidence.mjs +1 -0
- package/src/gateway/native-transport.mjs +61 -3
- package/src/native-provider.mjs +164 -39
- package/src/tool-protocol.mjs +26 -8
package/README.md
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
# opencode-gemini-app
|
|
2
2
|
|
|
3
|
+
[](https://www.npmjs.com/package/opencode-gemini-app)
|
|
4
|
+
|
|
3
5
|
Zero-dependency native Google Gemini HTTP/2 provider plugin for **OpenCode** (`opencode`). Connect your Google Gemini subscription (**AI Pro**, **AI Ultra**, or **Free**) directly in-process via OAuth—no local gateway server, no localhost port, no Docker, and zero external npm dependencies.
|
|
4
6
|
|
|
5
7
|
## Install
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-gemini-app",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"description": "Zero-dependency native Google Gemini HTTP/2 provider plugin for OpenCode (Gemini Neon, Hydrogen, Flash Lite, Auto) using your Google Gemini subscription via OAuth.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./extensions/opencode/index.js",
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { MODEL_MODES, canonicalModel } from '../openai-contract.mjs';
|
|
3
3
|
import { isVerifiedEmptyResponse } from './output-recovery.mjs';
|
|
4
4
|
import { isExplicitQuotaFailure } from './quota-failover.mjs';
|
|
5
|
-
const TOOL_ERRORS = new Set(['MALFORMED_TOOL_CALL', 'INVALID_TOOL_JSON', 'TRUNCATED_TOOL_CALL', 'INVALID_TOOL_CALL',
|
|
5
|
+
export const TOOL_ERRORS = new Set(['MALFORMED_TOOL_CALL', 'INVALID_TOOL_JSON', 'TRUNCATED_TOOL_CALL', 'INVALID_TOOL_CALL',
|
|
6
6
|
'INVALID_TOOL_ARGUMENTS', 'UNDECLARED_TOOL', 'TOOL_ARGUMENT_SCHEMA_MISMATCH', 'TOOL_CHOICE_NOT_SATISFIED',
|
|
7
7
|
'TOOL_CHOICE_MISMATCH', 'TOOL_CALL_NOT_ALLOWED', 'PARALLEL_TOOL_CALLS_DISABLED']);
|
|
8
8
|
const STRUCTURED_OUTPUT_ERRORS = new Set(['INVALID_STRUCTURED_OUTPUT_JSON', 'STRUCTURED_OUTPUT_SCHEMA_MISMATCH']);
|
|
@@ -10,7 +10,7 @@ const TRANSPORT_ERRORS = new Set(['NATIVE_STREAM_RESET', 'NATIVE_CONNECTION_FAIL
|
|
|
10
10
|
export function toolRecoveryInstruction(code) {
|
|
11
11
|
if (TOOL_ERRORS.has(code)) {
|
|
12
12
|
return '[Gateway automatic recovery: regenerate this turn; the previous response was not delivered and no caller tool was executed.]\n' +
|
|
13
|
-
'Answer the latest user request using the complete history. If a tool is needed and permitted, emit a complete tool_call block with exactly the keys "name" and "arguments" as valid JSON. Use only declared names and actual JSON-object arguments matching the original schema. Respect the selected tool choice and parallel-call restriction. Put both fences on separate lines. Do not invent tool results, duplicate already completed work, or discuss this recovery instruction. If tools are prohibited, answer normally without tool_call blocks.';
|
|
13
|
+
'Answer the latest user request using the complete history. If a tool is needed and permitted, emit a complete tool_call block with exactly the keys "name" and "arguments" as valid JSON. Emit one strict JSON object per tool_call block with properly escaped strings (no raw newlines, invalid escapes, or trailing commas). Use only declared names and actual JSON-object arguments matching the original schema. Respect the selected tool choice and parallel-call restriction. Put both fences on separate lines. Do not invent tool results, duplicate already completed work, or discuss this recovery instruction. If tools are prohibited, answer normally without tool_call blocks.';
|
|
14
14
|
}
|
|
15
15
|
if (STRUCTURED_OUTPUT_ERRORS.has(code)) {
|
|
16
16
|
return '[Gateway automatic recovery: regenerate this turn; the previous response was not delivered because it did not satisfy the required JSON output format.]\n' +
|
|
@@ -50,11 +50,17 @@ export function automaticRecoveryKind(error, model, { allowAutoModel = false } =
|
|
|
50
50
|
if (error.status !== 502) return null;
|
|
51
51
|
if (TRANSPORT_ERRORS.has(error.code) && ['open', 'read', 'decode', 'end'].includes(e.phase) &&
|
|
52
52
|
(e.upstreamHttpStatus === null || e.upstreamHttpStatus === 200) && (e.grpcStatus === null || e.grpcStatus === 0)) return 'transport';
|
|
53
|
+
if (error.code === 'NATIVE_IMAGE_UPLOAD_RESET' && e.phase === 'upload' &&
|
|
54
|
+
e.upstreamHttpStatus === null && e.grpcStatus === null) return 'transport';
|
|
53
55
|
const completed = e.phase === 'validate' && e.upstreamHttpStatus === 200 && e.grpcStatus === 0 && e.wireEnded === true &&
|
|
54
56
|
e.modelCompleted === true && modeOk(e.observedMode) && e.nativeRefusalPresent === false && e.http2ResetCode === undefined;
|
|
57
|
+
const earlyStoppedToolError = e.phase === 'validate' && e.toolErrorEarlyStop === true &&
|
|
58
|
+
(e.upstreamHttpStatus === null || e.upstreamHttpStatus === 200) &&
|
|
59
|
+
(e.grpcStatus === null || e.grpcStatus === 0) &&
|
|
60
|
+
modeOk(e.observedMode) && e.nativeRefusalPresent === false && e.http2ResetCode === undefined;
|
|
55
61
|
if (completed && error.code === 'NATIVE_SOFT_ERROR_RESPONSE' && e.outputFailureReason === 'generic_error_offer' &&
|
|
56
62
|
e.outputFailureSource === 'exact_text_signature' && e.outputToolCalls === 0 && e.nativeStructuredOutputPresent === false) return 'provider_soft_error';
|
|
57
|
-
if (completed && TOOL_ERRORS.has(error.code)) return 'tool_protocol';
|
|
63
|
+
if ((completed || earlyStoppedToolError) && TOOL_ERRORS.has(error.code)) return 'tool_protocol';
|
|
58
64
|
if (completed && STRUCTURED_OUTPUT_ERRORS.has(error.code)) return 'structured_output';
|
|
59
65
|
// A clean but incomplete turn may be regenerated; never treat it as success.
|
|
60
66
|
if (error.code === 'INCOMPLETE_NATIVE_RESPONSE' && e.phase === 'validate' && e.upstreamHttpStatus === 200 && e.grpcStatus === 0 &&
|
|
@@ -6,6 +6,7 @@ import { GATEWAY_USER_AGENT } from '../../native-wire/robin-current.mjs';
|
|
|
6
6
|
|
|
7
7
|
const ORIGIN = 'https://push.clients6.google.com';
|
|
8
8
|
export const DEFAULT_UPLOAD_CONCURRENCY = 8;
|
|
9
|
+
export const DEFAULT_MAX_IN_FLIGHT_BYTES = 4 * 1024 * 1024;
|
|
9
10
|
export const MAX_UPLOAD_TIMEOUT_MS = 600_000;
|
|
10
11
|
const fail = (suffix, status = 502) => { throw protocolError(`NATIVE_IMAGE_UPLOAD_${suffix}`, status); };
|
|
11
12
|
const mimeTypes = new Set(['image/png', 'image/jpeg', 'image/webp']);
|
|
@@ -82,7 +83,7 @@ function boundedLocation(value) {
|
|
|
82
83
|
export async function uploadNativeImages(
|
|
83
84
|
token,
|
|
84
85
|
images,
|
|
85
|
-
{ signal, timeoutMs = 60000, concurrency = DEFAULT_UPLOAD_CONCURRENCY } = {},
|
|
86
|
+
{ signal, timeoutMs = 60000, concurrency = DEFAULT_UPLOAD_CONCURRENCY, maxInFlightBytes = DEFAULT_MAX_IN_FLIGHT_BYTES, onUploaded } = {},
|
|
86
87
|
{ connect = connectHttp2 } = {},
|
|
87
88
|
) {
|
|
88
89
|
validateImages(images);
|
|
@@ -98,15 +99,45 @@ export async function uploadNativeImages(
|
|
|
98
99
|
!Number.isSafeInteger(concurrency) ||
|
|
99
100
|
concurrency < 1 ||
|
|
100
101
|
concurrency > 32 ||
|
|
102
|
+
!Number.isSafeInteger(maxInFlightBytes) ||
|
|
103
|
+
maxInFlightBytes < 1 ||
|
|
104
|
+
(onUploaded !== undefined && typeof onUploaded !== 'function') ||
|
|
101
105
|
(signal !== undefined && (!signal || typeof signal.addEventListener !== 'function')) ||
|
|
102
106
|
typeof connect !== 'function'
|
|
103
107
|
) fail('INVALID_RESPONSE');
|
|
104
108
|
if (signal?.aborted) fail('CANCELLED', 499);
|
|
105
109
|
const deadline = Date.now() + timeoutMs;
|
|
106
110
|
let session, timeout, sessionFailed = false, batchError = null;
|
|
111
|
+
let inFlightBytes = 0, activeUploads = 0;
|
|
107
112
|
const activeStops = new Set();
|
|
113
|
+
const budgetWaiters = [];
|
|
114
|
+
const wakeBudgetWaiters = () => {
|
|
115
|
+
while (budgetWaiters.length) {
|
|
116
|
+
const next = budgetWaiters[0];
|
|
117
|
+
if (activeUploads === 0 || inFlightBytes + next.bytes <= maxInFlightBytes || batchError || sessionFailed || signal?.aborted) {
|
|
118
|
+
budgetWaiters.shift();
|
|
119
|
+
next.resolve();
|
|
120
|
+
} else {
|
|
121
|
+
break;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
const acquireByteBudget = async (bytes) => {
|
|
126
|
+
while (activeUploads > 0 && inFlightBytes + bytes > maxInFlightBytes && !batchError && !sessionFailed && !signal?.aborted) {
|
|
127
|
+
await new Promise(resolve => budgetWaiters.push({ bytes, resolve }));
|
|
128
|
+
}
|
|
129
|
+
ensureAlive();
|
|
130
|
+
activeUploads++;
|
|
131
|
+
inFlightBytes += bytes;
|
|
132
|
+
};
|
|
133
|
+
const releaseByteBudget = (bytes) => {
|
|
134
|
+
activeUploads = Math.max(0, activeUploads - 1);
|
|
135
|
+
inFlightBytes = Math.max(0, inFlightBytes - bytes);
|
|
136
|
+
wakeBudgetWaiters();
|
|
137
|
+
};
|
|
108
138
|
const stopAll = (err) => {
|
|
109
139
|
if (!batchError) batchError = err;
|
|
140
|
+
wakeBudgetWaiters();
|
|
110
141
|
for (const stop of [...activeStops]) stop(err);
|
|
111
142
|
};
|
|
112
143
|
const abortCode = () => signal?.aborted ? ['CANCELLED', 499] : Date.now() >= deadline ? ['TIMEOUT', 504] : null;
|
|
@@ -168,22 +199,30 @@ export async function uploadNativeImages(
|
|
|
168
199
|
});
|
|
169
200
|
const onSessionError = () => { sessionFailed = true; stopAll(protocolError('NATIVE_IMAGE_UPLOAD_RESET', 502)); };
|
|
170
201
|
const uploadOne = async (image) => {
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
202
|
+
await acquireByteBudget(image.data.length);
|
|
203
|
+
try {
|
|
204
|
+
ensureAlive();
|
|
205
|
+
const initial = await request({ ':method': 'POST', ':path': '/upload/', authorization: `Bearer ${token}`, 'content-length': '0', 'push-id': 'feeds/mcudyrk2a4khkz', 'x-tenant-id': 'bard-storage', 'x-goog-upload-protocol': 'resumable', 'x-goog-upload-command': 'start', 'x-goog-upload-content-type': image.mimeType, 'x-goog-upload-content-length': String(image.data.length), 'user-agent': GATEWAY_USER_AGENT }, null, 8192);
|
|
206
|
+
if (String(initial.headers['x-goog-upload-status'] ?? '').toLowerCase() !== 'active') fail('INVALID_RESPONSE');
|
|
207
|
+
const location = boundedLocation(initial.headers['x-goog-upload-url']);
|
|
208
|
+
ensureAlive();
|
|
209
|
+
const final = await request({ ':method': 'PUT', ':path': location.pathname + location.search, 'content-length': String(image.data.length), 'x-goog-upload-protocol': 'resumable', 'x-goog-upload-command': 'upload, finalize', 'x-goog-upload-offset': '0', 'user-agent': GATEWAY_USER_AGENT }, image.data, 4096);
|
|
210
|
+
if (String(final.headers['x-goog-upload-status'] ?? '').toLowerCase() !== 'final') fail('INVALID_RESPONSE');
|
|
211
|
+
let blobId;
|
|
212
|
+
try { blobId = new TextDecoder('utf-8', { fatal: true }).decode(final.body); } catch { fail('INVALID_RESPONSE'); }
|
|
213
|
+
if (!blobId || Buffer.byteLength(blobId) > 4096 || /\s|[\x00-\x1f\x7f]/u.test(blobId)) fail('INVALID_RESPONSE');
|
|
214
|
+
ensureAlive();
|
|
215
|
+
return { blobId, mimeType: image.mimeType };
|
|
216
|
+
} finally {
|
|
217
|
+
releaseByteBudget(image.data.length);
|
|
218
|
+
}
|
|
183
219
|
};
|
|
220
|
+
const onSignalAbort = () => wakeBudgetWaiters();
|
|
221
|
+
signal?.addEventListener('abort', onSignalAbort, { once: true });
|
|
184
222
|
try {
|
|
185
223
|
try { session = connect(ORIGIN, { settings: { enablePush: false, maxHeaderListSize: 8192 } }); } catch { fail('RESET'); }
|
|
186
224
|
if (!session || typeof session.request !== 'function') fail('RESET');
|
|
225
|
+
try { session.socket?.setKeepAlive?.(true, 15_000); } catch {}
|
|
187
226
|
session.on?.('error', onSessionError);
|
|
188
227
|
session.on?.('close', onSessionError);
|
|
189
228
|
timeout = setTimeout(() => { stopAll(protocolError('NATIVE_IMAGE_UPLOAD_TIMEOUT', 504)); try { session.destroy(); } catch {} }, Math.max(1, deadline - Date.now()));
|
|
@@ -195,7 +234,9 @@ export async function uploadNativeImages(
|
|
|
195
234
|
const index = nextIndex++;
|
|
196
235
|
if (index >= images.length) return;
|
|
197
236
|
try {
|
|
198
|
-
|
|
237
|
+
const uploaded = await uploadOne(images[index]);
|
|
238
|
+
results[index] = uploaded;
|
|
239
|
+
try { onUploaded?.(index, uploaded); } catch {}
|
|
199
240
|
} catch (err) {
|
|
200
241
|
stopAll(err);
|
|
201
242
|
throw err;
|
|
@@ -213,6 +254,8 @@ export async function uploadNativeImages(
|
|
|
213
254
|
fail('RESET');
|
|
214
255
|
} finally {
|
|
215
256
|
clearTimeout(timeout);
|
|
257
|
+
signal?.removeEventListener('abort', onSignalAbort);
|
|
258
|
+
wakeBudgetWaiters();
|
|
216
259
|
try { session?.on?.('error', drainError); session?.removeListener?.('error', onSessionError); session?.removeListener?.('close', onSessionError); } catch {}
|
|
217
260
|
try { session?.destroy(); } catch {}
|
|
218
261
|
}
|
|
@@ -15,10 +15,11 @@ export const NATIVE_DIAGNOSTIC_LIMITS = Object.freeze({
|
|
|
15
15
|
});
|
|
16
16
|
const L = NATIVE_DIAGNOSTIC_LIMITS;
|
|
17
17
|
const eventNames = new Set(['provider_stop', 'provider_cleanup', 'provider_success', 'provider_failure',
|
|
18
|
-
'early_stop_post_tool_hallucination', '
|
|
18
|
+
'early_stop_post_tool_hallucination', 'early_stop_post_tool_error',
|
|
19
|
+
'post_complete_idle_finish', 'post_complete_idle_timeout', 'post_tool_error_idle_finish',
|
|
19
20
|
'post_tool_idle_timeout', 'post_output_idle_timeout',
|
|
20
21
|
'transport_open', 'local_stream_close', 'local_session_destroy', 'local_signal_abort', 'local_cancel',
|
|
21
|
-
'transport_failure', 'transport_deadline', 'peer_headers', 'peer_trailers', 'peer_reset',
|
|
22
|
+
'transport_failure', 'transport_deadline', 'transport_ping_timeout', 'peer_headers', 'peer_trailers', 'peer_reset',
|
|
22
23
|
'peer_goaway', 'stream_error', 'stream_close', 'stream_end', 'peer_data', 'local_half_close',
|
|
23
24
|
'peer_connection_end', 'peer_connection_close']);
|
|
24
25
|
const numberKeys = new Set(['httpStatus', 'grpcStatus', 'rstCode', 'requestedCode', 'goawayCode',
|
|
@@ -91,6 +91,7 @@ export function safeNativeEvidence(value) {
|
|
|
91
91
|
...(bounded(value.outputToolCalls, 0, 32) !== null ? { outputToolCalls: value.outputToolCalls } : {}),
|
|
92
92
|
...(nativeCompletenessState !== null ? { nativeCompletenessState } : {}),
|
|
93
93
|
...(toolProtocolReason ? { toolProtocolReason } : {}),
|
|
94
|
+
...(value.toolErrorEarlyStop === true ? { toolErrorEarlyStop: true } : {}),
|
|
94
95
|
...(emptyResponseReason ? { emptyResponseReason } : {}),
|
|
95
96
|
...(nativeTextBytes !== null ? { nativeTextBytes } : {}),
|
|
96
97
|
...(nativeShareableTextBytes !== null ? { nativeShareableTextBytes } : {}),
|
|
@@ -22,6 +22,7 @@ import { NATIVE_RESPONSE_LIMITS as RESPONSE_LIMITS } from './native-response-lim
|
|
|
22
22
|
import { observeNative } from './native-diagnostic.mjs';
|
|
23
23
|
import { connectHttp2 } from './outbound-proxy.mjs';
|
|
24
24
|
export const DEFAULT_HTTP2_PING_INTERVAL_MS = 15_000;
|
|
25
|
+
export const DEFAULT_HTTP2_PING_TIMEOUT_MS = 30_000;
|
|
25
26
|
export const MIN_CONNECT_ATTEMPT_TIMEOUT_MS = 5000;
|
|
26
27
|
// Node v22 defaults Happy Eyeballs per-family attempt timeout to 250ms, which aborts
|
|
27
28
|
// IPv4 connects over high-RTT VPN tunnels when IPv6 returns immediate EHOSTUNREACH.
|
|
@@ -53,6 +54,7 @@ export function openDirectTurn(
|
|
|
53
54
|
continuation,
|
|
54
55
|
timeoutMs = 180000,
|
|
55
56
|
pingIntervalMs = DEFAULT_HTTP2_PING_INTERVAL_MS,
|
|
57
|
+
pingTimeoutMs = DEFAULT_HTTP2_PING_TIMEOUT_MS,
|
|
56
58
|
signal,
|
|
57
59
|
allowNativeTools = false,
|
|
58
60
|
emitHeaders = false,
|
|
@@ -116,7 +118,9 @@ export function openDirectTurn(
|
|
|
116
118
|
request,
|
|
117
119
|
timer,
|
|
118
120
|
pingTimer = null,
|
|
121
|
+
pingAckTimer = null,
|
|
119
122
|
pingInFlight = false,
|
|
123
|
+
lastInboundAt = Date.now(),
|
|
120
124
|
closed = false,
|
|
121
125
|
ended = false,
|
|
122
126
|
error = null,
|
|
@@ -152,6 +156,10 @@ export function openDirectTurn(
|
|
|
152
156
|
clearInterval(pingTimer);
|
|
153
157
|
pingTimer = null;
|
|
154
158
|
}
|
|
159
|
+
if (pingAckTimer) {
|
|
160
|
+
clearTimeout(pingAckTimer);
|
|
161
|
+
pingAckTimer = null;
|
|
162
|
+
}
|
|
155
163
|
pingInFlight = false;
|
|
156
164
|
};
|
|
157
165
|
const stop = () => {
|
|
@@ -288,13 +296,60 @@ export function openDirectTurn(
|
|
|
288
296
|
client.on("error", () => fail("NATIVE_CONNECTION_FAILED"));
|
|
289
297
|
if (diagnostic) client.on('goaway', code => note('peer_goaway', { goawayCode: code }));
|
|
290
298
|
if (Number.isInteger(pingIntervalMs) && pingIntervalMs > 0 && typeof client.ping === "function") {
|
|
299
|
+
let pingSeq = 0, activePingSeq = 0;
|
|
291
300
|
pingTimer = setInterval(() => {
|
|
292
|
-
if (closed || ended || client.closed || client.destroyed || pingInFlight) return;
|
|
301
|
+
if (closed || ended || client.closed || client.destroyed || client.connecting || pingInFlight) return;
|
|
302
|
+
const seq = ++pingSeq;
|
|
303
|
+
activePingSeq = seq;
|
|
304
|
+
const pingStartedAt = Date.now();
|
|
293
305
|
pingInFlight = true;
|
|
306
|
+
let pingQueued = true;
|
|
307
|
+
let sent = false;
|
|
294
308
|
try {
|
|
295
|
-
client.ping(() => {
|
|
309
|
+
sent = client.ping((err) => {
|
|
310
|
+
if (!pingQueued || seq !== activePingSeq) return;
|
|
311
|
+
if (pingAckTimer) {
|
|
312
|
+
clearTimeout(pingAckTimer);
|
|
313
|
+
pingAckTimer = null;
|
|
314
|
+
}
|
|
315
|
+
pingInFlight = false;
|
|
316
|
+
if (closed || ended) return;
|
|
317
|
+
if (err) {
|
|
318
|
+
if (err.code === 'ERR_HTTP2_PING_CANCEL') return;
|
|
319
|
+
note('transport_ping_timeout');
|
|
320
|
+
fail('NATIVE_CONNECTION_FAILED');
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
lastInboundAt = Date.now();
|
|
324
|
+
});
|
|
296
325
|
} catch {
|
|
326
|
+
pingQueued = false;
|
|
327
|
+
if (activePingSeq === seq) activePingSeq = 0;
|
|
328
|
+
pingInFlight = false;
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
if (sent === false) {
|
|
332
|
+
pingQueued = false;
|
|
333
|
+
if (activePingSeq === seq) activePingSeq = 0;
|
|
297
334
|
pingInFlight = false;
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
if (Number.isInteger(pingTimeoutMs) && pingTimeoutMs > 0 && !closed && !ended && pingInFlight && activePingSeq === seq) {
|
|
338
|
+
const armAckWatchdog = (delayMs) => {
|
|
339
|
+
pingAckTimer = setTimeout(() => {
|
|
340
|
+
pingAckTimer = null;
|
|
341
|
+
if (closed || ended || !pingInFlight || activePingSeq !== seq) return;
|
|
342
|
+
const idleSinceInbound = Date.now() - lastInboundAt;
|
|
343
|
+
if (lastInboundAt >= pingStartedAt && idleSinceInbound < pingTimeoutMs) {
|
|
344
|
+
armAckWatchdog(Math.max(1, pingTimeoutMs - idleSinceInbound));
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
note('transport_ping_timeout');
|
|
348
|
+
fail('NATIVE_CONNECTION_FAILED');
|
|
349
|
+
}, delayMs);
|
|
350
|
+
pingAckTimer.unref();
|
|
351
|
+
};
|
|
352
|
+
armAckWatchdog(pingTimeoutMs);
|
|
298
353
|
}
|
|
299
354
|
}, pingIntervalMs);
|
|
300
355
|
pingTimer.unref();
|
|
@@ -309,11 +364,12 @@ export function openDirectTurn(
|
|
|
309
364
|
"user-agent": GATEWAY_USER_AGENT,
|
|
310
365
|
});
|
|
311
366
|
request.on("response", headers => {
|
|
367
|
+
lastInboundAt = Date.now();
|
|
312
368
|
note('peer_headers', { httpStatus: Number(headers[':status']), grpcStatus: Number(headers['grpc-status']) });
|
|
313
369
|
status(headers);
|
|
314
370
|
if (emitHeaders && !closed && httpStatus === 200) push({ type: 'headers', httpStatus });
|
|
315
371
|
});
|
|
316
|
-
request.on("trailers", headers => { note('peer_trailers', { grpcStatus: Number(headers['grpc-status']) }); status(headers); });
|
|
372
|
+
request.on("trailers", headers => { lastInboundAt = Date.now(); note('peer_trailers', { grpcStatus: Number(headers['grpc-status']) }); status(headers); });
|
|
317
373
|
request.on("error", () => {
|
|
318
374
|
note('stream_error', { rstCode: request?.rstCode });
|
|
319
375
|
if (!rejectPeerReset()) fail("NATIVE_STREAM_FAILED");
|
|
@@ -325,6 +381,7 @@ export function openDirectTurn(
|
|
|
325
381
|
});
|
|
326
382
|
request.on("data", (chunk) => {
|
|
327
383
|
if (closed) return;
|
|
384
|
+
lastInboundAt = Date.now();
|
|
328
385
|
note('peer_data', { bytes: chunk.length });
|
|
329
386
|
try {
|
|
330
387
|
received += chunk.length;
|
|
@@ -338,6 +395,7 @@ export function openDirectTurn(
|
|
|
338
395
|
}
|
|
339
396
|
});
|
|
340
397
|
request.on("end", () => {
|
|
398
|
+
lastInboundAt = Date.now();
|
|
341
399
|
note('stream_end', { rstCode: request?.rstCode });
|
|
342
400
|
if (closed) return;
|
|
343
401
|
// Node may emit readable 'end' for RST_STREAM(CANCEL). That is not a successful end.
|
package/src/native-provider.mjs
CHANGED
|
@@ -15,7 +15,7 @@ import { uploadNativeImages, createImageBlobCache } from './gateway/image-upload
|
|
|
15
15
|
import { downloadRemoteImages } from './gateway/image-download.mjs';
|
|
16
16
|
import { quotaDowngradeCode } from './gateway/quota-failover.mjs';
|
|
17
17
|
import { inspectNativeOutput } from './gateway/output-recovery.mjs';
|
|
18
|
-
import { toolRecoveryInstruction } from './gateway/automatic-recovery.mjs';
|
|
18
|
+
import { TOOL_ERRORS, toolRecoveryInstruction } from './gateway/automatic-recovery.mjs';
|
|
19
19
|
import { validateStructuredOutputText } from './gateway/structured-output.mjs';
|
|
20
20
|
import { mapNativeSearchAnnotations, extractNativeSearchSources } from './gateway/native-search-citations.mjs';
|
|
21
21
|
import { softErrorReason } from './gateway/soft-error.mjs';
|
|
@@ -163,21 +163,51 @@ export class NativeDirectProvider {
|
|
|
163
163
|
}
|
|
164
164
|
}
|
|
165
165
|
if (missImages.length) {
|
|
166
|
-
const
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
) {
|
|
172
|
-
fail('INVALID_NATIVE_IMAGE_UPLOAD');
|
|
173
|
-
}
|
|
174
|
-
for (let slot = 0; slot < uploaded.length; slot++) {
|
|
175
|
-
const item = uploaded[slot];
|
|
166
|
+
const deadline = Date.now() + uploadTimeoutMs;
|
|
167
|
+
const completed = new Array(missImages.length);
|
|
168
|
+
const recordSlot = (slot, item) => {
|
|
169
|
+
if (!item || item.mimeType !== missImages[slot].mimeType || typeof item.blobId !== 'string' || !item.blobId.length) return false;
|
|
170
|
+
completed[slot] = item;
|
|
176
171
|
for (const targetIndex of missSlotIndices[slot]) {
|
|
177
172
|
attachments[targetIndex] = item;
|
|
178
173
|
const key = keys[targetIndex];
|
|
179
174
|
if (this.blobCache && key) this.blobCache.set(key, item);
|
|
180
175
|
}
|
|
176
|
+
return true;
|
|
177
|
+
};
|
|
178
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
179
|
+
const pendingSlots = [];
|
|
180
|
+
for (let slot = 0; slot < missImages.length; slot++) {
|
|
181
|
+
if (!completed[slot]) pendingSlots.push(slot);
|
|
182
|
+
}
|
|
183
|
+
if (!pendingSlots.length) break;
|
|
184
|
+
const remainingMs = Math.max(1, deadline - Date.now());
|
|
185
|
+
const batch = pendingSlots.map(slot => missImages[slot]);
|
|
186
|
+
try {
|
|
187
|
+
const uploaded = await this.uploadImages(token, batch, {
|
|
188
|
+
signal,
|
|
189
|
+
timeoutMs: remainingMs,
|
|
190
|
+
...(attempt > 0 ? { concurrency: 1 } : {}),
|
|
191
|
+
onUploaded: (batchIndex, item) => {
|
|
192
|
+
const slot = pendingSlots[batchIndex];
|
|
193
|
+
if (slot !== undefined) recordSlot(slot, item);
|
|
194
|
+
},
|
|
195
|
+
});
|
|
196
|
+
if (!Array.isArray(uploaded) || uploaded.length !== batch.length) fail('INVALID_NATIVE_IMAGE_UPLOAD');
|
|
197
|
+
for (let batchIndex = 0; batchIndex < uploaded.length; batchIndex++) {
|
|
198
|
+
if (!recordSlot(pendingSlots[batchIndex], uploaded[batchIndex])) fail('INVALID_NATIVE_IMAGE_UPLOAD');
|
|
199
|
+
}
|
|
200
|
+
break;
|
|
201
|
+
} catch (err) {
|
|
202
|
+
const retryableReset = err?.code === 'NATIVE_IMAGE_UPLOAD_RESET' && !signal?.aborted && attempt < 2 && Date.now() + 250 < deadline;
|
|
203
|
+
if (!retryableReset) throw err;
|
|
204
|
+
await new Promise((resolve, reject) => {
|
|
205
|
+
const onAbort = () => { clearTimeout(t); reject(protocolError('NATIVE_IMAGE_UPLOAD_CANCELLED', 499)); };
|
|
206
|
+
const t = setTimeout(() => { signal?.removeEventListener('abort', onAbort); resolve(); }, 200);
|
|
207
|
+
t.unref?.();
|
|
208
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
209
|
+
});
|
|
210
|
+
}
|
|
181
211
|
}
|
|
182
212
|
}
|
|
183
213
|
return { attachments, usedCachedKeys };
|
|
@@ -281,7 +311,7 @@ export class NativeDirectProvider {
|
|
|
281
311
|
const requiresHydrogen = body.model === 'gemini-hydrogen';
|
|
282
312
|
const requiresNeon = body.model === 'gemini-neon';
|
|
283
313
|
let rawText = '', frames = 0, received = 0, observedMode = null, observedThinking = null;
|
|
284
|
-
let modelComplete = false, ended = false, grpc = null, httpStatus = null, downgrade = false, phase = 'auth';
|
|
314
|
+
let modelComplete = false, modelCompleteAt = null, lastTextProgressAt = null, ended = false, grpc = null, httpStatus = null, downgrade = false, phase = 'auth';
|
|
285
315
|
let observedFallback = null, downgradeReason = null, observedAttribution = null;
|
|
286
316
|
const attributionMatches = value => (!requiresHydrogen || HYDROGEN_ATTRIBUTION.test(value ?? '')) && (!requiresNeon || NEON_ATTRIBUTION.test(value ?? ''));
|
|
287
317
|
const attributionVerified = () => attributionMatches(observedAttribution);
|
|
@@ -293,7 +323,7 @@ export class NativeDirectProvider {
|
|
|
293
323
|
[RESPONSE_TOOL_IDENTITIES]: body[RESPONSE_TOOL_IDENTITIES],
|
|
294
324
|
requestedThinkingLevel: body.thinking_level, ignoredTokenParameters: ['max_tokens', 'max_completion_tokens'].filter(key => body[key] !== undefined),
|
|
295
325
|
...((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;
|
|
326
|
+
let liveSplitter = incremental ? createToolCallSplitter({ policy }) : null, liveItems = [], liveContent = '', liveCalls = [], publishedContent = '', publishedCalls = 0, liveSyncedLength = 0, liveToolError = null, liveToolErrorTailStart = 0, liveToolErrorDeadline = null, toolErrorEarlyStop = false, postCompleteIdleFinished = false, sinkFailed = false;
|
|
297
327
|
const deliver = async event => {
|
|
298
328
|
try { await onDelta(event); }
|
|
299
329
|
catch (error) { sinkFailed = true; throw error; }
|
|
@@ -360,35 +390,85 @@ export class NativeDirectProvider {
|
|
|
360
390
|
...(context.nativeDiagnostic ? { diagnostic: context.nativeDiagnostic } : {}) });
|
|
361
391
|
iterator = turn.events[Symbol.asyncIterator]();
|
|
362
392
|
try {
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
if (
|
|
393
|
+
let cachedProbeText = null, cachedProbeRevision = -1, cachedProbeLiveCalls = -1, cachedProbeStructured = false, cachedProbeResult = { kind: 'none' };
|
|
394
|
+
const probeIdleState = () => {
|
|
395
|
+
if (cachedProbeText === rawText && cachedProbeRevision === revisionCount && cachedProbeLiveCalls === liveCalls.length && cachedProbeStructured === outputShape.nativeStructuredOutputPresent) {
|
|
396
|
+
return cachedProbeResult;
|
|
397
|
+
}
|
|
398
|
+
cachedProbeText = rawText;
|
|
399
|
+
cachedProbeRevision = revisionCount;
|
|
400
|
+
cachedProbeLiveCalls = liveCalls.length;
|
|
401
|
+
cachedProbeStructured = outputShape.nativeStructuredOutputPresent;
|
|
402
|
+
if (!rawText.trim()) return (cachedProbeResult = { kind: 'none' });
|
|
403
|
+
if (/^\s*I'm on it\.\s*Responses with Deep Think can take some time, so check back in a bit\.\s*https?:\/\/googleusercontent\.com\/agentic_processing_chip\/\d+\s*$/i.test(rawText)) {
|
|
404
|
+
return (cachedProbeResult = { kind: 'none' });
|
|
405
|
+
}
|
|
406
|
+
let probeItems;
|
|
366
407
|
try {
|
|
367
408
|
const probe = createToolCallSplitter({ policy });
|
|
368
|
-
|
|
409
|
+
probeItems = [...probe.push(rawText), ...probe.flush()];
|
|
410
|
+
} catch (probeError) {
|
|
411
|
+
// Only a closed tool block (or malformed fence/call) failing parse/schema validation
|
|
412
|
+
// is a closed_tool_error. TRUNCATED_TOOL_CALL means a tool block is still streaming,
|
|
413
|
+
// and TOOL_CHOICE_NOT_SATISFIED is checked separately below so a valid preamble before
|
|
414
|
+
// a required tool_choice call is never misclassified as a closed tool error.
|
|
415
|
+
if (probeError?.code === 'TRUNCATED_TOOL_CALL') {
|
|
416
|
+
return (cachedProbeResult = { kind: 'streaming_tool' });
|
|
417
|
+
}
|
|
418
|
+
if (TOOL_ERRORS.has(probeError?.code)) {
|
|
419
|
+
return (cachedProbeResult = { kind: 'closed_tool_error', error: probeError });
|
|
420
|
+
}
|
|
421
|
+
return (cachedProbeResult = { kind: 'none' });
|
|
422
|
+
}
|
|
423
|
+
if (liveCalls.length > 0) return (cachedProbeResult = { kind: 'none' });
|
|
424
|
+
try {
|
|
369
425
|
const probeCalls = probeItems.filter(it => it.type === 'call').map(it => it.call);
|
|
370
426
|
const probeContent = probeItems.filter(it => it.type === 'content').map(it => it.text).join('');
|
|
371
|
-
if (!outputShape.nativeStructuredOutputPresent && softErrorReason(probeContent, body, probeCalls.length)) return
|
|
372
|
-
if (body.parallel_tool_calls === false && probeCalls.length > 1) return
|
|
427
|
+
if (!outputShape.nativeStructuredOutputPresent && softErrorReason(probeContent, body, probeCalls.length)) return (cachedProbeResult = { kind: 'none' });
|
|
428
|
+
if (body.parallel_tool_calls === false && probeCalls.length > 1) return (cachedProbeResult = { kind: 'none' });
|
|
373
429
|
validateToolCompletion(probeCalls, policy);
|
|
374
|
-
if (!probeCalls.length && !probeContent.trim()) return
|
|
430
|
+
if (!probeCalls.length && !probeContent.trim()) return (cachedProbeResult = { kind: 'none' });
|
|
375
431
|
if (body.response_format && !probeCalls.length) validateStructuredOutputText(probeContent, body.response_format);
|
|
376
|
-
return
|
|
432
|
+
return (cachedProbeResult = { kind: 'clean_output' });
|
|
377
433
|
} catch {
|
|
378
|
-
return
|
|
434
|
+
return (cachedProbeResult = { kind: 'none' });
|
|
379
435
|
}
|
|
380
436
|
};
|
|
437
|
+
const isCleanPostOutputIdleStall = () => probeIdleState().kind === 'clean_output';
|
|
381
438
|
const nextEventWithIdle = async () => {
|
|
382
439
|
const verified = !downgrade && !outputShape.nativeRefusalPresent && modeMatches(observedMode) && attributionVerified();
|
|
383
|
-
|
|
384
|
-
//
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
const
|
|
389
|
-
|
|
390
|
-
:
|
|
440
|
+
const probeState = (verified && !liveToolError) ? probeIdleState() : { kind: 'none' };
|
|
441
|
+
// Never arm an idle timer unless we already have verified, complete, deliverable output
|
|
442
|
+
// or a closed invalid tool block; never kill a slow still-streaming tool call (TRUNCATED_TOOL_CALL)
|
|
443
|
+
// or a valid preamble preceding a required tool_choice call.
|
|
444
|
+
const now = Date.now();
|
|
445
|
+
const toolErrorRemaining = liveToolError
|
|
446
|
+
? (postToolIdleMs === null ? null : Math.max(0, (liveToolErrorDeadline ?? now) - now))
|
|
447
|
+
: (postToolIdleMs === null ? null : Math.max(0, postToolIdleMs - (lastTextProgressAt !== null ? now - lastTextProgressAt : 0)));
|
|
448
|
+
const completeRemaining = (modelComplete && postCompleteGraceMs !== null)
|
|
449
|
+
? Math.max(0, postCompleteGraceMs - (modelCompleteAt !== null ? now - modelCompleteAt : 0))
|
|
391
450
|
: null;
|
|
451
|
+
let idleKind = null;
|
|
452
|
+
let idleMs = null;
|
|
453
|
+
if (verified && (liveToolError || probeState.kind === 'closed_tool_error')) {
|
|
454
|
+
// Take the shortest enabled deadline across post_tool_error and (when modelComplete) post_complete.
|
|
455
|
+
if (toolErrorRemaining !== null && (completeRemaining === null || toolErrorRemaining <= completeRemaining)) {
|
|
456
|
+
idleKind = 'post_tool_error';
|
|
457
|
+
idleMs = toolErrorRemaining;
|
|
458
|
+
} else if (completeRemaining !== null) {
|
|
459
|
+
idleKind = 'post_tool_error';
|
|
460
|
+
idleMs = completeRemaining;
|
|
461
|
+
}
|
|
462
|
+
} else if (modelComplete && verified && rawText.trim().length > 0) {
|
|
463
|
+
idleKind = 'post_complete';
|
|
464
|
+
idleMs = completeRemaining;
|
|
465
|
+
} else if (verified && liveCalls.length > 0 && probeState.kind !== 'streaming_tool') {
|
|
466
|
+
idleKind = 'post_tool';
|
|
467
|
+
idleMs = postToolIdleMs === null ? null : Math.max(0, postToolIdleMs - (lastTextProgressAt !== null ? now - lastTextProgressAt : 0));
|
|
468
|
+
} else if (probeState.kind === 'clean_output') {
|
|
469
|
+
idleKind = 'post_output';
|
|
470
|
+
idleMs = postOutputIdleMs === null ? null : Math.max(0, postOutputIdleMs - (lastTextProgressAt !== null ? now - lastTextProgressAt : 0));
|
|
471
|
+
}
|
|
392
472
|
const nextPromise = iterator.next();
|
|
393
473
|
if (idleMs === null) return bounded(nextPromise);
|
|
394
474
|
nextPromise.catch(() => {});
|
|
@@ -397,7 +477,7 @@ export class NativeDirectProvider {
|
|
|
397
477
|
return await Promise.race([
|
|
398
478
|
bounded(nextPromise),
|
|
399
479
|
new Promise(resolve => {
|
|
400
|
-
idleTimer = setTimeout(() => resolve({ [IDLE_TIMEOUT_SENTINEL]: idleKind, verified }), idleMs);
|
|
480
|
+
idleTimer = setTimeout(() => resolve({ [IDLE_TIMEOUT_SENTINEL]: idleKind, verified, probeError: probeState.error ?? null }), idleMs);
|
|
401
481
|
idleTimer.unref?.();
|
|
402
482
|
}),
|
|
403
483
|
]);
|
|
@@ -411,13 +491,21 @@ export class NativeDirectProvider {
|
|
|
411
491
|
if (item && item[IDLE_TIMEOUT_SENTINEL]) {
|
|
412
492
|
const idleKind = item[IDLE_TIMEOUT_SENTINEL];
|
|
413
493
|
if (idleKind === 'post_complete' && item.verified && rawText.trim().length > 0) {
|
|
414
|
-
note('post_complete_idle_finish', {
|
|
494
|
+
note('post_complete_idle_finish', { bytes: Buffer.byteLength(rawText) });
|
|
415
495
|
try { turn?.cancel(); } catch {}
|
|
496
|
+
postCompleteIdleFinished = true;
|
|
416
497
|
ended = true;
|
|
417
498
|
httpStatus = httpStatus ?? 200;
|
|
418
499
|
grpc = grpc ?? 0;
|
|
419
500
|
break;
|
|
420
501
|
}
|
|
502
|
+
if (idleKind === 'post_tool_error' && item.verified && (liveToolError || item.probeError)) {
|
|
503
|
+
if (!liveToolError) liveToolError = item.probeError;
|
|
504
|
+
note('post_tool_error_idle_finish', { code: liveToolError.code, bytes: Buffer.byteLength(rawText) });
|
|
505
|
+
try { turn?.cancel(); } catch {}
|
|
506
|
+
toolErrorEarlyStop = true;
|
|
507
|
+
break;
|
|
508
|
+
}
|
|
421
509
|
note(`${idleKind}_idle_timeout`, {
|
|
422
510
|
frames,
|
|
423
511
|
calls: liveCalls.length,
|
|
@@ -471,7 +559,9 @@ export class NativeDirectProvider {
|
|
|
471
559
|
if (!Number.isSafeInteger(info.thinkingLevel) || info.thinkingLevel < 0 || info.thinkingLevel > 4) fail('INVALID_NATIVE_THINKING_LEVEL');
|
|
472
560
|
observedThinking = info.thinkingLevel;
|
|
473
561
|
}
|
|
562
|
+
const wasComplete = modelComplete;
|
|
474
563
|
modelComplete ||= info.completed;
|
|
564
|
+
if (!wasComplete && modelComplete) modelCompleteAt = Date.now();
|
|
475
565
|
// Stop as soon as a wrong model is proven; do not pay for a full
|
|
476
566
|
// downgraded answer that this gateway can never return as success.
|
|
477
567
|
if (downgrade) {
|
|
@@ -498,24 +588,41 @@ export class NativeDirectProvider {
|
|
|
498
588
|
snapshotPriorBytes: Buffer.byteLength(rawText), snapshotNextBytes: Buffer.byteLength(info.text),
|
|
499
589
|
snapshotCommonPrefixBytes: commonPrefixBytes(rawText, info.text), ...committed });
|
|
500
590
|
if (liveSyncedLength > 0) await deliver({ reset: true, sameResponseIdentity: true, response: identity });
|
|
501
|
-
liveSplitter = createToolCallSplitter({ policy }); liveItems = []; liveContent = ''; liveCalls = []; publishedContent = ''; publishedCalls = 0; liveSyncedLength = 0;
|
|
591
|
+
liveSplitter = createToolCallSplitter({ policy }); liveItems = []; liveContent = ''; liveCalls = []; publishedContent = ''; publishedCalls = 0; liveSyncedLength = 0; liveToolError = null; liveToolErrorTailStart = 0; liveToolErrorDeadline = null;
|
|
502
592
|
}
|
|
503
593
|
}
|
|
504
594
|
if (id) snapshotId = id;
|
|
505
595
|
if (!extendsPrior) revisionCount++;
|
|
506
|
-
if (info.text !== rawText)
|
|
596
|
+
if (info.text !== rawText) {
|
|
597
|
+
modelComplete = info.completed;
|
|
598
|
+
modelCompleteAt = modelComplete ? Date.now() : null;
|
|
599
|
+
lastTextProgressAt = Date.now();
|
|
600
|
+
}
|
|
507
601
|
rawText = info.text;
|
|
508
602
|
} else if (snapshotId !== null && info.responseId && info.responseId !== snapshotId) {
|
|
509
603
|
fail('INVALID_NATIVE_RESPONSE');
|
|
510
604
|
}
|
|
511
|
-
if (incremental && modeMatches(observedMode) && attributionVerified() && liveSyncedLength < rawText.length) {
|
|
605
|
+
if (incremental && !liveToolError && modeMatches(observedMode) && attributionVerified() && liveSyncedLength < rawText.length) {
|
|
512
606
|
const delta = rawText.slice(liveSyncedLength);
|
|
513
607
|
liveSyncedLength = rawText.length;
|
|
514
|
-
|
|
608
|
+
try {
|
|
609
|
+
await publish(liveSplitter.push(delta));
|
|
610
|
+
} catch (splitError) {
|
|
611
|
+
// Defer recoverable tool-protocol errors briefly until stream completion so
|
|
612
|
+
// upstream completion/downgrade/refusal evidence is fully verified and
|
|
613
|
+
// automatic tool_protocol recovery (or same-ID revision) can run cleanly.
|
|
614
|
+
if (!sinkFailed && TOOL_ERRORS.has(splitError?.code)) {
|
|
615
|
+
liveToolError = splitError;
|
|
616
|
+
liveToolErrorTailStart = Number.isInteger(splitError.postFenceOffset) ? splitError.postFenceOffset : rawText.length;
|
|
617
|
+
liveToolErrorDeadline = postToolIdleMs === null ? null : Date.now() + postToolIdleMs;
|
|
618
|
+
} else {
|
|
619
|
+
throw splitError;
|
|
620
|
+
}
|
|
621
|
+
}
|
|
515
622
|
// Once valid tool_call(s) have been parsed and the model begins hallucinating
|
|
516
623
|
// a fake [Caller tool result], stop upstream immediately instead of waiting
|
|
517
624
|
// minutes for the model to finish generating discarded text.
|
|
518
|
-
if (liveSplitter.suppressed && liveCalls.length > 0 && !downgrade && !outputShape.nativeRefusalPresent) {
|
|
625
|
+
if (!liveToolError && liveSplitter.suppressed && liveCalls.length > 0 && !downgrade && !outputShape.nativeRefusalPresent) {
|
|
519
626
|
note('early_stop_post_tool_hallucination', { calls: liveCalls.length });
|
|
520
627
|
try { turn?.cancel(); } catch {}
|
|
521
628
|
ended = true;
|
|
@@ -525,6 +632,17 @@ export class NativeDirectProvider {
|
|
|
525
632
|
break;
|
|
526
633
|
}
|
|
527
634
|
}
|
|
635
|
+
if (incremental && liveToolError && !downgrade && !outputShape.nativeRefusalPresent && modeMatches(observedMode) && attributionVerified()) {
|
|
636
|
+
const postErrorTail = rawText.slice(liveToolErrorTailStart);
|
|
637
|
+
const postErrorTailBytes = Buffer.byteLength(postErrorTail);
|
|
638
|
+
const graceExpired = liveToolErrorDeadline !== null && Date.now() >= liveToolErrorDeadline;
|
|
639
|
+
if (postErrorTail.includes('[Caller tool result]') || postErrorTailBytes > 4096 || graceExpired) {
|
|
640
|
+
note('early_stop_post_tool_error', { code: liveToolError.code, bytes: postErrorTailBytes });
|
|
641
|
+
try { turn?.cancel(); } catch {}
|
|
642
|
+
toolErrorEarlyStop = true;
|
|
643
|
+
break;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
528
646
|
if (info.quotaObservation) {
|
|
529
647
|
quotaFrames++;
|
|
530
648
|
if (quotaFrames > 16) quotaObservation = null;
|
|
@@ -562,6 +680,12 @@ export class NativeDirectProvider {
|
|
|
562
680
|
}
|
|
563
681
|
phase = 'validate';
|
|
564
682
|
if (downgrade) fail('MODEL_DOWNGRADE_REJECTED');
|
|
683
|
+
if (outputShape.nativeRefusalPresent) fail('NATIVE_RESPONSE_REFUSED', 422);
|
|
684
|
+
if (toolErrorEarlyStop && liveToolError) {
|
|
685
|
+
if (!modeMatches(observedMode)) fail('MISSING_NATIVE_MODE_EVIDENCE');
|
|
686
|
+
if (!attributionVerified()) fail('MODEL_DOWNGRADE_REJECTED');
|
|
687
|
+
throw liveToolError;
|
|
688
|
+
}
|
|
565
689
|
if (!ended) fail('INCOMPLETE_NATIVE_RESPONSE');
|
|
566
690
|
// An ordinary RPC close is not model completion. Async UI placeholders
|
|
567
691
|
// must be non-retryable or PI will repeatedly submit fresh generations.
|
|
@@ -569,7 +693,6 @@ export class NativeDirectProvider {
|
|
|
569
693
|
if (!modelComplete) fail('INCOMPLETE_NATIVE_RESPONSE');
|
|
570
694
|
if (!modeMatches(observedMode)) fail('MISSING_NATIVE_MODE_EVIDENCE');
|
|
571
695
|
if (!attributionVerified()) fail('MODEL_DOWNGRADE_REJECTED');
|
|
572
|
-
if (outputShape.nativeRefusalPresent) fail('NATIVE_RESPONSE_REFUSED', 422);
|
|
573
696
|
if (!rawText.trim()) {
|
|
574
697
|
if (outputShape.nativeShareableTextBytes || outputShape.nativeStructuredOutputPresent) fail('NATIVE_OUTPUT_NOT_TEXT', 422);
|
|
575
698
|
emptyResponseReason = rawText.length ? 'whitespace_only' : outputShape.nativeThoughtsPresent ? 'thoughts_only' : 'no_text';
|
|
@@ -577,6 +700,7 @@ export class NativeDirectProvider {
|
|
|
577
700
|
}
|
|
578
701
|
let items;
|
|
579
702
|
if (incremental) {
|
|
703
|
+
if (liveToolError) throw liveToolError;
|
|
580
704
|
if (liveSyncedLength < rawText.length) {
|
|
581
705
|
const delta = rawText.slice(liveSyncedLength);
|
|
582
706
|
liveSyncedLength = rawText.length;
|
|
@@ -621,7 +745,7 @@ export class NativeDirectProvider {
|
|
|
621
745
|
return result;
|
|
622
746
|
} catch (error) {
|
|
623
747
|
const modeVerified = !downgrade && !outputShape.nativeRefusalPresent && modeMatches(observedMode) && attributionVerified();
|
|
624
|
-
if (incremental && modeVerified && !sinkFailed) {
|
|
748
|
+
if (incremental && !liveToolError && modeVerified && !sinkFailed) {
|
|
625
749
|
try { await publish(liveSplitter.flush()); }
|
|
626
750
|
catch { /* Retain already-published text; never release an invalid/incomplete tool body. */ }
|
|
627
751
|
}
|
|
@@ -644,6 +768,7 @@ export class NativeDirectProvider {
|
|
|
644
768
|
observedMode, observedThinking,
|
|
645
769
|
fallback: observedFallback, downgradeReason,
|
|
646
770
|
toolProtocolReason: safe.toolProtocolReason,
|
|
771
|
+
...((toolErrorEarlyStop || (postCompleteIdleFinished && phase === 'validate' && TOOL_ERRORS.has(safe.code))) ? { toolErrorEarlyStop: true } : {}),
|
|
647
772
|
...(outputObserved ? { nativeTextBytes: Buffer.byteLength(rawText), ...outputShape,
|
|
648
773
|
nativeResponseRevisions: revisionCount, nativeResponseIdentityVerified: snapshotId !== null } : {}),
|
|
649
774
|
...(responseLimitReason ? { nativeResponseLimitReason: responseLimitReason } : {}),
|
package/src/tool-protocol.mjs
CHANGED
|
@@ -130,7 +130,7 @@ export function buildToolInstruction(tools = [], choice = 'auto') {
|
|
|
130
130
|
'```tool_call',
|
|
131
131
|
'{"name":"declared_name","arguments":{}}',
|
|
132
132
|
'```',
|
|
133
|
-
'Arguments must be a JSON object matching the declared schema. Never invent tools or results.',
|
|
133
|
+
'Arguments must be a JSON object matching the declared schema. Emit one strict UTF-8 JSON object per tool_call block with properly escaped strings (for multiple calls, use separate tool_call blocks; no trailing commas or raw newlines in strings). Never invent tools or results.',
|
|
134
134
|
'Only the caller executes tools. Wait for linked caller tool results before using results.',
|
|
135
135
|
'After emitting your tool_call block(s), STOP your response immediately. Never emit, simulate, or echo [Caller tool result], [User], [Assistant], or any transcript role markers.',
|
|
136
136
|
'A standalone top-level tool_call fence is reserved for actual requests; use json fences for literal examples. Inline references are text.',
|
|
@@ -183,7 +183,7 @@ function callerResultPreviewCut(str) {
|
|
|
183
183
|
* `[Caller tool result]` continuation and everything after it is suppressed so
|
|
184
184
|
* the caller receives only the real tool calls. */
|
|
185
185
|
export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBytes(12).toString('hex'), policy = compileToolPolicy([]) } = {}) {
|
|
186
|
-
let pending = '', scanned = 0, seen = 0, closed = false, suppressed = false, bytes = 0;
|
|
186
|
+
let pending = '', scanned = 0, seen = 0, closed = false, suppressed = false, bytes = 0, consumedChars = 0;
|
|
187
187
|
let mode = 'text', marker = '`', fenceLength = 3, toolBody = '', toolBytes = 0, headerBytes = 0, inlineTicks = 0;
|
|
188
188
|
const ids = new Set();
|
|
189
189
|
const malformed = reason => {
|
|
@@ -243,7 +243,7 @@ export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBy
|
|
|
243
243
|
}
|
|
244
244
|
events.push({ type: 'content', text: raw });
|
|
245
245
|
};
|
|
246
|
-
const line = (raw, final, events) => {
|
|
246
|
+
const line = (raw, final, events, lineStartOffset = consumedChars) => {
|
|
247
247
|
if (suppressed) return;
|
|
248
248
|
const eol = /\r?\n$/.exec(raw)?.[0] ?? '';
|
|
249
249
|
const text = eol ? raw.slice(0, -eol.length) : raw;
|
|
@@ -254,7 +254,13 @@ export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBy
|
|
|
254
254
|
if (run?.[0] === '`' && run.length >= fenceLength) {
|
|
255
255
|
// JSON/name/schema validation, not incidental Markdown suffix layout,
|
|
256
256
|
// authorizes the call. Never scan the suffix again as another request.
|
|
257
|
-
|
|
257
|
+
try {
|
|
258
|
+
emitCall(events);
|
|
259
|
+
} catch (err) {
|
|
260
|
+
if (err && typeof err === 'object') err.postFenceOffset = lineStartOffset + opening[0].length;
|
|
261
|
+
throw err;
|
|
262
|
+
}
|
|
263
|
+
mode = 'text'; toolBody = ''; toolBytes = 0; inlineTicks = 0;
|
|
258
264
|
if (info.trim()) {
|
|
259
265
|
const markerIdx = info.indexOf(CALLER_RESULT_MARKER);
|
|
260
266
|
if (markerIdx >= 0) {
|
|
@@ -292,17 +298,29 @@ export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBy
|
|
|
292
298
|
};
|
|
293
299
|
const drain = final => {
|
|
294
300
|
const events = []; let consumed = 0, from = scanned;
|
|
301
|
+
const runLine = (raw, isFinal, lineStartOffset) => {
|
|
302
|
+
try { line(raw, isFinal, events, lineStartOffset); }
|
|
303
|
+
catch (err) {
|
|
304
|
+
if (err && typeof err === 'object' && err.postFenceOffset === undefined) {
|
|
305
|
+
err.postFenceOffset = lineStartOffset + raw.length;
|
|
306
|
+
}
|
|
307
|
+
throw err;
|
|
308
|
+
}
|
|
309
|
+
};
|
|
295
310
|
for (;;) {
|
|
296
311
|
const end = pending.indexOf('\n', from);
|
|
297
312
|
if (end < 0) break;
|
|
298
|
-
|
|
313
|
+
const lineStartOffset = consumedChars + consumed;
|
|
314
|
+
runLine(pending.slice(consumed, end + 1), false, lineStartOffset);
|
|
299
315
|
consumed = end + 1; from = consumed;
|
|
300
|
-
if (suppressed) { pending = ''; scanned = 0; return events; }
|
|
316
|
+
if (suppressed) { consumedChars += consumed; pending = ''; scanned = 0; return events; }
|
|
301
317
|
}
|
|
302
|
-
if (consumed) pending = pending.slice(consumed);
|
|
318
|
+
if (consumed) { consumedChars += consumed; pending = pending.slice(consumed); }
|
|
303
319
|
scanned = pending.length;
|
|
304
320
|
if (final && pending) {
|
|
305
|
-
|
|
321
|
+
const lineStartOffset = consumedChars;
|
|
322
|
+
runLine(pending, true, lineStartOffset);
|
|
323
|
+
consumedChars += pending.length;
|
|
306
324
|
pending = ''; scanned = 0;
|
|
307
325
|
if (suppressed) return events;
|
|
308
326
|
}
|