@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
@@ -50,36 +50,30 @@ function statusToKind(status) {
50
50
  return 'upstream_unavailable';
51
51
  return 'unknown';
52
52
  }
53
+ function nonBlankErrorMessage({ value }, _options = {}) {
54
+ return typeof value === 'string' && value.trim() ? value : undefined;
55
+ }
53
56
  function extractProviderErrorDetail(data, rawText) {
54
57
  const obj = data && typeof data === 'object' ? data : null;
55
58
  const error = obj ? obj.error : null;
56
59
  if (typeof error === 'string')
57
60
  return error;
58
61
  if (error && typeof error === 'object') {
59
- const message = error.message;
60
- if (typeof message === 'string' && message.trim())
62
+ const message = nonBlankErrorMessage({ value: error.message });
63
+ if (message !== undefined)
61
64
  return message;
62
65
  }
63
- const message = obj ? obj.message : null;
64
- if (typeof message === 'string' && message.trim())
65
- return message;
66
- return rawText.trim().slice(0, 240);
66
+ const message = nonBlankErrorMessage({ value: obj ? obj.message : null });
67
+ return message ?? rawText.trim().slice(0, 240);
67
68
  }
69
+ const INVALID_BASE_URL_NETWORK_CODES = new Set(['ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT', 'EHOSTUNREACH', 'ENETUNREACH', 'CERT_HAS_EXPIRED', 'UNABLE_TO_VERIFY_LEAF_SIGNATURE']);
68
70
  function networkErrorToKind(err) {
69
71
  if (err instanceof Error) {
70
72
  if (err.name === 'AbortError')
71
73
  return 'timeout';
72
74
  const cause = err.cause;
73
75
  const code = cause?.code;
74
- if (code === 'ENOTFOUND' ||
75
- code === 'EAI_AGAIN' ||
76
- code === 'ECONNREFUSED' ||
77
- code === 'ECONNRESET' ||
78
- code === 'ETIMEDOUT' ||
79
- code === 'EHOSTUNREACH' ||
80
- code === 'ENETUNREACH' ||
81
- code === 'CERT_HAS_EXPIRED' ||
82
- code === 'UNABLE_TO_VERIFY_LEAF_SIGNATURE') {
76
+ if (INVALID_BASE_URL_NETWORK_CODES.has(code)) {
83
77
  return 'invalid_base_url';
84
78
  }
85
79
  }
@@ -97,24 +91,13 @@ function uniqueModels(models) {
97
91
  }
98
92
  return out.sort((a, b) => a.id.localeCompare(b.id));
99
93
  }
94
+ const NON_CHAT_MODEL_FRAGMENTS = ['embedding', 'moderation', 'rerank', 'whisper', 'tts', 'transcribe', 'speech', 'image', 'video', 'dall-e', 'stable-diffusion', 'flux'];
100
95
  function isOpenAiChatModelId(id) {
101
96
  const normalized = id.trim().toLowerCase();
102
97
  if (!normalized)
103
98
  return false;
104
- if (normalized.includes('embedding') ||
105
- normalized.includes('moderation') ||
106
- normalized.includes('rerank') ||
107
- normalized.includes('whisper') ||
108
- normalized.includes('tts') ||
109
- normalized.includes('transcribe') ||
110
- normalized.includes('speech') ||
111
- normalized.includes('image') ||
112
- normalized.includes('video') ||
113
- normalized.includes('dall-e') ||
114
- normalized.includes('stable-diffusion') ||
115
- normalized.includes('flux') ||
116
- (normalized.includes('wan') &&
117
- /(?:^|[-_.:])(?:t2v|i2v|v2v)(?:[-_.:]|$)/u.test(normalized))) {
99
+ if (NON_CHAT_MODEL_FRAGMENTS.some(fragment => normalized.includes(fragment)) ||
100
+ (normalized.includes('wan') && /(?:^|[-_.:])(?:t2v|i2v|v2v)(?:[-_.:]|$)/u.test(normalized))) {
118
101
  return false;
119
102
  }
120
103
  return !/(?:^|[-_.:])(?:t2i|i2i|t2v|i2v|v2v|tts|asr|ocr)(?:[-_.:]|$)/u.test(normalized);
@@ -245,41 +228,9 @@ function extractModels(protocol, data) {
245
228
  export async function listProviderModels(requiredArgs, optionalArgs = {}) {
246
229
  const input = { ...optionalArgs, ...requiredArgs };
247
230
  const start = Date.now();
248
- if (input.protocol === 'azure') {
249
- return {
250
- ok: false,
251
- kind: 'unsupported_protocol',
252
- latencyMs: Date.now() - start,
253
- detail: 'Azure OpenAI deployment discovery is not supported from the inference endpoint.',
254
- };
255
- }
256
- const validated = await validateBaseUrlResolved({ baseUrl: input.baseUrl, lookup: input.dnsLookup ?? defaultDnsLookup });
257
- if (validated.error || !validated.parsed) {
258
- return {
259
- ok: false,
260
- kind: validated.forbidden ? 'forbidden' : 'invalid_base_url',
261
- latencyMs: Date.now() - start,
262
- // Non-null assertion, not a runtime guard: every BaseUrlValidationResult
263
- // this branch's guard condition can produce sets `error` alongside a
264
- // missing `parsed` (connection-guard.ts never returns neither/both) —
265
- // `?? ''` would satisfy the `detail: string` type too, but per this
266
- // package's coverage-loop policy an assertion is more honest about
267
- // "TS requires an `undefined` guard here that can't actually occur".
268
- detail: validated.error,
269
- };
270
- }
271
- if (input.protocol === 'bedrock') {
272
- return {
273
- ok: true,
274
- kind: 'success',
275
- latencyMs: Date.now() - start,
276
- models: BEDROCK_MODEL_OPTIONS,
277
- detail: 'AWS Bedrock uses a static seed until AWS credential-backed discovery is available.',
278
- };
279
- }
280
- if (PROTOCOLS_REQUIRING_API_KEY.has(input.protocol) && !input.apiKey.trim()) {
281
- return missingApiKeyResponse(start);
282
- }
231
+ const preflight = await modelCatalogPreflight({ input, start });
232
+ if (preflight)
233
+ return preflight;
283
234
  let url;
284
235
  try {
285
236
  url = providerModelsUrl(input.protocol, input.baseUrl, input.apiKey);
@@ -321,87 +272,7 @@ export async function listProviderModels(requiredArgs, optionalArgs = {}) {
321
272
  // assigns unconditionally.
322
273
  let result;
323
274
  try {
324
- const collected = [];
325
- const cursors = new Set();
326
- for (let page = 0; page < 100; page += 1) {
327
- const response = await (input.fetchFn ?? fetch)(url, {
328
- method: 'GET',
329
- headers: providerModelsHeaders(input.protocol, input.apiKey),
330
- ...input.requestInit,
331
- signal: controller.signal,
332
- redirect: 'error',
333
- });
334
- const latencyMs = Date.now() - start;
335
- const rawText = await response.text();
336
- let data = {};
337
- let parseError;
338
- try {
339
- data = rawText ? JSON.parse(rawText) : {};
340
- }
341
- catch (err) {
342
- // JSON.parse only ever throws a SyntaxError (an Error); the cast
343
- // documents that rather than adding an untestable non-Error branch.
344
- parseError = err.message;
345
- }
346
- if (!response.ok) {
347
- const detail = parseError
348
- ? rawText.trim().slice(0, 240) || parseError
349
- : extractProviderErrorDetail(data, rawText);
350
- return {
351
- ok: false,
352
- kind: statusToKind(response.status),
353
- latencyMs,
354
- status: response.status,
355
- detail: redactSecrets({ input: detail }, { exactSecrets: [input.apiKey] }),
356
- };
357
- }
358
- if (parseError) {
359
- return {
360
- ok: false,
361
- kind: 'unknown',
362
- latencyMs,
363
- status: response.status,
364
- detail: redactSecrets({ input: parseError }, { exactSecrets: [input.apiKey] }),
365
- };
366
- }
367
- // Safe: `url` above only resolves for the five protocols
368
- // `ModelListProtocol` covers (providerModelsUrl throws for every other
369
- // ConnectionTestProtocol, and azure/bedrock already returned above).
370
- collected.push(...extractModels(input.protocol, data));
371
- const envelope = data && typeof data === 'object' ? data : {};
372
- const cursor = input.protocol === 'google' && typeof envelope.nextPageToken === 'string' ? envelope.nextPageToken
373
- : envelope.has_more === true && typeof envelope.last_id === 'string' ? envelope.last_id
374
- : typeof envelope.next_cursor === 'string' ? envelope.next_cursor : undefined;
375
- if (envelope.has_more === true && !cursor)
376
- return { ok: false, kind: 'unknown', latencyMs, detail: 'Provider omitted its pagination cursor.' };
377
- if (cursor) {
378
- if (cursors.has(cursor))
379
- return { ok: false, kind: 'unknown', latencyMs, detail: 'Provider repeated a pagination cursor.' };
380
- cursors.add(cursor);
381
- const next = new URL(url);
382
- next.searchParams.set(input.protocol === 'google' ? 'pageToken' : input.protocol === 'anthropic' ? 'after_id' : 'cursor', cursor);
383
- url = next.toString();
384
- continue;
385
- }
386
- const models = uniqueModels(collected);
387
- if (models.length === 0) {
388
- return {
389
- ok: false,
390
- kind: 'no_models',
391
- latencyMs,
392
- status: response.status,
393
- detail: 'Provider returned no usable text-generation models.',
394
- };
395
- }
396
- return {
397
- ok: true,
398
- kind: 'success',
399
- latencyMs,
400
- status: response.status,
401
- models,
402
- };
403
- }
404
- return { ok: false, kind: 'unknown', latencyMs: Date.now() - start, detail: 'Provider pagination exceeded its safety limit.' };
275
+ return await collectModelPages({ input, start, url, signal: controller.signal });
405
276
  }
406
277
  catch (err) {
407
278
  const latencyMs = Date.now() - start;
@@ -420,4 +291,148 @@ export async function listProviderModels(requiredArgs, optionalArgs = {}) {
420
291
  }
421
292
  return result;
422
293
  }
294
+ async function modelCatalogPreflight({ input, start }, _options = {}) {
295
+ if (input.protocol === 'azure') {
296
+ return {
297
+ ok: false,
298
+ kind: 'unsupported_protocol',
299
+ latencyMs: Date.now() - start,
300
+ detail: 'Azure OpenAI deployment discovery is not supported from the inference endpoint.',
301
+ };
302
+ }
303
+ const validated = await validateBaseUrlResolved({ baseUrl: input.baseUrl, lookup: input.dnsLookup ?? defaultDnsLookup });
304
+ if (validated.error || !validated.parsed) {
305
+ return {
306
+ ok: false,
307
+ kind: validated.forbidden ? 'forbidden' : 'invalid_base_url',
308
+ latencyMs: Date.now() - start,
309
+ // Non-null assertion, not a runtime guard: every BaseUrlValidationResult
310
+ // this branch's guard condition can produce sets `error` alongside a
311
+ // missing `parsed` (connection-guard.ts never returns neither/both) —
312
+ // `?? ''` would satisfy the `detail: string` type too, but per this
313
+ // package's coverage-loop policy an assertion is more honest about
314
+ // "TS requires an `undefined` guard here that can't actually occur".
315
+ detail: validated.error,
316
+ };
317
+ }
318
+ if (input.protocol === 'bedrock') {
319
+ return {
320
+ ok: true,
321
+ kind: 'success',
322
+ latencyMs: Date.now() - start,
323
+ models: BEDROCK_MODEL_OPTIONS,
324
+ detail: 'AWS Bedrock uses a static seed until AWS credential-backed discovery is available.',
325
+ };
326
+ }
327
+ if (PROTOCOLS_REQUIRING_API_KEY.has(input.protocol) && !input.apiKey.trim()) {
328
+ return missingApiKeyResponse(start);
329
+ }
330
+ return undefined;
331
+ }
332
+ function parseCatalogBody({ rawText }, _options = {}) {
333
+ let data = {};
334
+ let parseError;
335
+ try {
336
+ data = rawText ? JSON.parse(rawText) : {};
337
+ }
338
+ catch (err) {
339
+ // JSON.parse only ever throws a SyntaxError (an Error); the cast
340
+ // documents that rather than adding an untestable non-Error branch.
341
+ parseError = err.message;
342
+ }
343
+ return { data, ...(parseError === undefined ? {} : { parseError }) };
344
+ }
345
+ async function fetchCatalogPage({ input, start, url, signal }, _options = {}) {
346
+ const response = await (input.fetchFn ?? fetch)(url, {
347
+ method: 'GET',
348
+ headers: providerModelsHeaders(input.protocol, input.apiKey),
349
+ ...input.requestInit,
350
+ signal,
351
+ redirect: 'error',
352
+ });
353
+ const latencyMs = Date.now() - start;
354
+ const rawText = await response.text();
355
+ const { data, parseError } = parseCatalogBody({ rawText });
356
+ if (!response.ok) {
357
+ const detail = parseError
358
+ ? rawText.trim().slice(0, 240) || parseError
359
+ : extractProviderErrorDetail(data, rawText);
360
+ return { failure: {
361
+ ok: false,
362
+ kind: statusToKind(response.status),
363
+ latencyMs,
364
+ status: response.status,
365
+ detail: redactSecrets({ input: detail }, { exactSecrets: [input.apiKey] }),
366
+ } };
367
+ }
368
+ if (parseError) {
369
+ return { failure: {
370
+ ok: false,
371
+ kind: 'unknown',
372
+ latencyMs,
373
+ status: response.status,
374
+ detail: redactSecrets({ input: parseError }, { exactSecrets: [input.apiKey] }),
375
+ } };
376
+ }
377
+ return { data, status: response.status, latencyMs };
378
+ }
379
+ function catalogPageCursor({ protocol, envelope }, _options = {}) {
380
+ if (protocol === 'google' && typeof envelope.nextPageToken === 'string')
381
+ return envelope.nextPageToken;
382
+ if (envelope.has_more === true && typeof envelope.last_id === 'string')
383
+ return envelope.last_id;
384
+ return typeof envelope.next_cursor === 'string' ? envelope.next_cursor : undefined;
385
+ }
386
+ function nextCatalogPage({ protocol, data, cursors, url, latencyMs }, _options = {}) {
387
+ const envelope = data && typeof data === 'object' ? data : {};
388
+ const cursor = catalogPageCursor({ protocol, envelope });
389
+ if (envelope.has_more === true && !cursor)
390
+ return { ok: false, kind: 'unknown', latencyMs, detail: 'Provider omitted its pagination cursor.' };
391
+ if (!cursor)
392
+ return undefined;
393
+ if (cursors.has(cursor))
394
+ return { ok: false, kind: 'unknown', latencyMs, detail: 'Provider repeated a pagination cursor.' };
395
+ cursors.add(cursor);
396
+ const next = new URL(url);
397
+ next.searchParams.set(protocol === 'google' ? 'pageToken' : protocol === 'anthropic' ? 'after_id' : 'cursor', cursor);
398
+ return next.toString();
399
+ }
400
+ function completedCatalog({ collected, status, latencyMs }, _options = {}) {
401
+ const models = uniqueModels(collected);
402
+ if (models.length === 0) {
403
+ return {
404
+ ok: false,
405
+ kind: 'no_models',
406
+ latencyMs,
407
+ status,
408
+ detail: 'Provider returned no usable text-generation models.',
409
+ };
410
+ }
411
+ return {
412
+ ok: true,
413
+ kind: 'success',
414
+ latencyMs,
415
+ status,
416
+ models,
417
+ };
418
+ }
419
+ async function collectModelPages({ input, start, url, signal }, _options = {}) {
420
+ const collected = [];
421
+ const cursors = new Set();
422
+ for (let pageNumber = 0; pageNumber < 100; pageNumber += 1) {
423
+ const page = await fetchCatalogPage({ input, start, url, signal });
424
+ if ('failure' in page)
425
+ return page.failure;
426
+ const { data, latencyMs } = page;
427
+ // Safe: `url` above only resolves for the five protocols
428
+ // `ModelListProtocol` covers (providerModelsUrl throws for every other
429
+ // ConnectionTestProtocol, and azure/bedrock already returned above).
430
+ collected.push(...extractModels(input.protocol, data));
431
+ const next = nextCatalogPage({ protocol: input.protocol, data, cursors, url, latencyMs });
432
+ if (typeof next !== 'string')
433
+ return next ?? completedCatalog({ collected, status: page.status, latencyMs });
434
+ url = next;
435
+ }
436
+ return { ok: false, kind: 'unknown', latencyMs: Date.now() - start, detail: 'Provider pagination exceeded its safety limit.' };
437
+ }
423
438
  //# sourceMappingURL=model-catalog.js.map
@@ -93,40 +93,8 @@ export async function startOAuthCallbackListener(requiredArgs, optionalArgs = {}
93
93
  res.end('Not found.');
94
94
  return;
95
95
  }
96
- const code = parsed.searchParams.get('code') ?? '';
97
- const state = parsed.searchParams.get('state') ?? '';
98
- const errorParam = parsed.searchParams.get('error') ?? '';
99
- let outcome;
100
- if (errorParam) {
101
- outcome = state
102
- ? { kind: 'error', error: errorParam, state }
103
- : { kind: 'error', error: errorParam };
104
- }
105
- else if (!code || !state) {
106
- outcome = { kind: 'error', error: 'missing code or state' };
107
- }
108
- else if (state !== input.expectedState) {
109
- outcome = { kind: 'error', error: 'state mismatch', state };
110
- }
111
- else {
112
- outcome = { kind: 'ok', code, state };
113
- }
114
- // Decide whether this hit *consumes* the listener. A stray browser tab
115
- // replaying an old `?state=...` (or `?error=...&state=...`) would
116
- // otherwise close a shared fixed-port listener before the real redirect
117
- // can arrive. Keep the listener open on stale/malformed requests; the
118
- // real callback will still find it. Consume on:
119
- // - ok callback (matched state, code present)
120
- // - explicit ?error= without a state (the server rejected before
121
- // issuing state, so there's nothing to match against — safe to
122
- // consume)
123
- // - explicit ?error= with state matching expectedState (the server
124
- // told the user the dance failed; propagate now instead of waiting
125
- // for the timeout)
126
- // An ?error= with a *mismatched* state is treated like the stale
127
- // success replay above: 400 the browser, leave the listener live.
128
- const errorConsumes = Boolean(errorParam) && (!state || state === input.expectedState);
129
- const consumesListener = outcome.kind === 'ok' || errorConsumes;
96
+ const outcome = callbackOutcome({ params: parsed.searchParams, expectedState: input.expectedState });
97
+ const consumesListener = callbackConsumesListener({ params: parsed.searchParams, expectedState: input.expectedState, outcome });
130
98
  if (consumesListener) {
131
99
  consumed = true;
132
100
  }
@@ -215,4 +183,39 @@ function escapeHtml(s) {
215
183
  .replace(/"/g, '&quot;')
216
184
  .replace(/'/g, '&#39;');
217
185
  }
186
+ function callbackOutcome({ params, expectedState }, _options = {}) {
187
+ const code = params.get('code') ?? '';
188
+ const state = params.get('state') ?? '';
189
+ const errorParam = params.get('error') ?? '';
190
+ if (errorParam) {
191
+ return state
192
+ ? { kind: 'error', error: errorParam, state }
193
+ : { kind: 'error', error: errorParam };
194
+ }
195
+ if (!code || !state)
196
+ return { kind: 'error', error: 'missing code or state' };
197
+ if (state !== expectedState)
198
+ return { kind: 'error', error: 'state mismatch', state };
199
+ return { kind: 'ok', code, state };
200
+ }
201
+ function callbackConsumesListener({ params, expectedState, outcome }, _options = {}) {
202
+ const state = params.get('state') ?? '';
203
+ const errorParam = params.get('error') ?? '';
204
+ // Decide whether this hit *consumes* the listener. A stray browser tab
205
+ // replaying an old `?state=...` (or `?error=...&state=...`) would
206
+ // otherwise close a shared fixed-port listener before the real redirect
207
+ // can arrive. Keep the listener open on stale/malformed requests; the
208
+ // real callback will still find it. Consume on:
209
+ // - ok callback (matched state, code present)
210
+ // - explicit ?error= without a state (the server rejected before
211
+ // issuing state, so there's nothing to match against — safe to
212
+ // consume)
213
+ // - explicit ?error= with state matching expectedState (the server
214
+ // told the user the dance failed; propagate now instead of waiting
215
+ // for the timeout)
216
+ // An ?error= with a *mismatched* state is treated like the stale
217
+ // success replay above: 400 the browser, leave the listener live.
218
+ const errorConsumes = Boolean(errorParam) && (!state || state === expectedState);
219
+ return outcome.kind === 'ok' || errorConsumes;
220
+ }
218
221
  //# sourceMappingURL=oauth-callback-server.js.map
@@ -34,29 +34,8 @@ export async function resolveOAuthBearer({ config, tokenFileName, dataDir }, { f
34
34
  if (!stored.refreshToken)
35
35
  return null;
36
36
  try {
37
- const fresh = await (({ config, refreshToken, ...optionalArgs }) => refreshOAuthPkceToken({ config, refreshToken }, optionalArgs))({
38
- config,
39
- refreshToken: stored.refreshToken,
40
- ...(fetchImpl ? { fetchImpl } : {}),
41
- });
42
- const next = {
43
- accessToken: fresh.access_token,
44
- tokenType: fresh.token_type ?? 'Bearer',
45
- savedAt: Date.now(),
46
- };
47
- // Preserves the existing refresh_token when the token endpoint omits
48
- // one in its response. RFC 6749 §6 lets a server skip refresh_token
49
- // rotation and keep the old one valid; dropping it here would leave the
50
- // next expiry with nothing to refresh against, forcing the user back
51
- // through a full sign-in even though their grant is still good.
52
- const carriedRefresh = fresh.refresh_token ?? stored.refreshToken;
53
- if (carriedRefresh)
54
- next.refreshToken = carriedRefresh;
55
- if (typeof fresh.expires_in === 'number') {
56
- next.expiresAt = Date.now() + fresh.expires_in * 1000;
57
- }
58
- if (fresh.scope)
59
- next.scope = fresh.scope;
37
+ const fresh = await refreshOAuthPkceToken({ config, refreshToken: stored.refreshToken }, fetchImpl ? { fetchImpl } : {});
38
+ const next = refreshedStoredToken({ fresh, stored });
60
39
  await setStoredOAuthToken({ dataDir: dataDir, fileName: tokenFileName, token: next });
61
40
  return { accessToken: next.accessToken, source: 'refreshed' };
62
41
  }
@@ -67,4 +46,25 @@ export async function resolveOAuthBearer({ config, tokenFileName, dataDir }, { f
67
46
  return null;
68
47
  }
69
48
  }
49
+ function refreshedStoredToken({ fresh, stored }, _options = {}) {
50
+ const next = {
51
+ accessToken: fresh.access_token,
52
+ tokenType: fresh.token_type ?? 'Bearer',
53
+ savedAt: Date.now(),
54
+ };
55
+ // Preserves the existing refresh_token when the token endpoint omits
56
+ // one in its response. RFC 6749 §6 lets a server skip refresh_token
57
+ // rotation and keep the old one valid; dropping it here would leave the
58
+ // next expiry with nothing to refresh against, forcing the user back
59
+ // through a full sign-in even though their grant is still good.
60
+ const carriedRefresh = fresh.refresh_token ?? stored.refreshToken;
61
+ if (carriedRefresh)
62
+ next.refreshToken = carriedRefresh;
63
+ if (typeof fresh.expires_in === 'number') {
64
+ next.expiresAt = Date.now() + fresh.expires_in * 1000;
65
+ }
66
+ if (fresh.scope)
67
+ next.scope = fresh.scope;
68
+ return next;
69
+ }
70
70
  //# sourceMappingURL=oauth-credentials.js.map
@@ -14,10 +14,6 @@
14
14
  import { chmod, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
15
15
  import { randomBytes } from 'node:crypto';
16
16
  import path from 'node:path';
17
- const EMPTY = {};
18
- function tokenFilePath(dataDir, fileName) {
19
- return path.join(dataDir, fileName);
20
- }
21
17
  function isPlainObject(v) {
22
18
  return Boolean(v) && typeof v === 'object' && !Array.isArray(v);
23
19
  }
@@ -28,27 +24,23 @@ export function sanitizeOAuthTokenFile({ raw }) {
28
24
  const tok = sanitizeToken(raw.token);
29
25
  return tok ? { token: tok } : {};
30
26
  }
27
+ function trimmedTokenString({ value }, _options = {}) {
28
+ return typeof value === 'string' ? value.trim() || undefined : undefined;
29
+ }
30
+ function finiteTokenNumber({ value }, _options = {}) {
31
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
32
+ }
31
33
  function sanitizeToken(raw) {
32
34
  if (!isPlainObject(raw))
33
35
  return null;
34
- const accessToken = typeof raw.accessToken === 'string' ? raw.accessToken.trim() : '';
36
+ const accessToken = trimmedTokenString({ value: raw.accessToken }) ?? '';
35
37
  if (!accessToken)
36
38
  return null;
37
- const tokenType = typeof raw.tokenType === 'string' && raw.tokenType.trim()
38
- ? raw.tokenType.trim()
39
- : 'Bearer';
40
- const refreshToken = typeof raw.refreshToken === 'string' && raw.refreshToken.trim()
41
- ? raw.refreshToken.trim()
42
- : undefined;
43
- const scope = typeof raw.scope === 'string' && raw.scope.trim()
44
- ? raw.scope.trim()
45
- : undefined;
46
- const expiresAt = typeof raw.expiresAt === 'number' && Number.isFinite(raw.expiresAt)
47
- ? raw.expiresAt
48
- : undefined;
49
- const savedAt = typeof raw.savedAt === 'number' && Number.isFinite(raw.savedAt)
50
- ? raw.savedAt
51
- : Date.now();
39
+ const tokenType = trimmedTokenString({ value: raw.tokenType }) || 'Bearer';
40
+ const refreshToken = trimmedTokenString({ value: raw.refreshToken });
41
+ const scope = trimmedTokenString({ value: raw.scope });
42
+ const expiresAt = finiteTokenNumber({ value: raw.expiresAt });
43
+ const savedAt = finiteTokenNumber({ value: raw.savedAt }) ?? Date.now();
52
44
  const out = { accessToken, tokenType, savedAt };
53
45
  if (refreshToken)
54
46
  out.refreshToken = refreshToken;
@@ -60,16 +52,16 @@ function sanitizeToken(raw) {
60
52
  }
61
53
  export async function readOAuthTokenFile({ dataDir, fileName }) {
62
54
  try {
63
- const raw = await readFile(tokenFilePath(dataDir, fileName), 'utf8');
55
+ const raw = await readFile(path.join(dataDir, fileName), 'utf8');
64
56
  return sanitizeOAuthTokenFile({ raw: JSON.parse(raw) });
65
57
  }
66
58
  catch (err) {
67
59
  const e = err;
68
60
  if (e.code === 'ENOENT')
69
- return { ...EMPTY };
61
+ return {};
70
62
  if (e.name === 'SyntaxError') {
71
63
  console.error('[oauth-tokens] Corrupted JSON, returning empty:', e.message);
72
- return { ...EMPTY };
64
+ return {};
73
65
  }
74
66
  throw err;
75
67
  }
@@ -88,7 +80,7 @@ async function withLock(lockKey, fn) {
88
80
  }
89
81
  }
90
82
  async function writeTokenFile(dataDir, fileName, next) {
91
- const file = tokenFilePath(dataDir, fileName);
83
+ const file = path.join(dataDir, fileName);
92
84
  await mkdir(path.dirname(file), { recursive: true });
93
85
  const tmp = file + '.' + randomBytes(4).toString('hex') + '.tmp';
94
86
  await writeFile(tmp, JSON.stringify(next, null, 2), 'utf8');
@@ -70,12 +70,14 @@ import { createRoleMarkerGuard } from '../role-marker-guard.js';
70
70
  import { type DnsLookupAddress, type DnsLookupFn, type PinnedFetch } from './connection-guard.js';
71
71
  import { type DecodedSseEvent } from './sse-decode.js';
72
72
  import { type TurnEndReason } from './turn-end-guard.js';
73
+ import type { ProviderToolSnapshotOptions, ProviderSchemaFallback, ProviderProtocol } from './tool-turn-types.js';
73
74
  export interface OpenAiFunctionToolDef {
74
75
  readonly type: 'function';
75
76
  readonly function: {
76
77
  readonly name: string;
77
78
  readonly description?: string;
78
79
  readonly parameters: Record<string, unknown>;
80
+ readonly strict?: boolean;
79
81
  };
80
82
  }
81
83
  export interface OpenAiToolCallParam {
@@ -157,6 +159,9 @@ export interface OpenAiTurnOptions {
157
159
  readonly model: string;
158
160
  readonly messages: readonly OpenAiMessageParam[];
159
161
  readonly tools?: readonly OpenAiFunctionToolDef[];
162
+ /** Refresh the run's projection immediately before each HTTP request. */
163
+ readonly getTools?: (options?: ProviderToolSnapshotOptions) => readonly OpenAiFunctionToolDef[];
164
+ readonly onSchemaFallback?: (event: ProviderSchemaFallback) => void;
160
165
  readonly temperature?: number;
161
166
  /** Defaults to {@link DEFAULT_OPENAI_MAX_TOKENS} (8192) when omitted or not a positive number — a token limit is always sent, matching OD's real behavior (see module doc). */
162
167
  readonly maxTokens?: number;
@@ -228,6 +233,12 @@ export interface OpenAiCompatibleRequestInit {
228
233
  * cannot retry again.
229
234
  */
230
235
  readonly retryableBody?: (status: number, rawErrorText: string) => Record<string, unknown> | null | undefined;
236
+ /** Independent of the legacy token-parameter retry; consumed only on a recognized tool rejection. */
237
+ readonly retryToolBody?: (input: {
238
+ status: number;
239
+ rawErrorText: string;
240
+ body: Record<string, unknown>;
241
+ }) => Record<string, unknown> | null;
231
242
  /** Injectable HTTP transport, defaulting to {@link pinnedFetch} (SSRF-guarded, DNS-pinned) — forwarded verbatim from the calling provider's own `OpenAiTurnOptions.fetchImpl`/`AzureTurnOptions.fetchImpl`/`OllamaTurnOptions.fetchImpl`. See `anthropic-messages.ts#AnthropicTurnOptions.fetchImpl`'s doc for the seam this exists for. */
232
243
  readonly fetchImpl?: PinnedFetch;
233
244
  }
@@ -239,6 +250,37 @@ export interface OpenAiStreamState {
239
250
  finishReason: string | null;
240
251
  usage: Record<string, unknown> | null;
241
252
  }
253
+ /** Per-turn state shared by the wire adapters; never retries streams or executes tools. */
254
+ export interface StrictToolRetryState {
255
+ readonly enabled: boolean;
256
+ readonly downgrade: (input: {
257
+ status: number;
258
+ rawErrorText: string;
259
+ toolNames: readonly string[];
260
+ }) => boolean;
261
+ }
262
+ /**
263
+ * Allow one recognized pre-generation downgrade for this turn. Diagnostic callbacks receive
264
+ * names and a closed reason code, never the provider's error text or tool arguments.
265
+ * @param input - Protocol and optional host diagnostic sink.
266
+ * @returns Turn-local strict preference and a rejection decision; callback errors propagate.
267
+ * @example const retry = createStrictToolRetry({ protocol: 'openai' });
268
+ * @complexity O(e + t) per rejection for bounded error text e and t tool names; O(t) diagnostic space.
269
+ */
270
+ export declare function createStrictToolRetry({ protocol, onSchemaFallback }: {
271
+ protocol: ProviderProtocol;
272
+ onSchemaFallback?: ((event: ProviderSchemaFallback) => void) | undefined;
273
+ }, _options?: {}): StrictToolRetryState;
274
+ /** Refresh OpenAI-compatible tools through the projection owner; legacy callers retain their schemas.
275
+ * @param input - Existing adapter options and the turn's downgrade state.
276
+ * @returns A request-local copy; projection callback failures propagate.
277
+ * @example refreshOpenAiTools({ options, retry });
278
+ * @complexity O(t) local time/space for t tools; projection cost belongs to getTools.
279
+ */
280
+ export declare function refreshOpenAiTools<T extends OpenAiTurnOptions>({ options, retry }: {
281
+ options: T;
282
+ retry: StrictToolRetryState;
283
+ }, _optional?: {}): T;
242
284
  /** Parses one SSE frame's data as a JSON object, or `null` for a malformed/empty keep-alive frame or a non-object payload — both are tolerated by the caller as "nothing to do this frame". */
243
285
  export declare function parseOpenAiSseData({ raw }: {
244
286
  raw: string;