@jini-ai/agent-runtime 0.4.11 → 0.4.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/acp-model-probe.d.ts +2 -20
  3. package/dist/agent-protocol/acp/json.js +46 -37
  4. package/dist/agent-protocol/acp/models.js +91 -73
  5. package/dist/agent-protocol/acp/rpc.d.ts +3 -2
  6. package/dist/agent-protocol/acp/rpc.js +3 -2
  7. package/dist/agent-protocol/acp/session-params.d.ts +1 -1
  8. package/dist/agent-protocol/acp/session-params.js +33 -30
  9. package/dist/agent-protocol/acp/session.d.ts +3 -1
  10. package/dist/agent-protocol/acp/session.js +62 -24
  11. package/dist/agent-protocol/acp/updates.js +49 -35
  12. package/dist/agent-protocol/pi-rpc/session.js +3 -1
  13. package/dist/anthropic-live-models.d.ts +12 -4
  14. package/dist/anthropic-live-models.js +0 -0
  15. package/dist/auth.js +84 -91
  16. package/dist/claude-code-models.d.ts +6 -5
  17. package/dist/claude-code-models.js +19 -12
  18. package/dist/claude-segment-usage.d.ts +3 -3
  19. package/dist/claude-segment-usage.js +63 -29
  20. package/dist/claude-stream.js +12 -5
  21. package/dist/copilot-stream.js +42 -50
  22. package/dist/defs/aider.js +3 -4
  23. package/dist/defs/amr.js +52 -61
  24. package/dist/defs/antigravity.d.ts +6 -5
  25. package/dist/defs/antigravity.js +48 -34
  26. package/dist/defs/auggie.d.ts +1 -1
  27. package/dist/defs/claude-compatible-args.d.ts +19 -0
  28. package/dist/defs/claude-compatible-args.js +42 -0
  29. package/dist/defs/claude.d.ts +7 -2
  30. package/dist/defs/claude.js +96 -85
  31. package/dist/defs/cline.d.ts +1 -1
  32. package/dist/defs/codebuddy.d.ts +1 -1
  33. package/dist/defs/codebuddy.js +29 -46
  34. package/dist/defs/codex.d.ts +15 -3
  35. package/dist/defs/codex.js +143 -108
  36. package/dist/defs/cursor-agent.d.ts +9 -7
  37. package/dist/defs/cursor-agent.js +53 -51
  38. package/dist/defs/devin.d.ts +1 -1
  39. package/dist/defs/goose.d.ts +1 -1
  40. package/dist/defs/hermes.d.ts +1 -1
  41. package/dist/defs/kilo.d.ts +1 -1
  42. package/dist/defs/kimi.d.ts +1 -1
  43. package/dist/defs/kiro.d.ts +1 -1
  44. package/dist/defs/opencode.d.ts +5 -4
  45. package/dist/defs/opencode.js +26 -32
  46. package/dist/defs/pi.d.ts +6 -5
  47. package/dist/defs/pi.js +24 -26
  48. package/dist/defs/qoder.d.ts +4 -3
  49. package/dist/defs/qoder.js +25 -25
  50. package/dist/defs/reasonix.d.ts +1 -1
  51. package/dist/defs/shared.d.ts +12 -3
  52. package/dist/defs/shared.js +19 -13
  53. package/dist/defs/trae-cli.d.ts +1 -1
  54. package/dist/defs/vibe.d.ts +1 -1
  55. package/dist/detection.d.ts +13 -20
  56. package/dist/detection.js +129 -111
  57. package/dist/env.js +56 -41
  58. package/dist/executables.js +103 -114
  59. package/dist/index.d.ts +1 -0
  60. package/dist/index.js +1 -0
  61. package/dist/json-event-stream.js +611 -527
  62. package/dist/launch.js +44 -37
  63. package/dist/model-discovery-adapters.d.ts +17 -0
  64. package/dist/model-discovery-adapters.js +223 -164
  65. package/dist/model-discovery-config.js +107 -87
  66. package/dist/model-discovery-sdk.d.ts +16 -2
  67. package/dist/model-discovery-sdk.js +4 -3
  68. package/dist/model-discovery-shared.d.ts +14 -0
  69. package/dist/model-discovery-shared.js +50 -15
  70. package/dist/model-discovery-types.d.ts +2 -0
  71. package/dist/model-discovery.js +219 -117
  72. package/dist/models.d.ts +14 -1
  73. package/dist/models.js +75 -19
  74. package/dist/native-tool-policy.d.ts +29 -0
  75. package/dist/native-tool-policy.js +36 -0
  76. package/dist/opencode-log.js +46 -30
  77. package/dist/paths.d.ts +2 -0
  78. package/dist/paths.js +3 -3
  79. package/dist/providers/aihubmix.js +13 -18
  80. package/dist/providers/anthropic-messages.d.ts +7 -0
  81. package/dist/providers/anthropic-messages.js +45 -21
  82. package/dist/providers/azure-chat.d.ts +5 -0
  83. package/dist/providers/azure-chat.js +13 -5
  84. package/dist/providers/connection-guard.d.ts +2 -45
  85. package/dist/providers/connection-guard.js +11 -10
  86. package/dist/providers/connection-test.d.ts +4 -0
  87. package/dist/providers/connection-test.js +127 -110
  88. package/dist/providers/elevenlabs.js +4 -1
  89. package/dist/providers/google-messages.d.ts +4 -0
  90. package/dist/providers/google-messages.js +48 -23
  91. package/dist/providers/google-schema.js +17 -23
  92. package/dist/providers/model-catalog.js +160 -145
  93. package/dist/providers/oauth-callback-server.js +37 -34
  94. package/dist/providers/oauth-credentials.js +23 -23
  95. package/dist/providers/oauth-tokens.js +16 -24
  96. package/dist/providers/openai-chat.d.ts +42 -0
  97. package/dist/providers/openai-chat.js +80 -10
  98. package/dist/providers/operation-schema.d.ts +25 -0
  99. package/dist/providers/operation-schema.js +226 -0
  100. package/dist/providers/response-text.d.ts +10 -0
  101. package/dist/providers/response-text.js +23 -0
  102. package/dist/providers/tool-turn-types.d.ts +35 -9
  103. package/dist/providers/tool-turn.d.ts +7 -0
  104. package/dist/providers/tool-turn.js +113 -32
  105. package/dist/qoder-stream.js +93 -80
  106. package/dist/registry.d.ts +45 -0
  107. package/dist/registry.js +39 -0
  108. package/dist/runtime-state.d.ts +1 -1
  109. package/dist/types.d.ts +43 -1
  110. package/package.json +16 -7
