@jini-ai/agent-runtime 0.6.15-rc.2 → 0.6.16

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 (119) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/agent-protocol/acp/rpc.js +4 -8
  3. package/dist/agent-protocol/acp/session.js +33 -37
  4. package/dist/agent-protocol/acp/text-suppression.js +10 -7
  5. package/dist/agent-protocol/acp/updates.js +4 -5
  6. package/dist/agent-protocol/core/json-line-stream.d.ts +6 -3
  7. package/dist/agent-protocol/core/json-line-stream.js +9 -10
  8. package/dist/agent-protocol/pi-rpc/events.js +27 -27
  9. package/dist/agent-protocol/pi-rpc/models.js +13 -11
  10. package/dist/agent-protocol/pi-rpc/session.js +7 -7
  11. package/dist/ai-trace/classify.js +4 -1
  12. package/dist/ai-trace/recorder.d.ts +2 -3
  13. package/dist/ai-trace/recorder.js +2 -3
  14. package/dist/ai-trace/sinks.js +19 -3
  15. package/dist/ai-trace/usage.js +3 -1
  16. package/dist/anthropic-live-models.js +0 -0
  17. package/dist/auth.js +20 -17
  18. package/dist/claude-code-models.js +29 -17
  19. package/dist/claude-filesystem-policy.d.ts +4 -3
  20. package/dist/claude-filesystem-policy.js +39 -12
  21. package/dist/claude-stream.js +65 -47
  22. package/dist/core/model-discovery-shared.js +4 -2
  23. package/dist/core/omit-keys.d.ts +7 -0
  24. package/dist/core/omit-keys.js +12 -0
  25. package/dist/defs/aider.d.ts +1 -1
  26. package/dist/defs/amp.d.ts +1 -1
  27. package/dist/defs/amp.js +2 -2
  28. package/dist/defs/amr.js +5 -9
  29. package/dist/defs/antigravity-event-stream.d.ts +19 -0
  30. package/dist/defs/antigravity-event-stream.js +83 -0
  31. package/dist/defs/antigravity.d.ts +4 -0
  32. package/dist/defs/antigravity.js +27 -15
  33. package/dist/defs/auggie.d.ts +3 -3
  34. package/dist/defs/claude.d.ts +3 -3
  35. package/dist/defs/cline.d.ts +3 -3
  36. package/dist/defs/codebuddy.d.ts +1 -1
  37. package/dist/defs/codex.js +3 -2
  38. package/dist/defs/crush.d.ts +1 -1
  39. package/dist/defs/cursor-agent.d.ts +3 -1
  40. package/dist/defs/cursor-agent.js +8 -6
  41. package/dist/defs/deepseek.d.ts +1 -1
  42. package/dist/defs/devin.d.ts +3 -3
  43. package/dist/defs/droid.d.ts +1 -1
  44. package/dist/defs/goose.d.ts +3 -3
  45. package/dist/defs/grok-build.js +7 -5
  46. package/dist/defs/hermes.d.ts +3 -3
  47. package/dist/defs/index.d.ts +0 -1
  48. package/dist/defs/index.js +0 -1
  49. package/dist/defs/kilo.d.ts +3 -3
  50. package/dist/defs/kimi.d.ts +3 -3
  51. package/dist/defs/kiro.d.ts +3 -3
  52. package/dist/defs/mimo.d.ts +1 -1
  53. package/dist/defs/opencode.d.ts +1 -1
  54. package/dist/defs/pi.d.ts +1 -1
  55. package/dist/defs/qoder.d.ts +1 -1
  56. package/dist/defs/qwen.d.ts +1 -1
  57. package/dist/defs/reasonix.d.ts +3 -3
  58. package/dist/defs/trae-cli.d.ts +3 -3
  59. package/dist/defs/vibe.d.ts +3 -3
  60. package/dist/detection.js +22 -2
  61. package/dist/executables.js +0 -1
  62. package/dist/index.d.ts +0 -1
  63. package/dist/index.js +0 -1
  64. package/dist/json-event-stream.d.ts +1 -2
  65. package/dist/json-event-stream.js +10 -9
  66. package/dist/launch.js +2 -1
  67. package/dist/metadata.js +0 -4
  68. package/dist/model-catalog-cache.js +6 -4
  69. package/dist/model-contracts.d.ts +29 -0
  70. package/dist/model-contracts.js +2 -0
  71. package/dist/model-discovery-adapters.js +47 -24
  72. package/dist/model-discovery-config.js +8 -5
  73. package/dist/model-discovery-sdk.d.ts +0 -29
  74. package/dist/model-discovery-sdk.js +0 -32
  75. package/dist/model-discovery-types.d.ts +3 -3
  76. package/dist/model-discovery-yaml.d.ts +9 -0
  77. package/dist/model-discovery-yaml.js +98 -0
  78. package/dist/model-discovery.js +10 -3
  79. package/dist/model-registry.js +2 -1
  80. package/dist/native-tool-policy.d.ts +28 -0
  81. package/dist/native-tool-policy.js +42 -0
  82. package/dist/opencode-log.js +13 -10
  83. package/dist/pi-models.js +13 -11
  84. package/dist/probe-scheduler.js +13 -5
  85. package/dist/providers/aihubmix.js +6 -7
  86. package/dist/providers/anthropic-messages.d.ts +7 -4
  87. package/dist/providers/anthropic-messages.js +22 -24
  88. package/dist/providers/azure-chat.d.ts +1 -1
  89. package/dist/providers/azure-chat.js +7 -10
  90. package/dist/providers/connection-guard.js +2 -1
  91. package/dist/providers/connection-test.js +16 -10
  92. package/dist/providers/google-messages.d.ts +1 -1
  93. package/dist/providers/google-messages.js +33 -35
  94. package/dist/providers/google.js +3 -4
  95. package/dist/providers/model-catalog.js +10 -7
  96. package/dist/providers/ollama-chat.d.ts +0 -8
  97. package/dist/providers/ollama-chat.js +17 -19
  98. package/dist/providers/openai-chat.d.ts +6 -3
  99. package/dist/providers/openai-chat.js +24 -22
  100. package/dist/providers/operation-schema.d.ts +2 -3
  101. package/dist/providers/operation-schema.js +25 -22
  102. package/dist/providers/provider-tool-policy.d.ts +13 -0
  103. package/dist/providers/provider-tool-policy.js +2 -0
  104. package/dist/providers/tool-loop-verdict.d.ts +22 -0
  105. package/dist/providers/tool-loop-verdict.js +17 -0
  106. package/dist/providers/tool-turn-types.d.ts +2 -12
  107. package/dist/providers/tool-turn.js +7 -2
  108. package/dist/registry.d.ts +1 -1
  109. package/dist/registry.js +2 -3
  110. package/dist/resolution.d.ts +21 -0
  111. package/dist/resolution.js +22 -1
  112. package/dist/role-marker-guard.d.ts +1 -1
  113. package/dist/role-marker-guard.js +1 -1
  114. package/dist/types.d.ts +8 -27
  115. package/package.json +14 -22
  116. package/dist/copilot-stream.d.ts +0 -65
  117. package/dist/copilot-stream.js +0 -123
  118. package/dist/defs/copilot.d.ts +0 -34
  119. package/dist/defs/copilot.js +0 -96
