@jini-ai/agent-runtime 0.6.15-rc.2 → 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 +33 -37
  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 +7 -2
  98. package/dist/types.d.ts +8 -27
  99. package/package.json +14 -8
package/dist/launch.js CHANGED
@@ -5,6 +5,7 @@
5
5
  import { accessSync, closeSync, constants, openSync, readdirSync, readSync, realpathSync, statSync } from 'node:fs';
6
6
  import path, { delimiter } from 'node:path';
7
7
  import { inspectAgentExecutableResolution, userToolchainBinDirs } from './executables.js';
8
+ import { trimCharsEnd } from '@jini-ai/core/text';
8
9
  export function resolveAgentLaunch({ def }, options = {}) {
9
10
  const resolution = inspectAgentExecutableResolution({ def: def }, options);
10
11
  if (!resolution.selectedPath) {
@@ -61,7 +62,7 @@ function pathEnvKey(env) {
61
62
  return Object.keys(env).find((k) => k.toLowerCase() === 'path') ?? 'PATH';
62
63
  }
63
64
  function normalizePathEntry(p) {
64
- const trimmed = p.replace(/[/\\]+$/, '');
65
+ const trimmed = trimCharsEnd({ text: p, chars: '/\\' });
65
66
  return process.platform === 'win32' ? trimmed.toLowerCase() : trimmed;
66
67
  }
67
68
  // Keep the first spelling of each directory (trailing separators ignored,
@@ -22,10 +22,12 @@ export class ModelCatalogCache {
22
22
  state = { inFlight: null, expiresAt: -Infinity, live: null };
23
23
  this.states.set(key, state);
24
24
  }
25
- if (state.inFlight) {
26
- await state.inFlight;
27
- }
28
- else if (state.expiresAt <= this.required.clock.nowMs()) {
25
+ // An in-flight load is awaited; otherwise an expired entry starts a refresh.
26
+ const pending = state.inFlight;
27
+ const refreshDue = !pending && state.expiresAt <= this.required.clock.nowMs();
28
+ if (pending)
29
+ await pending;
30
+ if (refreshDue) {
29
31
  state.expiresAt = this.required.clock.nowMs() + this.ttlMs;
30
32
  const current = state;
31
33
  const discover = options.discover ?? this.required.discover;
@@ -0,0 +1,29 @@
1
+ export type ModelIdentityKind = 'concrete' | 'alias' | 'routing-mode';
2
+ export type RuntimeEnv = NodeJS.ProcessEnv | Record<string, string>;
3
+ export type RuntimeModelOption = {
4
+ id: string;
5
+ label: string;
6
+ identityKind?: ModelIdentityKind;
7
+ resolvedId?: string;
8
+ /**
9
+ * The reasoning-effort levels THIS model supports, when the runtime's own catalog reports them
10
+ * per model rather than per agent.
11
+ *
12
+ * Present only where a live source actually carries the data — Codex's `debug models` catalog
13
+ * does (`supported_reasoning_levels`), and the levels genuinely differ between models on the same
14
+ * CLI: verified live against codex-cli 0.153.4, where `gpt-6-astra` offers
15
+ * low/medium/high/xhigh/max/ultra while `gpt-5.5` stops at `xhigh`. A single agent-level
16
+ * `RuntimeAgentDef.reasoningOptions` list cannot be correct for both, which is why this is a
17
+ * property of the model row rather than of the def.
18
+ *
19
+ * Consumed by `RuntimeAgentDef.deriveReasoningOptions` to compute the agent-level list a picker
20
+ * renders. Left `undefined` by every runtime whose effort vocabulary really is uniform, and by
21
+ * every static fallback list — an absent value means "nothing catalog-specific to say", never
22
+ * "this model supports no effort levels".
23
+ */
24
+ reasoning?: readonly RuntimeReasoningOption[];
25
+ };
26
+ /** A reasoning-effort choice; same shape as a model option. */
27
+ export interface RuntimeReasoningOption extends RuntimeModelOption {
28
+ }
29
+ //# sourceMappingURL=model-contracts.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=model-contracts.js.map
@@ -33,7 +33,9 @@ export async function probeCliSubcommand(context, config, deps, signal) {
33
33
  const models = config.parse?.({ stdout });
34
34
  if (!models)
35
35
  throw new ModelProbeError('malformed-response');
36
- const defaultSelectionId = stdout.match(/^\s*Default model:\s*(\S+)\s*$/mi)?.[1];
36
+ // The bracketed class is `\s` minus line terminators, so neither end of the line can slide into
37
+ // a neighbouring line (which is what made the plain `\s*` version backtrack quadratically).
38
+ const defaultSelectionId = stdout.match(/^[\t\v\f \u00a0\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]*Default model:\s*(\S+)[\t\v\f \u00a0\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]*$/mi)?.[1];
37
39
  return { models, source: 'cli', coverage: 'account', ...(defaultSelectionId ? { defaultSelectionId } : {}) };
38
40
  }
39
41
  /** ACP can create CLI session state/start services. It never sends a user prompt. */
@@ -60,14 +62,27 @@ function claudeInitializeRows(line) {
60
62
  return Array.isArray(rows) ? rows : null;
61
63
  }
62
64
  /** One selection row, plus its concrete resolved row when the selection is an alias. */
65
+ /** A selection that resolves to another id is an alias; an unresolved one is classified by shape. */
66
+ function selectionIdentityKind(id, resolvedId) {
67
+ return resolvedId ? 'alias' : modelIdentityKind(id);
68
+ }
63
69
  function claudeSelectionModels(id, resolvedId, displayName) {
64
70
  const label = typeof displayName === 'string' && displayName.trim() ? displayName.trim() : resolvedId || id;
65
- const identityKind = id === resolvedId ? 'concrete' : resolvedId ? 'alias' : modelIdentityKind(id);
71
+ const identityKind = id === resolvedId ? 'concrete' : selectionIdentityKind(id, resolvedId);
66
72
  const selection = { id, label, identityKind, ...(resolvedId ? { resolvedId } : {}) };
67
73
  if (!resolvedId || id === resolvedId)
68
74
  return [selection];
69
75
  return [selection, { id: resolvedId, label, identityKind: modelIdentityKind(resolvedId) }];
70
76
  }
77
+ /** The picker rows one initialize row contributes; the `default` row also names the default selection. */
78
+ function claudeRowModels(id, resolvedId, displayName) {
79
+ if (id !== 'default')
80
+ return { models: claudeSelectionModels(id, resolvedId, displayName) };
81
+ // This displayName describes the CLI's default policy, not the model it resolves to.
82
+ if (!resolvedId || modelIdentityKind(resolvedId) !== 'concrete')
83
+ return { models: [] };
84
+ return { models: [{ id: resolvedId, label: resolvedId, identityKind: 'concrete' }], defaultId: resolvedId };
85
+ }
71
86
  function claudeInitializeResult(rows) {
72
87
  const models = [];
73
88
  let defaultSelectionId;
@@ -76,15 +91,10 @@ function claudeInitializeResult(rows) {
76
91
  continue;
77
92
  const id = row.value.trim();
78
93
  const resolvedId = typeof row.resolvedModel === 'string' ? row.resolvedModel.trim() : undefined;
79
- if (id !== 'default') {
80
- models.push(...claudeSelectionModels(id, resolvedId, row.displayName));
81
- continue;
82
- }
83
- // This displayName describes the CLI's default policy, not the model it resolves to.
84
- if (resolvedId && modelIdentityKind(resolvedId) === 'concrete') {
85
- defaultSelectionId = resolvedId;
86
- models.push({ id: resolvedId, label: resolvedId, identityKind: 'concrete' });
87
- }
94
+ const rowResult = claudeRowModels(id, resolvedId, row.displayName);
95
+ models.push(...rowResult.models);
96
+ if (rowResult.defaultId)
97
+ defaultSelectionId = rowResult.defaultId;
88
98
  }
89
99
  return { models, source: 'rpc', coverage: 'account', ...withDefaultSelection(defaultSelectionId) };
90
100
  }
@@ -106,7 +116,9 @@ export async function probeClaudeInitialize(context, deps, signal) {
106
116
  if (context.settingSources)
107
117
  args.push('--setting-sources', context.settingSources.join(','));
108
118
  // The last settings argument must still disable hooks; the probe never executes hooks.
109
- const raw = context.settings ? (context.settings.trim().startsWith('{') ? context.settings : await deps.fs.read(context.settings, { signal })) : null;
119
+ // Inline JSON is used as is; anything else names a settings file to read.
120
+ const inlineSettings = context.settings?.trim().startsWith('{') ? context.settings : null;
121
+ const raw = inlineSettings ?? (context.settings ? await deps.fs.read(context.settings, { signal }) : null);
110
122
  const settings = raw ? parseSettingsJson(raw) : undefined;
111
123
  if (settings)
112
124
  args.push('--settings', JSON.stringify({ ...settings, disableAllHooks: true }));
@@ -164,10 +176,14 @@ function configurationCacheModels(entries) {
164
176
  if (!Array.isArray(entries))
165
177
  return [];
166
178
  return entries.flatMap((row) => {
167
- const id = typeof row?.slug === 'string' ? row.slug : typeof row?.value === 'string' ? row.value : typeof row?.id === 'string' ? row.id : undefined;
179
+ const id = firstString(row?.slug, row?.value, row?.id);
168
180
  return id ? [{ id, label: row.display_name || row.displayName || id, identityKind: modelIdentityKind(id) }] : [];
169
181
  });
170
182
  }
183
+ /** The first argument that is a string, or `undefined` when none is. */
184
+ function firstString(...values) {
185
+ return values.find((value) => typeof value === 'string');
186
+ }
171
187
  function parseGenericCliModels(stdout) {
172
188
  let parsed;
173
189
  try {
@@ -181,12 +197,12 @@ function parseGenericCliModels(stdout) {
181
197
  const entries = Array.isArray(parsed) ? parsed : object.models;
182
198
  if (Array.isArray(entries))
183
199
  return entries.flatMap((row) => {
184
- const id = typeof row === 'string' ? row : typeof row?.id === 'string' ? row.id : typeof row?.model === 'string' ? row.model : undefined;
200
+ const id = firstString(row, row?.id, row?.model);
185
201
  return id ? [{ id, label: typeof row?.name === 'string' ? row.name : id, identityKind: modelIdentityKind(id) }] : [];
186
202
  });
187
203
  }
188
204
  return stdout.split('\n').flatMap((line) => {
189
- const match = line.trim().match(/^(?:[-*•]\s*)?([\w][\w./:[\]-]*)(?:\s+-\s+(.+))?$/);
205
+ const match = line.trim().match(/^(?:[-*•]\s*)?(\w[\w./:[\]-]*)(?:\s+-\s+(\S.*))?$/);
190
206
  if (!match || /^(models|available|provider|model)$/i.test(match[1]))
191
207
  return [];
192
208
  return [{ id: match[1], label: match[2] || match[1], identityKind: modelIdentityKind(match[1]) }];
@@ -300,6 +316,13 @@ function runProcess(input) {
300
316
  const invocation = createCommandInvocation({ command: input.context.executable, args: [...input.args], env: input.context.env });
301
317
  const tree = input.terminateProcessTree && process.platform !== 'win32';
302
318
  let treeTimer;
319
+ /** Settles the probe with the exec outcome; an error only rejects when nothing completed first. */
320
+ const settle = (error, stdout, stderr) => {
321
+ if (error && !completed)
322
+ reject(error);
323
+ else
324
+ resolve({ stdout: String(stdout), stderr: String(stderr) });
325
+ };
303
326
  const killTree = () => { if (tree && child.pid) {
304
327
  try {
305
328
  process.kill(-child.pid, 'SIGKILL');
@@ -318,11 +341,12 @@ function runProcess(input) {
318
341
  input.signal.removeEventListener('abort', killTree);
319
342
  if (error)
320
343
  killTree();
321
- const settle = () => { error && !completed ? reject(error) : resolve({ stdout: String(stdout), stderr: String(stderr) }); };
344
+ // Wait for a still-running child to close before settling; otherwise settle now.
345
+ const settleOutcome = settle.bind(undefined, error, stdout, stderr);
322
346
  if (child.pid && child.exitCode === null && child.signalCode === null)
323
- child.once('close', settle);
347
+ child.once('close', settleOutcome);
324
348
  else
325
- settle();
349
+ settleOutcome();
326
350
  });
327
351
  if (tree) {
328
352
  input.signal.addEventListener('abort', killTree, { once: true });
@@ -468,9 +492,10 @@ export function parsePiRpcMetadata(stdout) {
468
492
  export function getRuntimeModelDiscoveryDeps({ state }, _optional = {}) {
469
493
  if (state === defaultRuntimeState)
470
494
  return defaultModelDiscoveryDeps;
471
- return state.discoveryDeps ??= { ...defaultModelDiscoveryDeps, cache: state.modelCatalog,
495
+ state.discoveryDeps ??= { ...defaultModelDiscoveryDeps, cache: state.modelCatalog,
472
496
  acp: createAcpDiscoveryAdapter({ probe: state.acpModelProbe ?? nativeAcpModelProbe }),
473
497
  };
498
+ return state.discoveryDeps;
474
499
  }
475
500
  /** Adapt the existing ACP port to catalog metadata; array-only transports cannot claim a default.
476
501
  * Keeps invocation normalization, cancellation and the shared process budget in the native adapter.
@@ -1,5 +1,8 @@
1
1
  import { join } from 'node:path';
2
2
  import { homedir } from 'node:os';
3
+ import { yamlModelCapture } from './model-discovery-yaml.js';
4
+ /** JSON path of the model setting in the Qoder and Qwen settings files. */
5
+ const MODEL_NAME_PATH = 'model.name';
3
6
  const json = (path, key = 'model') => ({ path, format: 'json', key });
4
7
  function codexConfigFiles({ env, context, user, local }) {
5
8
  const root = env.CODEX_HOME || user('.codex');
@@ -27,8 +30,8 @@ const CONFIG_FILES = new Map([
27
30
  ['copilot', ({ user }) => [json(user('.copilot/config.json'))]],
28
31
  ['cursor-agent', ({ user }) => [json(user('.cursor/cli-config.json'))]],
29
32
  ['droid', ({ user }) => [json(user('.factory/settings.json'), 'sessionDefaultSettings.model')]],
30
- ['qoder', ({ env, user, local }) => [json(join(env.QODER_CONFIG_DIR || user('.qoder'), 'settings.json'), 'model.name'), json(local('.qoder/settings.json'), 'model.name'), json(local('.qoder/settings.local.json'), 'model.name')]],
31
- ['qwen', ({ user, local }) => [json(user('.qwen/settings.json'), 'model.name'), json(local('.qwen/settings.json'), 'model.name')]],
33
+ ['qoder', ({ env, user, local }) => [json(join(env.QODER_CONFIG_DIR || user('.qoder'), 'settings.json'), MODEL_NAME_PATH), json(local('.qoder/settings.json'), MODEL_NAME_PATH), json(local('.qoder/settings.local.json'), MODEL_NAME_PATH)]],
34
+ ['qwen', ({ user, local }) => [json(user('.qwen/settings.json'), MODEL_NAME_PATH), json(local('.qwen/settings.json'), MODEL_NAME_PATH)]],
32
35
  ['deepseek', ({ user }) => [{ path: user('.deepseek/config.toml'), format: 'toml' }, { path: user('.codewhale/config.toml'), format: 'toml' }]],
33
36
  ['mimo', ({ configHome, local }) => [json(join(configHome, 'mimocode/mimocode.json')), json(local('.mimocode/mimocode.jsonc'))]],
34
37
  ['crush', ({ configHome, local }) => [json(join(configHome, 'crush/crush.json'), 'models.large.model'), json(local('crush.json'), 'models.large.model')]],
@@ -102,7 +105,7 @@ export function parseConfiguredModel(file, raw, profile) {
102
105
  if (file.format === 'json')
103
106
  return parseJsonModel(file, raw);
104
107
  if (file.format === 'yaml')
105
- return scalar(raw.match(/^model\s*:\s*["']?([^\n"'#]+)["']?\s*(?:#.*)?$/m)?.[1]);
108
+ return scalar(yamlModelCapture(raw));
106
109
  return parseTomlModel(file, raw, profile);
107
110
  }
108
111
  const MODEL_ENV = {
@@ -150,7 +153,8 @@ export async function readModelConfiguration(agentId, context, deps, signal) {
150
153
  const settingsRaw = await claudeSettingsRaw(agentId, context, deps, signal);
151
154
  const settingsModel = settingsRaw ? scalar(parseSettingsJson(settingsRaw)?.model) : undefined;
152
155
  // Precedence, strongest first: launch model, Claude --settings, model env, inline config content, config files.
153
- const selection = context.model || settingsModel || envSelection(agentId, context.env) || inlineSelection(agentId, context.env) || fileSelection(agentId, contents, context.profile);
156
+ const launchSelection = context.model || settingsModel;
157
+ const selection = launchSelection || envSelection(agentId, context.env) || inlineSelection(agentId, context.env) || fileSelection(agentId, contents, context.profile);
154
158
  // Material is hashed by the orchestration layer and is never exposed over HTTP.
155
159
  return { ...(selection ? { selection } : {}), fingerprintMaterial: JSON.stringify([contents.map(({ file, raw }) => [file.path, raw]), settingsRaw || '']) };
156
160
  }
@@ -1,7 +1,7 @@
1
- import type { RuntimeEnv, RuntimeModelOption } from './types.js';
1
+ import type { RuntimeEnv, RuntimeModelOption, ModelIdentityKind } from './model-contracts.js';
2
2
  import type { ProviderModelsInput } from './providers/model-catalog.js';
3
+ export type { ModelIdentityKind } from './model-contracts.js';
3
4
  export type ModelSource = 'cli' | 'rpc' | 'provider-api' | 'cli-cache' | 'config-file' | 'offline-fallback';
4
- export type ModelIdentityKind = 'concrete' | 'alias' | 'routing-mode';
5
5
  export interface DiscoveredModel extends RuntimeModelOption {
6
6
  identityKind: ModelIdentityKind;
7
7
  resolvedId?: string;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @file The `model:` value of a YAML agent config, read without a regex. The pattern this replaces,
3
+ * `/^model\s*:\s*["']?([^\n"'#]+)["']?\s*(?:#.*)?$/m`, backtracks super-linearly on long
4
+ * whitespace runs; `yamlModelCapture` returns exactly what its group captured, in time linear in
5
+ * the input for each `model` key it tries.
6
+ */
7
+ /** First `model:` capture of `/^model\s*:\s*["']?([^\n"'#]+)["']?\s*(?:#.*)?$/m` in `raw`. */
8
+ export declare function yamlModelCapture(raw: string): string | undefined;
9
+ //# sourceMappingURL=model-discovery-yaml.d.ts.map
@@ -0,0 +1,98 @@
1
+ /**
2
+ * @file The `model:` value of a YAML agent config, read without a regex. The pattern this replaces,
3
+ * `/^model\s*:\s*["']?([^\n"'#]+)["']?\s*(?:#.*)?$/m`, backtracks super-linearly on long
4
+ * whitespace runs; `yamlModelCapture` returns exactly what its group captured, in time linear in
5
+ * the input for each `model` key it tries.
6
+ */
7
+ // `/^model\s*:\s*["']?([^\n"'#]+)["']?\s*(?:#.*)?$/m`'s capture, as a linear scan. Two regex
8
+ // details survive: the group may end early at an in-run line terminator (`\r`, U+2028, U+2029,
9
+ // before which `$` matches), and it may start inside the whitespace after the colon (the regex
10
+ // backtracks out of `\s*` one character at a time when the value itself does not match).
11
+ const YAML_LINE_TERMINATORS = '\n\r\u2028\u2029';
12
+ const YAML_GROUP_STOPS = '\n"\'#';
13
+ const isYamlSpace = (ch) => ch !== undefined && /\s/.test(ch);
14
+ const isYamlQuote = (ch) => ch === '"' || ch === "'";
15
+ const isYamlTerminator = (ch) => ch !== undefined && YAML_LINE_TERMINATORS.includes(ch);
16
+ function yamlSpaceEnd(raw, index) {
17
+ let i = index;
18
+ while (isYamlSpace(raw[i]))
19
+ i += 1;
20
+ return i;
21
+ }
22
+ /** End of the run of group characters (anything but a newline, quote or `#`) from `index`. */
23
+ function yamlRunEnd(raw, index) {
24
+ let i = index;
25
+ while (i < raw.length && !YAML_GROUP_STOPS.includes(raw[i]))
26
+ i += 1;
27
+ return i;
28
+ }
29
+ /** Whether `["']?\s*(?:#.*)?$` matches at `index`. */
30
+ function yamlTailMatches(raw, index) {
31
+ const from = isYamlQuote(raw[index]) ? index + 1 : index;
32
+ const end = yamlSpaceEnd(raw, from);
33
+ if (end === raw.length || raw[end] === '#')
34
+ return true;
35
+ for (let i = from; i < end; i += 1)
36
+ if (isYamlTerminator(raw[i]))
37
+ return true;
38
+ return false;
39
+ }
40
+ /** Last line terminator strictly inside `(start, end)`, or -1. */
41
+ function yamlLastTerminator(raw, start, end) {
42
+ for (let i = end - 1; i > start; i -= 1)
43
+ if (isYamlTerminator(raw[i]))
44
+ return i;
45
+ return -1;
46
+ }
47
+ /** The group captured when it starts at `start` inside `run`, or undefined. */
48
+ function yamlGroupFrom(raw, start, run) {
49
+ if (run.end === start)
50
+ return undefined;
51
+ if (run.tailMatches)
52
+ return raw.slice(start, run.end);
53
+ return run.cut === -1 ? undefined : raw.slice(start, run.cut);
54
+ }
55
+ /** The capture for a `model` key whose colon ends just before `afterColon`, or undefined. */
56
+ function yamlModelValue(raw, afterColon) {
57
+ const valueStart = yamlSpaceEnd(raw, afterColon);
58
+ if (isYamlQuote(raw[valueStart])) {
59
+ const quotedEnd = yamlRunEnd(raw, valueStart + 1);
60
+ const quotedRun = { end: quotedEnd, tailMatches: yamlTailMatches(raw, quotedEnd), cut: yamlLastTerminator(raw, valueStart + 1, quotedEnd) };
61
+ const quoted = yamlGroupFrom(raw, valueStart + 1, quotedRun);
62
+ if (quoted !== undefined)
63
+ return quoted;
64
+ }
65
+ // Walk left from the value through the whitespace after the colon, updating the current run
66
+ // in O(1) per step: a newline ends the run to its left (and `$` matches before it), and each
67
+ // step can only add a new last-terminator candidate when the run has none yet.
68
+ const runEnd = yamlRunEnd(raw, valueStart);
69
+ const run = { end: runEnd, tailMatches: yamlTailMatches(raw, runEnd), cut: yamlLastTerminator(raw, valueStart, runEnd) };
70
+ for (let start = valueStart; start >= afterColon; start -= 1) {
71
+ const group = raw[start] === '\n' ? undefined : yamlGroupFrom(raw, start, run);
72
+ if (group !== undefined)
73
+ return group;
74
+ yamlExtendRunLeft(raw, start, run);
75
+ }
76
+ return undefined;
77
+ }
78
+ /** Moves `run` to start one character left of `start`. */
79
+ function yamlExtendRunLeft(raw, start, run) {
80
+ if (raw[start] === '\n') {
81
+ Object.assign(run, { end: start, tailMatches: true, cut: -1 });
82
+ return;
83
+ }
84
+ if (run.cut === -1 && start < run.end && isYamlTerminator(raw[start]))
85
+ run.cut = start;
86
+ }
87
+ /** First `model:` capture of `/^model\s*:\s*["']?([^\n"'#]+)["']?\s*(?:#.*)?$/m` in `raw`. */
88
+ export function yamlModelCapture(raw) {
89
+ for (let lineStart = 0; lineStart <= raw.length; lineStart += 1) {
90
+ const atLineStart = lineStart === 0 || isYamlTerminator(raw[lineStart - 1]);
91
+ const colon = atLineStart && raw.startsWith('model', lineStart) ? yamlSpaceEnd(raw, lineStart + 5) : -1;
92
+ const value = raw[colon] === ':' ? yamlModelValue(raw, colon + 1) : undefined;
93
+ if (value !== undefined)
94
+ return value;
95
+ }
96
+ return undefined;
97
+ }
98
+ //# sourceMappingURL=model-discovery-yaml.js.map
@@ -23,8 +23,12 @@ async function boundedProbe(deps, work, signal) {
23
23
  if (pool.active >= 1) {
24
24
  await new Promise((resolve, reject) => {
25
25
  const ready = () => { signal?.removeEventListener('abort', abort); resolve(); };
26
- const abort = () => { const index = pool.queue.indexOf(ready); if (index >= 0)
27
- pool.queue.splice(index, 1); reject(new ProbeTimeout('Probe cancelled')); };
26
+ const abort = () => {
27
+ const index = pool.queue.indexOf(ready);
28
+ if (index >= 0)
29
+ pool.queue.splice(index, 1);
30
+ reject(new ProbeTimeout('Probe cancelled'));
31
+ };
28
32
  pool.queue.push(ready);
29
33
  if (signal?.aborted)
30
34
  abort();
@@ -54,9 +58,12 @@ const DIAGNOSTIC_MESSAGES = {
54
58
  'malformed-response': 'Native metadata contained no usable catalog.',
55
59
  offline: 'Model discovery could not reach its source.',
56
60
  };
61
+ function probeErrorCode(error) {
62
+ return error instanceof ModelProbeError ? error.code : 'offline';
63
+ }
57
64
  function diagnostic(error) {
58
65
  // Never stringify vendor errors: stderr/HTTP bodies may include credentials or OAuth URLs.
59
- const code = error instanceof ProbeTimeout ? 'timeout' : error instanceof ModelProbeError ? error.code : 'offline';
66
+ const code = error instanceof ProbeTimeout ? 'timeout' : probeErrorCode(error);
60
67
  return { code, message: DIAGNOSTIC_MESSAGES[code] };
61
68
  }
62
69
  function isUnexpired(snapshot, now) {
@@ -1,3 +1,4 @@
1
+ import { trimCharsEnd } from '@jini-ai/core/text';
1
2
  /**
2
3
  * Resolves a provider's credential status for display. A provider that
3
4
  * doesn't require credentials is always `available`; otherwise the status
@@ -51,7 +52,7 @@ export function modelCatalogCacheKey({ providerId, baseUrl, credential }, { vari
51
52
  throw new TypeError('Model catalog variant must be a string');
52
53
  return [
53
54
  providerId,
54
- baseUrl.trim().replace(/\/+$/, ''),
55
+ trimCharsEnd({ text: baseUrl.trim(), chars: '/' }),
55
56
  fingerprintCredential({ value: credential.trim() }),
56
57
  variant.trim(),
57
58
  ].join('\n');
@@ -26,4 +26,32 @@ export declare function resolveNativeToolDenies(required: {
26
26
  enabled: boolean | undefined;
27
27
  denied?: readonly string[];
28
28
  }, _optional?: Record<string, never>): readonly string[];
29
+ /** Current run limits, shared by launch enforcement and browser preflight. */
30
+ export interface NativeToolPolicyInput {
31
+ nativeToolAccess?: boolean;
32
+ nativeCapabilities?: Partial<NativeCapabilities>;
33
+ cliParity?: boolean;
34
+ permissionMode?: 'bypass' | 'restricted';
35
+ }
36
+ /** Full-access-only runtimes always get full access, independently of workspace switches.
37
+ * Hosts still authorize assistant use; other runtime policies stay intact. Pure, O(1).
38
+ */
39
+ export declare function resolveNativeToolPolicy({ def, policy }: {
40
+ def: {
41
+ name?: string;
42
+ fullCliAccessOnly?: boolean;
43
+ };
44
+ policy: NativeToolPolicyInput;
45
+ }, _options?: Record<string, never>): NativeToolPolicyInput;
46
+ /** The same fail-closed assessment at selection and spawn; no CLI-name allowlist.
47
+ * Unknown explicit OFF switches stay blocked. O(c) over declared limits, without effects.
48
+ */
49
+ export declare function assessNativeToolPolicy({ def, policy }: {
50
+ def: {
51
+ name: string;
52
+ supportsNativeToolAccess?: boolean;
53
+ fullCliAccessOnly?: boolean;
54
+ };
55
+ policy: NativeToolPolicyInput;
56
+ }, _options?: Record<string, never>): string | null;
29
57
  //# sourceMappingURL=native-tool-policy.d.ts.map
@@ -33,4 +33,46 @@ export function resolveNativeToolDenies(required, _optional = {}) {
33
33
  return denied.filter(tool => !NATIVE_FALLBACK_TOOLS.includes(tool));
34
34
  return [...new Set([...denied, ...NATIVE_FALLBACK_TOOLS])];
35
35
  }
36
+ /** Full-access-only runtimes always get full access, independently of workspace switches.
37
+ * Hosts still authorize assistant use; other runtime policies stay intact. Pure, O(1).
38
+ */
39
+ export function resolveNativeToolPolicy({ def, policy }, _options = {}) {
40
+ if (!def.fullCliAccessOnly)
41
+ return policy;
42
+ return { ...policy, nativeToolAccess: true, cliParity: true, permissionMode: 'bypass',
43
+ nativeCapabilities: { shell: true, fileWrite: true, userMcp: true, subagents: true,
44
+ userSettings: true, web: true, workflows: true, loginEnvironment: true } };
45
+ }
46
+ /** Switch names a person sees for each native capability (the host's settings use the same words). */
47
+ const NATIVE_CAPABILITY_LABELS = {
48
+ shell: 'Bash/shell', fileWrite: 'File edit/write', userMcp: 'Your MCP servers', subagents: 'Subagents/Task',
49
+ userSettings: 'Your skills and settings', web: 'Web fetch/search', workflows: 'Workflows', loginEnvironment: 'Your shell environment',
50
+ };
51
+ /** The refusal a person reads when a CLI without a native-tool policy cannot honor this run's switches:
52
+ * it names the CLI and the switch to turn on. Owner 2026-10-27: the old "no native-tool policy and
53
+ * audit adapter" told a Gemini user nothing. Pure, O(c) for c OFF switches.
54
+ * @example nativeToolPolicyRefusal({ cliName: 'Antigravity', offSwitches: ['userMcp'] }, {});
55
+ */
56
+ function nativeToolPolicyRefusal({ cliName, offSwitches }, _options = {}) {
57
+ const switches = offSwitches.map(key => `'${NATIVE_CAPABILITY_LABELS[key] ?? key}'`);
58
+ const blocked = switches.length > 0 ? `with ${new Intl.ListFormat('en', { type: 'conjunction' }).format(switches)} off` : `with this chat's CLI tool limits`;
59
+ const pronoun = switches.length === 1 ? 'it' : 'them';
60
+ const action = switches.length === 0 ? `Turn on 'Full CLI access'` : `Turn ${pronoun} on`;
61
+ return `${cliName} can't run ${blocked}. ${action} in the assistant settings, or choose Claude or Codex.`;
62
+ }
63
+ /** The same fail-closed assessment at selection and spawn; no CLI-name allowlist.
64
+ * Unknown explicit OFF switches stay blocked. O(c) over declared limits, without effects.
65
+ */
66
+ export function assessNativeToolPolicy({ def, policy }, _options = {}) {
67
+ if (def.fullCliAccessOnly)
68
+ return null;
69
+ if (def.supportsNativeToolAccess === true)
70
+ return null;
71
+ const parity = policy.cliParity === true && policy.permissionMode === 'bypass' && policy.nativeToolAccess !== false;
72
+ const offSwitches = Object.entries(policy.nativeCapabilities ?? {}).filter(([, value]) => value === false).map(([key]) => key);
73
+ if ((policy.nativeToolAccess !== undefined && !parity) || offSwitches.length > 0) {
74
+ return nativeToolPolicyRefusal({ cliName: def.name, offSwitches });
75
+ }
76
+ return null;
77
+ }
36
78
  //# sourceMappingURL=native-tool-policy.js.map
@@ -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))));