@jini-ai/agent-runtime 0.4.11 → 0.6.10

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.
Files changed (111) hide show
  1. package/CHANGELOG.md +83 -1
  2. package/dist/acp-model-probe.d.ts +2 -20
  3. package/dist/agent-protocol/acp/json.js +46 -37
  4. package/dist/agent-protocol/acp/models.js +91 -73
  5. package/dist/agent-protocol/acp/rpc.d.ts +3 -2
  6. package/dist/agent-protocol/acp/rpc.js +3 -2
  7. package/dist/agent-protocol/acp/session-params.d.ts +1 -1
  8. package/dist/agent-protocol/acp/session-params.js +33 -30
  9. package/dist/agent-protocol/acp/session.d.ts +3 -1
  10. package/dist/agent-protocol/acp/session.js +62 -24
  11. package/dist/agent-protocol/acp/updates.js +49 -35
  12. package/dist/agent-protocol/pi-rpc/session.js +3 -1
  13. package/dist/anthropic-live-models.d.ts +12 -4
  14. package/dist/anthropic-live-models.js +0 -0
  15. package/dist/auth.js +84 -91
  16. package/dist/claude-code-models.d.ts +6 -5
  17. package/dist/claude-code-models.js +19 -12
  18. package/dist/claude-segment-usage.d.ts +3 -3
  19. package/dist/claude-segment-usage.js +63 -29
  20. package/dist/claude-stream.d.ts +2 -0
  21. package/dist/claude-stream.js +16 -5
  22. package/dist/copilot-stream.js +42 -50
  23. package/dist/defs/aider.js +3 -4
  24. package/dist/defs/amr.js +52 -61
  25. package/dist/defs/antigravity.d.ts +6 -5
  26. package/dist/defs/antigravity.js +48 -34
  27. package/dist/defs/auggie.d.ts +1 -1
  28. package/dist/defs/claude-compatible-args.d.ts +19 -0
  29. package/dist/defs/claude-compatible-args.js +42 -0
  30. package/dist/defs/claude.d.ts +7 -2
  31. package/dist/defs/claude.js +96 -85
  32. package/dist/defs/cline.d.ts +1 -1
  33. package/dist/defs/codebuddy.d.ts +1 -1
  34. package/dist/defs/codebuddy.js +29 -46
  35. package/dist/defs/codex.d.ts +15 -3
  36. package/dist/defs/codex.js +143 -108
  37. package/dist/defs/cursor-agent.d.ts +9 -7
  38. package/dist/defs/cursor-agent.js +53 -51
  39. package/dist/defs/devin.d.ts +1 -1
  40. package/dist/defs/goose.d.ts +1 -1
  41. package/dist/defs/hermes.d.ts +1 -1
  42. package/dist/defs/kilo.d.ts +1 -1
  43. package/dist/defs/kimi.d.ts +1 -1
  44. package/dist/defs/kiro.d.ts +1 -1
  45. package/dist/defs/opencode.d.ts +5 -4
  46. package/dist/defs/opencode.js +26 -32
  47. package/dist/defs/pi.d.ts +6 -5
  48. package/dist/defs/pi.js +24 -26
  49. package/dist/defs/qoder.d.ts +4 -3
  50. package/dist/defs/qoder.js +25 -25
  51. package/dist/defs/reasonix.d.ts +1 -1
  52. package/dist/defs/shared.d.ts +12 -3
  53. package/dist/defs/shared.js +19 -13
  54. package/dist/defs/trae-cli.d.ts +1 -1
  55. package/dist/defs/vibe.d.ts +1 -1
  56. package/dist/detection.d.ts +13 -20
  57. package/dist/detection.js +129 -111
  58. package/dist/env.js +56 -41
  59. package/dist/executables.js +103 -114
  60. package/dist/index.d.ts +1 -0
  61. package/dist/index.js +1 -0
  62. package/dist/json-event-stream.js +611 -527
  63. package/dist/launch.js +44 -37
  64. package/dist/model-discovery-adapters.d.ts +17 -0
  65. package/dist/model-discovery-adapters.js +223 -164
  66. package/dist/model-discovery-config.js +107 -87
  67. package/dist/model-discovery-sdk.d.ts +16 -2
  68. package/dist/model-discovery-sdk.js +4 -3
  69. package/dist/model-discovery-shared.d.ts +14 -0
  70. package/dist/model-discovery-shared.js +50 -15
  71. package/dist/model-discovery-types.d.ts +2 -0
  72. package/dist/model-discovery.js +219 -117
  73. package/dist/models.d.ts +14 -1
  74. package/dist/models.js +75 -19
  75. package/dist/native-tool-policy.d.ts +29 -0
  76. package/dist/native-tool-policy.js +36 -0
  77. package/dist/opencode-log.js +46 -30
  78. package/dist/paths.d.ts +2 -0
  79. package/dist/paths.js +3 -3
  80. package/dist/providers/aihubmix.js +13 -18
  81. package/dist/providers/anthropic-messages.d.ts +7 -0
  82. package/dist/providers/anthropic-messages.js +45 -21
  83. package/dist/providers/azure-chat.d.ts +5 -0
  84. package/dist/providers/azure-chat.js +13 -5
  85. package/dist/providers/connection-guard.d.ts +2 -45
  86. package/dist/providers/connection-guard.js +11 -10
  87. package/dist/providers/connection-test.d.ts +4 -0
  88. package/dist/providers/connection-test.js +127 -110
  89. package/dist/providers/elevenlabs.js +4 -1
  90. package/dist/providers/google-messages.d.ts +4 -0
  91. package/dist/providers/google-messages.js +48 -23
  92. package/dist/providers/google-schema.js +17 -23
  93. package/dist/providers/model-catalog.js +160 -145
  94. package/dist/providers/oauth-callback-server.js +37 -34
  95. package/dist/providers/oauth-credentials.js +23 -23
  96. package/dist/providers/oauth-tokens.js +16 -24
  97. package/dist/providers/openai-chat.d.ts +42 -0
  98. package/dist/providers/openai-chat.js +80 -10
  99. package/dist/providers/operation-schema.d.ts +25 -0
  100. package/dist/providers/operation-schema.js +226 -0
  101. package/dist/providers/response-text.d.ts +10 -0
  102. package/dist/providers/response-text.js +23 -0
  103. package/dist/providers/tool-turn-types.d.ts +56 -9
  104. package/dist/providers/tool-turn.d.ts +7 -0
  105. package/dist/providers/tool-turn.js +120 -32
  106. package/dist/qoder-stream.js +93 -80
  107. package/dist/registry.d.ts +45 -0
  108. package/dist/registry.js +39 -0
  109. package/dist/runtime-state.d.ts +1 -1
  110. package/dist/types.d.ts +43 -1
  111. package/package.json +19 -14
