@jini-ai/agent-runtime 0.4.11 → 0.6.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/CHANGELOG.md +83 -1
  2. package/dist/acp-model-probe.d.ts +2 -20
  3. package/dist/agent-protocol/acp/json.js +46 -37
  4. package/dist/agent-protocol/acp/models.js +91 -73
  5. package/dist/agent-protocol/acp/rpc.d.ts +3 -2
  6. package/dist/agent-protocol/acp/rpc.js +3 -2
  7. package/dist/agent-protocol/acp/session-params.d.ts +1 -1
  8. package/dist/agent-protocol/acp/session-params.js +33 -30
  9. package/dist/agent-protocol/acp/session.d.ts +3 -1
  10. package/dist/agent-protocol/acp/session.js +62 -24
  11. package/dist/agent-protocol/acp/updates.js +49 -35
  12. package/dist/agent-protocol/pi-rpc/session.js +3 -1
  13. package/dist/anthropic-live-models.d.ts +12 -4
  14. package/dist/anthropic-live-models.js +0 -0
  15. package/dist/auth.js +84 -91
  16. package/dist/claude-code-models.d.ts +6 -5
  17. package/dist/claude-code-models.js +19 -12
  18. package/dist/claude-segment-usage.d.ts +3 -3
  19. package/dist/claude-segment-usage.js +63 -29
  20. package/dist/claude-stream.d.ts +2 -0
  21. package/dist/claude-stream.js +16 -5
  22. package/dist/copilot-stream.js +42 -50
  23. package/dist/defs/aider.js +3 -4
  24. package/dist/defs/amr.js +52 -61
  25. package/dist/defs/antigravity.d.ts +6 -5
  26. package/dist/defs/antigravity.js +48 -34
  27. package/dist/defs/auggie.d.ts +1 -1
  28. package/dist/defs/claude-compatible-args.d.ts +19 -0
  29. package/dist/defs/claude-compatible-args.js +42 -0
  30. package/dist/defs/claude.d.ts +7 -2
  31. package/dist/defs/claude.js +96 -85
  32. package/dist/defs/cline.d.ts +1 -1
  33. package/dist/defs/codebuddy.d.ts +1 -1
  34. package/dist/defs/codebuddy.js +29 -46
  35. package/dist/defs/codex.d.ts +15 -3
  36. package/dist/defs/codex.js +143 -108
  37. package/dist/defs/cursor-agent.d.ts +9 -7
  38. package/dist/defs/cursor-agent.js +53 -51
  39. package/dist/defs/devin.d.ts +1 -1
  40. package/dist/defs/goose.d.ts +1 -1
  41. package/dist/defs/hermes.d.ts +1 -1
  42. package/dist/defs/kilo.d.ts +1 -1
  43. package/dist/defs/kimi.d.ts +1 -1
  44. package/dist/defs/kiro.d.ts +1 -1
  45. package/dist/defs/opencode.d.ts +5 -4
  46. package/dist/defs/opencode.js +26 -32
  47. package/dist/defs/pi.d.ts +6 -5
  48. package/dist/defs/pi.js +24 -26
  49. package/dist/defs/qoder.d.ts +4 -3
  50. package/dist/defs/qoder.js +25 -25
  51. package/dist/defs/reasonix.d.ts +1 -1
  52. package/dist/defs/shared.d.ts +12 -3
  53. package/dist/defs/shared.js +19 -13
  54. package/dist/defs/trae-cli.d.ts +1 -1
  55. package/dist/defs/vibe.d.ts +1 -1
  56. package/dist/detection.d.ts +13 -20
  57. package/dist/detection.js +129 -111
  58. package/dist/env.js +56 -41
  59. package/dist/executables.js +103 -114
  60. package/dist/index.d.ts +1 -0
  61. package/dist/index.js +1 -0
  62. package/dist/json-event-stream.js +611 -527
  63. package/dist/launch.js +44 -37
  64. package/dist/model-discovery-adapters.d.ts +17 -0
  65. package/dist/model-discovery-adapters.js +223 -164
  66. package/dist/model-discovery-config.js +107 -87
  67. package/dist/model-discovery-sdk.d.ts +16 -2
  68. package/dist/model-discovery-sdk.js +4 -3
  69. package/dist/model-discovery-shared.d.ts +14 -0
  70. package/dist/model-discovery-shared.js +50 -15
  71. package/dist/model-discovery-types.d.ts +2 -0
  72. package/dist/model-discovery.js +219 -117
  73. package/dist/models.d.ts +14 -1
  74. package/dist/models.js +75 -19
  75. package/dist/native-tool-policy.d.ts +29 -0
  76. package/dist/native-tool-policy.js +36 -0
  77. package/dist/opencode-log.js +46 -30
  78. package/dist/paths.d.ts +2 -0
  79. package/dist/paths.js +3 -3
  80. package/dist/providers/aihubmix.js +13 -18
  81. package/dist/providers/anthropic-messages.d.ts +7 -0
  82. package/dist/providers/anthropic-messages.js +45 -21
  83. package/dist/providers/azure-chat.d.ts +5 -0
  84. package/dist/providers/azure-chat.js +13 -5
  85. package/dist/providers/connection-guard.d.ts +2 -45
  86. package/dist/providers/connection-guard.js +11 -10
  87. package/dist/providers/connection-test.d.ts +4 -0
  88. package/dist/providers/connection-test.js +127 -110
  89. package/dist/providers/elevenlabs.js +4 -1
  90. package/dist/providers/google-messages.d.ts +4 -0
  91. package/dist/providers/google-messages.js +48 -23
  92. package/dist/providers/google-schema.js +17 -23
  93. package/dist/providers/model-catalog.js +160 -145
  94. package/dist/providers/oauth-callback-server.js +37 -34
  95. package/dist/providers/oauth-credentials.js +23 -23
  96. package/dist/providers/oauth-tokens.js +16 -24
  97. package/dist/providers/openai-chat.d.ts +42 -0
  98. package/dist/providers/openai-chat.js +80 -10
  99. package/dist/providers/operation-schema.d.ts +25 -0
  100. package/dist/providers/operation-schema.js +226 -0
  101. package/dist/providers/response-text.d.ts +10 -0
  102. package/dist/providers/response-text.js +23 -0
  103. package/dist/providers/tool-turn-types.d.ts +56 -9
  104. package/dist/providers/tool-turn.d.ts +7 -0
  105. package/dist/providers/tool-turn.js +120 -32
  106. package/dist/qoder-stream.js +93 -80
  107. package/dist/registry.d.ts +45 -0
  108. package/dist/registry.js +39 -0
  109. package/dist/runtime-state.d.ts +1 -1
  110. package/dist/types.d.ts +43 -1
  111. package/package.json +19 -14
