@jini-ai/agent-runtime 0.4.10 → 0.4.12

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 (112) hide show
  1. package/CHANGELOG.md +9 -0
  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.js +12 -5
  21. package/dist/copilot-stream.js +42 -50
  22. package/dist/defs/aider.js +3 -4
  23. package/dist/defs/amr.js +52 -61
  24. package/dist/defs/antigravity.d.ts +6 -5
  25. package/dist/defs/antigravity.js +48 -34
  26. package/dist/defs/auggie.d.ts +1 -1
  27. package/dist/defs/claude-compatible-args.d.ts +19 -0
  28. package/dist/defs/claude-compatible-args.js +42 -0
  29. package/dist/defs/claude.d.ts +7 -2
  30. package/dist/defs/claude.js +96 -85
  31. package/dist/defs/cline.d.ts +1 -1
  32. package/dist/defs/codebuddy.d.ts +1 -1
  33. package/dist/defs/codebuddy.js +29 -46
  34. package/dist/defs/codex.d.ts +15 -3
  35. package/dist/defs/codex.js +143 -108
  36. package/dist/defs/cursor-agent.d.ts +9 -7
  37. package/dist/defs/cursor-agent.js +53 -51
  38. package/dist/defs/devin.d.ts +1 -1
  39. package/dist/defs/goose.d.ts +1 -1
  40. package/dist/defs/hermes.d.ts +1 -1
  41. package/dist/defs/kilo.d.ts +1 -1
  42. package/dist/defs/kimi.d.ts +1 -1
  43. package/dist/defs/kiro.d.ts +1 -1
  44. package/dist/defs/opencode.d.ts +5 -4
  45. package/dist/defs/opencode.js +26 -32
  46. package/dist/defs/pi.d.ts +6 -5
  47. package/dist/defs/pi.js +24 -26
  48. package/dist/defs/qoder.d.ts +4 -3
  49. package/dist/defs/qoder.js +25 -25
  50. package/dist/defs/reasonix.d.ts +1 -1
  51. package/dist/defs/shared.d.ts +12 -3
  52. package/dist/defs/shared.js +19 -13
  53. package/dist/defs/trae-cli.d.ts +1 -1
  54. package/dist/defs/vibe.d.ts +1 -1
  55. package/dist/detection.d.ts +13 -20
  56. package/dist/detection.js +129 -111
  57. package/dist/env.js +56 -41
  58. package/dist/executables.js +103 -114
  59. package/dist/index.d.ts +1 -0
  60. package/dist/index.js +1 -0
  61. package/dist/json-event-stream.js +611 -527
  62. package/dist/launch.js +44 -37
  63. package/dist/model-discovery-adapters.d.ts +17 -0
  64. package/dist/model-discovery-adapters.js +223 -164
  65. package/dist/model-discovery-config.js +107 -87
  66. package/dist/model-discovery-sdk.d.ts +16 -2
  67. package/dist/model-discovery-sdk.js +4 -3
  68. package/dist/model-discovery-shared.d.ts +14 -0
  69. package/dist/model-discovery-shared.js +50 -15
  70. package/dist/model-discovery-types.d.ts +2 -0
  71. package/dist/model-discovery.js +219 -117
  72. package/dist/models.d.ts +14 -1
  73. package/dist/models.js +75 -19
  74. package/dist/native-tool-policy.d.ts +29 -0
  75. package/dist/native-tool-policy.js +36 -0
  76. package/dist/opencode-log.js +46 -30
  77. package/dist/paths.d.ts +2 -0
  78. package/dist/paths.js +3 -3
  79. package/dist/providers/aihubmix.js +13 -18
  80. package/dist/providers/anthropic-messages.d.ts +7 -0
  81. package/dist/providers/anthropic-messages.js +45 -21
  82. package/dist/providers/azure-chat.d.ts +5 -0
  83. package/dist/providers/azure-chat.js +13 -5
  84. package/dist/providers/connection-guard.d.ts +2 -45
  85. package/dist/providers/connection-guard.js +11 -10
  86. package/dist/providers/connection-test.d.ts +4 -0
  87. package/dist/providers/connection-test.js +127 -110
  88. package/dist/providers/elevenlabs.js +4 -1
  89. package/dist/providers/google-messages.d.ts +7 -0
  90. package/dist/providers/google-messages.js +69 -23
  91. package/dist/providers/google-schema.js +17 -23
  92. package/dist/providers/model-catalog.js +160 -145
  93. package/dist/providers/oauth-callback-server.js +37 -34
  94. package/dist/providers/oauth-credentials.js +23 -23
  95. package/dist/providers/oauth-tokens.js +16 -24
  96. package/dist/providers/openai-chat.d.ts +42 -0
  97. package/dist/providers/openai-chat.js +80 -10
  98. package/dist/providers/operation-schema.d.ts +25 -0
  99. package/dist/providers/operation-schema.js +226 -0
  100. package/dist/providers/response-text.d.ts +10 -0
  101. package/dist/providers/response-text.js +23 -0
  102. package/dist/providers/tool-turn-types.d.ts +35 -9
  103. package/dist/providers/tool-turn.d.ts +7 -0
  104. package/dist/providers/tool-turn.js +113 -32
  105. package/dist/qoder-stream.js +93 -80
  106. package/dist/registry.d.ts +45 -0
  107. package/dist/registry.js +39 -0
  108. package/dist/runtime-state.d.ts +1 -1
  109. package/dist/types.d.ts +43 -1
  110. package/package.json +16 -7
  111. package/dist/defs/gemini.d.ts +0 -24
  112. package/dist/defs/gemini.js +0 -81