@@ -1,7 +1,7 @@
1
1
  import { redactSecrets } from '@jini-ai/core';
2
2
  import { defaultDnsLookup, validateBaseUrlResolved } from './connection-guard.js';
3
3
  import { googleGenerateContentUrl } from './google.js';
4
- import { buildOpenAIChatTokenParam, buildLegacyMaxTokensParam, buildMaxCompletionTokensParam } from './token-params.js';
4
+ import { buildOpenAIChatTokenParam, buildLegacyMaxTokensParam } from './token-params.js';
5
5
  const SMOKE_PROMPT = 'Reply with only: ok';
6
6
  /**
7
7
  * Headroom for a reasoning model's hidden thinking, plus the two-character answer.
@@ -31,9 +31,8 @@ function appendVersionedApiPath(baseUrl, suffix) {
31
31
  url.pathname = /\/v\d+(\/|$)/.test(pathname) ? `${pathname}${suffix}` : `${pathname}/v1${suffix}`;
32
32
  return url.toString();
33
33
  }
34
+ /** Only ever called with the redacted string `extractText` produced, so no non-string guard is needed. */
34
35
  function truncateSample(text) {
35
- if (typeof text !== 'string')
36
- return '';
37
36
  const trimmed = text.replace(/\s+/g, ' ').trim();
38
37
  if (trimmed.length <= SAMPLE_MAX_CHARS)
39
38
  return trimmed;
@@ -42,6 +41,9 @@ function truncateSample(text) {
42
41
  function isSmokeOkReply(text) {
43
42
  return typeof text === 'string' && text.trim().toLowerCase() === 'ok';
44
43
  }
44
+ function firstCandidateFinishReason({ candidates }, _options = {}) {
45
+ return candidates?.[0]?.finishReason;
46
+ }
45
47
  /**
46
48
  * The provider's own reason for stopping, when a 2xx carried no usable text.
47
49
  *
@@ -55,7 +57,7 @@ function isSmokeOkReply(text) {
55
57
  */
56
58
  function extractFinishReason(data) {
57
59
  const root = data;
58
- const raw = root?.candidates?.[0]?.finishReason ?? root?.choices?.[0]?.finish_reason ?? root?.stop_reason;
60
+ const raw = firstCandidateFinishReason({ candidates: root?.candidates }) ?? root?.choices?.[0]?.finish_reason ?? root?.stop_reason;
59
61
  return typeof raw === 'string' && raw.trim() ? raw.trim() : '';
60
62
  }
61
63
  function isLikelyAuthErrorText(text) {
@@ -72,11 +74,12 @@ function statusToKind(status, detailText = '') {
72
74
  return isLikelyAuthErrorText(detailText) ? 'auth_failed' : 'forbidden';
73
75
  if (status === 404)
74
76
  return isLikelyModelErrorText(detailText) ? 'not_found_model' : 'invalid_base_url';
77
+ return fallbackStatusKind({ status });
78
+ }
79
+ function fallbackStatusKind({ status }, _options = {}) {
75
80
  if (status === 429)
76
81
  return 'rate_limited';
77
- if (status >= 500)
78
- return 'upstream_unavailable';
79
- return 'unknown';
82
+ return status >= 500 ? 'upstream_unavailable' : 'unknown';
80
83
  }
81
84
  function networkErrorToKind(err) {
82
85
  if (err instanceof Error) {
@@ -84,30 +87,29 @@ function networkErrorToKind(err) {
84
87
  return 'timeout';
85
88
  const cause = err.cause;
86
89
  const code = cause?.code;
87
- if (code === 'ENOTFOUND' ||
88
- code === 'EAI_AGAIN' ||
89
- code === 'ECONNREFUSED' ||
90
- code === 'ECONNRESET' ||
91
- code === 'ETIMEDOUT' ||
92
- code === 'EHOSTUNREACH' ||
93
- code === 'ENETUNREACH' ||
94
- code === 'CERT_HAS_EXPIRED' ||
95
- code === 'UNABLE_TO_VERIFY_LEAF_SIGNATURE') {
90
+ if ([
91
+ 'ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT',
92
+ 'EHOSTUNREACH', 'ENETUNREACH', 'CERT_HAS_EXPIRED', 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
93
+ ].includes(code ?? '')) {
96
94
  return 'invalid_base_url';
97
95
  }
98
96
  }
99
97
  return 'unknown';
100
98
  }
99
+ function providerErrorMessage({ error }, _options = {}) {
100
+ if (!error || typeof error !== 'object')
101
+ return '';
102
+ const message = error.message;
103
+ return typeof message === 'string' && message.trim() ? message : '';
104
+ }
101
105
  function extractProviderErrorDetail(data, rawText) {
102
106
  const obj = data && typeof data === 'object' ? data : null;
103
107
  const error = obj ? obj.error : null;
104
108
  if (typeof error === 'string')
105
109
  return error;
106
- if (error && typeof error === 'object') {
107
- const message = error.message;
108
- if (typeof message === 'string' && message.trim())
109
- return message;
110
- }
110
+ const nestedMessage = providerErrorMessage({ error });
111
+ if (nestedMessage)
112
+ return nestedMessage;
111
113
  const message = obj ? obj.message : null;
112
114
  if (typeof message === 'string' && message.trim())
113
115
  return message;
@@ -124,6 +126,35 @@ function extractOpenAIMessageText(data) {
124
126
  return first.text;
125
127
  return '';
126
128
  }
129
+ // `buildLegacyMaxTokensParam`/`buildMaxCompletionTokensParam` cover the Azure
130
+ // legacy-vs-`max_completion_tokens` split the same way OD's daemon retries a
131
+ // rejected `max_tokens` param; this smoke test keeps the simpler single-shot
132
+ // legacy param (a connection test failing on a param-name mismatch on a
133
+ // reasoning-tier Azure deployment is a known, narrow gap — see this
134
+ // package's `archived provenance ledger`) rather than porting OD's full retry-on-400 loop.
135
+ function buildAzureProviderCall({ input }, _options = {}) {
136
+ const { baseUrl, apiKey, model } = input;
137
+ const url = new URL(baseUrl);
138
+ const basePath = url.pathname.replace(/\/+$/, '');
139
+ const usesVersionedOpenAIPath = /\/openai\/v\d+(?:$|\/)/.test(basePath);
140
+ const apiVersion = input.apiVersion?.trim() || (usesVersionedOpenAIPath ? '' : '2024-10-21');
141
+ url.pathname = usesVersionedOpenAIPath
142
+ ? `${basePath}/chat/completions`
143
+ : `${basePath}/openai/deployments/${encodeURIComponent(model)}/chat/completions`;
144
+ if (apiVersion)
145
+ url.searchParams.set('api-version', apiVersion);
146
+ return {
147
+ url: url.toString(),
148
+ headers: { 'content-type': 'application/json', 'api-key': apiKey },
149
+ body: {
150
+ ...(usesVersionedOpenAIPath ? { model } : {}),
151
+ ...buildLegacyMaxTokensParam({ maxTokens: CONNECTION_TEST_MAX_TOKENS }),
152
+ messages: [{ role: 'user', content: SMOKE_PROMPT }],
153
+ stream: false,
154
+ },
155
+ extractText: extractOpenAIMessageText,
156
+ };
157
+ }
127
158
  function buildProviderCall(input) {
128
159
  const baseUrl = input.baseUrl;
129
160
  const apiKey = input.apiKey;
@@ -173,32 +204,14 @@ function buildProviderCall(input) {
173
204
  },
174
205
  extractText: extractOpenAIMessageText,
175
206
  };
176
- case 'azure': {
177
- const url = new URL(baseUrl);
178
- const basePath = url.pathname.replace(/\/+$/, '');
179
- const usesVersionedOpenAIPath = /\/openai\/v\d+(?:$|\/)/.test(basePath);
180
- const apiVersion = input.apiVersion?.trim() || (usesVersionedOpenAIPath ? '' : '2024-10-21');
181
- url.pathname = usesVersionedOpenAIPath
182
- ? `${basePath}/chat/completions`
183
- : `${basePath}/openai/deployments/${encodeURIComponent(model)}/chat/completions`;
184
- if (apiVersion)
185
- url.searchParams.set('api-version', apiVersion);
186
- return {
187
- url: url.toString(),
188
- headers: { 'content-type': 'application/json', 'api-key': apiKey },
189
- body: {
190
- ...(usesVersionedOpenAIPath ? { model } : {}),
191
- ...buildLegacyMaxTokensParam({ maxTokens: CONNECTION_TEST_MAX_TOKENS }),
192
- messages: [{ role: 'user', content: SMOKE_PROMPT }],
193
- stream: false,
194
- },
195
- extractText: extractOpenAIMessageText,
196
- };
197
- }
207
+ case 'azure':
208
+ return buildAzureProviderCall({ input });
198
209
  case 'google': {
199
- const effectiveBaseUrl = baseUrl.trim() || 'https://generativelanguage.googleapis.com';
210
+ // No empty-base-URL default here: `testProviderConnection` only reaches this builder after
211
+ // `validateBaseUrlResolved` parsed `baseUrl` as an http(s) URL, so it is never blank. `trim()`
212
+ // stays because the WHATWG parser accepts (and ignores) surrounding spaces the URL builder would not.
200
213
  return {
201
- url: googleGenerateContentUrl({ baseUrl: effectiveBaseUrl, model: model }),
214
+ url: googleGenerateContentUrl({ baseUrl: baseUrl.trim(), model: model }),
202
215
  headers: { 'content-type': 'application/json', 'x-goog-api-key': apiKey },
203
216
  body: {
204
217
  contents: [{ role: 'user', parts: [{ text: SMOKE_PROMPT }] }],
@@ -224,13 +237,59 @@ function buildProviderCall(input) {
224
237
  }
225
238
  }
226
239
  }
227
- // `buildLegacyMaxTokensParam`/`buildMaxCompletionTokensParam` cover the Azure
228
- // legacy-vs-`max_completion_tokens` split the same way OD's daemon retries a
229
- // rejected `max_tokens` param; this smoke test keeps the simpler single-shot
230
- // legacy param (a connection test failing on a param-name mismatch on a
231
- // reasoning-tier Azure deployment is a known, narrow gap — see this
232
- // package's `archived provenance ledger`) rather than porting OD's full retry-on-400 loop.
233
- void buildMaxCompletionTokensParam;
240
+ function parseProviderResponse({ rawText }, _options = {}) {
241
+ let data = {};
242
+ try {
243
+ data = rawText ? JSON.parse(rawText) : {};
244
+ }
245
+ catch {
246
+ // Non-JSON body — fall through to the not-`response.ok` / smoke-reply
247
+ // paths below, both of which treat an empty `data` as "no usable text".
248
+ }
249
+ return data;
250
+ }
251
+ function inspectProviderResponse({ response, data, rawText, call, input, latencyMs, model }, _options = {}) {
252
+ if (!response.ok) {
253
+ const redactedDetail = redactSecrets({ input: extractProviderErrorDetail(data, rawText).slice(0, 240) }, { exactSecrets: [input.apiKey] });
254
+ return {
255
+ ok: false,
256
+ kind: statusToKind(response.status, redactedDetail),
257
+ latencyMs,
258
+ model,
259
+ status: response.status,
260
+ detail: redactedDetail || (response.status === 404 ? 'HTTP 404 from provider; check the Base URL path.' : ''),
261
+ };
262
+ }
263
+ const text = call.extractText(data);
264
+ if (isSmokeOkReply(text)) {
265
+ return { ok: true, kind: 'success', latencyMs, model, status: response.status, detail: 'valid completion' };
266
+ }
267
+ // Redacted for exactly the reason the `!response.ok` branch above
268
+ // redacts. The transport succeeded here (HTTP 2xx) but the smoke reply
269
+ // did not match, so this is still a failure path echoing arbitrary
270
+ // provider text straight back into the admin UI — and a misbehaving or
271
+ // hostile endpoint that reflects the request's own `Authorization`
272
+ // header puts the operator's key in `detail` verbatim. Two independent
273
+ // audits reproduced that, each from a different call boundary; the
274
+ // redaction was simply missing on this one branch.
275
+ const sample = truncateSample(redactSecrets({ input: text }, { exactSecrets: [input.apiKey] }));
276
+ // Naming the stop reason turns an unactionable "it returned nothing" into a diagnosis:
277
+ // `MAX_TOKENS` means the smoke budget was too small (usually a thinking model), a safety or
278
+ // content-filter reason means the probe was blocked, not that the endpoint is broken.
279
+ const finishReason = extractFinishReason(data);
280
+ return {
281
+ ok: false,
282
+ kind: 'unknown',
283
+ latencyMs,
284
+ model,
285
+ status: response.status,
286
+ detail: sample
287
+ ? `Expected smoke test reply "ok"; got "${sample}"`
288
+ : finishReason
289
+ ? `Provider returned a 2xx response without assistant text (finish reason: ${finishReason})`
290
+ : 'Provider returned a 2xx response without assistant text',
291
+ };
292
+ }
234
293
  /**
235
294
  * Probes a BYOK provider endpoint with the supplied credentials by sending a
236
295
  * tiny smoke-test completion request, and classifies the result. Validates
@@ -274,13 +333,15 @@ export async function testProviderConnection(requiredArgs, optionalArgs = {}) {
274
333
  };
275
334
  }
276
335
  const validated = await validateBaseUrlResolved({ baseUrl: input.baseUrl, lookup: input.dnsLookup ?? defaultDnsLookup });
277
- if (validated.error || !validated.parsed) {
336
+ // `validateBaseUrlResolved` reports every rejection through `error`; a result without one always
337
+ // carries the parsed URL, so `error` alone decides.
338
+ if (validated.error !== undefined) {
278
339
  return {
279
340
  ok: false,
280
341
  kind: validated.forbidden ? 'forbidden' : 'invalid_base_url',
281
342
  latencyMs: Date.now() - start,
282
343
  model,
283
- detail: validated.error ?? '',
344
+ detail: validated.error,
284
345
  };
285
346
  }
286
347
  let call;
@@ -293,9 +354,15 @@ export async function testProviderConnection(requiredArgs, optionalArgs = {}) {
293
354
  kind: 'unknown',
294
355
  latencyMs: Date.now() - start,
295
356
  model,
296
- detail: redactSecrets({ input: err instanceof Error ? err.message : String(err) }, { exactSecrets: [input.apiKey] }),
357
+ detail: providerFailureDetail({ err, apiKey: input.apiKey }),
297
358
  };
298
359
  }
360
+ return performProviderCall({ input, call, start, model });
361
+ }
362
+ function providerFailureDetail({ err, apiKey }, _options = {}) {
363
+ return redactSecrets({ input: err instanceof Error ? err.message : String(err) }, { exactSecrets: [apiKey] });
364
+ }
365
+ async function performProviderCall({ input, call, start, model }, _options = {}) {
299
366
  const controller = new AbortController();
300
367
  const abortFromParent = () => controller.abort();
301
368
  if (input.signal?.aborted) {
@@ -304,10 +371,10 @@ export async function testProviderConnection(requiredArgs, optionalArgs = {}) {
304
371
  else {
305
372
  input.signal?.addEventListener('abort', abortFromParent, { once: true });
306
373
  }
307
- const timer = setTimeout(() => controller.abort(), CONNECTION_TEST_TIMEOUT_MS);
374
+ const timer = setTimeout(() => controller.abort(), input.timeoutMs ?? CONNECTION_TEST_TIMEOUT_MS);
308
375
  let result;
309
376
  try {
310
- const response = await fetch(call.url, {
377
+ const response = await (input.fetchFn ?? fetch)(call.url, {
311
378
  ...input.requestInit,
312
379
  method: 'POST',
313
380
  headers: call.headers,
@@ -316,58 +383,8 @@ export async function testProviderConnection(requiredArgs, optionalArgs = {}) {
316
383
  });
317
384
  const latencyMs = Date.now() - start;
318
385
  const rawText = await response.text().catch(() => '');
319
- let data = {};
320
- try {
321
- data = rawText ? JSON.parse(rawText) : {};
322
- }
323
- catch {
324
- // Non-JSON body — fall through to the not-`response.ok` / smoke-reply
325
- // paths below, both of which treat an empty `data` as "no usable text".
326
- }
327
- if (!response.ok) {
328
- const redactedDetail = redactSecrets({ input: extractProviderErrorDetail(data, rawText).slice(0, 240) }, { exactSecrets: [input.apiKey] });
329
- result = {
330
- ok: false,
331
- kind: statusToKind(response.status, redactedDetail),
332
- latencyMs,
333
- model,
334
- status: response.status,
335
- detail: redactedDetail || (response.status === 404 ? 'HTTP 404 from provider; check the Base URL path.' : ''),
336
- };
337
- }
338
- else {
339
- const text = call.extractText(data);
340
- if (isSmokeOkReply(text)) {
341
- result = { ok: true, kind: 'success', latencyMs, model, status: response.status, detail: 'valid completion' };
342
- }
343
- else {
344
- // Redacted for exactly the reason the `!response.ok` branch above
345
- // redacts. The transport succeeded here (HTTP 2xx) but the smoke reply
346
- // did not match, so this is still a failure path echoing arbitrary
347
- // provider text straight back into the admin UI — and a misbehaving or
348
- // hostile endpoint that reflects the request's own `Authorization`
349
- // header puts the operator's key in `detail` verbatim. Two independent
350
- // audits reproduced that, each from a different call boundary; the
351
- // redaction was simply missing on this one branch.
352
- const sample = truncateSample(redactSecrets({ input: text }, { exactSecrets: [input.apiKey] }));
353
- // Naming the stop reason turns an unactionable "it returned nothing" into a diagnosis:
354
- // `MAX_TOKENS` means the smoke budget was too small (usually a thinking model), a safety or
355
- // content-filter reason means the probe was blocked, not that the endpoint is broken.
356
- const finishReason = extractFinishReason(data);
357
- result = {
358
- ok: false,
359
- kind: 'unknown',
360
- latencyMs,
361
- model,
362
- status: response.status,
363
- detail: sample
364
- ? `Expected smoke test reply "ok"; got "${sample}"`
365
- : finishReason
366
- ? `Provider returned a 2xx response without assistant text (finish reason: ${finishReason})`
367
- : 'Provider returned a 2xx response without assistant text',
368
- };
369
- }
370
- }
386
+ const data = parseProviderResponse({ rawText });
387
+ result = inspectProviderResponse({ response, data, rawText, call, input, latencyMs, model });
371
388
  }
372
389
  catch (err) {
373
390
  result = {
@@ -375,7 +392,7 @@ export async function testProviderConnection(requiredArgs, optionalArgs = {}) {
375
392
  kind: networkErrorToKind(err),
376
393
  latencyMs: Date.now() - start,
377
394
  model,
378
- detail: redactSecrets({ input: err instanceof Error ? err.message : String(err) }, { exactSecrets: [input.apiKey] }),
395
+ detail: providerFailureDetail({ err, apiKey: input.apiKey }),
379
396
  };
380
397
  }
381
398
  finally {
@@ -87,6 +87,9 @@ function cloneVoiceOptions(voices) {
87
87
  ...(voice.labels ? { labels: { ...voice.labels } } : {}),
88
88
  }));
89
89
  }
90
+ function readVoiceCatalog({ payload }, _options = {}) {
91
+ return isRecord(payload) && Array.isArray(payload.voices) ? payload.voices : [];
92
+ }
90
93
  /** Owns transport, time and a bounded voice cache for one host lifecycle.
91
94
  * Supply the existing policy-enforcing HTTP client; this factory never constructs a raw transport.
92
95
  * @throws RangeError for an invalid cache bound; credential/transport/JSON errors propagate from listing.
@@ -130,7 +133,7 @@ export function createElevenLabsVoiceClient({ http, clock }, { maxCacheEntries =
130
133
  if (resp.bodyTruncated)
131
134
  throw new Error('elevenlabs voices response was truncated');
132
135
  const payload = JSON.parse(resp.bodyText);
133
- const rawVoices = isRecord(payload) && Array.isArray(payload.voices) ? payload.voices : [];
136
+ const rawVoices = readVoiceCatalog({ payload });
134
137
  const voices = rawVoices.map((voice) => normalizeVoice(voice))
135
138
  .filter((voice) => voice !== null);
136
139
  const now = clock.nowMs();
@@ -96,6 +96,7 @@
96
96
  import { createRoleMarkerGuard } from '../role-marker-guard.js';
97
97
  import { type DnsLookupFn, type PinnedFetch } from './connection-guard.js';
98
98
  import { type TurnEndReason } from './turn-end-guard.js';
99
+ import type { ProviderToolSnapshotOptions, ProviderSchemaFallback } from './tool-turn-types.js';
99
100
  export interface GoogleTextPart {
100
101
  readonly text: string;
101
102
  }
@@ -216,6 +217,9 @@ export interface GoogleTurnOptions {
216
217
  readonly system?: string;
217
218
  readonly contents: readonly GoogleContent[];
218
219
  readonly tools?: readonly GoogleToolDef[];
220
+ /** Refresh the run's projection immediately before each HTTP request. */
221
+ readonly getTools?: (options?: ProviderToolSnapshotOptions) => readonly GoogleToolDef[];
222
+ readonly onSchemaFallback?: (event: ProviderSchemaFallback) => void;
219
223
  readonly temperature?: number;
220
224
  readonly maxOutputTokens?: number;
221
225
  /** Same bound and rationale as `AnthropicTurnOptions.maxToolTurns`. Defaults to 8. */
@@ -99,6 +99,7 @@ import { defaultDnsLookup, pinnedFetch, validateBaseUrlResolved } from './connec
99
99
  import { googleStreamGenerateContentUrl } from './google.js';
100
100
  import { decodeSseStream } from './sse-decode.js';
101
101
  import { createTurnEndGuard } from './turn-end-guard.js';
102
+ import { createStrictToolRetry } from './openai-chat.js';
102
103
  const DEFAULT_GOOGLE_BASE_URL = 'https://generativelanguage.googleapis.com';
103
104
  const DEFAULT_MAX_TOOL_TURNS = 8;
104
105
  function isRecord(value) {
@@ -127,7 +128,10 @@ function googleHeaders(options) {
127
128
  ...(options.extraHeaders ?? {}),
128
129
  };
129
130
  }
130
- function googleRequestBody(options, contents) {
131
+ /** Build a request-local body; VALIDATED permits both calls and ordinary language responses.
132
+ * @complexity O(1) local time/space; JSON serialization later traverses the history and schemas.
133
+ */
134
+ function googleRequestBody(options, contents, { validated = false } = {}) {
131
135
  const generationConfig = {
132
136
  ...(options.temperature !== undefined ? { temperature: options.temperature } : {}),
133
137
  ...(options.maxOutputTokens !== undefined ? { maxOutputTokens: options.maxOutputTokens } : {}),
@@ -136,6 +140,7 @@ function googleRequestBody(options, contents) {
136
140
  contents,
137
141
  ...(options.system !== undefined ? { systemInstruction: { parts: [{ text: options.system }] } } : {}),
138
142
  ...(options.tools && options.tools.length > 0 ? { tools: options.tools } : {}),
143
+ ...(validated ? { toolConfig: { functionCallingConfig: { mode: 'VALIDATED' } } } : {}),
139
144
  ...(Object.keys(generationConfig).length > 0 ? { generationConfig } : {}),
140
145
  };
141
146
  }
@@ -255,6 +260,36 @@ export function processGoogleFrame({ state, data, onEvent }) {
255
260
  ? { action: 'end', reason: 'contaminated' }
256
261
  : { action: 'continue' };
257
262
  }
263
+ /** Refresh the projection once per request and retain the names used by strict retry. */
264
+ function refreshGoogleTools({ options, retry }, _options = {}) {
265
+ const tools = options.getTools?.({ strict: retry.enabled }) ?? options.tools;
266
+ const toolNames = (tools ?? []).flatMap(tool => tool.functionDeclarations.map(declaration => declaration.name));
267
+ const validated = Boolean(options.getTools && retry.enabled && toolNames.length > 0);
268
+ return { tools, toolNames, validated };
269
+ }
270
+ /** Resolve HTTP failures before inspecting the body; only validated requests may downgrade. */
271
+ async function resolveGoogleResponse({ response, options, contents, emitEnd, retry, toolNames, validated }, _options = {}) {
272
+ const { onEvent } = options;
273
+ if (!response.ok) {
274
+ const rawText = await response.text();
275
+ if (validated && retry.downgrade({ status: response.status, rawErrorText: rawText, toolNames })) {
276
+ return openGoogleResponseStream({ options, contents, emitEnd, retry });
277
+ }
278
+ onEvent({
279
+ type: 'error',
280
+ message: redactSecrets({ input: extractGoogleErrorDetail(rawText) }, { exactSecrets: [options.apiKey] }),
281
+ code: String(response.status),
282
+ });
283
+ emitEnd('error');
284
+ return null;
285
+ }
286
+ if (!response.body) {
287
+ onEvent({ type: 'error', message: 'Google response had no body' });
288
+ emitEnd('error');
289
+ return null;
290
+ }
291
+ return response.body;
292
+ }
258
293
  /**
259
294
  * Validates `options.baseUrl` and opens the streaming POST, returning the response's readable body
260
295
  * once every pre-stream failure mode (SSRF-guard rejection, network error, non-2xx status, missing
@@ -262,7 +297,7 @@ export function processGoogleFrame({ state, data, onEvent }) {
262
297
  * the caller only has to check for `null` — same split as
263
298
  * `anthropic-messages.ts#openAnthropicResponseStream`.
264
299
  */
265
- async function openGoogleResponseStream(options, contents, emitEnd) {
300
+ async function openGoogleResponseStream({ options, contents, emitEnd, retry }, _options = {}) {
266
301
  const { onEvent } = options;
267
302
  const baseUrlCheck = await validateBaseUrlResolved({ baseUrl: options.baseUrl ?? DEFAULT_GOOGLE_BASE_URL, lookup: options.dnsLookup ?? defaultDnsLookup });
268
303
  if (baseUrlCheck.error) {
@@ -270,12 +305,13 @@ async function openGoogleResponseStream(options, contents, emitEnd) {
270
305
  emitEnd('error');
271
306
  return null;
272
307
  }
308
+ const { tools, toolNames, validated } = refreshGoogleTools({ options, retry });
273
309
  let response;
274
310
  try {
275
311
  response = await (options.fetchImpl ?? pinnedFetch)({ url: googleRequestUrl(options.baseUrl, options.model), init: {
276
312
  method: 'POST',
277
313
  headers: googleHeaders(options),
278
- body: JSON.stringify(googleRequestBody(options, contents)),
314
+ body: JSON.stringify(googleRequestBody({ ...options, ...(tools !== undefined ? { tools } : {}) }, contents, { validated })),
279
315
  redirect: 'error',
280
316
  ...(options.signal ? { signal: options.signal } : {}),
281
317
  }, pinnedAddress: baseUrlCheck.pinnedAddress });
@@ -286,27 +322,12 @@ async function openGoogleResponseStream(options, contents, emitEnd) {
286
322
  emitEnd('error');
287
323
  return null;
288
324
  }
289
- if (!response.ok) {
290
- const rawText = await response.text();
291
- onEvent({
292
- type: 'error',
293
- message: redactSecrets({ input: extractGoogleErrorDetail(rawText) }, { exactSecrets: [options.apiKey] }),
294
- code: String(response.status),
295
- });
296
- emitEnd('error');
297
- return null;
298
- }
299
- if (!response.body) {
300
- onEvent({ type: 'error', message: 'Google response had no body' });
301
- emitEnd('error');
302
- return null;
303
- }
304
- return response.body;
325
+ return resolveGoogleResponse({ response, options, contents, emitEnd, retry, toolNames, validated });
305
326
  }
306
327
  /** Runs exactly one Gemini `streamGenerateContent` request and reduces its SSE events into a single outcome. Mirrors `anthropic-messages.ts#runSingleAnthropicRequest`'s `emitEnd` contract — see that function's doc. */
307
- async function runSingleGoogleRequest(options, contents, emitEnd) {
328
+ async function runSingleGoogleRequest(options, contents, emitEnd, retry) {
308
329
  const { onEvent } = options;
309
- const body = await openGoogleResponseStream(options, contents, emitEnd);
330
+ const body = await openGoogleResponseStream({ options, contents, emitEnd, retry });
310
331
  if (!body) {
311
332
  return { finishReason: null, toolCalls: [], text: '' };
312
333
  }
@@ -473,6 +494,9 @@ export async function executeGoogleToolCalls({ executeTool, calls, onEvent }) {
473
494
  }
474
495
  return { functionResponseParts, followUpParts };
475
496
  }
497
+ function isEmptyInitialGoogleTurn({ toolTurns, outcome }, _options = {}) {
498
+ return toolTurns === 0 && outcome.toolCalls.length === 0 && !outcome.text.trim();
499
+ }
476
500
  /**
477
501
  * Runs a full Gemini `streamGenerateContent` turn, including the
478
502
  * tool-execution loop when `options.executeTool` is supplied and the model
@@ -483,6 +507,7 @@ export async function executeGoogleToolCalls({ executeTool, calls, onEvent }) {
483
507
  */
484
508
  export async function runGoogleToolTurn(requiredArgs, optionalArgs = {}) {
485
509
  const options = { ...optionalArgs, ...requiredArgs };
510
+ const retry = createStrictToolRetry({ protocol: 'google', onSchemaFallback: options.onSchemaFallback });
486
511
  const maxToolTurns = options.maxToolTurns ?? DEFAULT_MAX_TOOL_TURNS;
487
512
  const executeTool = options.executeTool;
488
513
  const endGuard = createTurnEndGuard(options.onEvent, (reason) => ({ type: 'end', reason }));
@@ -491,11 +516,11 @@ export async function runGoogleToolTurn(requiredArgs, optionalArgs = {}) {
491
516
  let toolTurns = 0;
492
517
  let lastFinishReason = null;
493
518
  while (true) {
494
- const outcome = await runSingleGoogleRequest(options, contents, emitEnd);
519
+ const outcome = await runSingleGoogleRequest(options, contents, emitEnd, retry);
495
520
  lastFinishReason = outcome.finishReason;
496
521
  if (endGuard.hasEnded())
497
522
  break;
498
- if (toolTurns === 0 && outcome.toolCalls.length === 0 && !outcome.text.trim()) {
523
+ if (isEmptyInitialGoogleTurn({ toolTurns, outcome })) {
499
524
  // Thinking can consume the entire output budget without producing any answer. Preserve
500
525
  // the reason for operator diagnostics rather than turning a content-free response into stop.
501
526
  options.onEvent({ type: 'error', message: redactSecrets({
@@ -201,36 +201,30 @@ function findNumericEnumPathsValue(schema, prefix = []) {
201
201
  }
202
202
  return paths;
203
203
  }
204
- function readAtGooglePath(input, segments) {
205
- let current = input;
206
- for (const segment of segments) {
207
- if (!isRecord(current))
208
- return undefined;
209
- current = current[segment];
210
- }
211
- return current;
212
- }
213
- function writeAtGooglePath(input, segments, value) {
204
+ function coerceNumericEnumString(value) {
205
+ return typeof value === "string" && value.trim().length > 0 && Number.isFinite(Number(value)) ? Number(value) : value;
206
+ }
207
+ /** Walks `segments` and coerces the leaf in one pass, copying only the records on a changed path so
208
+ * the incoming argument is never mutated. A hop through a non-record leaves the input as-is. The
209
+ * earlier separate read/write walkers carried guards for "no segments" and "intermediate is not a
210
+ * record" on the write side that the read side had already ruled out (`String#split` always yields
211
+ * at least one segment, and a write only followed a read that reached a string leaf). */
212
+ function coerceAtGooglePath(node, segments) {
213
+ if (segments.length === 0)
214
+ return coerceNumericEnumString(node);
215
+ if (!isRecord(node))
216
+ return node;
214
217
  const [head, ...rest] = segments;
215
- if (head === undefined)
216
- return input;
217
- if (rest.length === 0)
218
- return { ...input, [head]: value };
219
- const child = input[head];
220
- if (!isRecord(child))
221
- return input;
222
- return { ...input, [head]: writeAtGooglePath(child, rest, value) };
218
+ const child = node[head];
219
+ const coerced = coerceAtGooglePath(child, rest);
220
+ return coerced === child ? node : { ...node, [head]: coerced };
223
221
  }
224
222
  function coerceNumericEnumStringsToNumbersValue(input, paths) {
225
223
  if (paths.length === 0 || !isRecord(input))
226
224
  return input;
227
225
  let result = input;
228
226
  for (const path of paths) {
229
- const segments = path.split(".");
230
- const current = readAtGooglePath(result, segments);
231
- if (typeof current === "string" && current.trim().length > 0 && Number.isFinite(Number(current))) {
232
- result = writeAtGooglePath(result, segments, Number(current));
233
- }
227
+ result = coerceAtGooglePath(result, path.split("."));
234
228
  }
235
229
  return result;
236
230
  }