@jini-ai/agent-runtime 0.6.15-rc.1 → 0.6.15

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 (99) hide show
  1. package/dist/agent-protocol/acp/rpc.js +4 -8
  2. package/dist/agent-protocol/acp/session.js +38 -47
  3. package/dist/agent-protocol/acp/text-suppression.js +10 -7
  4. package/dist/agent-protocol/acp/updates.js +4 -5
  5. package/dist/agent-protocol/core/json-line-stream.d.ts +6 -3
  6. package/dist/agent-protocol/core/json-line-stream.js +9 -10
  7. package/dist/agent-protocol/pi-rpc/events.js +27 -27
  8. package/dist/agent-protocol/pi-rpc/models.js +13 -11
  9. package/dist/agent-protocol/pi-rpc/session.js +7 -7
  10. package/dist/ai-trace/classify.js +4 -1
  11. package/dist/ai-trace/sinks.js +19 -3
  12. package/dist/ai-trace/usage.js +3 -1
  13. package/dist/anthropic-live-models.js +0 -0
  14. package/dist/auth.js +20 -17
  15. package/dist/claude-code-models.js +29 -17
  16. package/dist/claude-filesystem-policy.d.ts +4 -3
  17. package/dist/claude-filesystem-policy.js +39 -12
  18. package/dist/claude-stream.js +65 -47
  19. package/dist/copilot-stream.js +14 -11
  20. package/dist/core/model-discovery-shared.js +4 -2
  21. package/dist/core/omit-keys.d.ts +7 -0
  22. package/dist/core/omit-keys.js +12 -0
  23. package/dist/defs/aider.d.ts +1 -1
  24. package/dist/defs/amp.d.ts +1 -1
  25. package/dist/defs/amr.js +5 -9
  26. package/dist/defs/antigravity-event-stream.d.ts +19 -0
  27. package/dist/defs/antigravity-event-stream.js +83 -0
  28. package/dist/defs/antigravity.d.ts +4 -0
  29. package/dist/defs/antigravity.js +27 -15
  30. package/dist/defs/auggie.d.ts +3 -3
  31. package/dist/defs/claude.d.ts +3 -3
  32. package/dist/defs/cline.d.ts +3 -3
  33. package/dist/defs/codebuddy.d.ts +1 -1
  34. package/dist/defs/codex.js +3 -2
  35. package/dist/defs/copilot.d.ts +1 -1
  36. package/dist/defs/crush.d.ts +1 -1
  37. package/dist/defs/cursor-agent.d.ts +3 -1
  38. package/dist/defs/cursor-agent.js +8 -6
  39. package/dist/defs/deepseek.d.ts +1 -1
  40. package/dist/defs/devin.d.ts +3 -3
  41. package/dist/defs/droid.d.ts +1 -1
  42. package/dist/defs/goose.d.ts +3 -3
  43. package/dist/defs/grok-build.js +7 -5
  44. package/dist/defs/hermes.d.ts +3 -3
  45. package/dist/defs/kilo.d.ts +3 -3
  46. package/dist/defs/kimi.d.ts +3 -3
  47. package/dist/defs/kiro.d.ts +3 -3
  48. package/dist/defs/mimo.d.ts +1 -1
  49. package/dist/defs/opencode.d.ts +1 -1
  50. package/dist/defs/pi.d.ts +1 -1
  51. package/dist/defs/qoder.d.ts +1 -1
  52. package/dist/defs/qwen.d.ts +1 -1
  53. package/dist/defs/reasonix.d.ts +3 -3
  54. package/dist/defs/trae-cli.d.ts +3 -3
  55. package/dist/defs/vibe.d.ts +3 -3
  56. package/dist/detection.js +22 -2
  57. package/dist/json-event-stream.d.ts +1 -2
  58. package/dist/json-event-stream.js +10 -9
  59. package/dist/launch.js +2 -1
  60. package/dist/model-catalog-cache.js +6 -4
  61. package/dist/model-contracts.d.ts +29 -0
  62. package/dist/model-contracts.js +2 -0
  63. package/dist/model-discovery-adapters.js +44 -19
  64. package/dist/model-discovery-config.js +8 -4
  65. package/dist/model-discovery-types.d.ts +2 -2
  66. package/dist/model-discovery-yaml.d.ts +9 -0
  67. package/dist/model-discovery-yaml.js +98 -0
  68. package/dist/model-discovery.js +10 -3
  69. package/dist/model-registry.js +2 -1
  70. package/dist/native-tool-policy.d.ts +28 -0
  71. package/dist/native-tool-policy.js +42 -0
  72. package/dist/opencode-log.js +13 -10
  73. package/dist/pi-models.js +13 -11
  74. package/dist/probe-scheduler.js +13 -5
  75. package/dist/providers/aihubmix.js +6 -7
  76. package/dist/providers/anthropic-messages.d.ts +6 -3
  77. package/dist/providers/anthropic-messages.js +21 -23
  78. package/dist/providers/azure-chat.d.ts +1 -1
  79. package/dist/providers/azure-chat.js +7 -10
  80. package/dist/providers/connection-guard.js +2 -1
  81. package/dist/providers/connection-test.js +16 -10
  82. package/dist/providers/google-messages.d.ts +1 -1
  83. package/dist/providers/google-messages.js +33 -35
  84. package/dist/providers/google.js +3 -4
  85. package/dist/providers/model-catalog.js +10 -7
  86. package/dist/providers/ollama-chat.d.ts +0 -8
  87. package/dist/providers/ollama-chat.js +17 -19
  88. package/dist/providers/openai-chat.d.ts +6 -3
  89. package/dist/providers/openai-chat.js +24 -22
  90. package/dist/providers/operation-schema.d.ts +2 -3
  91. package/dist/providers/operation-schema.js +25 -22
  92. package/dist/providers/provider-tool-policy.d.ts +13 -0
  93. package/dist/providers/provider-tool-policy.js +2 -0
  94. package/dist/providers/tool-loop-verdict.d.ts +22 -0
  95. package/dist/providers/tool-loop-verdict.js +17 -0
  96. package/dist/providers/tool-turn-types.d.ts +2 -12
  97. package/dist/providers/tool-turn.js +19 -45
  98. package/dist/types.d.ts +8 -27
  99. package/package.json +14 -8