package/dist/detection.js CHANGED
@@ -25,23 +25,12 @@ import { spawnEnvForAgent } from './env.js';
25
25
  import { probeAgentAuthStatus } from './auth.js';
26
26
  import { noopAmrProfileResolver } from './amr-profile-resolver.js';
27
27
  import { buildAuthDiagnostic, buildExecutableDiagnostic, buildNotInvocableDiagnostic } from './diagnostics.js';
28
- function amrModelScopeFromEnv(env, amrProfileResolver) {
29
- return amrProfileResolver.resolveProfile({ env: env });
30
- }
31
- function withRememberedAmrModels(def, env, modelResult, amrProfileResolver) {
32
- // The old remembered AMR list had no age/launch fingerprint. Scoped snapshots now own
33
- // last-good recovery; never present unscoped remembered rows as live.
34
- void def;
35
- void env;
36
- void amrProfileResolver;
37
- return modelResult;
38
- }
39
- async function fetchModels(def, resolvedBin, env, optional = {}) {
40
- const context = optional.context ?? { executable: resolvedBin, env, cwd: optional.cwd ?? process.cwd(), ...(optional.version !== undefined ? { version: optional.version } : {}) };
41
- const options = { ...(optional.deps ? { deps: optional.deps } : {}), ...(optional.force ? { force: true } : {}) };
28
+ async function fetchModels({ def, resolvedBin, env, deps }, { context, version, force } = {}) {
29
+ const scope = context ?? { executable: resolvedBin, env, cwd: process.cwd(), ...(version !== undefined ? { version } : {}) };
30
+ const options = { deps, ...(force ? { force: true } : {}) };
42
31
  const discovery = modelDiscoveryForDef(def);
43
- const catalog = await discovery.discoverModels({ context }, options);
44
- const defaultModelResolution = await discovery.resolveDefaultModel({ context, catalog }, options);
32
+ const catalog = await discovery.discoverModels({ context: scope }, options);
33
+ const defaultModelResolution = await discovery.resolveDefaultModel({ context: scope, catalog }, options);
45
34
  // Models lists can exceed 1MB (e.g. opencode's OpenRouter catalog); the shared process port
46
35
  // retains the existing 8MB bound. Empty/unusable metadata falls back with explicit provenance,
47
36
  // so a failed CLI never silently empties the picker or labels packaged hints as live.
@@ -83,27 +72,37 @@ async function probeVersionAtPath(def, resolved, env) {
83
72
  return { kind: 'spawned', version };
84
73
  }
85
74
  catch (err) {
86
- const code = err?.code;
87
- if (typeof code === 'string') {
88
- if (code === 'EACCES')
89
- return { kind: 'not-invocable', cause: 'not-executable' };
90
- if (code === 'ENOENT' || code === 'ENOTDIR')
91
- return { kind: 'not-invocable', cause: 'missing-target' };
92
- }
93
- else if (typeof code === 'number' && (code === 126 || code === 127)) {
94
- return { kind: 'not-invocable', cause: code === 126 ? 'not-executable' : 'missing-target' };
95
- }
96
- return { kind: 'spawned', version: null };
75
+ const cause = notInvocableCause(err?.code);
76
+ return cause ? { kind: 'not-invocable', cause } : { kind: 'spawned', version: null };
77
+ }
78
+ }
79
+ /** Classify a spawn rejection's `code`: OS-level string codes and wrapper exit statuses 126/127 mean not invocable. */
80
+ function notInvocableCause(code) {
81
+ switch (code) {
82
+ case 'EACCES':
83
+ case 126:
84
+ return 'not-executable';
85
+ case 'ENOENT':
86
+ case 'ENOTDIR':
87
+ case 127:
88
+ return 'missing-target';
89
+ default:
90
+ return undefined;
97
91
  }
98
92
  }
93
+ function unavailableModels(def) {
94
+ // `fallbackModels` is a required field on `RuntimeAgentDef`, never
95
+ // `undefined` for a well-typed def.
96
+ const catalog = offlineSnapshot('', Date.now(), def.fallbackModels);
97
+ return { models: catalog.models, source: 'fallback', catalog, defaultModelResolution: { status: 'unresolved', reason: 'Agent executable is unavailable.' } };
98
+ }
99
99
  function unavailableAgent(def, diagnostics = []) {
100
+ const fallback = unavailableModels(def);
100
101
  return {
101
102
  ...stripFns(def),
102
- // `fallbackModels` is a required field on `RuntimeAgentDef`, never
103
- // `undefined` for a well-typed def.
104
- models: offlineSnapshot('', Date.now(), def.fallbackModels).models,
105
- modelCatalog: offlineSnapshot('', Date.now(), def.fallbackModels),
106
- defaultModelResolution: { status: 'unresolved', reason: 'Agent executable is unavailable.' },
103
+ models: fallback.models,
104
+ modelCatalog: fallback.catalog,
105
+ defaultModelResolution: fallback.defaultModelResolution,
107
106
  modelsSource: 'fallback',
108
107
  available: false,
109
108
  ...(diagnostics.length > 0 ? { diagnostics } : {}),
@@ -113,13 +112,11 @@ function unavailableAgent(def, diagnostics = []) {
113
112
  // Probe the agent's `--help` once and record which advertised flags the
114
113
  // installed CLI supports, so buildArgs can consult the cache. Extracted
115
114
  // from the main probe so it can run before model discovery. It shares the existing
116
- // capability cache with real launches. Returns the capability map (or null when the
117
- // agent declares no help/capability metadata or the probe failed).
118
- async function probeCapabilities(def, launchPath, env) {
119
- if (!def.helpArgs || !def.capabilityFlags)
120
- return null;
115
+ // capability cache with real launches (`ensureAgentCapabilities` only calls this
116
+ // when the def declares help/capability metadata).
117
+ async function probeCapabilitiesOrEmpty({ helpArgs, capabilityFlags, launchPath, env }) {
121
118
  try {
122
- return await readCapabilities(def.helpArgs, def.capabilityFlags, launchPath, env);
119
+ return await readCapabilities(helpArgs, capabilityFlags, launchPath, env);
123
120
  }
124
121
  catch {
125
122
  // If --help fails, leave caps empty so buildArgs falls back to the
@@ -189,12 +186,8 @@ function derivedReasoningOverride(def, models) {
189
186
  return derived && derived.length > 0 ? { reasoningOptions: derived } : {};
190
187
  }
191
188
  /** The env every probe of one def spawns with — the same env a real run would see. */
192
- function probeEnvForLaunch(def, configuredEnv, launch, options = {}) {
193
- return applyAgentLaunchEnv({ env: spawnEnvForAgent({ agentId: def.id, baseEnv: { ...(options.env ?? process.env), ...(def.env || {}) } }, { configuredEnv: configuredEnv, hooks: {} }), launch: launch }, { appendPathDirs: userToolchainBinDirs({}, options) });
194
- }
195
- function unavailableModels(def) {
196
- const catalog = offlineSnapshot('', Date.now(), def.fallbackModels);
197
- return { models: catalog.models, source: 'fallback', catalog, defaultModelResolution: { status: 'unresolved', reason: 'Agent executable is unavailable.' } };
189
+ function probeEnvForLaunch({ def, configuredEnv, launch, state, env }) {
190
+ return applyAgentLaunchEnv({ env: spawnEnvForAgent({ agentId: def.id, baseEnv: { ...env, ...(def.env || {}) } }, { configuredEnv: configuredEnv, hooks: {} }), launch: launch }, { appendPathDirs: userToolchainBinDirs({}, { state, env }) });
198
191
  }
199
192
  /**
200
193
  * The model half of {@link detectAgents} for ONE def, without the `--version`/`--help`/auth probes:
@@ -208,22 +201,26 @@ function unavailableModels(def) {
208
201
  * `source: 'fallback'` (including when the binary is not found). Never rejects.
209
202
  * @complexity At most one model-listing spawn, bounded by the def's own timeout.
210
203
  */
211
- export async function probeAgentModels({ def }, { configuredEnv = {}, amrProfileResolver = noopAmrProfileResolver, context, deps, force = false, state = defaultRuntimeState, env = process.env } = {}) {
204
+ export async function probeAgentModels({ def }, { configuredEnv = {}, amrProfileResolver = noopAmrProfileResolver, context, version, deps, force = false, state = defaultRuntimeState, env = process.env } = {}) {
205
+ return probeModels({ def, configuredEnv, amrProfileResolver, state, env }, { context, version, deps, force });
206
+ }
207
+ async function probeModels({ def, configuredEnv, amrProfileResolver, state, env }, { context, version, deps, force }) {
212
208
  try {
213
209
  const launch = resolveAgentLaunch({ def: def }, { configuredEnv: configuredEnv, state, env });
214
210
  if (!launch.launchPath)
215
211
  return unavailableModels(def);
216
- const probeEnv = probeEnvForLaunch(def, configuredEnv, launch, { state, env });
217
- const fetched = await fetchModels(def, launch.launchPath, probeEnv, { ...(context ? { context } : {}), deps: deps ?? getRuntimeModelDiscoveryDeps({ state }), force });
218
- const result = withRememberedAmrModels(def, probeEnv, fetched, amrProfileResolver);
219
- rememberDetectedModelList(def, configuredEnv, result.models, amrProfileResolver, { state, env });
220
- return result;
212
+ const probeEnv = probeEnvForLaunch({ def, configuredEnv, launch, state, env });
213
+ const fetched = await fetchModels({ def, resolvedBin: launch.launchPath, env: probeEnv, deps: deps ?? getRuntimeModelDiscoveryDeps({ state }) }, { context, version, force });
214
+ // The old remembered AMR list had no age/launch fingerprint. Scoped snapshots now own
215
+ // last-good recovery; never present unscoped remembered rows as live.
216
+ rememberDetectedModelList({ def, configuredEnv, models: fetched.models, amrProfileResolver }, { state, env });
217
+ return fetched;
221
218
  }
222
219
  catch {
223
220
  return unavailableModels(def);
224
221
  }
225
222
  }
226
- async function probe(def, configuredEnv = {}, amrProfileResolver, options = {}) {
223
+ async function probe(def, configuredEnv, options) {
227
224
  // Detection must probe the exact path the runtime will spawn, not just
228
225
  // the PATH-visible shim. This is load-bearing under nvm/fnm/mise: the
229
226
  // discovered entry is often a `#!/usr/bin/env node` wrapper that is not
@@ -232,47 +229,59 @@ async function probe(def, configuredEnv = {}, amrProfileResolver, options = {})
232
229
  // detection probes the shim but chat/run spawns the native binary, the
233
230
  // UI incorrectly reports "not installed" until the user pins the bin
234
231
  // override by hand even though the real launch path is healthy.
235
- const launch = resolveAgentLaunch({ def: def }, { configuredEnv: configuredEnv, ...(options.state ? { state: options.state } : {}), ...(options.env ? { env: options.env } : {}) });
232
+ const { state, env } = options;
233
+ const launch = resolveAgentLaunch({ def: def }, { configuredEnv: configuredEnv, state, env });
236
234
  if (!launch.selectedPath || !launch.launchPath) {
237
- return unavailableAgent(def, [buildExecutableDiagnostic({ def: def }, { configuredEnv: configuredEnv, ...(options.state ? { state: options.state } : {}), ...(options.env ? { env: options.env } : {}) })]);
235
+ return unavailableAgent(def, [buildExecutableDiagnostic({ def: def }, { configuredEnv: configuredEnv, state, env })]);
238
236
  }
239
- const probeEnv = probeEnvForLaunch(def, configuredEnv, launch, options);
237
+ const probeEnv = probeEnvForLaunch({ def, configuredEnv, launch, state, env });
240
238
  const outcome = await probeVersionAtPath(def, launch.launchPath, probeEnv);
241
239
  if (outcome.kind === 'not-invocable') {
242
240
  return unavailableAgent(def, [buildNotInvocableDiagnostic({ def: def, launch: launch, cause: outcome.cause })]);
243
241
  }
242
+ return probeInvocableAgent({ def, launchPath: launch.launchPath, selectedPath: launch.selectedPath, probeEnv, version: outcome.version }, options);
243
+ }
244
+ /** Drop stale capability evidence (always on force) and re-probe through the shared cache. */
245
+ async function refreshCapabilities({ def, launchPath, probeEnv, state }, { force }) {
246
+ const capabilityKey = `${def.id}\u0000${launchPath}`;
247
+ if (force || !state.capabilityProbes.has(capabilityKey)) {
248
+ state.capabilities.delete(def.id);
249
+ if (force)
250
+ state.capabilityProbes.delete(capabilityKey);
251
+ }
252
+ await ensureAgentCapabilities({ def, launchPath, env: probeEnv }, { state, probe: probeCapabilitiesOrEmpty });
253
+ return state.capabilities.get(def.id);
254
+ }
255
+ async function probeInvocableAgent({ def, launchPath, selectedPath, probeEnv, version }, options) {
244
256
  // The version probe must finish first (it gates availability). Cheap help/auth checks
245
257
  // precede model discovery; the shared process scheduler prevents concurrent CLI startups.
246
258
  // Capability evidence belongs to the existing ensureAgentCapabilities cache, also used by runs.
247
- const runtimeState = options.state ?? defaultRuntimeState;
248
- const capabilityKey = `${def.id}\u0000${launch.launchPath}`;
249
- if (options.force || !runtimeState.capabilityProbes.has(capabilityKey)) {
250
- runtimeState.capabilities.delete(def.id);
251
- if (options.force)
252
- runtimeState.capabilityProbes.delete(capabilityKey);
253
- }
254
- await ensureAgentCapabilities({ def, launchPath: launch.launchPath, env: probeEnv }, { state: runtimeState,
255
- probe: async () => (await probeCapabilities(def, launch.launchPath, probeEnv)) ?? {},
256
- });
257
- const caps = runtimeState.capabilities.get(def.id);
258
- const auth = await probeAgentAuthStatus({ def, resolvedBin: launch.launchPath, env: probeEnv });
259
- const modelResult = await fetchModels(def, launch.launchPath, probeEnv, { version: outcome.version, ...options, deps: options.deps ?? getRuntimeModelDiscoveryDeps({ state: runtimeState }) });
260
- const surfacedModelResult = withRememberedAmrModels(def, probeEnv, modelResult, amrProfileResolver);
259
+ const caps = await refreshCapabilities({ def, launchPath, probeEnv, state: options.state }, { force: options.force === true });
260
+ const auth = await probeAgentAuthStatus({ def, resolvedBin: launchPath, env: probeEnv });
261
+ const fetched = await fetchModels({ def, resolvedBin: launchPath, env: probeEnv, deps: options.deps }, { version, context: options.context, force: options.force });
261
262
  if (caps) {
262
- (options.state ?? defaultRuntimeState).capabilities.set(def.id, caps);
263
+ options.state.capabilities.set(def.id, caps);
263
264
  }
265
+ return availableAgent({ def, selectedPath, version, fetched, auth });
266
+ }
267
+ function authFields(auth) {
268
+ if (!auth)
269
+ return {};
270
+ return { authStatus: auth.status, ...(auth.message ? { authMessage: auth.message } : {}) };
271
+ }
272
+ function availableAgent({ def, selectedPath, version, fetched, auth }) {
264
273
  const authDiagnostic = auth ? buildAuthDiagnostic({ def: def, auth: auth }) : null;
265
274
  return {
266
275
  ...stripFns(def),
267
- ...derivedReasoningOverride(def, surfacedModelResult.models),
268
- models: surfacedModelResult.models,
269
- modelsSource: surfacedModelResult.source,
270
- ...(surfacedModelResult.catalog ? { modelCatalog: surfacedModelResult.catalog } : {}),
271
- ...(surfacedModelResult.defaultModelResolution ? { defaultModelResolution: surfacedModelResult.defaultModelResolution } : {}),
276
+ ...derivedReasoningOverride(def, fetched.models),
277
+ models: fetched.models,
278
+ modelsSource: fetched.source,
279
+ modelCatalog: fetched.catalog,
280
+ defaultModelResolution: fetched.defaultModelResolution,
272
281
  available: true,
273
- path: launch.selectedPath,
274
- version: outcome.version,
275
- ...(auth ? { authStatus: auth.status, ...(auth.message ? { authMessage: auth.message } : {}) } : {}),
282
+ path: selectedPath,
283
+ version,
284
+ ...authFields(auth),
276
285
  ...(authDiagnostic ? { diagnostics: [authDiagnostic] } : {}),
277
286
  ...installMetaForAgent({ agentId: def.id }),
278
287
  };
@@ -299,39 +308,48 @@ function stripFns(def) {
299
308
  const { discoverModels: _discoverModels, resolveDefaultModel: _resolveDefaultModel, buildArgs: _buildArgs, listModels: _listModels, fetchModels: _fetchModels, deriveReasoningOptions: _deriveReasoningOptions, fallbackModels: _fallbackModels, fallbackModelsAssertedAt: _fallbackModelsAssertedAt, helpArgs: _helpArgs, capabilityFlags: _capabilityFlags, fallbackBins: _fallbackBins, versionProbeTimeoutMs: _versionProbeTimeoutMs, maxPromptArgBytes: _maxPromptArgBytes, env: _env, inactivityTimeoutMs: _inactivityTimeoutMs, authProbe: _authProbe, needsAgentLogFile: _needsAgentLogFile, stdoutPolicy: _stdoutPolicy, runtimeLock: _runtimeLock, ...rest } = def;
300
309
  return rest;
301
310
  }
302
- /** Cache complete detection per host and effective launch. No TTL re-spawns version/help/auth.
311
+ /** Cache executable/version/help/auth per host and effective launch; only expired catalogs refresh.
303
312
  * Explicit force queues after the current scan, so a rescan cannot overlap its predecessor.
304
313
  * Hash credentials rather than retaining them in keys. @complexity O(e) launch-env hashing. */
305
- function safeProbe(def, configuredEnv, amrProfileResolver, options = {}) {
306
- const state = options.state ?? defaultRuntimeState;
314
+ function safeProbe(def, configuredEnv, amrProfileResolver, options) {
315
+ const { state } = options;
307
316
  let key;
308
317
  try {
309
- key = detectionCacheKey({ def, configuredEnv, options, state });
318
+ key = detectionCacheKey({ def, configuredEnv, options });
310
319
  }
311
320
  catch {
312
321
  return Promise.resolve(unavailableAgent(def));
313
322
  }
314
323
  const previous = state.detections.get(key);
315
- if (previous && !options.force)
316
- return previous;
317
- const pending = (previous ?? Promise.resolve()).then(() => executeSafeProbe(def, configuredEnv, amrProfileResolver, options));
324
+ const pending = previous && !options.force
325
+ ? previous.then(agent => refreshExpiredCatalog({ def, agent, configuredEnv, amrProfileResolver }, options))
326
+ : (previous ?? Promise.resolve()).then(() => executeSafeProbe(def, configuredEnv, amrProfileResolver, options));
318
327
  state.detections.set(key, pending);
319
328
  return pending;
320
329
  }
330
+ /** A cached detection, with its model catalog re-probed once that catalog has expired. */
331
+ async function refreshExpiredCatalog({ def, agent, configuredEnv, amrProfileResolver }, options) {
332
+ const now = options.deps.clock.now();
333
+ if (!agent.available || !agent.modelCatalog || Date.parse(agent.modelCatalog.expiresAt) > now)
334
+ return agent;
335
+ // Reuse the model-only probe with the detected version so the launch fingerprint stays stable.
336
+ const result = await probeModels({ def, configuredEnv, amrProfileResolver, state: options.state, env: options.env }, { context: options.context, version: agent.version, deps: options.deps, force: options.force });
337
+ return { ...agent, ...derivedReasoningOverride(def, result.models), models: result.models, modelsSource: result.source,
338
+ modelCatalog: result.catalog, defaultModelResolution: result.defaultModelResolution };
339
+ }
321
340
  /** Effective launch material is hashed, so cache keys never expose credentials.
322
341
  * Legacy remembered-model profile resolution must not gate executable availability. */
323
- function detectionCacheKey({ def, configuredEnv, options, state }, _options = {}) {
324
- const launch = resolveAgentLaunch({ def }, { configuredEnv, state, ...(options.env ? { env: options.env } : {}) });
325
- const env = options.env ?? process.env;
342
+ function detectionCacheKey({ def, configuredEnv, options }, _options = {}) {
343
+ const launch = resolveAgentLaunch({ def }, { configuredEnv, state: options.state, env: options.env });
326
344
  return createHash('sha256').update(JSON.stringify({ id: def.id, path: launch.launchPath,
327
- env: Object.entries(env).sort(([a], [b]) => a.localeCompare(b)), configuredEnv,
345
+ env: Object.entries(options.env).sort(([a], [b]) => a.localeCompare(b)), configuredEnv,
328
346
  context: options.context })).digest('hex');
329
347
  }
330
- async function executeSafeProbe(def, configuredEnv = {}, amrProfileResolver, options = {}) {
348
+ async function executeSafeProbe(def, configuredEnv, amrProfileResolver, options) {
331
349
  try {
332
350
  if (options.probeAgent)
333
351
  return await options.probeAgent({ def, configuredEnv, amrProfileResolver }, options);
334
- return await probe(def, configuredEnv, amrProfileResolver, options);
352
+ return await probe(def, configuredEnv, options);
335
353
  }
336
354
  catch {
337
355
  // Fault isolation: one adapter's probe blowing up — e.g. a
@@ -341,30 +359,32 @@ async function executeSafeProbe(def, configuredEnv = {}, amrProfileResolver, opt
341
359
  return unavailableAgent(def);
342
360
  }
343
361
  }
344
- function rememberDetectedLiveModels(def, configuredEnv, agent, amrProfileResolver, options = {}) {
345
- rememberDetectedModelList(def, configuredEnv, agent.models, amrProfileResolver, options);
346
- }
347
- function rememberDetectedModelList(def, configuredEnv, models, amrProfileResolver, options = {}) {
362
+ function rememberDetectedModelList({ def, configuredEnv, models, amrProfileResolver }, { state, env }) {
348
363
  if (def.id === 'amr' && models.length === 0)
349
364
  return;
350
365
  const scope = def.id === 'amr'
351
- ? amrModelScopeFromEnv({ ...(options.env ?? process.env), ...(def.env || {}), ...configuredEnv }, amrProfileResolver)
366
+ ? amrProfileResolver.resolveProfile({ env: { ...env, ...(def.env || {}), ...configuredEnv } })
352
367
  : null;
353
- rememberLiveModels({ agentId: def.id, models: models.filter((row) => row.identityKind !== 'routing-mode') }, { scope: scope, ...(options.state ? { state: options.state } : {}) });
368
+ rememberLiveModels({ agentId: def.id, models: models.filter((row) => row.identityKind !== 'routing-mode') }, { scope: scope, state });
354
369
  }
355
- export async function detectAgents({}, { configuredEnvByAgent = {}, amrProfileResolver = noopAmrProfileResolver, modelContextByAgent = {}, modelDiscoveryDeps, force = false, state = defaultRuntimeState, env = process.env, probeAgent } = {}) {
356
- const results = await Promise.all(AGENT_DEFS.map((def) => safeProbe(def, configuredEnvByAgent?.[def.id] ?? {}, amrProfileResolver, { ...(modelContextByAgent[def.id] ? { context: modelContextByAgent[def.id] } : {}), deps: modelDiscoveryDeps ?? getRuntimeModelDiscoveryDeps({ state }), force, state, env, ...(probeAgent ? { probeAgent } : {}) })));
370
+ function detectionSettings({ configuredEnvByAgent = {}, amrProfileResolver = noopAmrProfileResolver, modelContextByAgent = {}, modelDiscoveryDeps, force = false, state = defaultRuntimeState, env = process.env, probeAgent }) {
371
+ return { configuredEnvByAgent, amrProfileResolver, modelContextByAgent,
372
+ base: { deps: modelDiscoveryDeps ?? getRuntimeModelDiscoveryDeps({ state }), force, state, env, ...(probeAgent ? { probeAgent } : {}) } };
373
+ }
374
+ /** Probe one def with the shared settings, refreshing the model-validation cache from the result. */
375
+ async function detectOne(def, { configuredEnvByAgent, amrProfileResolver, modelContextByAgent, base }) {
376
+ const configuredEnv = configuredEnvByAgent[def.id] ?? {};
377
+ const context = modelContextByAgent[def.id];
378
+ const agent = await safeProbe(def, configuredEnv, amrProfileResolver, { ...(context ? { context } : {}), ...base });
357
379
  // Refresh the validation cache from whatever we just surfaced to the UI
358
380
  // so a chat endpoint can accept any model the user could have just
359
381
  // picked, including ones that only showed up after a CLI re-auth.
360
- for (const [index, agent] of results.entries()) {
361
- // `results` is `AGENT_DEFS.map(...)`, so every index in `results.entries()`
362
- // is in-bounds for `AGENT_DEFS` too — the assertion just satisfies
363
- // `noUncheckedIndexedAccess`.
364
- const def = AGENT_DEFS[index];
365
- rememberDetectedLiveModels(def, configuredEnvByAgent?.[def.id] ?? {}, agent, amrProfileResolver, { state, env });
366
- }
367
- return results;
382
+ rememberDetectedModelList({ def, configuredEnv, models: agent.models, amrProfileResolver }, { state: base.state, env: base.env });
383
+ return agent;
384
+ }
385
+ export async function detectAgents({}, optional = {}) {
386
+ const settings = detectionSettings(optional);
387
+ return Promise.all(AGENT_DEFS.map((def) => detectOne(def, settings)));
368
388
  }
369
389
  // Streaming variant: yields each agent the moment its probe settles, in
370
390
  // completion order rather than registry order, so the UI can paint a card
@@ -372,11 +392,9 @@ export async function detectAgents({}, { configuredEnvByAgent = {}, amrProfileRe
372
392
  // validation cache is refreshed per-agent (same effect as the batch path,
373
393
  // just incrementally). `detectAgents` keeps the array contract for callers
374
394
  // that don't care about incremental delivery.
375
- export async function* detectAgentsStream({}, { configuredEnvByAgent = {}, amrProfileResolver = noopAmrProfileResolver, modelContextByAgent = {}, modelDiscoveryDeps, force = false, state = defaultRuntimeState, env = process.env, probeAgent } = {}) {
376
- const tagged = AGENT_DEFS.map((def, index) => safeProbe(def, configuredEnvByAgent?.[def.id] ?? {}, amrProfileResolver, { ...(modelContextByAgent[def.id] ? { context: modelContextByAgent[def.id] } : {}), deps: modelDiscoveryDeps ?? getRuntimeModelDiscoveryDeps({ state }), force, state, env, ...(probeAgent ? { probeAgent } : {}) }).then((agent) => {
377
- rememberDetectedLiveModels(def, configuredEnvByAgent?.[def.id] ?? {}, agent, amrProfileResolver, { state, env });
378
- return { index, agent };
379
- }));
395
+ export async function* detectAgentsStream({}, optional = {}) {
396
+ const settings = detectionSettings(optional);
397
+ const tagged = AGENT_DEFS.map((def, index) => detectOne(def, settings).then((agent) => ({ index, agent })));
380
398
  const pending = new Set(tagged.keys());
381
399
  while (pending.size > 0) {
382
400
  const { index, agent } = await Promise.race(tagged.filter((_, i) => pending.has(i)));
package/dist/env.js CHANGED
@@ -17,50 +17,65 @@ function stripKeysCaseInsensitive(env, keysToStrip) {
17
17
  delete env[key];
18
18
  }
19
19
  }
20
- export function spawnEnvForAgent({ agentId, baseEnv }, { configuredEnv = {}, systemProxyEnv = resolveSystemProxyEnv(), hooks = {} } = {}) {
21
- const expandedConfiguredEnv = expandConfiguredEnv({ configuredEnv: configuredEnv });
22
- const env = mergeProxyAwareEnv(process.platform, systemProxyEnv, baseEnv, expandedConfiguredEnv);
23
- if (agentId === 'amr') {
24
- // `execAgentFile` REPLACES the child environment (execFile with `env`
25
- // set), so anything missing here is genuinely absent for the AMR CLI.
26
- // `vela model list` resolves its config home up front and exits
27
- // non-zero with "$HOME is not defined" when HOME is unset. Backfill
28
- // HOME from the OS so the authoritative catalog call is never silently
29
- // decapitated by a missing home dir.
30
- if (!env.HOME?.trim()) {
31
- const home = os.homedir();
32
- if (home)
33
- env.HOME = home;
34
- }
35
- if (!env.VELA_OPENCODE_BIN?.trim()) {
36
- const opencodeBin = resolveAmrOpenCodeExecutable({}, { env: env });
37
- if (opencodeBin)
38
- env.VELA_OPENCODE_BIN = opencodeBin;
39
- }
20
+ /**
21
+ * AMR housekeeping. `execAgentFile` REPLACES the child environment (execFile with `env`
22
+ * set), so anything missing here is genuinely absent for the AMR CLI.
23
+ */
24
+ function backfillAmrEnv({ env }) {
25
+ // `vela model list` resolves its config home up front and exits
26
+ // non-zero with "$HOME is not defined" when HOME is unset. Backfill
27
+ // HOME from the OS so the authoritative catalog call is never silently
28
+ // decapitated by a missing home dir.
29
+ if (!env.HOME?.trim()) {
30
+ const home = os.homedir();
31
+ if (home)
32
+ env.HOME = home;
33
+ }
34
+ if (!env.VELA_OPENCODE_BIN?.trim()) {
35
+ const opencodeBin = resolveAmrOpenCodeExecutable({}, { env: env });
36
+ if (opencodeBin)
37
+ env.VELA_OPENCODE_BIN = opencodeBin;
40
38
  }
41
- if (agentId === 'opencode') {
42
- stripKeysCaseInsensitive(env, ['OPENCODE', 'OPENCODE_PID', 'OPENCODE_RUN_ID', 'OPENCODE_SERVER_PASSWORD']);
43
- // OpenCode is bun-based and, left to its defaults, walks up from its
44
- // cwd to the nearest project root and runs `bun install` there at
45
- // startup to set up local plugins. When that root is a pnpm workspace
46
- // (the host's own repo, or a project nested inside it), the install
47
- // replaces the pnpm `.pnpm` store with a bun `node_modules/.bun` +
48
- // `bun.lock` and breaks the workspace. Disable project-config
49
- // discovery (and its install) so OpenCode only honors the config
50
- // injected via `OPENCODE_CONFIG_CONTENT`.
51
- if (!env.OPENCODE_DISABLE_PROJECT_CONFIG?.trim()) {
52
- env.OPENCODE_DISABLE_PROJECT_CONFIG = 'true';
53
- }
39
+ }
40
+ /**
41
+ * Strip the parent's server-identity keys and force project-config discovery off unless the
42
+ * caller already set the disable flag to a non-blank value.
43
+ */
44
+ function isolateProjectConfig({ env, identityKeys, disableKey }) {
45
+ stripKeysCaseInsensitive(env, identityKeys);
46
+ if (!env[disableKey]?.trim()) {
47
+ env[disableKey] = 'true';
54
48
  }
55
- if (agentId === 'mimo') {
56
- stripKeysCaseInsensitive(env, ['MIMOCODE', 'MIMOCODE_PID', 'MIMOCODE_RUN_ID', 'MIMOCODE_SERVER_PASSWORD']);
57
- // MiMo builds on the same toolchain as OpenCode and has the same
58
- // workspace-corruption risk. Disable project-config discovery so MiMo
59
- // only honors the config injected through `MIMOCODE_CONFIG_CONTENT`.
60
- if (!env.MIMOCODE_DISABLE_PROJECT_CONFIG?.trim()) {
61
- env.MIMOCODE_DISABLE_PROJECT_CONFIG = 'true';
62
- }
49
+ }
50
+ /** Built-in per-agent housekeeping, applied before the host's `perAgentEnv` hook. */
51
+ function applyAgentHousekeeping({ env, agentId }) {
52
+ switch (agentId) {
53
+ case 'amr':
54
+ backfillAmrEnv({ env });
55
+ return;
56
+ case 'opencode':
57
+ // OpenCode is bun-based and, left to its defaults, walks up from its
58
+ // cwd to the nearest project root and runs `bun install` there at
59
+ // startup to set up local plugins. When that root is a pnpm workspace
60
+ // (the host's own repo, or a project nested inside it), the install
61
+ // replaces the pnpm `.pnpm` store with a bun `node_modules/.bun` +
62
+ // `bun.lock` and breaks the workspace. Disable project-config
63
+ // discovery (and its install) so OpenCode only honors the config
64
+ // injected via `OPENCODE_CONFIG_CONTENT`.
65
+ isolateProjectConfig({ env, identityKeys: ['OPENCODE', 'OPENCODE_PID', 'OPENCODE_RUN_ID', 'OPENCODE_SERVER_PASSWORD'], disableKey: 'OPENCODE_DISABLE_PROJECT_CONFIG' });
66
+ return;
67
+ case 'mimo':
68
+ // MiMo builds on the same toolchain as OpenCode and has the same
69
+ // workspace-corruption risk. Disable project-config discovery so MiMo
70
+ // only honors the config injected through `MIMOCODE_CONFIG_CONTENT`.
71
+ isolateProjectConfig({ env, identityKeys: ['MIMOCODE', 'MIMOCODE_PID', 'MIMOCODE_RUN_ID', 'MIMOCODE_SERVER_PASSWORD'], disableKey: 'MIMOCODE_DISABLE_PROJECT_CONFIG' });
72
+ return;
63
73
  }
74
+ }
75
+ export function spawnEnvForAgent({ agentId, baseEnv }, { configuredEnv = {}, systemProxyEnv = resolveSystemProxyEnv(), hooks = {} } = {}) {
76
+ const expandedConfiguredEnv = expandConfiguredEnv({ configuredEnv: configuredEnv });
77
+ const env = mergeProxyAwareEnv(process.platform, systemProxyEnv, baseEnv, expandedConfiguredEnv);
78
+ applyAgentHousekeeping({ env, agentId });
64
79
  const perAgentOverrides = hooks.perAgentEnv?.({ agentId: agentId, env: env });
65
80
  if (perAgentOverrides)
66
81
  Object.assign(env, perAgentOverrides);