@@ -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. */
@@ -247,6 +251,7 @@ export interface GoogleStreamState {
247
251
  finishReason: string | null;
248
252
  usage: Record<string, unknown> | null;
249
253
  }
254
+ /** Adds the shared `input_tokens`/`output_tokens` fields (the only ones the chat usage reducers read) to raw Gemini `usageMetadata` and emits usage. */
250
255
  export declare function applyGoogleUsage({ state, data, onEvent }: {
251
256
  state: GoogleStreamState;
252
257
  data: Record<string, unknown>;
@@ -337,6 +342,8 @@ export declare function executeGoogleToolCalls({ executeTool, calls, onEvent }:
337
342
  * tool-execution loop when `options.executeTool` is supplied and the model
338
343
  * requests a function call. See `anthropic-messages.ts#runAnthropicToolTurn`'s
339
344
  * doc for the shared event-stream/`ended`-flag contract this mirrors.
345
+ * An initial response without text or calls emits an error with its provider finish reason,
346
+ * not a successful stop. Tool-only turns remain valid: the host may already have acted on them.
340
347
  */
341
348
  export declare function runGoogleToolTurn(requiredArgs: Pick<GoogleTurnOptions, "apiKey" | "model" | "contents" | "onEvent">, optionalArgs?: Omit<GoogleTurnOptions, "apiKey" | "model" | "contents" | "onEvent">): Promise<GoogleTurnResult>;
342
349
  export {};
@@ -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
  }
@@ -151,10 +156,20 @@ function extractGoogleErrorDetail(rawText) {
151
156
  }
152
157
  return rawText.trim().slice(0, 500);
153
158
  }
159
+ /** Adds the shared `input_tokens`/`output_tokens` fields (the only ones the chat usage reducers read) to raw Gemini `usageMetadata` and emits usage. */
154
160
  export function applyGoogleUsage({ state, data, onEvent }) {
155
161
  if (!isRecord(data.usageMetadata))
156
162
  return;
157
- state.usage = data.usageMetadata;
163
+ const usage = data.usageMetadata;
164
+ const candidateTokens = typeof usage.candidatesTokenCount === 'number' ? usage.candidatesTokenCount : undefined;
165
+ const thoughtsTokens = typeof usage.thoughtsTokenCount === 'number' ? usage.thoughtsTokenCount : undefined;
166
+ state.usage = {
167
+ ...usage,
168
+ // Thoughts are reported separately from candidates; they count as output, as thinking/reasoning
169
+ // tokens already do inside Anthropic's `output_tokens` and OpenAI's `completion_tokens`.
170
+ ...(typeof usage.promptTokenCount === 'number' ? { input_tokens: usage.promptTokenCount } : {}),
171
+ ...(candidateTokens !== undefined || thoughtsTokens !== undefined ? { output_tokens: (candidateTokens ?? 0) + (thoughtsTokens ?? 0) } : {}),
172
+ };
158
173
  onEvent({ type: 'usage', usage: state.usage });
159
174
  }
160
175
  /** The frame's first candidate, unnarrowed — `processGoogleFrame` distinguishes "no candidate at all" (checks `promptFeedback` for a blocked-prompt error) from "a candidate that isn't a record" (silently skipped), so this deliberately does not collapse both into one `null`. */
@@ -245,6 +260,36 @@ export function processGoogleFrame({ state, data, onEvent }) {
245
260
  ? { action: 'end', reason: 'contaminated' }
246
261
  : { action: 'continue' };
247
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
+ }
248
293
  /**
249
294
  * Validates `options.baseUrl` and opens the streaming POST, returning the response's readable body
250
295
  * once every pre-stream failure mode (SSRF-guard rejection, network error, non-2xx status, missing
@@ -252,7 +297,7 @@ export function processGoogleFrame({ state, data, onEvent }) {
252
297
  * the caller only has to check for `null` — same split as
253
298
  * `anthropic-messages.ts#openAnthropicResponseStream`.
254
299
  */
255
- async function openGoogleResponseStream(options, contents, emitEnd) {
300
+ async function openGoogleResponseStream({ options, contents, emitEnd, retry }, _options = {}) {
256
301
  const { onEvent } = options;
257
302
  const baseUrlCheck = await validateBaseUrlResolved({ baseUrl: options.baseUrl ?? DEFAULT_GOOGLE_BASE_URL, lookup: options.dnsLookup ?? defaultDnsLookup });
258
303
  if (baseUrlCheck.error) {
@@ -260,12 +305,13 @@ async function openGoogleResponseStream(options, contents, emitEnd) {
260
305
  emitEnd('error');
261
306
  return null;
262
307
  }
308
+ const { tools, toolNames, validated } = refreshGoogleTools({ options, retry });
263
309
  let response;
264
310
  try {
265
311
  response = await (options.fetchImpl ?? pinnedFetch)({ url: googleRequestUrl(options.baseUrl, options.model), init: {
266
312
  method: 'POST',
267
313
  headers: googleHeaders(options),
268
- body: JSON.stringify(googleRequestBody(options, contents)),
314
+ body: JSON.stringify(googleRequestBody({ ...options, ...(tools !== undefined ? { tools } : {}) }, contents, { validated })),
269
315
  redirect: 'error',
270
316
  ...(options.signal ? { signal: options.signal } : {}),
271
317
  }, pinnedAddress: baseUrlCheck.pinnedAddress });
@@ -276,27 +322,12 @@ async function openGoogleResponseStream(options, contents, emitEnd) {
276
322
  emitEnd('error');
277
323
  return null;
278
324
  }
279
- if (!response.ok) {
280
- const rawText = await response.text();
281
- onEvent({
282
- type: 'error',
283
- message: redactSecrets({ input: extractGoogleErrorDetail(rawText) }, { exactSecrets: [options.apiKey] }),
284
- code: String(response.status),
285
- });
286
- emitEnd('error');
287
- return null;
288
- }
289
- if (!response.body) {
290
- onEvent({ type: 'error', message: 'Google response had no body' });
291
- emitEnd('error');
292
- return null;
293
- }
294
- return response.body;
325
+ return resolveGoogleResponse({ response, options, contents, emitEnd, retry, toolNames, validated });
295
326
  }
296
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. */
297
- async function runSingleGoogleRequest(options, contents, emitEnd) {
328
+ async function runSingleGoogleRequest(options, contents, emitEnd, retry) {
298
329
  const { onEvent } = options;
299
- const body = await openGoogleResponseStream(options, contents, emitEnd);
330
+ const body = await openGoogleResponseStream({ options, contents, emitEnd, retry });
300
331
  if (!body) {
301
332
  return { finishReason: null, toolCalls: [], text: '' };
302
333
  }
@@ -463,14 +494,20 @@ export async function executeGoogleToolCalls({ executeTool, calls, onEvent }) {
463
494
  }
464
495
  return { functionResponseParts, followUpParts };
465
496
  }
497
+ function isEmptyInitialGoogleTurn({ toolTurns, outcome }, _options = {}) {
498
+ return toolTurns === 0 && outcome.toolCalls.length === 0 && !outcome.text.trim();
499
+ }
466
500
  /**
467
501
  * Runs a full Gemini `streamGenerateContent` turn, including the
468
502
  * tool-execution loop when `options.executeTool` is supplied and the model
469
503
  * requests a function call. See `anthropic-messages.ts#runAnthropicToolTurn`'s
470
504
  * doc for the shared event-stream/`ended`-flag contract this mirrors.
505
+ * An initial response without text or calls emits an error with its provider finish reason,
506
+ * not a successful stop. Tool-only turns remain valid: the host may already have acted on them.
471
507
  */
472
508
  export async function runGoogleToolTurn(requiredArgs, optionalArgs = {}) {
473
509
  const options = { ...optionalArgs, ...requiredArgs };
510
+ const retry = createStrictToolRetry({ protocol: 'google', onSchemaFallback: options.onSchemaFallback });
474
511
  const maxToolTurns = options.maxToolTurns ?? DEFAULT_MAX_TOOL_TURNS;
475
512
  const executeTool = options.executeTool;
476
513
  const endGuard = createTurnEndGuard(options.onEvent, (reason) => ({ type: 'end', reason }));
@@ -479,10 +516,19 @@ export async function runGoogleToolTurn(requiredArgs, optionalArgs = {}) {
479
516
  let toolTurns = 0;
480
517
  let lastFinishReason = null;
481
518
  while (true) {
482
- const outcome = await runSingleGoogleRequest(options, contents, emitEnd);
519
+ const outcome = await runSingleGoogleRequest(options, contents, emitEnd, retry);
483
520
  lastFinishReason = outcome.finishReason;
484
521
  if (endGuard.hasEnded())
485
522
  break;
523
+ if (isEmptyInitialGoogleTurn({ toolTurns, outcome })) {
524
+ // Thinking can consume the entire output budget without producing any answer. Preserve
525
+ // the reason for operator diagnostics rather than turning a content-free response into stop.
526
+ options.onEvent({ type: 'error', message: redactSecrets({
527
+ input: `Google returned no text or tool calls (${outcome.finishReason ?? 'missing finish reason'})`,
528
+ }, { exactSecrets: [options.apiKey] }) });
529
+ emitEnd('error');
530
+ break;
531
+ }
486
532
  const exitReason = googleLoopExitReason({ outcome: outcome, toolTurns: toolTurns, maxToolTurns: maxToolTurns });
487
533
  if (exitReason) {
488
534
  emitEnd(exitReason);
@@ -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
  }