@@ -90,7 +90,12 @@ function readFileTail({ file, maxBytes }) {
90
90
  // prompt text, but tool schemas and user prompts could still contain a
91
91
  // stray `"message"` key, so this keyword gate keeps unrelated payload text
92
92
  // from masquerading as the error.
93
- const SERVICE_ERROR_MESSAGE_RE = /usage limit|rate[ _-]?limit|quota|limit reached|insufficient|credit|balance|overloaded|unavailable|unauthor|authenticat|invalid[ _-]?(?:api[ _-]?)?key|api key|\/login|exhaust|too many requests/i;
93
+ // Split by theme only to keep each pattern readable; any one matching is enough.
94
+ const SERVICE_ERROR_MESSAGE_PATTERNS = [
95
+ /usage limit|rate[ _-]?limit|quota|limit reached|exhaust|too many requests/i,
96
+ /insufficient|credit|balance|overloaded|unavailable/i,
97
+ /unauthor|authenticat|invalid[ _-]?(?:api[ _-]?)?key|api key|\/login/i,
98
+ ];
94
99
  function pickServiceErrorMessage(line) {
95
100
  const re = /"message":"((?:[^"\\]|\\.)*)"/g;
96
101
  let match;
@@ -110,7 +115,7 @@ function pickServiceErrorMessage(line) {
110
115
  // anti-masquerade keyword gate this function exists to enforce. Independently recommended
111
116
  // as the safe default by three separate reviews (code review, security, and a prior model
112
117
  // session) — see ADS-memory/reports/{code-review,security}/*-backend-coverage-push-2026-07-20.md.
113
- if (SERVICE_ERROR_MESSAGE_RE.test(value))
118
+ if (SERVICE_ERROR_MESSAGE_PATTERNS.some((pattern) => pattern.test(value)))
114
119
  return value;
115
120
  }
116
121
  return null;
@@ -124,15 +129,13 @@ function codeFromStatus(statusCode) {
124
129
  return 'UPSTREAM_UNAVAILABLE';
125
130
  return null;
126
131
  }
132
+ const DEFAULT_FAILURE_MESSAGES = {
133
+ AGENT_AUTH_REQUIRED: 'OpenCode could not authenticate with the model provider.',
134
+ RATE_LIMITED: 'OpenCode hit a provider usage or rate limit.',
135
+ UPSTREAM_UNAVAILABLE: "OpenCode's model provider is temporarily unavailable.",
136
+ };
127
137
  function defaultMessageForCode(code) {
128
- switch (code) {
129
- case 'AGENT_AUTH_REQUIRED':
130
- return 'OpenCode could not authenticate with the model provider.';
131
- case 'RATE_LIMITED':
132
- return 'OpenCode hit a provider usage or rate limit.';
133
- case 'UPSTREAM_UNAVAILABLE':
134
- return "OpenCode's model provider is temporarily unavailable.";
135
- }
138
+ return DEFAULT_FAILURE_MESSAGES[code];
136
139
  }