@@ -2,6 +2,7 @@ import { redactSecrets } from '@jini-ai/core';
2
2
  import { defaultDnsLookup, validateBaseUrlResolved } from './connection-guard.js';
3
3
  import { aihubmixCatalogUrl, aihubmixHeaders, parseAIHubMixCatalog } from './aihubmix.js';
4
4
  import { googleProviderModelsUrl, normalizeGoogleModelId } from './google.js';
5
+ import { trimCharsEnd } from '@jini-ai/core/text';
5
6
  const PROVIDER_MODELS_TIMEOUT_MS = 12_000;
6
7
  // Every protocol `providerModelsUrl` resolves an endpoint for EXCEPT
7
8
  // `aihubmix` — its catalogue is public and `providerModelsHeaders` already
@@ -31,7 +32,7 @@ const BEDROCK_MODEL_OPTIONS = [
31
32
  ];
32
33
  function appendVersionedApiPath(baseUrl, suffix) {
33
34
  const url = new URL(baseUrl);
34
- const pathname = url.pathname.replace(/\/+$/, '');
35
+ const pathname = trimCharsEnd({ text: url.pathname, chars: '/' });
35
36
  url.pathname = /\/v\d+(\/|$)/.test(pathname)
36
37
  ? `${pathname}${suffix}`
37
38
  : `${pathname}/v1${suffix}`;
@@ -122,11 +123,7 @@ function extractAnthropicModels(data) {
122
123
  ? item
123
124
  : null;
124
125
  const id = typeof obj?.id === 'string' ? obj.id : '';
125
- const label = typeof obj?.display_name === 'string'
126
- ? obj.display_name
127
- : typeof obj?.displayName === 'string'
128
- ? obj.displayName
129
- : id;
126
+ const label = [obj?.display_name, obj?.displayName].find((name) => typeof name === 'string') ?? id;
130
127
  return id ? { id, label } : null;
131
128
  })
132
129
  .filter((item) => item != null));
@@ -166,6 +163,12 @@ function extractGoogleModels(data) {
166
163
  })
167
164
  .filter((item) => item != null));
168
165
  }
