@jini-ai/agent-runtime 0.4.11 → 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 (110) hide show
  1. package/CHANGELOG.md +4 -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 +4 -0
  90. package/dist/providers/google-messages.js +48 -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
@@ -38,6 +38,22 @@ export function resolveOpenCodeLogDir({ env }) {
38
38
  // perms).
39
39
  export function readLatestOpenCodeLogTail({ logDir }, options = {}) {
40
40
  const { maxBytes = 2_000_000, since } = options;
41
+ const names = listLogNamesNewestFirst({ logDir });
42
+ if (!names)
43
+ return null;
44
+ for (const name of names) {
45
+ const full = path.join(logDir, name);
46
+ if (since != null && predatesSince({ file: full, since }))
47
+ continue;
48
+ const tail = readFileTail({ file: full, maxBytes });
49
+ if (tail !== null)
50
+ return tail;
51
+ }
52
+ return null;
53
+ }
54
+ // `.log` names in the dir, newest filename first; null when the dir is
55
+ // unreadable or holds no logs.
56
+ function listLogNamesNewestFirst({ logDir }) {
41
57
  let names;
42
58
  try {
43
59
  names = readdirSync(logDir).filter((name) => name.endsWith('.log'));
@@ -47,27 +63,27 @@ export function readLatestOpenCodeLogTail({ logDir }, options = {}) {
47
63
  }
48
64
  if (names.length === 0)
49
65
  return null;
50
- names.sort().reverse(); // newest filename first
51
- for (const name of names) {
52
- const full = path.join(logDir, name);
53
- if (since != null) {
54
- try {
55
- if (statSync(full).mtimeMs < since)
56
- continue;
57
- }
58
- catch {
59
- continue;
60
- }
61
- }
62
- try {
63
- const buf = readFileSync(full, 'utf8');
64
- return buf.length > maxBytes ? buf.slice(-maxBytes) : buf;
65
- }
66
- catch {
67
- continue;
68
- }
66
+ return names.sort().reverse(); // newest filename first
67
+ }
68
+ // True when the file was last written before `since` (an earlier session's
69
+ // log), or cannot be stat'ed — either way it is skipped.
70
+ function predatesSince({ file, since }) {
71
+ try {
72
+ return statSync(file).mtimeMs < since;
73
+ }
74
+ catch {
75
+ return true;
76
+ }
77
+ }
78
+ // The last `maxBytes` of the file, or null when it cannot be read.
79
+ function readFileTail({ file, maxBytes }) {
80
+ try {
81
+ const buf = readFileSync(file, 'utf8');
82
+ return buf.length > maxBytes ? buf.slice(-maxBytes) : buf;
83
+ }
84
+ catch {
85
+ return null;
69
86
  }
70
- return null;
71
87
  }
72
88
  // Only treat a `"message":"…"` value as the failure reason when it reads
73
89
  // like a service error. The embedded request body uses `"content":` for
@@ -122,26 +138,26 @@ function defaultMessageForCode(code) {
122
138
  // We scope to that single line so the huge request body of *other* lines
123
139
  // can't leak in, key the classification on the unambiguous HTTP `statusCode`
124
140
  // first, and fall back to keyword matching the extracted message only.
125
- export function extractOpenCodeServiceFailure({ logTail }) {
126
- if (!logTail || !logTail.trim())
127
- return null;
128
- const lines = logTail.split(/\r?\n/);
129
- let line = null;
141
+ function findLatestLlmErrorLine({ lines }) {
130
142
  for (let i = lines.length - 1; i >= 0; i -= 1) {
131
143
  const candidate = lines[i];
132
144
  if (candidate.includes('service=llm') && /\bERROR\b/.test(candidate) && candidate.includes('error=')) {
133
- line = candidate;
134
- break;
145
+ return candidate;
135
146
  }
136
147
  }
148
+ return null;
149
+ }
150
+ export function extractOpenCodeServiceFailure({ logTail }) {
151
+ if (!logTail || !logTail.trim())
152
+ return null;
153
+ const line = findLatestLlmErrorLine({ lines: logTail.split(/\r?\n/) });
137
154
  if (!line)
138
155
  return null;
139
156
  const statusMatch = /"statusCode":\s*(\d{3})/.exec(line);
140
157
  const statusCode = statusMatch ? Number(statusMatch[1]) : null;
141
158
  const message = pickServiceErrorMessage(line);
142
- let code = statusCode != null ? codeFromStatus(statusCode) : null;
143
- if (!code && message)
144
- code = classifyAgentServiceFailure({ text: message });
159
+ const statusDerived = statusCode != null ? codeFromStatus(statusCode) : null;
160
+ const code = statusDerived ?? (message ? classifyAgentServiceFailure({ text: message }) : null);
145
161
  if (!code)
146
162
  return null;
147
163
  return { code, message: message || defaultMessageForCode(code), statusCode };
package/dist/paths.d.ts CHANGED
@@ -3,5 +3,7 @@ export declare function expandConfiguredEnv({ configuredEnv }: {
3
3
  }): Record<string, string>;
4
4
  export declare function expandHomePath({ value }: {
5
5
  value: string;
6
+ }, { home }?: {
7
+ home?: string;
6
8
  }): string;
7
9
  //# sourceMappingURL=paths.d.ts.map
package/dist/paths.js CHANGED
@@ -15,11 +15,11 @@ export function expandConfiguredEnv({ configuredEnv }) {
15
15
  }
16
16
  return out;
17
17
  }
18
- export function expandHomePath({ value }) {
18
+ export function expandHomePath({ value }, { home = homedir() } = {}) {
19
19
  if (value === '~')
20
- return homedir();
20
+ return home;
21
21
  if (value.startsWith('~/') || value.startsWith('~\\')) {
22
- return path.join(homedir(), value.slice(2));
22
+ return path.join(home, value.slice(2));
23
23
  }
24
24
  return value;
25
25
  }
@@ -175,13 +175,7 @@ export function aihubmixVideoSeconds({ wireModel, requested }) {
175
175
  return String(snapped);
176
176
  }
177
177
  export function aihubmixCatalogUrl({ baseUrl, type }) {
178
- let origin;
179
- try {
180
- origin = new URL(baseUrl || AIHUBMIX_DEFAULT_BASE_URL).origin;
181
- }
182
- catch {
183
- origin = 'https://aihubmix.com';
184
- }
178
+ const origin = aihubmixOriginFromBase({ baseUrl });
185
179
  return `${origin}/api/v1/models?type=${type}`;
186
180
  }
187
181
  // AIHubMix tags every catalogue row with a comma-separated `types` field
@@ -198,6 +192,15 @@ function aihubmixRowTypes(row) {
198
192
  .map((t) => t.trim().toLowerCase())
199
193
  .filter(Boolean);
200
194
  }
195
+ function aihubmixRowString({ row, key }, _options = {}) {
196
+ const value = row?.[key];
197
+ return typeof value === 'string' ? value : '';
198
+ }
199
+ function shouldSkipAIHubMixRow({ id, seen, row }, options = {}) {
200
+ if (!id || seen.has(id))
201
+ return true;
202
+ return Boolean(options?.chatOnly && aihubmixRowTypes(row).some((type) => AIHUBMIX_MEDIA_GENERATION_TYPES.has(type)));
203
+ }
201
204
  /** Parses the AIHubMix catalogue envelope into { id, label } options. Reads
202
205
  * `model_id` (the wire name sent as `model`) and `model_name` (display). */
203
206
  export function parseAIHubMixCatalog({ data }, options = {}) {
@@ -207,19 +210,11 @@ export function parseAIHubMixCatalog({ data }, options = {}) {
207
210
  const seen = new Set();
208
211
  const out = [];
209
212
  for (const row of rows) {
210
- const id = typeof row?.model_id === 'string'
211
- ? row.model_id
212
- : '';
213
- if (!id || seen.has(id))
214
- continue;
215
- if (options?.chatOnly &&
216
- aihubmixRowTypes(row).some((t) => AIHUBMIX_MEDIA_GENERATION_TYPES.has(t))) {
213
+ const id = aihubmixRowString({ row, key: 'model_id' });
214
+ if (shouldSkipAIHubMixRow({ id, seen, row }, options))
217
215
  continue;
218
- }
219
216
  seen.add(id);
220
- const name = typeof row?.model_name === 'string'
221
- ? row.model_name
222
- : '';
217
+ const name = aihubmixRowString({ row, key: 'model_name' });
223
218
  out.push({ id, label: name || id });
224
219
  }
225
220
  return out;
@@ -76,6 +76,7 @@
76
76
  import { createRoleMarkerGuard } from '../role-marker-guard.js';
77
77
  import { type DnsLookupFn, type PinnedFetch } from './connection-guard.js';
78
78
  import { type TurnEndReason } from './turn-end-guard.js';
79
+ import type { ProviderToolSnapshotOptions, ProviderSchemaFallback } from './tool-turn-types.js';
79
80
  export interface AnthropicTextBlockParam {
80
81
  readonly type: 'text';
81
82
  readonly text: string;
@@ -118,6 +119,7 @@ export interface AnthropicToolDef {
118
119
  readonly name: string;
119
120
  readonly description?: string;
120
121
  readonly input_schema: Record<string, unknown>;
122
+ readonly strict?: boolean;
121
123
  }
122
124
  export interface AnthropicToolCall {
123
125
  readonly id: string;
@@ -173,6 +175,9 @@ export interface AnthropicTurnOptions {
173
175
  readonly system?: string;
174
176
  readonly messages: readonly AnthropicMessageParam[];
175
177
  readonly tools?: readonly AnthropicToolDef[];
178
+ /** Refresh the run's projection immediately before each HTTP request. */
179
+ readonly getTools?: (options?: ProviderToolSnapshotOptions) => readonly AnthropicToolDef[];
180
+ readonly onSchemaFallback?: (event: ProviderSchemaFallback) => void;
176
181
  readonly maxTokens: number;
177
182
  readonly temperature?: number;
178
183
  /** Tool-loop iteration ceiling (a single request counts as one iteration once it returns `stop_reason: 'tool_use'`). Defaults to 8 — generous for a real agentic turn, bounded so a misbehaving tool/model pair cannot loop forever. */
@@ -187,6 +192,8 @@ export interface AnthropicTurnOptions {
187
192
  * own routing header). Never hardcode a caller/product identity string
188
193
  * here — this is the generalized fix for the confirmed OD product-identity
189
194
  * leak documented in this module's header comment.
195
+ * Endpoints requiring the structured-output beta may supply
196
+ * `anthropic-beta: structured-outputs-2025-11-13` here; native GA needs no header.
190
197
  */
191
198
  readonly extraHeaders?: Record<string, string>;
192
199
  /**
@@ -78,6 +78,7 @@ import { createRoleMarkerGuard } from '../role-marker-guard.js';
78
78
  import { defaultDnsLookup, pinnedFetch, validateBaseUrlResolved } from './connection-guard.js';
79
79
  import { decodeSseStream } from './sse-decode.js';
80
80
  import { createTurnEndGuard } from './turn-end-guard.js';
81
+ import { createStrictToolRetry } from './openai-chat.js';
81
82
  const DEFAULT_ANTHROPIC_BASE_URL = 'https://api.anthropic.com';
82
83
  const DEFAULT_ANTHROPIC_VERSION = '2023-06-01';
83
84
  const DEFAULT_MAX_TOOL_TURNS = 8;
@@ -319,6 +320,42 @@ const ANTHROPIC_FRAME_HANDLERS = {
319
320
  return { action: 'end', reason: 'error' };
320
321
  },
321
322
  };
323
+ /** Refresh the projection before sending; a downgrade strips only wire strict flags for legacy callers.
324
+ * @complexity O(t) local time/space for t tools; projection work belongs to getTools.
325
+ */
326
+ function refreshAnthropicTools(options, retry) {
327
+ let tools = options.getTools?.({ strict: retry.enabled }) ?? options.tools;
328
+ if (!retry.enabled)
329
+ tools = tools?.map(tool => {
330
+ const { strict: _strict, ...definition } = tool;
331
+ return definition;
332
+ });
333
+ return { ...options, ...(tools !== undefined ? { tools } : {}) };
334
+ }
335
+ /** Resolve strict retry before terminal HTTP errors and missing-body failures. */
336
+ async function resolveAnthropicResponse({ response, options, requestOptions, messages, emitEnd, retry }, _options = {}) {
337
+ const { onEvent } = options;
338
+ if (!response.ok) {
339
+ const rawText = await response.text();
340
+ const toolNames = (requestOptions.tools ?? []).filter(tool => tool.strict).map(tool => tool.name);
341
+ if (retry.downgrade({ status: response.status, rawErrorText: rawText, toolNames })) {
342
+ return openAnthropicResponseStream({ options, messages, emitEnd, retry });
343
+ }
344
+ onEvent({
345
+ type: 'error',
346
+ message: redactSecrets({ input: extractAnthropicErrorDetail({ rawText: rawText }) }, { exactSecrets: [options.apiKey] }),
347
+ code: String(response.status),
348
+ });
349
+ emitEnd('error');
350
+ return null;
351
+ }
352
+ if (!response.body) {
353
+ onEvent({ type: 'error', message: 'Anthropic response had no body' });
354
+ emitEnd('error');
355
+ return null;
356
+ }
357
+ return response.body;
358
+ }
322
359
  /**
323
360
  * Validates `options.baseUrl` and opens the streaming POST, returning the response's readable
324
361
  * body once every pre-stream failure mode (SSRF-guard rejection, network error, non-2xx status,
@@ -326,7 +363,7 @@ const ANTHROPIC_FRAME_HANDLERS = {
326
363
  * those — the caller only has to check for `null`, keeping the single `ended` flag as the sole
327
364
  * gate for every exit path (see `runAnthropicToolTurn`'s doc).
328
365
  */
329
- async function openAnthropicResponseStream(options, messages, emitEnd) {
366
+ async function openAnthropicResponseStream({ options, messages, emitEnd, retry }, _options = {}) {
330
367
  const { onEvent } = options;
331
368
  // DNS-resolving, not merely textual — see the identical note in `openai-chat.ts`. A literal
332
369
  // private IP was already rejected; a hostname resolving to one was not.
@@ -336,12 +373,13 @@ async function openAnthropicResponseStream(options, messages, emitEnd) {
336
373
  emitEnd('error');
337
374
  return null;
338
375
  }
376
+ const requestOptions = refreshAnthropicTools(options, retry);
339
377
  let response;
340
378
  try {
341
379
  response = await (options.fetchImpl ?? pinnedFetch)({ url: anthropicRequestUrl({ baseUrl: options.baseUrl }), init: {
342
380
  method: 'POST',
343
381
  headers: (({ apiKey, model, messages, maxTokens, onEvent, ...optionalArgs }) => anthropicHeaders({ apiKey, model, messages, maxTokens, onEvent }, optionalArgs))(options),
344
- body: JSON.stringify(anthropicRequestBody({ options: options, messages: messages })),
382
+ body: JSON.stringify(anthropicRequestBody({ options: requestOptions, messages: messages })),
345
383
  redirect: 'error',
346
384
  ...(options.signal ? { signal: options.signal } : {}),
347
385
  }, pinnedAddress: baseUrlCheck.pinnedAddress });
@@ -352,27 +390,12 @@ async function openAnthropicResponseStream(options, messages, emitEnd) {
352
390
  emitEnd('error');
353
391
  return null;
354
392
  }
355
- if (!response.ok) {
356
- const rawText = await response.text();
357
- onEvent({
358
- type: 'error',
359
- message: redactSecrets({ input: extractAnthropicErrorDetail({ rawText: rawText }) }, { exactSecrets: [options.apiKey] }),
360
- code: String(response.status),
361
- });
362
- emitEnd('error');
363
- return null;
364
- }
365
- if (!response.body) {
366
- onEvent({ type: 'error', message: 'Anthropic response had no body' });
367
- emitEnd('error');
368
- return null;
369
- }
370
- return response.body;
393
+ return resolveAnthropicResponse({ response, options, requestOptions, messages, emitEnd, retry });
371
394
  }
372
395
  /** Runs exactly one Anthropic Messages API streaming request and reduces its SSE events into a single outcome. Calls `emitEnd` directly (and only) on contamination or a fatal request/stream error — the caller (`runAnthropicToolTurn`) is responsible for the normal-completion `emitEnd` call once the tool loop actually concludes, so the single `ended` flag stays the sole gate for every exit path. */
373
- async function runSingleAnthropicRequest(options, messages, emitEnd) {
396
+ async function runSingleAnthropicRequest(options, messages, emitEnd, retry) {
374
397
  const { onEvent } = options;
375
- const body = await openAnthropicResponseStream(options, messages, emitEnd);
398
+ const body = await openAnthropicResponseStream({ options, messages, emitEnd, retry });
376
399
  if (!body) {
377
400
  return { stopReason: null, toolCalls: [], text: '' };
378
401
  }
@@ -455,6 +478,7 @@ export async function executeAnthropicToolCalls({ executeTool, calls, onEvent })
455
478
  }
456
479
  export async function runAnthropicToolTurn(requiredArgs, optionalArgs = {}) {
457
480
  const options = { ...optionalArgs, ...requiredArgs };
481
+ const retry = createStrictToolRetry({ protocol: 'anthropic', onSchemaFallback: options.onSchemaFallback });
458
482
  const maxToolTurns = options.maxToolTurns ?? DEFAULT_MAX_TOOL_TURNS;
459
483
  const executeTool = options.executeTool;
460
484
  const endGuard = createTurnEndGuard(options.onEvent, (reason) => ({ type: 'end', reason }));
@@ -463,7 +487,7 @@ export async function runAnthropicToolTurn(requiredArgs, optionalArgs = {}) {
463
487
  let toolTurns = 0;
464
488
  let lastStopReason = null;
465
489
  while (true) {
466
- const outcome = await runSingleAnthropicRequest(options, messages, emitEnd);
490
+ const outcome = await runSingleAnthropicRequest(options, messages, emitEnd, retry);
467
491
  lastStopReason = outcome.stopReason;
468
492
  if (endGuard.hasEnded())
469
493
  break;
@@ -74,6 +74,7 @@
74
74
  */
75
75
  import { type DnsLookupFn, type PinnedFetch } from './connection-guard.js';
76
76
  import { type OpenAiCompatibleRequestOutcome } from './openai-chat.js';
77
+ import type { ProviderToolSnapshotOptions, ProviderSchemaFallback } from './tool-turn-types.js';
77
78
  import { type TurnEndReason } from './turn-end-guard.js';
78
79
  export interface AzureFunctionToolDef {
79
80
  readonly type: 'function';
@@ -81,6 +82,7 @@ export interface AzureFunctionToolDef {
81
82
  readonly name: string;
82
83
  readonly description?: string;
83
84
  readonly parameters: Record<string, unknown>;
85
+ readonly strict?: boolean;
84
86
  };
85
87
  }
86
88
  export interface AzureToolCallParam {
@@ -165,6 +167,9 @@ export interface AzureTurnOptions {
165
167
  readonly apiVersion?: string;
166
168
  readonly messages: readonly AzureMessageParam[];
167
169
  readonly tools?: readonly AzureFunctionToolDef[];
170
+ /** Refresh the run's projection immediately before each HTTP request. */
171
+ readonly getTools?: (options?: ProviderToolSnapshotOptions) => readonly AzureFunctionToolDef[];
172
+ readonly onSchemaFallback?: (event: ProviderSchemaFallback) => void;
168
173
  readonly temperature?: number;
169
174
  /** Defaults to 8192 when omitted or not a positive number — a token limit is always sent, matching OD's real `azure` proxy handler (see module doc). */
170
175
  readonly maxTokens?: number;
@@ -73,7 +73,7 @@
73
73
  * See docs/decisions/DR-001-provider-native-tool-lifecycle.md.
74
74
  */
75
75
  import { defaultDnsLookup, validateBaseUrlResolved } from './connection-guard.js';
76
- import { runOpenAiCompatibleRequest } from './openai-chat.js';
76
+ import { runOpenAiCompatibleRequest, refreshOpenAiTools, createStrictToolRetry } from './openai-chat.js';
77
77
  import { buildLegacyMaxTokensParam, buildMaxCompletionTokensParam, isUnsupportedMaxTokensError } from './token-params.js';
78
78
  import { createTurnEndGuard } from './turn-end-guard.js';
79
79
  const DEFAULT_AZURE_API_VERSION = '2024-10-21';
@@ -107,7 +107,7 @@ function azureRequestBody(options, messages, tokenParam) {
107
107
  };
108
108
  }
109
109
  /** Validates `options.baseUrl`, then delegates to `openai-chat.ts#runOpenAiCompatibleRequest` with Azure's own URL/header/body builders. */
110
- async function runSingleAzureRequest(options, messages, emitEnd, hasEnded) {
110
+ async function runSingleAzureRequest(options, messages, emitEnd, hasEnded, retry) {
111
111
  const baseUrlCheck = await validateBaseUrlResolved({ baseUrl: options.baseUrl, lookup: options.dnsLookup ?? defaultDnsLookup });
112
112
  if (baseUrlCheck.error) {
113
113
  options.onEvent({ type: 'error', message: baseUrlCheck.error });
@@ -115,12 +115,19 @@ async function runSingleAzureRequest(options, messages, emitEnd, hasEnded) {
115
115
  return { finishReason: null, toolCalls: [], text: '' };
116
116
  }
117
117
  const maxTokens = effectiveAzureMaxTokens(options);
118
+ const requestOptions = refreshOpenAiTools({ options, retry });
118
119
  return (({ url, headers, body, redactSecretsList, guardMessageId, providerLabel, onEvent, emitEnd, hasEnded, ...optionalArgs }) => runOpenAiCompatibleRequest({ url, headers, body, redactSecretsList, guardMessageId, providerLabel, onEvent, emitEnd, hasEnded }, optionalArgs))({
119
120
  url: azureRequestUrl(options.baseUrl, options.model, options.apiVersion),
120
121
  headers: azureHeaders(options),
121
- body: azureRequestBody(options, messages, buildLegacyMaxTokensParam({ maxTokens: maxTokens })),
122
+ body: azureRequestBody(requestOptions, messages, buildLegacyMaxTokensParam({ maxTokens: maxTokens })),
123
+ retryToolBody: ({ status, rawErrorText, body }) => {
124
+ const toolNames = (requestOptions.tools ?? []).filter(tool => tool.function.strict).map(tool => tool.function.name);
125
+ if (!retry.downgrade({ status, rawErrorText, toolNames }))
126
+ return null;
127
+ return { ...body, tools: refreshOpenAiTools({ options, retry }).tools };
128
+ },
122
129
  retryableBody: (status, rawErrorText) => status === 400 && isUnsupportedMaxTokensError({ detail: rawErrorText })
123
- ? azureRequestBody(options, messages, buildMaxCompletionTokensParam({ maxTokens: maxTokens }))
130
+ ? azureRequestBody(refreshOpenAiTools({ options, retry }), messages, buildMaxCompletionTokensParam({ maxTokens: maxTokens }))
124
131
  : null,
125
132
  ...(baseUrlCheck.pinnedAddress ? { pinnedAddress: baseUrlCheck.pinnedAddress } : {}),
126
133
  ...(options.signal ? { signal: options.signal } : {}),
@@ -224,6 +231,7 @@ export function buildAzureToolExchangeMessages({ toolResultMessages, followUpPar
224
231
  */
225
232
  export async function runAzureToolTurn(requiredArgs, optionalArgs = {}) {
226
233
  const options = { ...optionalArgs, ...requiredArgs };
234
+ const retry = createStrictToolRetry({ protocol: 'azure', onSchemaFallback: options.onSchemaFallback });
227
235
  const maxToolTurns = options.maxToolTurns ?? DEFAULT_MAX_TOOL_TURNS;
228
236
  const executeTool = options.executeTool;
229
237
  const endGuard = createTurnEndGuard(options.onEvent, (reason) => ({ type: 'end', reason }));
@@ -232,7 +240,7 @@ export async function runAzureToolTurn(requiredArgs, optionalArgs = {}) {
232
240
  let toolTurns = 0;
233
241
  let lastFinishReason = null;
234
242
  while (true) {
235
- const outcome = await runSingleAzureRequest(options, messages, emitEnd, endGuard.hasEnded);
243
+ const outcome = await runSingleAzureRequest(options, messages, emitEnd, endGuard.hasEnded, retry);
236
244
  lastFinishReason = outcome.finishReason;
237
245
  if (endGuard.hasEnded())
238
246
  break;
@@ -1,48 +1,3 @@
1
- /**
2
- * @module providers/connection-guard
3
- *
4
- * SSRF validation and pinned transport needed by
5
- * this package's own `model-catalog.ts`. Vendored from the small generic
6
- * subset of OD's `packages/contracts/src/api/connectionTest.ts` (the
7
- * `isLoopbackApiHost`/`isBlockedExternalApiHostname`/`validateBaseUrl` triad)
8
- * and `apps/daemon/src/connectionTest.ts` (`validateBaseUrlResolved`'s
9
- * DNS-aware follow-up check, `redactSecrets`) — not the surrounding
10
- * 2,600-line file, which is almost entirely OD's own agent-CLI
11
- * connection-test orchestration (proxy dispatchers, product-specific
12
- * executable-fallback copy and env-var names) and out of this task's
13
- * scope; see `archived provenance ledger` for the exact origin details. The shared classifiers now live in `@jini-ai/platform/net`, and redaction
14
- * lives in core. Validation and transport here retain
15
- * no product coupling in the origin — reject requests to loopback-disguised
16
- * or RFC1918/link-local/CGNAT/metadata-service addresses, and strip bearer
17
- * tokens / API-key headers / `?key=` query values out of free-form text
18
- * before it is logged or surfaced to a caller. Provider modules call core with
19
- * explicit exactSecrets because upstream 401 bodies can echo configured credentials.
20
- *
21
- * The provider redaction contract removes bearer tokens,
22
- * `x-api-key`/`api-key`/`x-goog-api-key` headers, `?key=` query values,
23
- * and exact secret strings supplied by the caller from free-form text.
24
- * It is used for logging or surfacing upstream failures without leaking
25
- * credentials embedded in them (some providers echo the key in a 401 body).
26
- * Core owns this union now; provider model/request IDs remain readable.
27
- *
28
- * Exports `pinnedFetch` — a `node:https`/`node:http`-based POST that dials the exact address
29
- * `validateBaseUrlResolved` already validated, instead of leaving the transport to re-resolve DNS
30
- * independently when it connects. Added later than the four functions above, for the same
31
- * explicit network boundary; see `pinnedFetch`'s own doc for why `fetch()` itself cannot do this.
32
- *
33
- * ## Paired with `@jini-ai/ui`'s `utils/endpoint-policy.ts`
34
- *
35
- * That module carries a browser-safe copy of the SYNCHRONOUS half below —
36
- * `isLoopbackApiHost`/`isBlockedExternalApiHostname`/`validateBaseUrl` — so the
37
- * settings tabs can reject a bad endpoint as the operator types it. It is a
38
- * copy rather than an import because `endpoint-policy.ts` itself has zero
39
- * imports by design and this package is Node-only (`validateBaseUrlResolved`
40
- * needs `node:dns`); see that file's header for the full reasoning.
41
- *
42
- * **If the platform/net block-list changes, change the browser copy too.** A divergence means
43
- * the UI accepts an endpoint this guard then refuses — or, in the direction
44
- * that actually matters, the UI accepts one this guard would have refused.
45
- */
46
1
  export interface BaseUrlValidationResult {
47
2
  parsed?: URL;
48
3
  error?: string;
@@ -193,6 +148,8 @@ export declare function pinnedFetch({ url, init, pinnedAddress }: {
193
148
  url: string;
194
149
  init: PinnedFetchInit;
195
150
  pinnedAddress: DnsLookupAddress | undefined;
151
+ }, { idleTimeoutMs }?: {
152
+ idleTimeoutMs?: number;
196
153
  }): Promise<PinnedFetchResponse>;
197
154
  /** Default DNS lookup for {@link validateBaseUrlResolved} — `node:dns/promises`' `lookup(hostname, { all: true, family: 0 })`. */
198
155
  export declare function defaultDnsLookup({ hostname }: {
@@ -1,3 +1,4 @@
1
+ import { readProviderResponseText, MAX_PROVIDER_ERROR_BYTES } from './response-text.js';
1
2
  /**
2
3
  * @module providers/connection-guard
3
4
  *
@@ -201,7 +202,7 @@ const PINNED_FETCH_IDLE_TIMEOUT_MS = 300_000;
201
202
  * (`lookup` option simply omitted). That is intentional, not a gap: an IP literal has nothing left
202
203
  * to re-resolve, and loopback literals are the documented carve-out, outside this threat model.
203
204
  */
204
- export async function pinnedFetch({ url, init, pinnedAddress }) {
205
+ export async function pinnedFetch({ url, init, pinnedAddress }, { idleTimeoutMs = PINNED_FETCH_IDLE_TIMEOUT_MS } = {}) {
205
206
  const parsed = new URL(url);
206
207
  const isHttps = parsed.protocol === 'https:';
207
208
  const { request: httpsRequest } = await import('node:https');
@@ -242,7 +243,10 @@ export async function pinnedFetch({ url, init, pinnedAddress }) {
242
243
  }
243
244
  : {}),
244
245
  }, (res) => {
245
- const status = res.statusCode ?? 0;
246
+ // `IncomingMessage.statusCode` is typed optional only because the same class also models
247
+ // server-side requests; a response handed to a `http(s).request` callback always carries
248
+ // one, so no fallback branch is needed.
249
+ const status = Number(res.statusCode);
246
250
  // A server may compress despite `accept-encoding: identity`. Nothing downstream
247
251
  // decompresses, so failing loudly here is strictly better than handing back bytes the
248
252
  // caller will misparse: a hard error names the cause, silent garbage does not.
@@ -264,7 +268,7 @@ export async function pinnedFetch({ url, init, pinnedAddress }) {
264
268
  // `fetch` itself treats as redirects (a `Location` header is what actually enables the
265
269
  // rebinding hop) — NOT every 3xx: `304 Not Modified` carries no `Location` and no provider
266
270
  // in this package sends conditional-request headers that could ever produce one.
267
- if (status === 301 || status === 302 || status === 303 || status === 307 || status === 308) {
271
+ if ([301, 302, 303, 307, 308].includes(status)) {
268
272
  res.resume();
269
273
  reject(new Error(`pinnedFetch: refused to follow a ${status} redirect`
270
274
  + (typeof res.headers.location === 'string' ? ` to "${res.headers.location}"` : '')
@@ -275,11 +279,8 @@ export async function pinnedFetch({ url, init, pinnedAddress }) {
275
279
  ok: status >= 200 && status < 300,
276
280
  status,
277
281
  body: res,
278
- text: () => new Promise((resolveText, rejectText) => {
279
- const chunks = [];
280
- res.on('data', (chunk) => chunks.push(chunk));
281
- res.on('end', () => resolveText(Buffer.concat(chunks).toString('utf8')));
282
- res.on('error', rejectText);
282
+ text: () => readProviderResponseText({ body: res }, {
283
+ maxBytes: status >= 200 && status < 300 ? 8 * 1024 * 1024 : MAX_PROVIDER_ERROR_BYTES,
283
284
  }),
284
285
  });
285
286
  });
@@ -294,8 +295,8 @@ export async function pinnedFetch({ url, init, pinnedAddress }) {
294
295
  // Fires on socket INACTIVITY (no bytes sent or received), covering connect hangs, a
295
296
  // provider that accepts the connection and then never speaks, and a body that stalls
296
297
  // mid-stream — not on total request duration, matching `setTimeout`'s own semantics.
297
- req.setTimeout(PINNED_FETCH_IDLE_TIMEOUT_MS, () => {
298
- req.destroy(new Error(`pinnedFetch: no activity for ${PINNED_FETCH_IDLE_TIMEOUT_MS}ms`));
298
+ req.setTimeout(idleTimeoutMs, () => {
299
+ req.destroy(new Error(`pinnedFetch: no activity for ${idleTimeoutMs}ms`));
299
300
  });
300
301
  req.on('error', reject);
301
302
  req.end(init.body);
@@ -36,6 +36,10 @@ export type ProviderConnectionTestInput = ProviderConnectionTestRequest & {
36
36
  requestInit?: Pick<RequestInit, 'dispatcher'>;
37
37
  /** Injectable DNS resolver for the base-URL SSRF guard; defaults to `node:dns`. */
38
38
  dnsLookup?: DnsLookupFn;
39
+ /** Injectable HTTP transport (same port `listProviderModels` takes); defaults to the global `fetch`. */
40
+ fetchFn?: typeof fetch;
41
+ /** Hard ceiling on the whole probe; defaults to {@link CONNECTION_TEST_TIMEOUT_MS}. */
42
+ timeoutMs?: number;
39
43
  };
40
44
  export interface ConnectionTestResponse {
41
45
  ok: boolean;