137
140
  // Classify the latest `service=llm` provider error in an OpenCode log tail.
138
141
  // We scope to that single line so the huge request body of *other* lines
package/dist/pi-models.js CHANGED
@@ -14,21 +14,23 @@ export function parsePiModels({ stdout }) {
14
14
  // defined; the non-null assertion documents that runtime invariant
15
15
  // instead of a `noUncheckedIndexedAccess`-driven guard that could never
16
16
  // actually trigger.
17
- const line = lines[i];
18
- const parts = line.split(/\s+/);
19
- if (parts.length < 2)
20
- continue;
21
- // `parts.length >= 2` (just checked) guarantees both indices are
22
- // defined; same non-null-assertion rationale as above.
23
- const provider = parts[0];
24
- const modelId = parts[1];
25
- // Skip duplicates (some providers list the same model under multiple names).
26
- const fullId = `${provider}/${modelId}`;
27
- if (seen.has(fullId))
17
+ const fullId = providerModelId(lines[i]);
18
+ // Skip rows without both columns, and duplicates (some providers list the
19
+ // same model under multiple names).
20
+ if (fullId === null || seen.has(fullId))
28
21
  continue;
29
22
  seen.add(fullId);
30
23
  entries.push({ id: fullId, label: fullId });
31
24
  }
32
25
  return entries.length > 1 ? entries : null;
33
26
  }
27
+ /** `provider/model` from one table row's first two whitespace-separated columns, or `null` when
28
+ * the row has fewer than two. */
29
+ function providerModelId(line) {
30
+ const parts = line.split(/\s+/);
31
+ if (parts.length < 2)
32
+ return null;
33
+ // `parts.length >= 2` (just checked) guarantees both indices are defined.
34
+ return `${parts[0]}/${parts[1]}`;
35
+ }
34
36
  //# sourceMappingURL=pi-models.js.map