166
+ /** The query parameter each protocol's model listing pages with. */
167
+ function pageCursorParam(protocol) {
168
+ if (protocol === 'google')
169
+ return 'pageToken';
170
+ return protocol === 'anthropic' ? 'after_id' : 'cursor';
171
+ }
169
172
  function providerModelsUrl(protocol, baseUrl, apiKey) {
170
173
  if (protocol === 'aihubmix') {
171
174
  // AIHubMix exposes its chat catalogue on a dedicated endpoint
@@ -394,7 +397,7 @@ function nextCatalogPage({ protocol, data, cursors, url, latencyMs }, _options =
394
397
  return { ok: false, kind: 'unknown', latencyMs, detail: 'Provider repeated a pagination cursor.' };
395
398
  cursors.add(cursor);
396
399
  const next = new URL(url);
397
- next.searchParams.set(protocol === 'google' ? 'pageToken' : protocol === 'anthropic' ? 'after_id' : 'cursor', cursor);
400
+ next.searchParams.set(pageCursorParam(protocol), cursor);
398
401
  return next.toString();
399
402
  }
400
403
  function completedCatalog({ collected, status, latencyMs }, _options = {}) {
@@ -265,14 +265,6 @@ export declare function handleOllamaTextContent({ state, content, onEvent }: {
265
265
  content: string;
266
266
  onEvent: (event: OllamaTurnEvent) => void;
267
267
  }): 'continue' | 'break';
268
- /**
269
- * Reduces one already-parsed NDJSON line into `state`, reporting whether the caller's line loop
270
- * should stop and, if so, why. `'break'` calls `emitEnd('contaminated')` itself (mirroring the
271
- * `content`-delta contamination path being the only in-loop `emitEnd` call site in every sibling
272
- * provider); `'done'` reports the terminal `done: true` line with no `emitEnd` call of its own —
273
- * the caller (`runSingleOllamaRequest`) still owns the normal-completion `emitEnd`, exactly like
274
- * every sibling turn-runner's `emitEnd` contract.
275
- */
276
268
  export declare function processOllamaLine({ state, line, onEvent, emitEnd }: {
277
269
  state: OllamaStreamState;
278
270
  line: Record<string, unknown>;
@@ -107,6 +107,8 @@ import { redactSecrets } from '@jini-ai/core';
107
107
  import { createRoleMarkerGuard } from '../role-marker-guard.js';
108
108
  import { defaultDnsLookup, pinnedFetch, validateBaseUrlResolved } from './connection-guard.js';
109
109
  import { createTurnEndGuard } from './turn-end-guard.js';
110
+ import { trimCharsEnd } from '@jini-ai/core/text';
111
+ import { toolLoopVerdict } from './tool-loop-verdict.js';
110
112
  const DEFAULT_OLLAMA_BASE_URL = 'https://ollama.com';
111
113
  const DEFAULT_MAX_TOOL_TURNS = 8;
112
114
  function isRecord(value) {
@@ -114,7 +116,7 @@ function isRecord(value) {
114
116
  }
115
117
  /** Strips a trailing `/api` (with or without a trailing slash) before appending `/api/chat` — matches OD's `.replace(/\/+$/, '').replace(/\/api\/?$/, '')` so a caller-supplied `baseUrl` ending in `/api` doesn't produce `/api/api/chat`. */
116
118
  function ollamaRequestUrl(baseUrl) {
117
- const trimmed = (baseUrl ?? DEFAULT_OLLAMA_BASE_URL).replace(/\/+$/, '').replace(/\/api\/?$/, '');
119
+ const trimmed = trimCharsEnd({ text: baseUrl ?? DEFAULT_OLLAMA_BASE_URL, chars: '/' }).replace(/\/api\/?$/, '');
118
120
  return `${trimmed}/api/chat`;
119
121
  }
120
122
  function ollamaHeaders(options) {
@@ -260,14 +262,17 @@ export function handleOllamaTextContent({ state, content, onEvent }) {
260
262
  * the caller (`runSingleOllamaRequest`) still owns the normal-completion `emitEnd`, exactly like
261
263
  * every sibling turn-runner's `emitEnd` contract.
262
264
  */
265
+ /** The message's text content when it is a non-empty string, else `null`. */
266
+ function nonEmptyContent(message) {
267
+ return message && typeof message.content === 'string' && message.content.length > 0 ? message.content : null;
268
+ }
263
269
  export function processOllamaLine({ state, line, onEvent, emitEnd }) {
264
270
  const message = isRecord(line.message) ? line.message : null;
265
- if (message && typeof message.content === 'string' && message.content.length > 0) {
266
- if (handleOllamaTextContent({ state: state, content: message.content, onEvent: onEvent }) === 'break') {
267
- state.finishReason = 'contaminated';
268
- emitEnd('contaminated');
269
- return 'break';
270
- }
271
+ const text = nonEmptyContent(message);
272
+ if (text !== null && handleOllamaTextContent({ state: state, content: text, onEvent: onEvent }) === 'break') {
273
+ state.finishReason = 'contaminated';
274
+ emitEnd('contaminated');
275
+ return 'break';
271
276
  }
272
277
  if (message)
273
278
  handleOllamaToolCallsField({ state: state, message: message });
@@ -407,9 +412,7 @@ async function runSingleOllamaRequest(options, messages, emitEnd) {
407
412
  finishReason: null,
408
413
  };
409
414
  for await (const line of decodeNdjsonStream(body)) {
410
- if (!isRecord(line))
411
- continue;
412
- const result = processOllamaLine({ state: state, line: line, onEvent: onEvent, emitEnd: emitEnd });
415
+ const result = isRecord(line) ? processOllamaLine({ state: state, line: line, onEvent: onEvent, emitEnd: emitEnd }) : null;
413
416
  if (result === 'break' || result === 'done')
414
417
  break;
415
418
  }
@@ -479,15 +482,10 @@ export async function runOllamaToolTurn(requiredArgs, optionalArgs = {}) {
479
482
  while (true) {
480
483
  const outcome = await runSingleOllamaRequest(options, messages, emitEnd);
481
484
  lastFinishReason = outcome.finishReason;
482
- if (endGuard.hasEnded())
483
- break;
484
- const exitReason = ollamaLoopExitReason({ outcome: outcome, toolTurns: toolTurns, maxToolTurns: maxToolTurns });
485
- if (exitReason) {
486
- emitEnd(exitReason);
487
- break;
488
- }
489
- if (!executeTool) {
490
- emitEnd('stop');
485
+ const verdict = toolLoopVerdict({ ended: endGuard.hasEnded(), hasExecutor: Boolean(executeTool), exitReason: () => ollamaLoopExitReason({ outcome: outcome, toolTurns: toolTurns, maxToolTurns: maxToolTurns }) });
486
+ if (verdict.stop || !executeTool) {
487
+ if (verdict.emit)
488
+ emitEnd(verdict.emit);
491
489
  break;
492
490
  }
493
491
  toolTurns += 1;
@@ -70,7 +70,7 @@ 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
+ import type { ProviderToolSnapshotOptions, ProviderSchemaFallback, ProviderProtocol } from './provider-tool-policy.js';
74
74
  export interface OpenAiFunctionToolDef {
75
75
  readonly type: 'function';
76
76
  readonly function: {
@@ -186,7 +186,9 @@ export declare const DEFAULT_OPENAI_MAX_TOKENS = 8192;
186
186
  export declare function openAiRequestUrl({ baseUrl }: {
187
187
  baseUrl: string | undefined;
188
188
  }): string;
189
- export declare function openAiHeaders(requiredArgs: Pick<OpenAiTurnOptions, "apiKey" | "model" | "messages" | "onEvent">, optionalArgs?: Omit<OpenAiTurnOptions, "apiKey" | "model" | "messages" | "onEvent">): Record<string, string>;
189
+ /** The `OpenAiTurnOptions` keys every caller must pass. */
190
+ type OpenAiRequiredOption = "apiKey" | "model" | "messages" | "onEvent";
191
+ export declare function openAiHeaders(requiredArgs: Pick<OpenAiTurnOptions, OpenAiRequiredOption>, optionalArgs?: Omit<OpenAiTurnOptions, OpenAiRequiredOption>): Record<string, string>;
190
192
  export declare function openAiRequestBody({ options, messages }: {
191
193
  options: OpenAiTurnOptions;
192
194
  messages: readonly OpenAiMessageParam[];
@@ -448,5 +450,6 @@ export declare function buildOpenAiToolExchangeMessages({ toolResultMessages, fo
448
450
  * function call. See `anthropic-messages.ts#runAnthropicToolTurn`'s doc for
449
451
  * the shared event-stream/`ended`-flag contract this mirrors exactly.
450
452
  */
451
- export declare function runOpenAiToolTurn(requiredArgs: Pick<OpenAiTurnOptions, "apiKey" | "model" | "messages" | "onEvent">, optionalArgs?: Omit<OpenAiTurnOptions, "apiKey" | "model" | "messages" | "onEvent">): Promise<OpenAiTurnResult>;
453
+ export declare function runOpenAiToolTurn(requiredArgs: Pick<OpenAiTurnOptions, OpenAiRequiredOption>, optionalArgs?: Omit<OpenAiTurnOptions, OpenAiRequiredOption>): Promise<OpenAiTurnResult>;
454
+ export {};
452
455
  //# sourceMappingURL=openai-chat.d.ts.map
@@ -72,6 +72,9 @@ import { defaultDnsLookup, pinnedFetch, validateBaseUrlResolved } from './connec
72
72
  import { decodeSseStream } from './sse-decode.js';
73
73
  import { buildOpenAIChatTokenParam } from './token-params.js';
74
74
  import { createTurnEndGuard } from './turn-end-guard.js';
75
+ import { trimCharsEnd } from '@jini-ai/core/text';
76
+ import { toolLoopVerdict } from './tool-loop-verdict.js';
77
+ import { omitKeys } from '../core/omit-keys.js';
75
78
  const DEFAULT_OPENAI_BASE_URL = 'https://api.openai.com';
76
79
  const DEFAULT_MAX_TOOL_TURNS = 8;
77
80
  const DONE_SENTINEL = '[DONE]';
@@ -81,7 +84,7 @@ function isRecord(value) {
81
84
  return typeof value === 'object' && value !== null && !Array.isArray(value);
82
85
  }
83
86
  export function openAiRequestUrl({ baseUrl }) {
84
- const base = (baseUrl ?? DEFAULT_OPENAI_BASE_URL).replace(/\/+$/, '');
87
+ const base = trimCharsEnd({ text: baseUrl ?? DEFAULT_OPENAI_BASE_URL, chars: '/' });
85
88
  return /\/v\d+(\/|$)/.test(base) ? `${base}/chat/completions` : `${base}/v1/chat/completions`;
86
89
  }
87
90
  export function openAiHeaders(requiredArgs, optionalArgs = {}) {
@@ -116,6 +119,12 @@ export function extractOpenAiErrorDetail({ rawText }) {
116
119
  }
117
120
  return rawText.trim().slice(0, 500);
118
121
  }
122
+ /** Wordings a provider uses to refuse a strict/schema feature; any one matching is enough. */
123
+ const STRICT_REJECTION_PATTERNS = [
124
+ /unsupported|not support|unknown (?:field|parameter|name)|unrecognized|not (?:allowed|permitted)/i,
125
+ /invalid (?:json )?schema|schema[^\n]*invalid|requires?[^\n]*beta/i,
126
+ /invalid (?:enum )?value[^\n]*(?:VALIDATED|function[_ .]?calling[_ .]?config)/i,
127
+ ];
119
128
  /** Only explicit HTTP schema/capability rejections qualify, never auth, rate limits or transport failures.
120
129
  * @complexity O(e) time and O(e) space for at most 16 KiB of error text; no I/O.
121
130
  */
@@ -124,7 +133,7 @@ function isStrictToolRejection({ status, rawErrorText }) {
124
133
  return false;
125
134
  const detail = rawErrorText.slice(0, 16384);
126
135
  const namesFeature = /\bstrict\b|\bVALIDATED\b|function[_ .]?calling[_ .]?config|(?:input[_ ]|json[_ ])?schema|structured.outputs/i.test(detail);
127
- const rejectsFeature = /unsupported|not support|unknown (?:field|parameter|name)|unrecognized|not (?:allowed|permitted)|invalid (?:json )?schema|schema[^\n]*invalid|invalid (?:enum )?value[^\n]*(?:VALIDATED|function[_ .]?calling[_ .]?config)|requires?[^\n]*beta/i.test(detail);
136
+ const rejectsFeature = STRICT_REJECTION_PATTERNS.some((pattern) => pattern.test(detail));
128
137
  return namesFeature && rejectsFeature;
129
138
  }
130
139
  /**
@@ -161,7 +170,7 @@ export function refreshOpenAiTools({ options, retry }, _optional = {}) {
161
170
  let tools = options.getTools?.({ strict: retry.enabled }) ?? options.tools;
162
171
  if (!retry.enabled)
163
172
  tools = tools?.map(tool => {
164
- const { strict: _strict, ...definition } = tool.function;
173
+ const definition = omitKeys(tool.function, ['strict']);
165
174
  return { ...tool, function: definition };
166
175
  });
167
176
  return { ...options, ...(tools !== undefined ? { tools } : {}) };
@@ -236,10 +245,9 @@ export function handleOpenAiChoiceDelta({ state, choice, onEvent }) {
236
245
  const delta = isRecord(choice.delta) ? choice.delta : null;
237
246
  if (!delta)
238
247
  return 'continue';
239
- if (typeof delta.content === 'string' && delta.content.length > 0) {
240
- if (handleOpenAiTextContentDelta({ state: state, content: delta.content, onEvent: onEvent }) === 'break')
241
- return 'break';
242
- }
248
+ const text = typeof delta.content === 'string' && delta.content.length > 0 ? delta.content : null;
249
+ if (text !== null && handleOpenAiTextContentDelta({ state: state, content: text, onEvent: onEvent }) === 'break')
250
+ return 'break';
243
251
  if (Array.isArray(delta.tool_calls)) {
244
252
  for (const rawCall of delta.tool_calls) {
245
253
  accumulateOpenAiToolCallDelta({ state: state, rawCall: rawCall });
@@ -271,12 +279,12 @@ function emitPendingOpenAiToolUseEvents(toolCalls, onEvent) {
271
279
  function resolveOpenAiRetry({ init, status, rawText }, _options = {}) {
272
280
  const toolRetryBody = init.retryToolBody?.({ status, rawErrorText: rawText, body: init.body });
273
281
  if (toolRetryBody) {
274
- const { retryToolBody: _retryToolBody, ...retryInit } = init;
282
+ const retryInit = omitKeys(init, ['retryToolBody']);
275
283
  return { type: 'retry', retryInit: { ...retryInit, body: toolRetryBody } };
276
284
  }
277
285
  const retryBody = init.retryableBody?.(status, rawText);
278
286
  if (retryBody) {
279
- const { retryableBody: _retryableBody, ...retryInit } = init;
287
+ const retryInit = omitKeys(init, ['retryableBody']);
280
288
  return { type: 'retry', retryInit: { ...retryInit, body: retryBody } };
281
289
  }
282
290
  return null;
@@ -396,10 +404,9 @@ export async function runOpenAiCompatibleRequest(requiredArgs, optionalArgs = {}
396
404
  // after this loop, to decide whether pending tool_use events should still be emitted (a
397
405
  // contaminating delta can arrive on a *later* chunk than the one that set `finish_reason`).
398
406
  const result = processOpenAiStreamFrame({ state: state, frame: frame, onEvent: onEvent });
399
- if (result === 'done')
400
- break;
401
- if (result === 'contaminated') {
402
- init.emitEnd('contaminated');
407
+ if (result === 'done' || result === 'contaminated') {
408
+ if (result === 'contaminated')
409
+ init.emitEnd('contaminated');
403
410
  break;
404
411
  }
405
412
  }
@@ -596,15 +603,10 @@ export async function runOpenAiToolTurn(requiredArgs, optionalArgs = {}) {
596
603
  while (true) {
597
604
  const outcome = await runSingleOpenAiRequest(options, messages, emitEnd, endGuard.hasEnded, retry);
598
605
  lastFinishReason = outcome.finishReason;
599
- if (endGuard.hasEnded())
600
- break;
601
- const exitReason = openAiLoopExitReason({ outcome: outcome, toolTurns: toolTurns, maxToolTurns: maxToolTurns });
602
- if (exitReason) {
603
- emitEnd(exitReason);
604
- break;
605
- }
606
- if (!executeTool) {
607
- emitEnd('stop');
606
+ const verdict = toolLoopVerdict({ ended: endGuard.hasEnded(), hasExecutor: Boolean(executeTool), exitReason: () => openAiLoopExitReason({ outcome: outcome, toolTurns: toolTurns, maxToolTurns: maxToolTurns }) });
607
+ if (verdict.stop || !executeTool) {
608
+ if (verdict.emit)
609
+ emitEnd(verdict.emit);
608
610
  break;
609
611
  }
610
612
  toolTurns += 1;
@@ -1,6 +1,5 @@
1
- import type { ProviderProtocol } from './tool-turn-types.js';
2
- /** Closed reason codes are safe to observe: no schema, argument values or provider error text. */
3
- export type OperationSchemaFallbackReason = 'endpoint-unsupported' | 'endpoint-rejected' | 'open-map' | 'recursive-schema' | 'unresolved-reference' | 'unsupported-schema' | 'optional-nullable' | 'schema-limit';
1
+ import type { ProviderProtocol, OperationSchemaFallbackReason } from './provider-tool-policy.js';
2
+ export type { OperationSchemaFallbackReason } from './provider-tool-policy.js';
4
3
  export interface CompiledOperationSchema {
5
4
  readonly schema: Record<string, unknown>;
6
5
  readonly strict: boolean;
@@ -12,6 +12,8 @@ const TYPES = new Set(['object', 'array', 'string', 'integer', 'number', 'boolea
12
12
  function isRecord(value) {
13
13
  return value !== null && typeof value === 'object' && !Array.isArray(value);
14
14
  }
15
+ /** The fallback reason for any schema construct this projection does not translate. */
16
+ const UNSUPPORTED_SCHEMA = 'unsupported-schema';
15
17
  function reject(reason) { throw new SchemaProjectionError(reason); }
16
18
  /** Resolve local JSON pointers only. Expansion is bounded by the same node/depth budget as inline schemas. */
17
19
  function resolveReference(schema, context) {
@@ -20,7 +22,7 @@ function resolveReference(schema, context) {
20
22
  if (typeof schema.$ref !== 'string' || !schema.$ref.startsWith('#/'))
21
23
  return reject('unresolved-reference');
22
24
  if (Object.keys(schema).some(key => !['$ref', 'description', 'title'].includes(key)))
23
- return reject('unsupported-schema');
25
+ return reject(UNSUPPORTED_SCHEMA);
24
26
  let target = context.root;
25
27
  for (const part of schema.$ref.slice(2).split('/')) {
26
28
  const key = part.replace(/~1/g, '/').replace(/~0/g, '~');
@@ -37,30 +39,30 @@ function normalizedNode(schema) {
37
39
  if (schema.anyOf === undefined)
38
40
  return schema;
39
41
  if (!Array.isArray(schema.anyOf) || schema.anyOf.length !== 2)
40
- return reject('unsupported-schema');
42
+ return reject(UNSUPPORTED_SCHEMA);
41
43
  const nullMember = schema.anyOf.find(member => isRecord(member) && member.type === 'null');
42
44
  if (!isRecord(nullMember) || Object.keys(nullMember).some(key => !['type', 'title', 'description'].includes(key)))
43
- return reject('unsupported-schema');
45
+ return reject(UNSUPPORTED_SCHEMA);
44
46
  const nonNull = schema.anyOf.filter(member => !isRecord(member) || member.type !== 'null');
45
47
  if (nonNull.length !== 1 || !isRecord(nonNull[0]))
46
- return reject('unsupported-schema');
48
+ return reject(UNSUPPORTED_SCHEMA);
47
49
  if (Object.keys(schema).some(key => !['anyOf', 'title', 'description', 'default'].includes(key)))
48
- return reject('unsupported-schema');
50
+ return reject(UNSUPPORTED_SCHEMA);
49
51
  const child = nonNull[0];
50
52
  if (typeof child.type !== 'string')
51
- return reject('unsupported-schema');
53
+ return reject(UNSUPPORTED_SCHEMA);
52
54
  return { ...child, type: [child.type, 'null'] };
53
55
  }
54
56
  function nodeTypes(schema) {
55
57
  const types = Array.isArray(schema.type) ? schema.type : [schema.type];
56
58
  if (types.length === 0)
57
- return reject('unsupported-schema');
59
+ return reject(UNSUPPORTED_SCHEMA);
58
60
  if (!types.every((type) => typeof type === 'string' && TYPES.has(type)))
59
- return reject('unsupported-schema');
61
+ return reject(UNSUPPORTED_SCHEMA);
60
62
  if (new Set(types).size !== types.length)
61
- return reject('unsupported-schema');
63
+ return reject(UNSUPPORTED_SCHEMA);
62
64
  if (types.length > 1 && (types.length !== 2 || !types.includes('null')))
63
- return reject('unsupported-schema');
65
+ return reject(UNSUPPORTED_SCHEMA);
64
66
  return types;
65
67
  }
66
68
  function schemaMetadata(schema) {
@@ -72,15 +74,15 @@ function projectLiterals(schema, projected) {
72
74
  projected.enum = literalValues(schema.enum);
73
75
  if (Object.hasOwn(schema, 'const')) {
74
76
  if (schema.enum !== undefined)
75
- return reject('unsupported-schema');
77
+ return reject(UNSUPPORTED_SCHEMA);
76
78
  projected.enum = literalValues([schema.const]);
77
79
  }
78
80
  }
79
81
  function literalValues(value) {
80
82
  if (!Array.isArray(value) || value.length === 0)
81
- return reject('unsupported-schema');
83
+ return reject(UNSUPPORTED_SCHEMA);
82
84
  if (value.some(member => member !== null && !['string', 'number', 'boolean'].includes(typeof member)))
83
- return reject('unsupported-schema');
85
+ return reject(UNSUPPORTED_SCHEMA);
84
86
  return [...value];
85
87
  }
86
88
  function childContext(context, schema) {
@@ -96,9 +98,9 @@ function projectObject(schema, context) {
96
98
  const properties = schema.properties ?? {};
97
99
  const required = schema.required ?? [];
98
100
  if (!isRecord(properties) || !Array.isArray(required))
99
- return reject('unsupported-schema');
101
+ return reject(UNSUPPORTED_SCHEMA);
100
102
  if (required.some(key => typeof key !== 'string' || !Object.hasOwn(properties, key)))
101
- return reject('unsupported-schema');
103
+ return reject(UNSUPPORTED_SCHEMA);
102
104
  const requiredKeys = new Set(required);
103
105
  const children = Object.entries(properties).map(([key, child]) => [key, projectNode(child, context, !requiredKeys.has(key))]);
104
106
  const projected = {
@@ -134,25 +136,26 @@ function googleEnumDecoder(schema, decoder, protocol) {
134
136
  if (schema.enum.includes(null)) {
135
137
  const types = nodeTypes(schema);
136
138
  if (!types.includes('null'))
137
- return reject('unsupported-schema');
139
+ return reject(UNSUPPORTED_SCHEMA);
138
140
  schema.enum = values;
139
141
  }
140
142
  return { ...decoder, numericEnum: values };
141
143
  }
142
144
  /** O(n) for the expanded tree, bounded to 2048 nodes and 32 levels; no I/O or input mutation. */
143
145
  function projectNode(value, context, optional) {
144
- if (--context.budget.remaining < 0 || context.depth > 32)
146
+ context.budget.remaining -= 1;
147
+ if (context.budget.remaining < 0 || context.depth > 32)
145
148
  return reject('schema-limit');
146
149
  if (!isRecord(value))
147
- return reject('unsupported-schema');
150
+ return reject(UNSUPPORTED_SCHEMA);
148
151
  const resolved = resolveReference(value, context);
149
152
  if (context.ancestors.has(resolved))
150
153
  return reject('recursive-schema');
151
154
  if (Object.keys(resolved).some(key => !SCHEMA_KEYS.has(key)))
152
- return reject('unsupported-schema');
155
+ return reject(UNSUPPORTED_SCHEMA);
153
156
  const schema = normalizedNode(resolved);
154
157
  if (Object.keys(schema).some(key => !SCHEMA_KEYS.has(key)))
155
- return reject('unsupported-schema');
158
+ return reject(UNSUPPORTED_SCHEMA);
156
159
  const types = nodeTypes(schema);
157
160
  // Required wire properties cannot represent both omission and a genuine null-as-clear.
158
161
  // Prefer fallback over inventing a sentinel or forcing an unintended clear operation.
@@ -196,7 +199,7 @@ function fallback(schema, protocol, reason) {
196
199
  function compileStrict(schema, protocol) {
197
200
  const result = projectNode(schema, { root: schema, protocol, ancestors: new Set(), budget: { remaining: 2048 }, depth: 0 }, false);
198
201
  if (result.schema.type !== 'object')
199
- return reject('unsupported-schema');
202
+ return reject(UNSUPPORTED_SCHEMA);
200
203
  const wireSchema = protocol === 'google' ? googleParametersOf({ descriptor: { id: '', inputSchema: result.schema } }) : result.schema;
201
204
  return { schema: wireSchema, strict: true, decodeInput: input => decodeValue(input, result.decoder) };
202
205
  }
@@ -211,7 +214,7 @@ function compileStrict(schema, protocol) {
211
214
  export function compileOperationSchema({ schema: inputSchema, protocol }, { strict = false } = {}) {
212
215
  const schema = isRecord(inputSchema) ? inputSchema : EMPTY_SCHEMA;
213
216
  if (inputSchema !== undefined && !isRecord(inputSchema))
214
- return fallback(schema, protocol, 'unsupported-schema');
217
+ return fallback(schema, protocol, UNSUPPORTED_SCHEMA);
215
218
  if (!strict)
216
219
  return fallback(schema, protocol, 'endpoint-unsupported');
217
220
  try {
@@ -0,0 +1,13 @@
1
+ /** Request adapters choose strict support for their actual endpoint/model; policy is always prefer. */
2
+ export interface ProviderToolSnapshotOptions {
3
+ readonly strict?: boolean;
4
+ }
5
+ export interface ProviderSchemaFallback {
6
+ readonly toolId: string;
7
+ readonly protocol: ProviderProtocol;
8
+ readonly reason: OperationSchemaFallbackReason;
9
+ }
10
+ export type ProviderProtocol = "anthropic" | "openai" | "azure" | "google";
11
+ /** Closed reason codes are safe to observe: no schema, argument values or provider error text. */
12
+ export type OperationSchemaFallbackReason = 'endpoint-unsupported' | 'endpoint-rejected' | 'open-map' | 'recursive-schema' | 'unresolved-reference' | 'unsupported-schema' | 'optional-nullable' | 'schema-limit';
13
+ //# sourceMappingURL=provider-tool-policy.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=provider-tool-policy.js.map
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @file The stop decision every provider's tool loop makes once a request settles, shared so the
3
+ * five loops (Anthropic, Azure, Google, Ollama, OpenAI) cannot drift apart.
4
+ */
5
+ /** What a tool loop does after one request: stop (emitting `emit` as the end reason when set), or
6
+ * run the requested tools when `stop` is false. */
7
+ export interface ToolLoopVerdict<R extends string> {
8
+ readonly stop: boolean;
9
+ readonly emit: R | 'stop' | null;
10
+ }
11
+ /**
12
+ * A turn that already ended mid-request stops with nothing more to emit. Otherwise the provider's
13
+ * own exit reason stops it, and so does a missing executor: pending tool calls were already emitted
14
+ * as `tool_use` events, so with nothing to run them the turn ends with `'stop'` rather than
15
+ * silently retrying forever. `exitReason` is only consulted for a turn that has not ended.
16
+ */
17
+ export declare function toolLoopVerdict<R extends string>({ ended, hasExecutor, exitReason }: {
18
+ ended: boolean;
19
+ hasExecutor: boolean;
20
+ exitReason: () => R | null;
21
+ }): ToolLoopVerdict<R>;
22
+ //# sourceMappingURL=tool-loop-verdict.d.ts.map
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @file The stop decision every provider's tool loop makes once a request settles, shared so the
3
+ * five loops (Anthropic, Azure, Google, Ollama, OpenAI) cannot drift apart.
4
+ */
5
+ /**
6
+ * A turn that already ended mid-request stops with nothing more to emit. Otherwise the provider's
7
+ * own exit reason stops it, and so does a missing executor: pending tool calls were already emitted
8
+ * as `tool_use` events, so with nothing to run them the turn ends with `'stop'` rather than
9
+ * silently retrying forever. `exitReason` is only consulted for a turn that has not ended.
10
+ */
11
+ export function toolLoopVerdict({ ended, hasExecutor, exitReason }) {
12
+ if (ended)
13
+ return { stop: true, emit: null };
14
+ const emit = exitReason() || (hasExecutor ? null : 'stop');
15
+ return { stop: emit !== null, emit };
16
+ }
17
+ //# sourceMappingURL=tool-loop-verdict.js.map
@@ -2,16 +2,8 @@ import type { runAnthropicToolTurn, AnthropicToolDef } from './anthropic-message
2
2
  import type { runOpenAiToolTurn, OpenAiFunctionToolDef } from './openai-chat.js';
3
3
  import type { runAzureToolTurn, AzureFunctionToolDef } from './azure-chat.js';
4
4
  import type { runGoogleToolTurn, GoogleToolDef } from './google-messages.js';
5
- import type { OperationSchemaFallbackReason } from './operation-schema.js';
6
- /** Request adapters choose strict support for their actual endpoint/model; policy is always prefer. */
7
- export interface ProviderToolSnapshotOptions {
8
- readonly strict?: boolean;
9
- }
10
- export interface ProviderSchemaFallback {
11
- readonly toolId: string;
12
- readonly protocol: ProviderProtocol;
13
- readonly reason: OperationSchemaFallbackReason;
14
- }
5
+ import type { ProviderToolSnapshotOptions, ProviderSchemaFallback, ProviderProtocol } from './provider-tool-policy.js';
6
+ export type { ProviderToolSnapshotOptions, ProviderSchemaFallback, ProviderProtocol } from './provider-tool-policy.js';
15
7
  type RefreshableAdapter<Required, Optional, Result, Tool> = (required: Required, optional?: Optional & {
16
8
  /** Read immediately before each request, including a recognized schema downgrade. */
17
9
  readonly getTools?: (options?: ProviderToolSnapshotOptions) => readonly Tool[];
@@ -36,7 +28,6 @@ export interface ProviderToolDescriptor {
36
28
  /** Preserve a wire name already assigned by the run's core exposure snapshot. */
37
29
  readonly wireName?: string;
38
30
  }
39
- export type ProviderProtocol = "anthropic" | "openai" | "azure" | "google";
40
31
  export interface ProviderChatMessage {
41
32
  readonly role: "user" | "assistant";
42
33
  readonly content: string;
@@ -137,5 +128,4 @@ export interface ProviderToolTurnOptions {
137
128
  readonly maxToolTurns?: number;
138
129
  readonly signal?: AbortSignal;
139
130
  }
140
- export {};
141
131
  //# sourceMappingURL=tool-turn-types.d.ts.map
@@ -26,7 +26,7 @@ function toGoogleToolContent(content) {
26
26
  return content;
27
27
  return content.map((block) => (block.type === "text" ? { text: block.text } : { inlineData: { mimeType: block.mimeType, data: block.data } }));
28
28
  }
29
- function foldToolError(content, isError) {
29
+ function foldToolError(content, isError = false) {
30
30
  if (!isError)
31
31
  return content;
32
32
  return typeof content === "string" ? `${TOOL_ERROR_PREFIX}${content}` : [{ type: "text", text: TOOL_ERROR_PREFIX.trimEnd() }, ...content];
@@ -73,7 +73,7 @@ function pinWireName(descriptor, names, occupied) {
73
73
  return;
74
74
  const existing = names.get(descriptor.id);
75
75
  const owner = occupied.get(descriptor.wireName);
76
- if (!/^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(descriptor.wireName))
76
+ if (!/^[A-Za-z_]\w{0,63}$/.test(descriptor.wireName))
77
77
  throw new ProviderToolProjectionError({});
78
78
  if (existing !== undefined && existing !== descriptor.wireName)
79
79
  throw new ProviderToolProjectionError({});
@@ -310,6 +310,11 @@ export async function runProviderToolTurn(required, optional = {}) {
310
310
  return runAzureTurn(input);
311
311
  case "google":
312
312
  return runGoogleTurn(input);
313
+ default: {
314
+ // Unreachable: every supported protocol has a case above, and a new one fails typecheck here.
315
+ const unsupported = input.protocol;
316
+ throw new TypeError(`Unsupported provider tool-turn protocol: ${String(unsupported)}`);
317
+ }
313
318
  }
314
319
  }
315
320
  //# sourceMappingURL=tool-turn.js.map
@@ -9,7 +9,7 @@ export declare function getAgentDef({ id }: {
9
9
  * tools) into a session run by this
10
10
  * def, per its own `externalMcpInjection` declaration (`types.ts`'s own doc names the six wired
11
11
  * strategies and the defs that leave the field `undefined` because the CLI has no mechanism to
12
- * receive one — `aider`, `amp`, `copilot`, `crush`, `cursor-agent`, `deepseek`, `droid`,
12
+ * receive one — `aider`, `amp`, `crush`, `cursor-agent`, `deepseek`, `droid`,
13
13
  * `grok-build`, `pi`, `qoder`, and `qwen` today, each documenting why in its own def file).
14
14
  *
15
15
  * This is the single seam a tool-availability UI (e.g. the chat runtime picker's "No tools" badge)
package/dist/registry.js CHANGED
@@ -17,7 +17,7 @@
17
17
  * can reintroduce a de-branded, sandbox-free local-profile loader as an
18
18
  * injected port if a consumer needs it. See `archived provenance ledger`.
19
19
  */
20
- import { aiderAgentDef, ampAgentDef, amrAgentDef, antigravityAgentDef, auggieAgentDef, claudeAgentDef, clineAgentDef, codebuddyAgentDef, codexAgentDef, copilotAgentDef, crushAgentDef, cursorAgentDef, deepseekAgentDef, devinAgentDef, droidAgentDef, gooseAgentDef, grokBuildAgentDef, hermesAgentDef, kiloAgentDef, kimiAgentDef, kiroAgentDef, mimoAgentDef, opencodeAgentDef, piAgentDef, qoderAgentDef, qwenAgentDef, reasonixAgentDef, traeCliAgentDef, vibeAgentDef, } from './defs/index.js';
20
+ import { aiderAgentDef, ampAgentDef, amrAgentDef, antigravityAgentDef, auggieAgentDef, claudeAgentDef, clineAgentDef, codebuddyAgentDef, codexAgentDef, crushAgentDef, cursorAgentDef, deepseekAgentDef, devinAgentDef, droidAgentDef, gooseAgentDef, grokBuildAgentDef, hermesAgentDef, kiloAgentDef, kimiAgentDef, kiroAgentDef, mimoAgentDef, opencodeAgentDef, piAgentDef, qoderAgentDef, qwenAgentDef, reasonixAgentDef, traeCliAgentDef, vibeAgentDef, } from './defs/index.js';
21
21
  export const BASE_AGENT_DEFS = [
22
22
  amrAgentDef,
23
23
  claudeAgentDef,
@@ -32,7 +32,6 @@ export const BASE_AGENT_DEFS = [
32
32
  qwenAgentDef,
33
33
  // Gemini CLI retired 2026-10-06; Antigravity (agy) is the Google CLI path.
34
34
  qoderAgentDef,
35
- copilotAgentDef,
36
35
  ampAgentDef,
37
36
  piAgentDef,
38
37
  kiroAgentDef,
@@ -66,7 +65,7 @@ export function getAgentDef({ id }) {
66
65
  * tools) into a session run by this
67
66
  * def, per its own `externalMcpInjection` declaration (`types.ts`'s own doc names the six wired
68
67
  * strategies and the defs that leave the field `undefined` because the CLI has no mechanism to
69
- * receive one — `aider`, `amp`, `copilot`, `crush`, `cursor-agent`, `deepseek`, `droid`,
68
+ * receive one — `aider`, `amp`, `crush`, `cursor-agent`, `deepseek`, `droid`,
70
69
  * `grok-build`, `pi`, `qoder`, and `qwen` today, each documenting why in its own def file).
71
70
  *
72
71
  * This is the single seam a tool-availability UI (e.g. the chat runtime picker's "No tools" badge)
@@ -1,3 +1,24 @@
1
+ /** Resolve a saved selection against the host's registry; retired ids use its default.
2
+ * `onFallback` reports the first stale selection once per resolver, keeping repeated turns quiet
3
+ * without retaining an unbounded collection of caller-supplied ids. Missing selections are silent.
4
+ * Registry lookup failures propagate; executable availability remains the launcher's responsibility.
5
+ * @complexity O(registry lookup) time per selection, O(1) retained space.
6
+ */
7
+ export declare function createAgentSelectionResolver({ defaultAgentId, onFallback }: {
8
+ defaultAgentId: string;
9
+ onFallback: (input: {
10
+ agentId: string;
11
+ defaultAgentId: string;
12
+ }) => void;
13
+ }, { getDef }?: {
14
+ getDef?: (input: {
15
+ id: string;
16
+ }) => {
17
+ id: string;
18
+ } | null;
19
+ }): (input: {
20
+ agentId?: string | undefined;
21
+ }, options?: Record<string, never>) => string;
1
22
  export declare function resolveAgentBin({ id }: {
2
23
  id: string;
3
24
  }, { configuredEnv }?: {