package/dist/launch.js CHANGED
@@ -47,28 +47,36 @@ export function applyAgentLaunchEnv({ env, launch }, { nodeBinDir = path.dirname
47
47
  const toPrepend = [...(nodeBinDir ? [nodeBinDir] : []), ...launch.childPathPrepend];
48
48
  if (toPrepend.length === 0 && appendPathDirs.length === 0)
49
49
  return env;
50
- // Case-insensitive key lookup — Windows uses 'Path', not 'PATH'. Using
51
- // env.PATH directly would be undefined on Windows, yielding a
52
- // one-entry PATH that contains only toPrepend and discards all system
53
- // paths. Find the actual key name so we update in place rather than
54
- // adding a conflicting duplicate key.
55
- const pathKey = Object.keys(env).find((k) => k.toLowerCase() === 'path') ?? 'PATH';
50
+ const pathKey = pathEnvKey(env);
56
51
  const existing = typeof env[pathKey] === 'string' ? env[pathKey] : '';
57
- const normalize = (p) => {
58
- const trimmed = p.replace(/[/\\]+$/, '');
59
- return process.platform === 'win32' ? trimmed.toLowerCase() : trimmed;
60
- };
61
52
  const existingParts = existing.split(delimiter).filter((e) => e.length > 0);
53
+ return { ...env, [pathKey]: dedupePathEntries([...toPrepend, ...existingParts, ...appendPathDirs]).join(delimiter) };
54
+ }
55
+ // Case-insensitive key lookup — Windows uses 'Path', not 'PATH'. Using
56
+ // env.PATH directly would be undefined on Windows, yielding a
57
+ // one-entry PATH that contains only toPrepend and discards all system
58
+ // paths. Find the actual key name so we update in place rather than
59
+ // adding a conflicting duplicate key.
60
+ function pathEnvKey(env) {
61
+ return Object.keys(env).find((k) => k.toLowerCase() === 'path') ?? 'PATH';
62
+ }
63
+ function normalizePathEntry(p) {
64
+ const trimmed = p.replace(/[/\\]+$/, '');
65
+ return process.platform === 'win32' ? trimmed.toLowerCase() : trimmed;
66
+ }
67
+ // Keep the first spelling of each directory (trailing separators ignored,
68
+ // case-insensitive on Windows).
69
+ function dedupePathEntries(entries) {
62
70
  const seen = new Set();
63
71
  const merged = [];
64
- for (const entry of [...toPrepend, ...existingParts, ...appendPathDirs]) {
65
- const n = normalize(entry);
72
+ for (const entry of entries) {
73
+ const n = normalizePathEntry(entry);
66
74
  if (!seen.has(n)) {
67
75
  seen.add(n);
68
76
  merged.push(entry);
69
77
  }
70
78
  }
71
- return { ...env, [pathKey]: merged.join(delimiter) };
79
+ return merged;
72
80
  }
73
81
  function tryResolveCodexNativeBinary(wrapperPath) {
74
82
  const packageSuffix = codexNativePackageSuffix();
@@ -89,17 +97,18 @@ function tryResolveCodexNativeBinary(wrapperPath) {
89
97
  };
90
98
  }
91
99
  function codexSearchRoots(wrapperPath) {
92
- const roots = new Set();
93
- for (const seed of [wrapperPath, safeRealpath(wrapperPath)]) {
94
- if (!seed)
95
- continue;
96
- let current = path.dirname(seed);
97
- while (current !== path.dirname(current)) {
98
- roots.add(current);
99
- current = path.dirname(current);
100
- }
101
- }
102
- return [...roots];
100
+ const resolved = safeRealpath(wrapperPath) ?? wrapperPath;
101
+ const directory = path.dirname(resolved);
102
+ // npm bin symlinks resolve inside @openai/codex/bin. Only that package's
103
+ // install directory owns the upgrade; ancestors of the shim or package do not.
104
+ if (path.basename(directory) !== 'bin' || path.basename(path.dirname(directory)) !== 'codex')
105
+ return [directory];
106
+ const packageDir = path.dirname(directory);
107
+ const scopeDir = path.dirname(packageDir);
108
+ // Hoisted npm and pnpm layouts put the native package beside @openai/codex in the same
109
+ // node_modules; that tree already owns the wrapper, so it is not an ancestor search.
110
+ const ownsHoistedSibling = path.basename(scopeDir) === '@openai' && path.basename(path.dirname(scopeDir)) === 'node_modules';
111
+ return ownsHoistedSibling ? [packageDir, path.dirname(path.dirname(scopeDir))] : [packageDir];
103
112
  }
104
113
  function codexNativeCandidates(root, packageSuffix, targetTriple) {
105
114
  const scoped = path.join(root, 'node_modules', '@openai');
@@ -130,20 +139,18 @@ function codexNativeCandidates(root, packageSuffix, targetTriple) {
130
139
  function codexNativePackageSuffix() {
131
140
  return `${process.platform}-${process.arch}`;
132
141
  }
142
+ const CODEX_NATIVE_TARGET_TRIPLES = new Map([
143
+ ['darwin-arm64', 'aarch64-apple-darwin'],
144
+ ['darwin-x64', 'x86_64-apple-darwin'],
145
+ ['linux-arm64', 'aarch64-unknown-linux-musl'],
146
+ ['linux-x64', 'x86_64-unknown-linux-musl'],
147
+ ['win32-arm64', 'aarch64-pc-windows-msvc'],
148
+ ['win32-x64', 'x86_64-pc-windows-msvc'],
149
+ ]);
150
+ // Unmapped platform/arch pairs fall back to the npm package suffix itself.
133
151
  function codexNativeTargetTriple() {
134
- if (process.platform === 'darwin' && process.arch === 'arm64')
135
- return 'aarch64-apple-darwin';
136
- if (process.platform === 'darwin' && process.arch === 'x64')
137
- return 'x86_64-apple-darwin';
138
- if (process.platform === 'linux' && process.arch === 'arm64')
139
- return 'aarch64-unknown-linux-musl';
140
- if (process.platform === 'linux' && process.arch === 'x64')
141
- return 'x86_64-unknown-linux-musl';
142
- if (process.platform === 'win32' && process.arch === 'arm64')
143
- return 'aarch64-pc-windows-msvc';
144
- if (process.platform === 'win32' && process.arch === 'x64')
145
- return 'x86_64-pc-windows-msvc';
146
- return `${process.platform}-${process.arch}`;
152
+ const suffix = codexNativePackageSuffix();
153
+ return CODEX_NATIVE_TARGET_TRIPLES.get(suffix) ?? suffix;
147
154
  }
148
155
  function looksLikeCodexNodeWrapper(filePath) {
149
156
  // Read only the first 64KB rather than slurping the whole file: the
@@ -17,6 +17,22 @@ export declare function probeProviderApi(agentId: string, context: ModelDiscover
17
17
  /** Caches are partial observed catalogs, always stale, never silently promoted to live. */
18
18
  export declare function probeCliCache(agentId: string, context: ModelDiscoveryContext, deps: ModelDiscoveryDeps, signal: AbortSignal): Promise<ModelProbeResult>;
19
19
  export declare function probeAgentCatalog(agentId: string, context: ModelDiscoveryContext, configuration: AgentDiscoveryConfiguration, deps: ModelDiscoveryDeps, signal: AbortSignal): Promise<ModelProbeResult>;
20
+ /** Load the catalog owner only for a default URL, so importing the runtime never needs this peer.
21
+ * @param required - The vendor whose default endpoint is needed.
22
+ * @returns The catalog-owned base URL; explicit host URLs bypass this lookup.
23
+ * @throws An actionable load error retaining the original import failure as its cause.
24
+ * @complexity O(1) lookup after Node's cached module load.
25
+ */
26
+ type ProviderCatalogModule = typeof import('@jini-ai/integrations/media-providers/catalog');
27
+ /** The module-loading port for the optional catalog peer; Node's dynamic import by default. */
28
+ export type ProviderCatalogImport = () => Promise<{
29
+ readonly VENDOR_API_BASE_URLS: Readonly<Record<keyof ProviderCatalogModule['VENDOR_API_BASE_URLS'], string>>;
30
+ }>;
31
+ /** The env-backed credential port. `importCatalog` loads the optional provider-catalog peer for
32
+ * default base URLs; injectable so a missing peer is testable without uninstalling it. */
33
+ export declare function createEnvCredentialPort(_required?: Record<string, never>, { importCatalog }?: {
34
+ importCatalog?: ProviderCatalogImport;
35
+ }): ModelDiscoveryDeps['credential'];
20
36
  export declare const defaultModelDiscoveryDeps: ModelDiscoveryDeps;
21
37
  /** Pi's native RPC supplies catalog AND current provider/id without making an inference call. */
22
38
  export declare function parsePiRpcMetadata(stdout: string): ModelProbeResult;
@@ -33,4 +49,5 @@ export declare function getRuntimeModelDiscoveryDeps({ state }: {
33
49
  export declare function createAcpDiscoveryAdapter({ probe }: {
34
50
  probe: AcpModelProbe;
35
51
  }, _optional?: Record<string, never>): ModelDiscoveryDeps['acp'];
52
+ export {};
36
53
  //# sourceMappingURL=model-discovery-adapters.d.ts.map
@@ -28,9 +28,8 @@ export function modelProbeTimeoutMs(agentId) {
28
28
  }
29
29
  /** Shared CLI-subcommand adapter. Output parsers are pure def-owned functions, not vendor tools. */
30
30
  export async function probeCliSubcommand(context, config, deps, signal) {
31
- // Reserve two seconds of the outer budget for CLI-owned cache recovery. The inner
32
- // abort signal stops only the listing; the parent remains usable for reading fallback files.
33
- const { stdout } = await withModelProbeTimeout(active => deps.process.run({ context, args: config.args || [], signal: active, timeoutMs: 8_000 }), 8_000, signal);
31
+ const timeoutMs = config.timeoutMs ?? 8_000;
32
+ const { stdout } = await withModelProbeTimeout(active => deps.process.run({ context, args: config.args || [], signal: active, timeoutMs }), timeoutMs, signal);
34
33
  const models = config.parse?.({ stdout });
35
34
  if (!models)
36
35
  throw new ModelProbeError('malformed-response');
@@ -41,46 +40,63 @@ export async function probeCliSubcommand(context, config, deps, signal) {
41
40
  export async function probeAcpMetadata(context, args, deps, signal) {
42
41
  return deps.acp.probe({ context, args, signal });
43
42
  }
43
+ /** Spread a native default selection only when the source reported one. */
44
+ function withDefaultSelection(defaultSelectionId) {
45
+ return defaultSelectionId ? { defaultSelectionId } : {};
46
+ }
47
+ /** The model rows of one successful initialize control response, or null for any other line. */
48
+ function claudeInitializeRows(line) {
49
+ let obj;
50
+ try {
51
+ obj = JSON.parse(line);
52
+ }
53
+ catch {
54
+ return null;
55
+ }
56
+ if (obj?.type !== 'control_response')
57
+ return null;
58
+ const response = obj.response;
59
+ const rows = response?.subtype === 'success' ? response.response?.models : undefined;
60
+ return Array.isArray(rows) ? rows : null;
61
+ }
62
+ /** One selection row, plus its concrete resolved row when the selection is an alias. */
63
+ function claudeSelectionModels(id, resolvedId, displayName) {
64
+ const label = typeof displayName === 'string' && displayName.trim() ? displayName.trim() : resolvedId || id;
65
+ const identityKind = id === resolvedId ? 'concrete' : resolvedId ? 'alias' : modelIdentityKind(id);
66
+ const selection = { id, label, identityKind, ...(resolvedId ? { resolvedId } : {}) };
67
+ if (!resolvedId || id === resolvedId)
68
+ return [selection];
69
+ return [selection, { id: resolvedId, label, identityKind: modelIdentityKind(resolvedId) }];
70
+ }
71
+ function claudeInitializeResult(rows) {
72
+ const models = [];
73
+ let defaultSelectionId;
74
+ for (const row of rows) {
75
+ if (!row || typeof row.value !== 'string')
76
+ continue;
77
+ const id = row.value.trim();
78
+ 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
+ }
88
+ }
89
+ return { models, source: 'rpc', coverage: 'account', ...withDefaultSelection(defaultSelectionId) };
90
+ }
44
91
  /** Keep selection IDs, resolved concrete IDs and display names, including capability variants.
45
92
  * Default-policy display names become the exact resolved ID; malformed responses return null.
46
93
  * @complexity O(s + n) time and space in stdout length s and listed models n.
47
94
  */
48
95
  export function parseClaudeInitializeMetadata(stdout) {
49
96
  for (const line of stdout.split('\n')) {
50
- let obj;
51
- try {
52
- obj = JSON.parse(line);
53
- }
54
- catch {
55
- continue;
56
- }
57
- if (obj?.type !== 'control_response')
58
- continue;
59
- const response = obj.response;
60
- const rows = response?.subtype === 'success' ? response.response?.models : undefined;
61
- if (!Array.isArray(rows))
62
- continue;
63
- const models = [];
64
- let defaultSelectionId;
65
- for (const row of rows) {
66
- if (!row || typeof row.value !== 'string')
67
- continue;
68
- const id = row.value.trim();
69
- const resolvedId = typeof row.resolvedModel === 'string' ? row.resolvedModel.trim() : undefined;
70
- const label = typeof row.displayName === 'string' && row.displayName.trim() ? row.displayName.trim() : resolvedId || id;
71
- if (id === 'default') {
72
- // This displayName describes the CLI's default policy, not the model it resolves to.
73
- if (resolvedId && modelIdentityKind(resolvedId) === 'concrete') {
74
- defaultSelectionId = resolvedId;
75
- models.push({ id: resolvedId, label: resolvedId, identityKind: 'concrete' });
76
- }
77
- continue;
78
- }
79
- models.push({ id, label, identityKind: id === resolvedId ? 'concrete' : resolvedId ? 'alias' : modelIdentityKind(id), ...(resolvedId ? { resolvedId } : {}) });
80
- if (resolvedId && id !== resolvedId)
81
- models.push({ id: resolvedId, label, identityKind: modelIdentityKind(resolvedId) });
82
- }
83
- return { models, source: 'rpc', coverage: 'account', ...(defaultSelectionId ? { defaultSelectionId } : {}) };
97
+ const rows = claudeInitializeRows(line);
98
+ if (rows)
99
+ return claudeInitializeResult(rows);
84
100
  }
85
101
  return null;
86
102
  }
@@ -100,6 +116,11 @@ export async function probeClaudeInitialize(context, deps, signal) {
100
116
  throw new ModelProbeError('malformed-response');
101
117
  return metadata;
102
118
  }
119
+ const PROVIDER_LIST_FAILURES = { auth_failed: 'auth-missing', timeout: 'timeout' };
120
+ /** Aider qualifies listed rows with the provider of a qualified selection ("openai/" for "openai/gpt-x"). */
121
+ function aiderProviderPrefix(agentId, selection) {
122
+ return agentId === 'aider' && selection?.includes('/') ? selection.slice(0, selection.indexOf('/') + 1) : '';
123
+ }
103
124
  export async function probeProviderApi(agentId, context, deps, signal) {
104
125
  const config = await readModelConfiguration(agentId, context, deps, signal);
105
126
  const effectiveContext = config.selection ? { ...context, model: config.selection } : context;
@@ -110,37 +131,34 @@ export async function probeProviderApi(agentId, context, deps, signal) {
110
131
  throw new ModelProbeError('unsupported-version');
111
132
  const result = await deps.http.list({ ...input, signal });
112
133
  if (!result.ok || !result.models)
113
- throw new ModelProbeError(result.kind === 'auth_failed' ? 'auth-missing' : result.kind === 'timeout' ? 'timeout' : 'offline');
114
- const prefix = agentId === 'aider' && config.selection?.includes('/') ? config.selection.slice(0, config.selection.indexOf('/') + 1) : '';
134
+ throw new ModelProbeError(PROVIDER_LIST_FAILURES[result.kind] ?? 'offline');
135
+ const prefix = aiderProviderPrefix(agentId, config.selection);
115
136
  return { models: result.models.map((row) => ({ ...row, id: prefix && !row.id.startsWith(prefix) ? `${prefix}${row.id}` : row.id })), source: 'provider-api', coverage: 'provider' };
116
137
  }
138
+ const optionCacheModels = (data) => configurationCacheModels(data.additionalModelOptionsCache);
139
+ const CLI_CACHES = new Map([
140
+ ['codex', { path: (env, home) => join(env.CODEX_HOME || join(home, '.codex'), 'models_cache.json'), models: (data) => configurationCacheModels(data.models) }],
141
+ ['opencode', { path: (env, home) => join(env.XDG_CACHE_HOME || join(home, '.cache'), 'opencode/models.json'), models: opencodeCacheModels }],
142
+ ['claude', { path: (env, home) => join(env.CLAUDE_CONFIG_DIR || home, '.claude.json'), models: optionCacheModels }],
143
+ // UNVERIFIED CodeBuddy cache schema. Configured model is weaker than an account catalog.
144
+ ['codebuddy', { path: (_env, home) => join(home, '.codebuddy/settings.json'), models: optionCacheModels }],
145
+ ]);
117
146
  /** Caches are partial observed catalogs, always stale, never silently promoted to live. */
118
147
  export async function probeCliCache(agentId, context, deps, signal) {
119
- const home = context.env.HOME || homedir();
120
- const path = agentId === 'codex' ? join(context.env.CODEX_HOME || join(home, '.codex'), 'models_cache.json')
121
- : agentId === 'opencode' ? join(context.env.XDG_CACHE_HOME || join(home, '.cache'), 'opencode/models.json')
122
- : agentId === 'claude' ? join(context.env.CLAUDE_CONFIG_DIR || home, '.claude.json')
123
- : agentId === 'codebuddy' ? join(home, '.codebuddy/settings.json') : '';
124
- if (!path)
148
+ const cache = CLI_CACHES.get(agentId);
149
+ if (!cache)
125
150
  throw new ModelProbeError('unsupported-version');
126
- const raw = await deps.fs.read(path, { signal });
151
+ const raw = await deps.fs.read(cache.path(context.env, context.env.HOME || homedir()), { signal });
127
152
  const data = raw ? parseSettingsJson(raw) : null;
128
153
  if (!data)
129
154
  throw new ModelProbeError('offline');
130
- if (agentId === 'codex' && raw)
131
- return { models: configurationCacheModels(data.models), source: 'cli-cache', coverage: 'observed' };
132
- if (agentId === 'opencode') {
133
- const models = [];
134
- for (const [provider, value] of Object.entries(data)) {
135
- const entries = value && typeof value === 'object' ? value.models : undefined;
136
- for (const [id, row] of Object.entries(entries || {}))
137
- models.push({ id: `${provider}/${id}`, label: row.name || `${provider}/${id}`, provider, identityKind: modelIdentityKind(id) });
138
- }
139
- return { models, source: 'cli-cache', coverage: 'observed' };
140
- }
141
- // UNVERIFIED CodeBuddy cache schema. Configured model is weaker than an account catalog.
142
- const entries = data.additionalModelOptionsCache;
143
- return { models: configurationCacheModels(entries), source: 'cli-cache', coverage: 'observed' };
155
+ return { models: cache.models(data), source: 'cli-cache', coverage: 'observed' };
156
+ }
157
+ function opencodeCacheModels(data) {
158
+ return Object.entries(data).flatMap(([provider, value]) => {
159
+ const entries = value && typeof value === 'object' ? value.models : undefined;
160
+ return Object.entries(entries || {}).map(([id, row]) => ({ id: `${provider}/${id}`, label: row.name || `${provider}/${id}`, provider, identityKind: modelIdentityKind(id) }));
161
+ });
144
162
  }
145
163
  function configurationCacheModels(entries) {
146
164
  if (!Array.isArray(entries))
@@ -174,75 +192,97 @@ function parseGenericCliModels(stdout) {
174
192
  return [{ id: match[1], label: match[2] || match[1], identityKind: modelIdentityKind(match[1]) }];
175
193
  });
176
194
  }
177
- export async function probeAgentCatalog(agentId, context, configuration, deps, signal) {
178
- const acpArgs = ACP_ARGS[agentId];
179
- // UNVERIFIED installed ACP agents: existing declared commands; metadata preserves native defaults.
180
- if (acpArgs && agentId !== 'amr')
181
- return probeAcpMetadata(context, acpArgs, deps, signal);
182
- if (agentId === 'claude') {
183
- try {
184
- return await probeClaudeInitialize(context, deps, signal);
185
- }
186
- catch {
187
- try {
188
- return await probeProviderApi(agentId, context, deps, signal);
189
- }
190
- catch {
191
- return probeCliCache(agentId, context, deps, signal);
192
- }
193
- }
195
+ const probeRpc = (agentId, context, deps, signal) => deps.rpc.probe({ agentId, context, signal });
196
+ async function probeClaudeCatalog(agentId, context, deps, signal) {
197
+ try {
198
+ return await probeClaudeInitialize(context, deps, signal);
194
199
  }
195
- if (agentId === 'pi' || agentId === 'copilot' || agentId === 'droid')
196
- return deps.rpc.probe({ agentId, context, signal });
197
- // UNVERIFIED CLI-owned effective credential adapters; OAuth/unknown endpoints require host ports.
198
- if (agentId === 'aider' || agentId === 'qwen' || agentId === 'mimo')
199
- return probeProviderApi(agentId, context, deps, signal);
200
- if (agentId === 'codebuddy') {
201
- // UNVERIFIED: survey identifies initialize compatibility as a candidate, not a guarantee.
202
- // Try the same prompt-free metadata category; failed compatibility stays explicitly offline.
200
+ catch {
203
201
  try {
204
- return await probeClaudeInitialize(context, deps, signal);
202
+ return await probeProviderApi(agentId, context, deps, signal);
205
203
  }
206
204
  catch {
207
205
  return probeCliCache(agentId, context, deps, signal);
208
206
  }
209
207
  }
210
- if (configuration.args) {
208
+ }
209
+ async function probeCodeBuddyCatalog(agentId, context, deps, signal) {
210
+ // UNVERIFIED: survey identifies initialize compatibility as a candidate, not a guarantee.
211
+ // Try the same prompt-free metadata category; failed compatibility stays explicitly offline.
212
+ try {
213
+ return await probeClaudeInitialize(context, deps, signal);
214
+ }
215
+ catch {
216
+ return probeCliCache(agentId, context, deps, signal);
217
+ }
218
+ }
219
+ /** Agents with a dedicated discovery category, checked before any declared listing command. */
220
+ const AGENT_PROBES = new Map([
221
+ ['claude', probeClaudeCatalog],
222
+ ['pi', probeRpc], ['copilot', probeRpc], ['droid', probeRpc],
223
+ // UNVERIFIED CLI-owned effective credential adapters; OAuth/unknown endpoints require host ports.
224
+ ['aider', probeProviderApi], ['qwen', probeProviderApi], ['mimo', probeProviderApi],
225
+ ['codebuddy', probeCodeBuddyCatalog],
226
+ ]);
227
+ const DISK_CACHE_LISTINGS = new Set(['codex', 'opencode']);
228
+ async function probeDeclaredListing(agentId, context, configuration, deps, signal) {
229
+ // Only disk-cache adapters reserve two seconds for recovery. Antigravity has no disk
230
+ // fallback, so its declared listing timeout can use the full outer discovery budget.
231
+ const diskCache = DISK_CACHE_LISTINGS.has(agentId);
232
+ const budget = modelProbeTimeoutMs(agentId) - (diskCache ? 2_000 : 0);
233
+ const timeoutMs = Math.min(configuration.timeoutMs ?? 8_000, budget);
234
+ try {
235
+ return await probeCliSubcommand(context, { ...configuration, timeoutMs }, deps, signal);
236
+ }
237
+ catch (error) {
238
+ if (!diskCache)
239
+ throw error;
211
240
  try {
212
- return await probeCliSubcommand(context, configuration, deps, signal);
241
+ return await probeCliCache(agentId, context, deps, signal);
213
242
  }
214
- catch (error) {
215
- if (agentId === 'codex' || agentId === 'opencode') {
216
- try {
217
- return await probeCliCache(agentId, context, deps, signal);
218
- }
219
- catch {
220
- throw error;
221
- }
222
- }
243
+ catch {
223
244
  throw error;
224
245
  }
225
246
  }
226
- if (agentId === 'amr') {
227
- // Every ACP def uses this category. Vela's documented list command remains a fallback
228
- // when its ACP version omits the model catalog; launch still confirms explicit selection.
229
- try {
230
- const metadata = await probeAcpMetadata(context, ACP_ARGS.amr, deps, signal);
231
- const first = metadata.models.find((row) => row.id !== 'default' && modelIdentityKind(row.id) === 'concrete');
232
- if (!first)
233
- throw new ModelProbeError('malformed-response');
234
- return { ...metadata, defaultSelectionId: context.env.VELA_DEFAULT_MODEL || metadata.defaultSelectionId || first.id };
235
- }
236
- catch (error) {
237
- if (signal.aborted)
238
- throw error;
239
- }
240
- const result = await deps.process.run({ context, args: ['model', 'list', '--format', 'json'], signal, timeoutMs: 10_000 });
241
- const models = configuration.parse?.({ stdout: result.stdout }) || [];
242
- // Vela requires an explicit concrete set_model before prompting; retain the first native row.
243
- const first = models.find((row) => row.id !== 'default');
244
- return { models, source: 'cli', coverage: 'account', ...(first ? { defaultSelectionId: context.env.VELA_DEFAULT_MODEL || first.id } : {}) };
247
+ }
248
+ async function probeAmrAcp(context, deps, signal) {
249
+ const metadata = await probeAcpMetadata(context, ACP_ARGS.amr, deps, signal);
250
+ const first = metadata.models.find((row) => row.id !== 'default' && modelIdentityKind(row.id) === 'concrete');
251
+ if (!first)
252
+ throw new ModelProbeError('malformed-response');
253
+ return { ...metadata, defaultSelectionId: context.env.VELA_DEFAULT_MODEL || metadata.defaultSelectionId || first.id };
254
+ }
255
+ async function probeAmrList(context, configuration, deps, signal) {
256
+ const result = await deps.process.run({ context, args: ['model', 'list', '--format', 'json'], signal, timeoutMs: 10_000 });
257
+ const models = configuration.parse?.({ stdout: result.stdout }) || [];
258
+ // Vela requires an explicit concrete set_model before prompting; retain the first native row.
259
+ const first = models.find((row) => row.id !== 'default');
260
+ return { models, source: 'cli', coverage: 'account', ...(first ? { defaultSelectionId: context.env.VELA_DEFAULT_MODEL || first.id } : {}) };
261
+ }
262
+ async function probeAmrCatalog(context, configuration, deps, signal) {
263
+ // Every ACP def uses this category. Vela's documented list command remains a fallback
264
+ // when its ACP version omits the model catalog; launch still confirms explicit selection.
265
+ try {
266
+ return await probeAmrAcp(context, deps, signal);
245
267
  }
268
+ catch (error) {
269
+ if (signal.aborted)
270
+ throw error;
271
+ }
272
+ return probeAmrList(context, configuration, deps, signal);
273
+ }
274
+ export async function probeAgentCatalog(agentId, context, configuration, deps, signal) {
275
+ const acpArgs = ACP_ARGS[agentId];
276
+ // UNVERIFIED installed ACP agents: existing declared commands; metadata preserves native defaults.
277
+ if (acpArgs && agentId !== 'amr')
278
+ return probeAcpMetadata(context, acpArgs, deps, signal);
279
+ const probe = AGENT_PROBES.get(agentId);
280
+ if (probe)
281
+ return probe(agentId, context, deps, signal);
282
+ if (configuration.args)
283
+ return probeDeclaredListing(agentId, context, configuration, deps, signal);
284
+ if (agentId === 'amr')
285
+ return probeAmrCatalog(context, configuration, deps, signal);
246
286
  const args = CLI_ARGS[agentId];
247
287
  if (!args)
248
288
  throw new ModelProbeError('unsupported-version');
@@ -287,8 +327,8 @@ function runProcess(input) {
287
327
  if (tree) {
288
328
  input.signal.addEventListener('abort', killTree, { once: true });
289
329
  treeTimer = setTimeout(killTree, input.timeoutMs);
290
- if (input.signal.aborted)
291
- killTree();
330
+ // No already-aborted check here: the probe scheduler refuses a cancelled signal immediately
331
+ // before running this executor, and nothing between that check and this line yields.
292
332
  }
293
333
  if (input.complete)
294
334
  child.stdout?.on('data', (chunk) => {
@@ -302,21 +342,49 @@ function runProcess(input) {
302
342
  child.stdin?.end(input.stdin);
303
343
  }) }, { signal: input.signal });
304
344
  }
305
- /** Load the catalog owner only for a default URL, so importing the runtime never needs this peer.
306
- * @param required - The vendor whose default endpoint is needed.
307
- * @returns The catalog-owned base URL; explicit host URLs bypass this lookup.
308
- * @throws An actionable load error retaining the original import failure as its cause.
309
- * @complexity O(1) lookup after Node's cached module load.
310
- */
311
- async function defaultProviderBaseUrl({ provider }, _optional = {}) {
345
+ const importProviderCatalog = () => import('@jini-ai/integrations/media-providers/catalog');
346
+ async function defaultProviderBaseUrl({ provider }, { importCatalog = importProviderCatalog } = {}) {
312
347
  try {
313
- const { VENDOR_API_BASE_URLS } = await import('@jini-ai/integrations/media-providers/catalog');
348
+ const { VENDOR_API_BASE_URLS } = await importCatalog();
314
349
  return VENDOR_API_BASE_URLS[provider];
315
350
  }
316
351
  catch (cause) {
317
352
  throw new Error('Could not load @jini-ai/integrations/media-providers/catalog. Install the optional peer @jini-ai/integrations or inject ModelDiscoveryDeps.credential to discover models with default provider URLs.', { cause });
318
353
  }
319
354
  }
355
+ /** First matching rule with its key present wins; a match without a key falls through to the next rule. */
356
+ const ENV_CONNECTIONS = [
357
+ { protocol: 'anthropic', provider: 'anthropic', key: 'ANTHROPIC_API_KEY', matches: (selected) => /^(anthropic\/|claude-)/.test(selected), baseUrl: (env) => env.ANTHROPIC_BASE_URL },
358
+ { protocol: 'google', provider: 'google', key: 'GEMINI_API_KEY', matches: (selected) => /^(gemini\/|google\/|gemini-)/.test(selected), baseUrl: () => undefined },
359
+ { protocol: 'openai', provider: 'openrouter', key: 'OPENROUTER_API_KEY', matches: (selected) => /^openrouter\//.test(selected), baseUrl: (env) => env.OPENROUTER_API_BASE },
360
+ { protocol: 'openai', provider: 'openai', key: 'OPENAI_API_KEY',
361
+ matches: (selected, agentId, env) => /^(openai\/|gpt-|o\d)/.test(selected) || agentId === 'qwen' && Boolean(env.OPENAI_MODEL || env.OPENAI_BASE_URL),
362
+ baseUrl: (env) => env.OPENAI_BASE_URL || env.OPENAI_API_BASE },
363
+ ];
364
+ async function envConnection(rule, env, importCatalog) {
365
+ return { protocol: rule.protocol, baseUrl: rule.baseUrl(env) || await defaultProviderBaseUrl({ provider: rule.provider }, { importCatalog }), apiKey: env[rule.key] };
366
+ }
367
+ function selectedModelFromEnv(agentId, env) {
368
+ if (agentId === 'aider')
369
+ return env.AIDER_MODEL;
370
+ return agentId === 'qwen' ? env.QWEN_MODEL || env.OPENAI_MODEL : undefined;
371
+ }
372
+ /** The env-backed credential port. `importCatalog` loads the optional provider-catalog peer for
373
+ * default base URLs; injectable so a missing peer is testable without uninstalling it. */
374
+ export function createEnvCredentialPort(_required = {}, { importCatalog = importProviderCatalog } = {}) {
375
+ return { async connection({ agentId, context }) {
376
+ // Deliberately do not steal tokens from another CLI's store. Hosts can inject keychain/OAuth
377
+ // handles. BYOK env is usable only when it identifies this CLI's effective provider.
378
+ const env = context.env;
379
+ if (agentId === 'claude' && env.ANTHROPIC_API_KEY)
380
+ return envConnection(ENV_CONNECTIONS[0], env, importCatalog);
381
+ const selected = context.model || selectedModelFromEnv(agentId, env);
382
+ if (!selected)
383
+ return null;
384
+ const rule = ENV_CONNECTIONS.find((candidate) => candidate.matches(selected, agentId, env) && env[candidate.key]);
385
+ return rule ? envConnection(rule, env, importCatalog) : null;
386
+ } };
387
+ }
320
388
  export const defaultModelDiscoveryDeps = {
321
389
  process: { run: runProcess },
322
390
  fs: {
@@ -335,25 +403,7 @@ export const defaultModelDiscoveryDeps = {
335
403
  },
336
404
  },
337
405
  http: { list: (input) => { const { protocol, baseUrl, apiKey, ...optional } = input; return listProviderModels({ protocol, baseUrl, apiKey }, optional); } },
338
- credential: { async connection({ agentId, context }) {
339
- // Deliberately do not steal tokens from another CLI's store. Hosts can inject keychain/OAuth
340
- // handles. BYOK env is usable only when it identifies this CLI's effective provider.
341
- const env = context.env;
342
- if (agentId === 'claude' && env.ANTHROPIC_API_KEY)
343
- return { protocol: 'anthropic', baseUrl: env.ANTHROPIC_BASE_URL || await defaultProviderBaseUrl({ provider: 'anthropic' }), apiKey: env.ANTHROPIC_API_KEY };
344
- const selected = context.model || (agentId === 'aider' ? env.AIDER_MODEL : agentId === 'qwen' ? env.QWEN_MODEL || env.OPENAI_MODEL : undefined);
345
- if (!selected)
346
- return null;
347
- if (/^(anthropic\/|claude-)/.test(selected) && env.ANTHROPIC_API_KEY)
348
- return { protocol: 'anthropic', baseUrl: env.ANTHROPIC_BASE_URL || await defaultProviderBaseUrl({ provider: 'anthropic' }), apiKey: env.ANTHROPIC_API_KEY };
349
- if (/^(gemini\/|google\/|gemini-)/.test(selected) && env.GEMINI_API_KEY)
350
- return { protocol: 'google', baseUrl: await defaultProviderBaseUrl({ provider: 'google' }), apiKey: env.GEMINI_API_KEY };
351
- if (/^openrouter\//.test(selected) && env.OPENROUTER_API_KEY)
352
- return { protocol: 'openai', baseUrl: env.OPENROUTER_API_BASE || await defaultProviderBaseUrl({ provider: 'openrouter' }), apiKey: env.OPENROUTER_API_KEY };
353
- if ((/^(openai\/|gpt-|o\d)/.test(selected) || agentId === 'qwen' && (env.OPENAI_MODEL || env.OPENAI_BASE_URL)) && env.OPENAI_API_KEY)
354
- return { protocol: 'openai', baseUrl: env.OPENAI_BASE_URL || env.OPENAI_API_BASE || await defaultProviderBaseUrl({ provider: 'openai' }), apiKey: env.OPENAI_API_KEY };
355
- return null;
356
- } },
406
+ credential: createEnvCredentialPort(),
357
407
  acp: createAcpDiscoveryAdapter({ probe: nativeAcpModelProbe }),
358
408
  rpc: { async probe({ agentId, context, signal }) {
359
409
  // UNVERIFIED locally: use official prompt-free SDK interfaces, not invented CLI flags.
@@ -377,33 +427,42 @@ export const defaultModelDiscoveryDeps = {
377
427
  } },
378
428
  clock: { now: Date.now }, cache: defaultRuntimeState.modelCatalog,
379
429
  };
430
+ /** A successful Pi RPC response, or null for events, failures and non-JSON lines. */
431
+ function piRpcResponse(line) {
432
+ let response;
433
+ try {
434
+ response = JSON.parse(line);
435
+ }
436
+ catch {
437
+ return null;
438
+ }
439
+ return response.type === 'response' && response.success ? response : null;
440
+ }
441
+ function piCatalogModels(response) {
442
+ if (response.command !== 'get_available_models' || !Array.isArray(response.data?.models))
443
+ return [];
444
+ return response.data.models.flatMap((raw) => {
445
+ const row = raw;
446
+ return row.provider && row.id ? [{ id: `${row.provider}/${row.id}`, label: row.name || row.id, provider: row.provider, identityKind: modelIdentityKind(row.id) }] : [];
447
+ });
448
+ }
449
+ function piCurrentSelection(response) {
450
+ const model = response.command === 'get_state' ? response.data?.model : undefined;
451
+ return model?.provider && model.id ? `${model.provider}/${model.id}` : undefined;
452
+ }
380
453
  /** Pi's native RPC supplies catalog AND current provider/id without making an inference call. */
381
454
  export function parsePiRpcMetadata(stdout) {
382
455
  const models = [];
383
456
  let defaultSelectionId;
384
- for (const line of stdout.split('\n')) {
385
- let response;
386
- try {
387
- response = JSON.parse(line);
388
- }
389
- catch {
457
+ for (const response of stdout.split('\n').map(piRpcResponse)) {
458
+ if (!response)
390
459
  continue;
391
- }
392
- if (response.type !== 'response' || !response.success)
393
- continue;
394
- if (response.command === 'get_available_models' && Array.isArray(response.data?.models)) {
395
- for (const raw of response.data.models) {
396
- const row = raw;
397
- if (row.provider && row.id)
398
- models.push({ id: `${row.provider}/${row.id}`, label: row.name || row.id, provider: row.provider, identityKind: modelIdentityKind(row.id) });
399
- }
400
- }
401
- if (response.command === 'get_state' && response.data?.model?.provider && response.data.model.id)
402
- defaultSelectionId = `${response.data.model.provider}/${response.data.model.id}`;
460
+ models.push(...piCatalogModels(response));
461
+ defaultSelectionId = piCurrentSelection(response) ?? defaultSelectionId;
403
462
  }
404
463
  if (!models.length)
405
464
  throw new ModelProbeError('malformed-response');
406
- return { models, source: 'rpc', coverage: 'account', ...(defaultSelectionId ? { defaultSelectionId } : {}) };
465
+ return { models, source: 'rpc', coverage: 'account', ...withDefaultSelection(defaultSelectionId) };
407
466
  }
408
467
  /** Stable dependency identity preserves the existing per-host single-probe budget as well as its cache. */
409
468
  export function getRuntimeModelDiscoveryDeps({ state }, _optional = {}) {