@@ -1,3 +1,11 @@
1
+ /** Runs `work` on a later microtask unless `signal` was aborted while it waited in the queue. */
2
+ function startProbe({ work, signal }) {
3
+ return Promise.resolve().then(() => {
4
+ if (signal?.aborted)
5
+ throw new Error('Probe cancelled');
6
+ return work();
7
+ });
8
+ }
1
9
  /** All metadata process adapters share one process-wide slot. Version checks precede queued
2
10
  * metadata, so expensive discovery cannot delay cheap availability checks. Actual chat runs
3
11
  * never use this queue. A slot is held until the child adapter settles, including cancellation.
@@ -13,14 +21,14 @@ export function createProbeScheduler(_input, _options = {}) {
13
21
  running = true;
14
22
  entry.start();
15
23
  }
24
+ function release() {
25
+ running = false;
26
+ drain();
27
+ }
16
28
  return function schedule({ work }, { priority = 'metadata', signal } = {}) {
17
29
  return new Promise((resolve, reject) => {
18
30
  queue.push({ priority, start: () => {
19
- Promise.resolve().then(() => {
20
- if (signal?.aborted)
21
- throw new Error('Probe cancelled');
22
- return work();
23
- }).then(resolve, reject).finally(() => { running = false; drain(); });
31
+ startProbe({ work, signal }).then(resolve, reject).finally(release);
24
32
  } });
25
33
  drain();
26
34
  });
@@ -156,16 +156,15 @@ export function aihubmixWireModel({ catalogId }) {
156
156
  // wan: 5, 10 (default 5)
157
157
  // seedance/doubao + unknown: accepts a range — clamp to 3-12.
158
158
  // `wireModel` is the upstream name (prefix already stripped).
159
+ const AIHUBMIX_VIDEO_SECONDS = [
160
+ ['veo', [4, 6, 8]],
161
+ ['sora', [4, 8, 12]],
162
+ ['wan', [5, 10]],
163
+ ];
159
164
  export function aihubmixVideoSeconds({ wireModel, requested }) {
160
165
  const m = (wireModel || '').toLowerCase();
161
166
  const req = Number.isFinite(requested) ? requested : 5;
162
- let allowed = null;
163
- if (m.startsWith('veo'))
164
- allowed = [4, 6, 8];
165
- else if (m.startsWith('sora'))
166
- allowed = [4, 8, 12];
167
- else if (m.startsWith('wan'))
168
- allowed = [5, 10];
167
+ const allowed = AIHUBMIX_VIDEO_SECONDS.find(([prefix]) => m.startsWith(prefix))?.[1] ?? null;
169
168
  if (!allowed) {
170
169
  // Seedance/doubao and unknown families take a continuous range.
171
170
  return String(Math.min(12, Math.max(3, Math.round(req))));
@@ -76,7 +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
+ import type { ProviderToolSnapshotOptions, ProviderSchemaFallback } from './provider-tool-policy.js';
80
80
  export interface AnthropicTextBlockParam {
81
81
  readonly type: 'text';
82
82
  readonly text: string;
@@ -217,7 +217,9 @@ export interface AnthropicTurnResult {
217
217
  export declare function anthropicRequestUrl({ baseUrl }: {
218
218
  baseUrl: string | undefined;
219
219
  }): string;
220
- export declare function anthropicHeaders(requiredArgs: Pick<AnthropicTurnOptions, "apiKey" | "model" | "messages" | "maxTokens" | "onEvent">, optionalArgs?: Omit<AnthropicTurnOptions, "apiKey" | "model" | "messages" | "maxTokens" | "onEvent">): Record<string, string>;
220
+ /** The `AnthropicTurnOptions` keys every caller must pass. */
221
+ type AnthropicRequiredOption = "apiKey" | "model" | "messages" | "maxTokens" | "onEvent";
222
+ export declare function anthropicHeaders(requiredArgs: Pick<AnthropicTurnOptions, AnthropicRequiredOption>, optionalArgs?: Omit<AnthropicTurnOptions, AnthropicRequiredOption>): Record<string, string>;
221
223
  export declare function anthropicRequestBody({ options, messages }: {
222
224
  options: AnthropicTurnOptions;
223
225
  messages: readonly AnthropicMessageParam[];
@@ -368,5 +370,6 @@ export declare function executeAnthropicToolCalls({ executeTool, calls, onEvent
368
370
  calls: readonly AnthropicToolCall[];
369
371
  onEvent: (event: AnthropicTurnEvent) => void;
370
372
  }): Promise<AnthropicToolResultBlockParam[]>;
371
- export declare function runAnthropicToolTurn(requiredArgs: Pick<AnthropicTurnOptions, "apiKey" | "model" | "messages" | "maxTokens" | "onEvent">, optionalArgs?: Omit<AnthropicTurnOptions, "apiKey" | "model" | "messages" | "maxTokens" | "onEvent">): Promise<AnthropicTurnResult>;
373
+ export declare function runAnthropicToolTurn(requiredArgs: Pick<AnthropicTurnOptions, AnthropicRequiredOption>, optionalArgs?: Omit<AnthropicTurnOptions, AnthropicRequiredOption>): Promise<AnthropicTurnResult>;
374
+ export {};
372
375
  //# sourceMappingURL=anthropic-messages.d.ts.map
@@ -79,6 +79,9 @@ import { defaultDnsLookup, pinnedFetch, validateBaseUrlResolved } from './connec
79
79
  import { decodeSseStream } from './sse-decode.js';
80
80
  import { createTurnEndGuard } from './turn-end-guard.js';
81
81
  import { createStrictToolRetry } from './openai-chat.js';
82
+ import { trimCharsEnd } from '@jini-ai/core/text';
83
+ import { toolLoopVerdict } from './tool-loop-verdict.js';
84
+ import { omitKeys } from '../core/omit-keys.js';
82
85
  const DEFAULT_ANTHROPIC_BASE_URL = 'https://api.anthropic.com';
83
86
  const DEFAULT_ANTHROPIC_VERSION = '2023-06-01';
84
87
  const DEFAULT_MAX_TOOL_TURNS = 8;
@@ -86,7 +89,7 @@ function isRecord(value) {
86
89
  return typeof value === 'object' && value !== null && !Array.isArray(value);
87
90
  }
88
91
  export function anthropicRequestUrl({ baseUrl }) {
89
- const base = (baseUrl ?? DEFAULT_ANTHROPIC_BASE_URL).replace(/\/+$/, '');
92
+ const base = trimCharsEnd({ text: baseUrl ?? DEFAULT_ANTHROPIC_BASE_URL, chars: '/' });
90
93
  return `${base}/v1/messages`;
91
94
  }
92
95
  export function anthropicHeaders(requiredArgs, optionalArgs = {}) {
@@ -333,8 +336,7 @@ function refreshAnthropicTools(options, retry) {
333
336
  let tools = options.getTools?.({ strict: retry.enabled }) ?? options.tools;
334
337
  if (!retry.enabled)
335
338
  tools = tools?.map(tool => {
336
- const { strict: _strict, ...definition } = tool;
337
- return definition;
339
+ return omitKeys(tool, ['strict']);
338
340
  });
339
341
  return { ...options, ...(tools !== undefined ? { tools } : {}) };
340
342
  }
@@ -414,6 +416,16 @@ async function runSingleAnthropicRequest(options, messages, emitEnd, retry) {
414
416
  stopReason: null,
415
417
  usage: null,
416
418
  };
419
+ /** The handler's verdict for one frame, or `null` when the frame carries nothing to act on. */
420
+ const handleFrame = (frame) => {
421
+ const data = parseAnthropicSseData({ raw: frame.data });
422
+ if (!data)
423
+ return null; // malformed/empty keep-alive frame, or a non-object payload
424
+ const handler = ANTHROPIC_FRAME_HANDLERS[anthropicFrameKind({ data: data, frameEvent: frame.event })];
425
+ if (!handler)
426
+ return null; // `message_stop`, `ping`, or a future event type — nothing to do
427
+ return handler(state, data, onEvent, options.apiKey);
428
+ };
417
429
  for await (const frame of decodeSseStream({ source: body })) {
418
430
  // No `isEnded()` re-check at the top of this loop: every `emitEnd(...)` call site below is
419
431
  // immediately followed by `break`, so `ended` can never be true when a new iteration starts
@@ -421,14 +433,8 @@ async function runSingleAnthropicRequest(options, messages, emitEnd, retry) {
421
433
  // early returns inside `openAnthropicResponseStream` plus the two in-loop
422
434
  // contamination/error branches below). Verified, not assumed; see
423
435
  // `__tests__/anthropic-messages.test.ts`'s duplicate-end-event regression case.
424
- const data = parseAnthropicSseData({ raw: frame.data });
425
- if (!data)
426
- continue; // malformed/empty keep-alive frame, or a non-object payload
427
- const handler = ANTHROPIC_FRAME_HANDLERS[anthropicFrameKind({ data: data, frameEvent: frame.event })];
428
- if (!handler)
429
- continue; // `message_stop`, `ping`, or a future event type — nothing to do
430
- const outcome = handler(state, data, onEvent, options.apiKey);
431
- if (outcome.action === 'end') {
436
+ const outcome = handleFrame(frame);
437
+ if (outcome?.action === 'end') {
432
438
  emitEnd(outcome.reason);
433
439
  break;
434
440
  }
@@ -495,18 +501,10 @@ export async function runAnthropicToolTurn(requiredArgs, optionalArgs = {}) {
495
501
  while (true) {
496
502
  const outcome = await runSingleAnthropicRequest(options, messages, emitEnd, retry);
497
503
  lastStopReason = outcome.stopReason;
498
- if (endGuard.hasEnded())
499
- break;
500
- const exitReason = anthropicLoopExitReason({ outcome: outcome, toolTurns: toolTurns, maxToolTurns: maxToolTurns });
501
- if (exitReason) {
502
- emitEnd(exitReason);
503
- break;
504
- }
505
- if (!executeTool) {
506
- // Pending tool calls were already emitted as `tool_use` events above;
507
- // with no executor to run them, the turn ends here rather than
508
- // silently retrying forever.
509
- emitEnd('stop');
504
+ const verdict = toolLoopVerdict({ ended: endGuard.hasEnded(), hasExecutor: Boolean(executeTool), exitReason: () => anthropicLoopExitReason({ outcome: outcome, toolTurns: toolTurns, maxToolTurns: maxToolTurns }) });
505
+ if (verdict.stop || !executeTool) {
506
+ if (verdict.emit)
507
+ emitEnd(verdict.emit);
510
508
  break;
511
509
  }
512
510
  toolTurns += 1;
@@ -74,7 +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
+ import type { ProviderToolSnapshotOptions, ProviderSchemaFallback } from './provider-tool-policy.js';
78
78
  import { type TurnEndReason } from './turn-end-guard.js';
79
79
  export interface AzureFunctionToolDef {
80
80
  readonly type: 'function';
@@ -76,12 +76,14 @@ import { defaultDnsLookup, validateBaseUrlResolved } from './connection-guard.js
76
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
+ import { trimCharsEnd } from '@jini-ai/core/text';
80
+ import { toolLoopVerdict } from './tool-loop-verdict.js';
79
81
  const DEFAULT_AZURE_API_VERSION = '2024-10-21';
80
82
  const DEFAULT_MAX_TOOL_TURNS = 8;
81
83
  /** Matches OD's real azure handler's default when `maxTokens` isn't supplied — see module doc. */
82
84
  const DEFAULT_AZURE_MAX_TOKENS = 8192;
83
85
  function azureRequestUrl(baseUrl, model, apiVersion) {
84
- const base = baseUrl.replace(/\/+$/, '');
86
+ const base = trimCharsEnd({ text: baseUrl, chars: '/' });
85
87
  const version = apiVersion && apiVersion.trim() ? apiVersion.trim() : DEFAULT_AZURE_API_VERSION;
86
88
  return `${base}/openai/deployments/${encodeURIComponent(model)}/chat/completions?api-version=${encodeURIComponent(version)}`;
87
89
  }
@@ -242,15 +244,10 @@ export async function runAzureToolTurn(requiredArgs, optionalArgs = {}) {
242
244
  while (true) {
243
245
  const outcome = await runSingleAzureRequest(options, messages, emitEnd, endGuard.hasEnded, retry);
244
246
  lastFinishReason = outcome.finishReason;
245
- if (endGuard.hasEnded())
246
- break;
247
- const exitReason = azureLoopExitReason({ outcome: outcome, toolTurns: toolTurns, maxToolTurns: maxToolTurns });
248
- if (exitReason) {
249
- emitEnd(exitReason);
250
- break;
251
- }
252
- if (!executeTool) {
253
- emitEnd('stop');
247
+ const verdict = toolLoopVerdict({ ended: endGuard.hasEnded(), hasExecutor: Boolean(executeTool), exitReason: () => azureLoopExitReason({ outcome: outcome, toolTurns: toolTurns, maxToolTurns: maxToolTurns }) });
248
+ if (verdict.stop || !executeTool) {
249
+ if (verdict.emit)
250
+ emitEnd(verdict.emit);
254
251
  break;
255
252
  }
256
253
  toolTurns += 1;
@@ -45,6 +45,7 @@ import { readProviderResponseText, MAX_PROVIDER_ERROR_BYTES } from './response-t
45
45
  * that actually matters, the UI accepts one this guard would have refused.
46
46
  */
47
47
  import { isLoopbackApiHost, isBlockedExternalApiHostname } from '@jini-ai/platform/net';
48
+ import { trimCharsEnd } from '@jini-ai/core/text';
48
49
  /**
49
50
  * Synchronous base-URL check: scheme allow-list + literal-hostname block-list.
50
51
  * Does not resolve DNS — see {@link validateBaseUrlResolved}.
@@ -70,7 +71,7 @@ export function validateBaseUrl({ baseUrl }) {
70
71
  try {
71
72
  // Trim BEFORE stripping trailing slashes: in `"https://x/ "` the trailing
72
73
  // character is the space, so the slash strip alone would never reach it.
73
- parsed = new URL(String(baseUrl).trim().replace(/\/+$/, ''));
74
+ parsed = new URL(trimCharsEnd({ text: String(baseUrl).trim(), chars: '/' }));
74
75
  }
75
76
  catch {
76
77
  return { error: 'Invalid baseUrl' };
@@ -2,6 +2,7 @@ import { redactSecrets } from '@jini-ai/core';
2
2
  import { defaultDnsLookup, validateBaseUrlResolved } from './connection-guard.js';
3
3
  import { googleGenerateContentUrl } from './google.js';
4
4
  import { buildOpenAIChatTokenParam, buildLegacyMaxTokensParam } from './token-params.js';
5
+ import { trimCharsEnd } from '@jini-ai/core/text';
5
6
  const SMOKE_PROMPT = 'Reply with only: ok';
6
7
  /**
7
8
  * Headroom for a reasoning model's hidden thinking, plus the two-character answer.
@@ -27,7 +28,7 @@ function isSupportedProtocol(protocol) {
27
28
  }
28
29
  function appendVersionedApiPath(baseUrl, suffix) {
29
30
  const url = new URL(baseUrl);
30
- const pathname = url.pathname.replace(/\/+$/, '');
31
+ const pathname = trimCharsEnd({ text: url.pathname, chars: '/' });
31
32
  url.pathname = /\/v\d+(\/|$)/.test(pathname) ? `${pathname}${suffix}` : `${pathname}/v1${suffix}`;
32
33
  return url.toString();
33
34
  }
@@ -135,7 +136,7 @@ function extractOpenAIMessageText(data) {
135
136
  function buildAzureProviderCall({ input }, _options = {}) {
136
137
  const { baseUrl, apiKey, model } = input;
137
138
  const url = new URL(baseUrl);
138
- const basePath = url.pathname.replace(/\/+$/, '');
139
+ const basePath = trimCharsEnd({ text: url.pathname, chars: '/' });
139
140
  const usesVersionedOpenAIPath = /\/openai\/v\d+(?:$|\/)/.test(basePath);
140
141
  const apiVersion = input.apiVersion?.trim() || (usesVersionedOpenAIPath ? '' : '2024-10-21');
141
142
  url.pathname = usesVersionedOpenAIPath
@@ -155,10 +156,14 @@ function buildAzureProviderCall({ input }, _options = {}) {
155
156
  extractText: extractOpenAIMessageText,
156
157
  };
157
158
  }
159
+ /** Why a 2xx reply with no assistant text failed the smoke test, naming the finish reason when known. */
160
+ function emptyReplyDetail(finishReason) {
161
+ return finishReason
162
+ ? `Provider returned a 2xx response without assistant text (finish reason: ${finishReason})`
163
+ : 'Provider returned a 2xx response without assistant text';
164
+ }
158
165
  function buildProviderCall(input) {
159
- const baseUrl = input.baseUrl;
160
- const apiKey = input.apiKey;
161
- const model = input.model;
166
+ const { baseUrl, apiKey, model } = input;
162
167
  switch (input.protocol) {
163
168
  case 'anthropic':
164
169
  return {
@@ -235,6 +240,11 @@ function buildProviderCall(input) {
235
240
  },
236
241
  };
237
242
  }
243
+ default: {
244
+ // Unreachable: every supported protocol has a case above, and a new one fails typecheck here.
245
+ const unsupported = input.protocol;
246
+ throw new TypeError(`Unsupported connection-test protocol: ${String(unsupported)}`);
247
+ }
238
248
  }
239
249
  }
240
250
  function parseProviderResponse({ rawText }, _options = {}) {
@@ -283,11 +293,7 @@ function inspectProviderResponse({ response, data, rawText, call, input, latency
283
293
  latencyMs,
284
294
  model,
285
295
  status: response.status,
286
- detail: sample
287
- ? `Expected smoke test reply "ok"; got "${sample}"`
288
- : finishReason
289
- ? `Provider returned a 2xx response without assistant text (finish reason: ${finishReason})`
290
- : 'Provider returned a 2xx response without assistant text',
296
+ detail: sample ? `Expected smoke test reply "ok"; got "${sample}"` : emptyReplyDetail(finishReason),
291
297
  };
292
298
  }
293
299
  /**
@@ -96,7 +96,7 @@
96
96
  import { createRoleMarkerGuard } from '../role-marker-guard.js';
97
97
  import { type DnsLookupFn, type PinnedFetch } from './connection-guard.js';
98
98
  import { type TurnEndReason } from './turn-end-guard.js';
99
- import type { ProviderToolSnapshotOptions, ProviderSchemaFallback } from './tool-turn-types.js';
99
+ import type { ProviderToolSnapshotOptions, ProviderSchemaFallback } from './provider-tool-policy.js';
100
100
  export interface GoogleTextPart {
101
101
  readonly text: string;
102
102
  }
@@ -100,6 +100,7 @@ import { googleStreamGenerateContentUrl } from './google.js';
100
100
  import { decodeSseStream } from './sse-decode.js';
101
101
  import { createTurnEndGuard } from './turn-end-guard.js';
102
102
  import { createStrictToolRetry } from './openai-chat.js';
103
+ import { toolLoopVerdict } from './tool-loop-verdict.js';
103
104
  const DEFAULT_GOOGLE_BASE_URL = 'https://generativelanguage.googleapis.com';
104
105
  const DEFAULT_MAX_TOOL_TURNS = 8;
105
106
  function isRecord(value) {
@@ -339,28 +340,30 @@ async function runSingleGoogleRequest(options, contents, emitEnd, retry) {
339
340
  finishReason: null,
340
341
  usage: null,
341
342
  };
342
- frameLoop: for await (const frame of decodeSseStream({ source: body })) {
343
+ for await (const frame of decodeSseStream({ source: body })) {
343
344
  // No re-check of an "ended" flag at the top of this loop: the only way this loop calls
344
345
  // `emitEnd` is the `outcome.action === 'end'` branch below, immediately followed by
345
- // `break frameLoop` — same reachability proof as
346
+ // `break` — same reachability proof as
346
347
  // `anthropic-messages.ts#runSingleAnthropicRequest`.
347
- let data;
348
- try {
349
- data = JSON.parse(frame.data);
350
- }
351
- catch {
352
- continue; // tolerate a malformed/empty keep-alive frame
353
- }
354
- if (!isRecord(data))
355
- continue;
356
- const outcome = processGoogleFrame({ state: state, data: data, onEvent: onEvent });
357
- if (outcome.action === 'end') {
348
+ const data = parseGoogleFrameData(frame.data);
349
+ // A malformed/empty keep-alive frame, or a non-object payload, carries nothing to process.
350
+ const outcome = isRecord(data) ? processGoogleFrame({ state: state, data: data, onEvent: onEvent }) : null;
351
+ if (outcome?.action === 'end') {
358
352
  emitEnd(outcome.reason);
359
- break frameLoop;
353
+ break;
360
354
  }
361
355
  }
362
356
  return { finishReason: state.finishReason, toolCalls: state.toolCalls, text: state.fullText };
363
357
  }
358
+ /** The parsed JSON of one SSE frame, or `undefined` when it is not valid JSON (a keep-alive). */
359
+ function parseGoogleFrameData(raw) {
360
+ try {
361
+ return JSON.parse(raw);
362
+ }
363
+ catch {
364
+ return undefined;
365
+ }
366
+ }
364
367
  const GOOGLE_ALLOWED_IMAGE_MIME_TYPES = new Set([
365
368
  'image/png',
366
369
  'image/jpeg',
@@ -515,30 +518,25 @@ export async function runGoogleToolTurn(requiredArgs, optionalArgs = {}) {
515
518
  let contents = options.contents.slice();
516
519
  let toolTurns = 0;
517
520
  let lastFinishReason = null;
521
+ /** `'error'` (after reporting it) for a content-free first turn, else the regular loop exit reason. */
522
+ const turnExitReason = (outcome, turns) => {
523
+ if (!isEmptyInitialGoogleTurn({ toolTurns: turns, outcome })) {
524
+ return googleLoopExitReason({ outcome: outcome, toolTurns: turns, maxToolTurns: maxToolTurns });
525
+ }
526
+ // Thinking can consume the entire output budget without producing any answer. Preserve
527
+ // the reason for operator diagnostics rather than turning a content-free response into stop.
528
+ options.onEvent({ type: 'error', message: redactSecrets({
529
+ input: `Google returned no text or tool calls (${outcome.finishReason ?? 'missing finish reason'})`,
530
+ }, { exactSecrets: [options.apiKey] }) });
531
+ return 'error';
532
+ };
518
533
  while (true) {
519
534
  const outcome = await runSingleGoogleRequest(options, contents, emitEnd, retry);
520
535
  lastFinishReason = outcome.finishReason;
521
- if (endGuard.hasEnded())
522
- break;
523
- if (isEmptyInitialGoogleTurn({ toolTurns, outcome })) {
524
- // Thinking can consume the entire output budget without producing any answer. Preserve
525
- // the reason for operator diagnostics rather than turning a content-free response into stop.
526
- options.onEvent({ type: 'error', message: redactSecrets({
527
- input: `Google returned no text or tool calls (${outcome.finishReason ?? 'missing finish reason'})`,
528
- }, { exactSecrets: [options.apiKey] }) });
529
- emitEnd('error');
530
- break;
531
- }
532
- const exitReason = googleLoopExitReason({ outcome: outcome, toolTurns: toolTurns, maxToolTurns: maxToolTurns });
533
- if (exitReason) {
534
- emitEnd(exitReason);
535
- break;
536
- }
537
- if (!executeTool) {
538
- // Pending tool calls were already emitted as `tool_use` events above;
539
- // with no executor to run them, the turn ends here rather than
540
- // silently retrying forever.
541
- emitEnd('stop');
536
+ const verdict = toolLoopVerdict({ ended: endGuard.hasEnded(), hasExecutor: Boolean(executeTool), exitReason: () => turnExitReason(outcome, toolTurns) });
537
+ if (verdict.stop || !executeTool) {
538
+ if (verdict.emit)
539
+ emitEnd(verdict.emit);
542
540
  break;
543
541
  }
544
542
  toolTurns += 1;
@@ -1,3 +1,4 @@
1
+ import { trimCharsEnd } from '@jini-ai/core/text';
1
2
  /**
2
3
  * @module providers/google
3
4
  *
@@ -10,11 +11,9 @@ export function googleGenerativeLanguageBaseUrl({ baseUrl }) {
10
11
  const url = new URL(baseUrl);
11
12
  url.search = '';
12
13
  url.hash = '';
13
- const pathname = url.pathname
14
- .replace(/\/+$/, '')
15
- .replace(/\/v\d+(?:beta)?$/i, '');
14
+ const pathname = trimCharsEnd({ text: url.pathname, chars: '/' }).replace(/\/v\d+(?:beta)?$/i, '');
16
15
  url.pathname = pathname || '/';
17
- return url.toString().replace(/\/+$/, '');
16
+ return trimCharsEnd({ text: url.toString(), chars: '/' });
18
17
  }
19
18
  /** Strips the `models/` prefix Google's API sometimes includes in a model id. */
20
19
  export function normalizeGoogleModelId({ model }) {
@@ -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>;