@jini-ai/agent-runtime 0.4.10 → 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 (112) hide show
  1. package/CHANGELOG.md +9 -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 +7 -0
  90. package/dist/providers/google-messages.js +69 -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
  111. package/dist/defs/gemini.d.ts +0 -24
  112. package/dist/defs/gemini.js +0 -81
@@ -5,6 +5,12 @@ export { ModelProbeError, modelIdentityKind, normalizeDiscoveredModels, withMode
5
5
  export const MODEL_CATALOG_TTL_MS = 15 * 60_000;
6
6
  export const MODEL_NEGATIVE_TTL_MS = 30_000;
7
7
  const MAX_CATALOG_SCOPES = 128;
8
+ /** CLIs that keep their own on-disk model catalog a fresh host can read before probing. */
9
+ const DISK_CATALOG_AGENTS = ['codex', 'opencode', 'claude', 'codebuddy'];
10
+ /** Agents whose config-file selection outranks native rpc default metadata. */
11
+ const CONFIG_FIRST_AGENTS = ['claude', 'codebuddy'];
12
+ const NO_CONCRETE_EVIDENCE = 'The configured selection has no concrete model evidence.';
13
+ const RESUMED_MODEL_REQUIRED = { status: 'unresolved', reason: 'Resumed session model metadata is required.' };
8
14
  /** Hash all launch-affecting state, including env credentials; none of the raw material escapes. */
9
15
  export function modelLaunchFingerprint(context, configMaterial = '') {
10
16
  return createHash('sha256').update(JSON.stringify({ ...context, env: Object.entries(context.env).sort(([a], [b]) => a.localeCompare(b)), configMaterial })).digest('hex');
@@ -41,97 +47,200 @@ async function boundedProbe(deps, work, signal) {
41
47
  pool.active -= 1;
42
48
  }
43
49
  }
50
+ const DIAGNOSTIC_MESSAGES = {
51
+ timeout: 'Model discovery timed out or was cancelled.',
52
+ 'auth-missing': 'CLI credentials are unavailable.',
53
+ 'unsupported-version': 'Native metadata discovery is unavailable for this version.',
54
+ 'malformed-response': 'Native metadata contained no usable catalog.',
55
+ offline: 'Model discovery could not reach its source.',
56
+ };
44
57
  function diagnostic(error) {
45
58
  // Never stringify vendor errors: stderr/HTTP bodies may include credentials or OAuth URLs.
46
59
  const code = error instanceof ProbeTimeout ? 'timeout' : error instanceof ModelProbeError ? error.code : 'offline';
47
- return { code, message: ({ timeout: 'Model discovery timed out or was cancelled.', 'auth-missing': 'CLI credentials are unavailable.', 'unsupported-version': 'Native metadata discovery is unavailable for this version.', 'malformed-response': 'Native metadata contained no usable catalog.', offline: 'Model discovery could not reach its source.' })[code] };
60
+ return { code, message: DIAGNOSTIC_MESSAGES[code] };
61
+ }
62
+ function isUnexpired(snapshot, now) {
63
+ return Date.parse(snapshot.expiresAt) > now;
64
+ }
65
+ /** What a stale-while-revalidate caller may see: a recorded failure, else the last good catalog aged to `stale` once expired. */
66
+ function lastGoodSnapshot(cached, now) {
67
+ if (cached.failed)
68
+ return cached.failed;
69
+ if (!cached.good)
70
+ return undefined;
71
+ return { ...cached.good, freshness: isUnexpired(cached.good, now) ? cached.good.freshness : 'stale' };
72
+ }
73
+ /** A cached catalog that needs no refresh: the cooling-down failure, else an unexpired good catalog. */
74
+ function settledAnswer(cached, now, { staleWhileRevalidate }) {
75
+ if (cached.retryAt && cached.retryAt > now && cached.failed)
76
+ return cached.failed;
77
+ if (staleWhileRevalidate || cached.failed || !cached.good)
78
+ return undefined;
79
+ return isUnexpired(cached.good, now) ? cached.good : undefined;
80
+ }
81
+ /** Answer from the scope's cache entry, or undefined when a refresh must start. */
82
+ function cachedAnswer({ cached, now }, { force, staleWhileRevalidate }) {
83
+ if (cached.pending)
84
+ return (staleWhileRevalidate && lastGoodSnapshot(cached, now)) || cached.pending;
85
+ return force ? undefined : settledAnswer(cached, now, { staleWhileRevalidate });
86
+ }
87
+ /** Native default metadata outranks a config guess (Grok can route despite its TOML). */
88
+ function pickSelection({ agentId, context, configSelection, result }) {
89
+ if (context.model)
90
+ return context.model;
91
+ const nativeWins = result.source === 'rpc' && !CONFIG_FIRST_AGENTS.includes(agentId) || agentId === 'grok-build';
92
+ return nativeWins ? result.defaultSelectionId || configSelection : configSelection || result.defaultSelectionId;
93
+ }
94
+ function liveSnapshot({ models, result, fingerprint, selection, fetched }) {
95
+ // Disk fallbacks must let inventory readers retry live discovery after the failure cooldown.
96
+ const fromDisk = result.source === 'cli-cache';
97
+ const ttl = fromDisk ? MODEL_NEGATIVE_TTL_MS : MODEL_CATALOG_TTL_MS;
98
+ return { models, source: result.source, coverage: result.coverage,
99
+ fetchedAt: new Date(fetched).toISOString(), expiresAt: new Date(fetched + ttl).toISOString(),
100
+ freshness: fromDisk ? 'stale' : 'fresh', launchFingerprint: fingerprint, diagnostics: [],
101
+ ...(selection ? { defaultSelectionId: selection } : {}) };
102
+ }
103
+ /** Evict settled scopes first; coalesced callers must retain their in-flight entry. */
104
+ function evictSettledScopes(cache) {
105
+ for (const [oldKey, entry] of cache) {
106
+ if (cache.size <= MAX_CATALOG_SCOPES)
107
+ break;
108
+ if (!entry.pending)
109
+ cache.delete(oldKey);
110
+ }
111
+ }
112
+ function missingResumedModel(context) {
113
+ return Boolean(context.resumeSessionId && !context.resumedModelId && !context.model);
114
+ }
115
+ function findRow(models, selection) {
116
+ return models.find((model) => model.id === selection || model.label === selection);
117
+ }
118
+ /** The launch ID a catalog row vouches for: its resolved ID, or its own ID when concrete. */
119
+ function rowEvidence(row) {
120
+ return row?.resolvedId || (row?.identityKind === 'concrete' ? row.id : undefined);
121
+ }
122
+ function isConcreteId(id) {
123
+ return Boolean(id) && modelIdentityKind(id) === 'concrete';
124
+ }
125
+ function catalogSelection({ context, catalog, configSelection }) {
126
+ return context.model || context.resumedModelId || catalog.defaultSelectionId || configSelection;
127
+ }
128
+ /** Offline hints carry no alias metadata, so only an exact ID match is trustworthy. */
129
+ function isOfflineLabelMatch({ catalog, row, selection }) {
130
+ return catalog.freshness === 'offline-fallback' && row !== undefined && row.id !== selection;
131
+ }
132
+ /** Resolve a scoped catalog's selection to concrete launch evidence. Pure. */
133
+ function resolveFromCatalog({ context, catalog, configSelection, fingerprint, resolvedAt }) {
134
+ if (missingResumedModel(context))
135
+ return RESUMED_MODEL_REQUIRED;
136
+ const selection = catalogSelection({ context, catalog, configSelection });
137
+ if (!selection)
138
+ return { status: 'unresolved', reason: 'Native metadata did not resolve a default; pick a concrete model.' };
139
+ const row = findRow(catalog.models, selection);
140
+ if (isOfflineLabelMatch({ catalog, row, selection }))
141
+ return { status: 'unresolved', selectionId: selection, reason: 'Offline hints cannot resolve a display name or alias.' };
142
+ const id = rowEvidence(row);
143
+ if (!isConcreteId(id))
144
+ return { status: 'unresolved', selectionId: selection, reason: NO_CONCRETE_EVIDENCE };
145
+ return { status: 'resolved', id, selectionId: selection, source: configSelection === selection ? 'config-file' : catalog.source, resolvedAt, launchFingerprint: fingerprint };
48
146
  }
49
147
  /** Bind supplied effect ports and probes without loading their native implementations. */
50
148
  export function createAgentModelDiscovery({ agentId, configuration, deps: suppliedDeps, probes }, _optional = {}) {
51
149
  async function scoped(context, deps, signal) {
52
150
  const config = await withModelProbeTimeout((active) => readModelConfiguration(agentId, context, deps, active), 1000, signal);
53
- return { config, key: `${agentId}:${modelLaunchFingerprint(context, config.fingerprintMaterial)}` };
151
+ const key = `${agentId}:${modelLaunchFingerprint(context, config.fingerprintMaterial)}`;
152
+ return { config, key, fingerprint: key.slice(agentId.length + 1) };
153
+ }
154
+ async function readDiskCatalog({ context, deps, signal, fingerprint, config, now }) {
155
+ try {
156
+ const disk = await withModelProbeTimeout(active => probes.cliCache({ agentId, context, deps, signal: active }), 1000, signal);
157
+ const models = normalizeDiscoveredModels(disk.models);
158
+ if (!models.length)
159
+ return undefined;
160
+ return { models, source: 'cli-cache', coverage: disk.coverage,
161
+ freshness: 'stale', fetchedAt: new Date(now).toISOString(), expiresAt: new Date(now).toISOString(),
162
+ launchFingerprint: fingerprint, diagnostics: [],
163
+ ...(config.selection ? { defaultSelectionId: config.selection } : {}) };
164
+ }
165
+ catch { /* No usable disk cache: keep the bounded cold-probe path below. */
166
+ return undefined;
167
+ }
168
+ }
169
+ /** A fresh host process may still have a CLI-owned disk catalog. Use its observed rows
170
+ * immediately; keep stale provenance and refresh without holding the first user prompt.
171
+ * Returns a concurrent caller's answer when one started refreshing during the read. */
172
+ async function primeFromDisk(scope) {
173
+ const disk = await readDiskCatalog(scope);
174
+ if (disk)
175
+ scope.cached.good = disk;
176
+ // Another caller may have started the refresh while disk metadata was read.
177
+ const concurrent = scope.deps.cache.get(scope.key);
178
+ return concurrent?.pending ? concurrent.failed || concurrent.good || concurrent.pending : undefined;
179
+ }
180
+ function failureSnapshot({ cached, deps, fingerprint }, error) {
181
+ const retryAt = cached.retryAt;
182
+ // Outer inventory caches must retry failed refreshes on the negative lifetime too.
183
+ if (cached.good)
184
+ return { ...cached.good, freshness: 'stale', expiresAt: new Date(retryAt).toISOString(), diagnostics: [diagnostic(error)] };
185
+ return offlineSnapshot(fingerprint, deps.clock.now(), configuration.fallbackModels(), diagnostic(error));
186
+ }
187
+ async function probeAndStore(scope) {
188
+ const { context, deps, signal, cached } = scope;
189
+ const result = await boundedProbe(deps, () => withModelProbeTimeout((active) => probes.catalog({ agentId, context, configuration, deps, signal: active }), probes.timeoutMs({ agentId }), signal), signal);
190
+ const models = normalizeDiscoveredModels(result.models);
191
+ if (models.length === 0)
192
+ throw new ModelProbeError('malformed-response');
193
+ const selection = pickSelection({ agentId, context, configSelection: scope.config.selection, result });
194
+ const snapshot = liveSnapshot({ models, result, fingerprint: scope.fingerprint, selection, fetched: deps.clock.now() });
195
+ cached.good = snapshot;
196
+ delete cached.retryAt;
197
+ delete cached.failed;
198
+ return snapshot;
199
+ }
200
+ async function refresh(scope) {
201
+ const { deps, cached } = scope;
202
+ let snapshot;
203
+ try {
204
+ snapshot = await probeAndStore(scope);
205
+ }
206
+ catch (error) {
207
+ cached.retryAt = deps.clock.now() + MODEL_NEGATIVE_TTL_MS;
208
+ snapshot = failureSnapshot(scope, error);
209
+ cached.failed = snapshot;
210
+ }
211
+ finally {
212
+ delete cached.pending;
213
+ }
214
+ return snapshot;
215
+ }
216
+ async function discover({ context, deps }, { signal, force, staleWhileRevalidate }) {
217
+ let state;
218
+ try {
219
+ state = await scoped(context, deps, signal);
220
+ }
221
+ catch (error) {
222
+ return offlineSnapshot(modelLaunchFingerprint(context), deps.clock.now(), configuration.fallbackModels(), diagnostic(error));
223
+ }
224
+ const now = deps.clock.now();
225
+ const scope = { context, deps, signal, ...state, cached: deps.cache.get(state.key) || {}, now };
226
+ const hit = cachedAnswer({ cached: scope.cached, now }, { force, staleWhileRevalidate });
227
+ if (hit)
228
+ return hit;
229
+ // Only await on the disk path: any other await here would let a concurrent caller start a second probe.
230
+ const joined = staleWhileRevalidate && !scope.cached.good && DISK_CATALOG_AGENTS.includes(agentId) ? await primeFromDisk(scope) : undefined;
231
+ if (joined)
232
+ return joined;
233
+ const pending = refresh(scope);
234
+ scope.cached.pending = pending;
235
+ deps.cache.set(scope.key, scope.cached);
236
+ evictSettledScopes(deps.cache);
237
+ // Explicit rescan still waits for live evidence. Launches retain the scoped last-good
238
+ // catalog while this coalesced, timeout-bounded refresh updates the cache in the background.
239
+ return (staleWhileRevalidate && lastGoodSnapshot(scope.cached, now)) || pending;
54
240
  }
55
241
  const port = {
56
- async discoverModels({ context }, { signal, force = false, staleWhileRevalidate = false, deps = suppliedDeps } = {}) {
57
- let state;
58
- try {
59
- state = await scoped(context, deps, signal);
60
- }
61
- catch (error) {
62
- return offlineSnapshot(modelLaunchFingerprint(context), deps.clock.now(), configuration.fallbackModels(), diagnostic(error));
63
- }
64
- const { key, config } = state;
65
- const fingerprint = key.slice(agentId.length + 1);
66
- const now = deps.clock.now();
67
- const cached = deps.cache.get(key) || {};
68
- const lastGood = () => cached.failed || (cached.good && {
69
- ...cached.good, freshness: Date.parse(cached.good.expiresAt) > now ? cached.good.freshness : 'stale',
70
- });
71
- if (cached.pending)
72
- return staleWhileRevalidate && lastGood() || cached.pending;
73
- if (!force && cached.retryAt && cached.retryAt > now && cached.failed)
74
- return cached.failed;
75
- if (!force && !staleWhileRevalidate && !cached.failed && cached.good && Date.parse(cached.good.expiresAt) > now)
76
- return cached.good;
77
- // A fresh host process may still have a CLI-owned disk catalog. Use its observed rows
78
- // immediately; keep stale provenance and refresh without holding the first user prompt.
79
- if (staleWhileRevalidate && !cached.good && ['codex', 'opencode', 'claude', 'codebuddy'].includes(agentId)) {
80
- try {
81
- const disk = await withModelProbeTimeout(active => probes.cliCache({ agentId, context, deps, signal: active }), 1000, signal);
82
- const models = normalizeDiscoveredModels(disk.models);
83
- if (models.length)
84
- cached.good = { models, source: 'cli-cache', coverage: disk.coverage,
85
- freshness: 'stale', fetchedAt: new Date(now).toISOString(), expiresAt: new Date(now).toISOString(),
86
- launchFingerprint: fingerprint, diagnostics: [],
87
- ...(config.selection ? { defaultSelectionId: config.selection } : {}) };
88
- }
89
- catch { /* No usable disk cache: keep the bounded cold-probe path below. */ }
90
- // Another caller may have started the refresh while disk metadata was read.
91
- const concurrent = deps.cache.get(key);
92
- if (concurrent?.pending)
93
- return concurrent.failed || concurrent.good || concurrent.pending;
94
- }
95
- const pending = (async () => {
96
- try {
97
- const result = await boundedProbe(deps, () => withModelProbeTimeout((active) => probes.catalog({ agentId, context, configuration, deps, signal: active }), probes.timeoutMs({ agentId }), signal), signal);
98
- const models = normalizeDiscoveredModels(result.models);
99
- if (models.length === 0)
100
- throw new ModelProbeError('malformed-response');
101
- const fetched = deps.clock.now();
102
- // Native default metadata outranks a config guess (Grok can route despite its TOML).
103
- const nativeWins = result.source === 'rpc' && !['claude', 'codebuddy'].includes(agentId) || agentId === 'grok-build';
104
- const selection = context.model || (nativeWins ? result.defaultSelectionId || config.selection : config.selection || result.defaultSelectionId);
105
- const snapshot = { models, source: result.source, coverage: result.coverage,
106
- fetchedAt: new Date(fetched).toISOString(), expiresAt: new Date(fetched + MODEL_CATALOG_TTL_MS).toISOString(),
107
- freshness: result.source === 'cli-cache' ? 'stale' : 'fresh', launchFingerprint: fingerprint, diagnostics: [],
108
- ...(selection ? { defaultSelectionId: selection } : {}) };
109
- cached.good = snapshot;
110
- delete cached.retryAt;
111
- delete cached.failed;
112
- return snapshot;
113
- }
114
- catch (error) {
115
- cached.retryAt = deps.clock.now() + MODEL_NEGATIVE_TTL_MS;
116
- cached.failed = cached.good ? { ...cached.good, freshness: 'stale', diagnostics: [diagnostic(error)] } : offlineSnapshot(fingerprint, deps.clock.now(), configuration.fallbackModels(), diagnostic(error));
117
- return cached.failed;
118
- }
119
- finally {
120
- delete cached.pending;
121
- }
122
- })();
123
- cached.pending = pending;
124
- deps.cache.set(key, cached);
125
- // Evict settled scopes first; coalesced callers must retain their in-flight entry.
126
- for (const [oldKey, entry] of deps.cache) {
127
- if (deps.cache.size <= MAX_CATALOG_SCOPES)
128
- break;
129
- if (!entry.pending)
130
- deps.cache.delete(oldKey);
131
- }
132
- // Explicit rescan still waits for live evidence. Launches retain the scoped last-good
133
- // catalog while this coalesced, timeout-bounded refresh updates the cache in the background.
134
- return staleWhileRevalidate && lastGood() || pending;
242
+ async discoverModels({ context }, optional = {}) {
243
+ return discover({ context, deps: optional.deps ?? suppliedDeps }, { signal: optional.signal, force: optional.force === true, staleWhileRevalidate: optional.staleWhileRevalidate === true });
135
244
  },
136
245
  async resolveDefaultModel({ context, catalog }, { signal, deps = suppliedDeps } = {}) {
137
246
  let state;
@@ -141,21 +250,9 @@ export function createAgentModelDiscovery({ agentId, configuration, deps: suppli
141
250
  catch {
142
251
  return { status: 'unresolved', reason: 'Launch configuration could not be read.' };
143
252
  }
144
- const fingerprint = state.key.slice(agentId.length + 1);
145
- if (fingerprint !== catalog.launchFingerprint)
253
+ if (state.fingerprint !== catalog.launchFingerprint)
146
254
  return { status: 'unresolved', reason: 'Launch configuration changed; refresh the catalog.' };
147
- if (context.resumeSessionId && !context.resumedModelId && !context.model)
148
- return { status: 'unresolved', reason: 'Resumed session model metadata is required.' };
149
- const selection = context.model || context.resumedModelId || catalog.defaultSelectionId || state.config.selection;
150
- if (!selection)
151
- return { status: 'unresolved', reason: 'Native metadata did not resolve a default; pick a concrete model.' };
152
- const row = catalog.models.find((model) => model.id === selection || model.label === selection);
153
- if (catalog.freshness === 'offline-fallback' && row && row.id !== selection)
154
- return { status: 'unresolved', selectionId: selection, reason: 'Offline hints cannot resolve a display name or alias.' };
155
- const id = row?.resolvedId || (row?.identityKind === 'concrete' ? row.id : undefined);
156
- if (!id || modelIdentityKind(id) !== 'concrete')
157
- return { status: 'unresolved', selectionId: selection, reason: 'The configured selection has no concrete model evidence.' };
158
- return { status: 'resolved', id, selectionId: selection, source: state.config.selection === selection ? 'config-file' : catalog.source, resolvedAt: new Date(deps.clock.now()).toISOString(), launchFingerprint: fingerprint };
255
+ return resolveFromCatalog({ context, catalog, configSelection: state.config.selection, fingerprint: state.fingerprint, resolvedAt: new Date(deps.clock.now()).toISOString() });
159
256
  },
160
257
  };
161
258
  return port;
@@ -163,30 +260,35 @@ export function createAgentModelDiscovery({ agentId, configuration, deps: suppli
163
260
  export function offlineSnapshot(fingerprint, now, fallback, issue) {
164
261
  return { models: normalizeDiscoveredModels(fallback), source: 'offline-fallback', freshness: 'offline-fallback', fetchedAt: new Date(now).toISOString(), expiresAt: new Date(now + MODEL_NEGATIVE_TTL_MS).toISOString(), coverage: 'configured', launchFingerprint: fingerprint, diagnostics: issue ? [issue] : [] };
165
262
  }
263
+ /** The definition's declared env default, trimmed; undefined when unset or blank. */
264
+ function configuredDefault(def, context) {
265
+ return (def.defaultModelEnvVar && context.env[def.defaultModelEnvVar]?.trim()) || undefined;
266
+ }
267
+ async function staticDiscover({ def, context, deps }) {
268
+ const catalog = offlineSnapshot(modelLaunchFingerprint(context), deps.clock.now(), def.fallbackModels || []);
269
+ // Static hosts used their first concrete fallback before discovery existed. Preserve
270
+ // that contract while letting a declared env default or explicit selection take precedence.
271
+ const selection = context.model || context.resumedModelId || configuredDefault(def, context) || catalog.models.find(row => row.identityKind === 'concrete')?.id;
272
+ return { ...catalog, ...(selection ? { defaultSelectionId: selection } : {}) };
273
+ }
274
+ async function staticResolve({ def, context, catalog, deps }) {
275
+ if (missingResumedModel(context))
276
+ return RESUMED_MODEL_REQUIRED;
277
+ const configured = configuredDefault(def, context);
278
+ const selection = context.model || context.resumedModelId || configured || catalog.defaultSelectionId;
279
+ if (!selection)
280
+ return { status: 'unresolved', reason: NO_CONCRETE_EVIDENCE };
281
+ // A host's declared env default is authoritative even when its static hints lag behind.
282
+ const id = rowEvidence(findRow(catalog.models, selection)) || (configured === selection ? configured : undefined);
283
+ if (!isConcreteId(id))
284
+ return { status: 'unresolved', selectionId: selection, reason: NO_CONCRETE_EVIDENCE };
285
+ return { status: 'resolved', id, selectionId: selection, source: configured === selection ? 'config-file' : catalog.source,
286
+ resolvedAt: new Date(deps.clock.now()).toISOString(), launchFingerprint: catalog.launchFingerprint };
287
+ }
166
288
  export function modelDiscoveryForDef({ def, deps: suppliedDeps }, _optional = {}) {
167
289
  return {
168
- discoverModels: def.discoverModels?.bind(def) || (async ({ context }, { deps = suppliedDeps } = {}) => {
169
- const catalog = offlineSnapshot(modelLaunchFingerprint(context), deps.clock.now(), def.fallbackModels || []);
170
- const configured = def.defaultModelEnvVar && context.env[def.defaultModelEnvVar]?.trim();
171
- // Static hosts used their first concrete fallback before discovery existed. Preserve
172
- // that contract while letting a declared env default or explicit selection take precedence.
173
- const selection = context.model || context.resumedModelId || configured || catalog.models.find(row => row.identityKind === 'concrete')?.id;
174
- return { ...catalog, ...(selection ? { defaultSelectionId: selection } : {}) };
175
- }),
176
- resolveDefaultModel: def.resolveDefaultModel?.bind(def) || (async ({ context, catalog }, { deps = suppliedDeps } = {}) => {
177
- if (context.resumeSessionId && !context.resumedModelId && !context.model)
178
- return { status: 'unresolved', reason: 'Resumed session model metadata is required.' };
179
- const configured = def.defaultModelEnvVar && context.env[def.defaultModelEnvVar]?.trim();
180
- const selection = context.model || context.resumedModelId || configured || catalog.defaultSelectionId;
181
- const row = catalog.models.find(model => model.id === selection || model.label === selection);
182
- // A host's declared env default is authoritative even when its static hints lag behind.
183
- const id = row?.resolvedId || (row?.identityKind === 'concrete' ? row.id : undefined)
184
- || (configured === selection && configured ? configured : undefined);
185
- if (!id || modelIdentityKind(id) !== 'concrete')
186
- return { status: 'unresolved', ...(selection ? { selectionId: selection } : {}), reason: 'The configured selection has no concrete model evidence.' };
187
- return { status: 'resolved', id, ...(selection ? { selectionId: selection } : {}), source: configured === selection ? 'config-file' : catalog.source,
188
- resolvedAt: new Date(deps.clock.now()).toISOString(), launchFingerprint: catalog.launchFingerprint };
189
- }),
290
+ discoverModels: def.discoverModels?.bind(def) || (async ({ context }, { deps = suppliedDeps } = {}) => staticDiscover({ def, context, deps })),
291
+ resolveDefaultModel: def.resolveDefaultModel?.bind(def) || (async ({ context, catalog }, { deps = suppliedDeps } = {}) => staticResolve({ def, context, catalog, deps })),
190
292
  };
191
293
  }
192
294
  /** Resolve against the actual launch scope, pinning the same ID shown by the picker. */
package/dist/models.d.ts CHANGED
@@ -3,7 +3,19 @@ import { type AgentRuntimeState } from './runtime-state.js';
3
3
  * @module models
4
4
  * Model-option defaults, a per-agent last-surfaced live-model cache and model-id sanitization.
5
5
  */
6
- import type { RuntimeAgentDef, RuntimeModelOption } from './types.js';
6
+ import type { DetectedAgent, RuntimeAgentDef, RuntimeModelOption } from './types.js';
7
+ type SelectableAgent = Pick<DetectedAgent, 'id' | 'available' | 'models' | 'modelsSource' | 'reasoningOptions' | 'reasoningInModelId' | 'authStatus' | 'supportsConcreteModelSelection' | 'defaultModelResolution'>;
8
+ /** Validate an explicit selection against the same discovered inventory the picker displays.
9
+ * Empty model/effort means the runtime default. Refusals include the current choices rather
10
+ * than silently substituting a different model. Pure; O(agents + models + effort options).
11
+ * @example validateRuntimeSelection({ agents, agentId: 'runtime', modelId: 'catalog-model' });
12
+ */
13
+ export declare function validateRuntimeSelection({ agents, agentId, modelId, effort }: {
14
+ agents: readonly SelectableAgent[];
15
+ agentId: string;
16
+ modelId?: string;
17
+ effort?: string;
18
+ }, _options?: {}): string | null;
7
19
  export declare const DEFAULT_MODEL_OPTION: RuntimeModelOption;
8
20
  export declare function rememberLiveModels({ agentId, models }: {
9
21
  agentId: string;
@@ -40,4 +52,5 @@ export declare function resolveModelForAgent({ def, resolved }: {
40
52
  export declare function sanitizeCustomModel({ id }: {
41
53
  id: string | null | undefined;
42
54
  }): string | null;
55
+ export {};
43
56
  //# sourceMappingURL=models.d.ts.map
package/dist/models.js CHANGED
@@ -1,4 +1,54 @@
1
+ import { concreteModelOptions } from './model-discovery-shared.js';
1
2
  import { defaultRuntimeState } from './runtime-state.js';
3
+ /** Refusal for an agent that cannot take this pick at all, before any model lookup. */
4
+ function agentReadinessRefusal({ agent, agentId, modelId, effort }) {
5
+ // Executable presence is not credential readiness; unknown/unprobed auth fails closed.
6
+ if (agent.authStatus !== 'ok')
7
+ return `Credentials for '${agentId}' are not ready (${agent.authStatus ?? 'unverified'}). Sign in and rescan the chat picker.`;
8
+ if (agent.supportsConcreteModelSelection === false)
9
+ return `Agent '${agentId}' cannot pin a concrete starting model.`;
10
+ // A detector's static fallback is useful for display, but is not live evidence of a valid pick.
11
+ if ((modelId || effort) && agent.modelsSource !== 'live')
12
+ return `Live model catalog for '${agentId}' is unavailable. Rescan the chat picker before choosing a model or effort.`;
13
+ return null;
14
+ }
15
+ /** The concrete id a pick launches: the explicit model, else the resolved default (if any). */
16
+ function selectedModelId({ agent, modelId }) {
17
+ if (modelId && modelId !== 'default')
18
+ return modelId;
19
+ const resolution = agent.defaultModelResolution;
20
+ return resolution?.status === 'resolved' ? resolution.id : undefined;
21
+ }
22
+ /** Refusal for an unknown model, or an effort the selected model does not offer. */
23
+ function modelAndEffortRefusal({ agent, agentId, modelId, effort }) {
24
+ const choices = concreteModelOptions(agent);
25
+ const resolvedId = selectedModelId({ agent, modelId });
26
+ const model = choices.find(candidate => candidate.id === resolvedId);
27
+ if (modelId && modelId !== 'default' && !model)
28
+ return `Unknown model '${modelId}' for '${agentId}'. Available models: ${choices.map(candidate => candidate.id).join(', ')}.`;
29
+ if (!effort)
30
+ return null;
31
+ // Default must resolve before checking model-specific effort; agent-wide levels can differ.
32
+ if (!model)
33
+ return `Default model for '${agentId}' is unresolved. Pick a concrete model before choosing effort.`;
34
+ // Suffix-based runtimes own effort in the model id; a second effort setting would disagree.
35
+ const levels = agent.reasoningInModelId ? [] : model.reasoning ?? agent.reasoningOptions ?? [];
36
+ if (!levels.some(candidate => candidate.id === effort))
37
+ return `Unknown effort '${effort}' for '${agentId}'. Available effort levels: ${levels.map(candidate => candidate.id).join(', ')} (empty means Default).`;
38
+ return null;
39
+ }
40
+ /** Validate an explicit selection against the same discovered inventory the picker displays.
41
+ * Empty model/effort means the runtime default. Refusals include the current choices rather
42
+ * than silently substituting a different model. Pure; O(agents + models + effort options).
43
+ * @example validateRuntimeSelection({ agents, agentId: 'runtime', modelId: 'catalog-model' });
44
+ */
45
+ export function validateRuntimeSelection({ agents, agentId, modelId, effort }, _options = {}) {
46
+ const agent = agents.find(candidate => candidate.id === agentId && candidate.available);
47
+ if (!agent)
48
+ return `Unknown or unavailable agent '${agentId}'. Available agents: ${agents.filter(candidate => candidate.available).map(candidate => candidate.id).join(', ')}.`;
49
+ const request = { agent, agentId, modelId, effort };
50
+ return agentReadinessRefusal(request) ?? modelAndEffortRefusal(request);
51
+ }
2
52
  export const DEFAULT_MODEL_OPTION = {
3
53
  id: 'default',
4
54
  label: 'Default (CLI config)',
@@ -41,25 +91,18 @@ export function isKnownModel({ def, modelId }, { scope, state = defaultRuntimeSt
41
91
  }
42
92
  return false;
43
93
  }
44
- // Some adapters reject the synthetic `'default'` model id (they require an
45
- // explicit model-selection call before the first prompt). Those defs
46
- // declare it by omitting DEFAULT_MODEL_OPTION from `fallbackModels`
47
- // entirely. When the chat run produces a null or 'default' model for one
48
- // of those adapters, prefer the first model from the live list last
49
- // surfaced to the UI, then fall back to the def's first concrete fallback
50
- // id so the spawn layer always has a real model to forward. Defs that DO
51
- // list 'default' (the common case) are left untouched.
52
- export function resolveModelForAgent({ def, resolved }, { env = process.env, liveModelScope, state = defaultRuntimeState } = {}) {
53
- if (resolved && resolved !== 'default')
54
- return resolved;
55
- // Host-process env override. Lets an operator pin a different fallback
56
- // id without a code change when the hardcoded default goes away
57
- // upstream.
58
- if (def.defaultModelEnvVar) {
59
- const raw = env[def.defaultModelEnvVar];
60
- if (typeof raw === 'string' && raw.trim())
61
- return raw.trim();
62
- }
94
+ // Host-process env override. Lets an operator pin a different fallback
95
+ // id without a code change when the hardcoded default goes away
96
+ // upstream.
97
+ function envDefaultModel({ def, env }) {
98
+ if (!def.defaultModelEnvVar)
99
+ return undefined;
100
+ const raw = env[def.defaultModelEnvVar];
101
+ return typeof raw === 'string' && raw.trim() ? raw.trim() : undefined;
102
+ }
103
+ // `def` omits 'default' from its fallbacks: first remembered live id, else the first concrete
104
+ // fallback id, else `resolved` unchanged. Defs that list 'default' return `resolved` untouched.
105
+ function concreteFallbackModel({ def, resolved, state }, { liveModelScope } = {}) {
63
106
  // `def.fallbackModels` is typed `RuntimeModelOption[]` (never optional/non-array) and every
64
107
  // entry is a well-formed object — no defensive Array.isArray/truthy-entry guard needed for a
65
108
  // state the type system already excludes (CR-R7).
@@ -74,6 +117,19 @@ export function resolveModelForAgent({ def, resolved }, { env = process.env, liv
74
117
  return resolved;
75
118
  return fallbacks[0].id;
76
119
  }
120
+ // Some adapters reject the synthetic `'default'` model id (they require an
121
+ // explicit model-selection call before the first prompt). Those defs
122
+ // declare it by omitting DEFAULT_MODEL_OPTION from `fallbackModels`
123
+ // entirely. When the chat run produces a null or 'default' model for one
124
+ // of those adapters, prefer the first model from the live list last
125
+ // surfaced to the UI, then fall back to the def's first concrete fallback
126
+ // id so the spawn layer always has a real model to forward. Defs that DO
127
+ // list 'default' (the common case) are left untouched.
128
+ export function resolveModelForAgent({ def, resolved }, { env = process.env, liveModelScope, state = defaultRuntimeState } = {}) {
129
+ if (resolved && resolved !== 'default')
130
+ return resolved;
131
+ return envDefaultModel({ def, env }) ?? concreteFallbackModel({ def, resolved, state }, { liveModelScope });
132
+ }
77
133
  // Permit user-typed model ids that didn't appear in either the live
78
134
  // listing or the static fallback (e.g. the user is on a brand-new model
79
135
  // the CLI's `models` command hasn't surfaced yet). The CLI gets the value
@@ -0,0 +1,29 @@
1
+ /** Native fallback tools, independent of a host's catalog and identity policy. */
2
+ export declare const NATIVE_FALLBACK_TOOLS: readonly string[];
3
+ /** Independent native CLI dimensions; hosts own identity, defaults and persistence. */
4
+ export interface NativeCapabilities {
5
+ shell: boolean;
6
+ fileWrite: boolean;
7
+ userMcp: boolean;
8
+ subagents: boolean;
9
+ userSettings: boolean;
10
+ web: boolean;
11
+ workflows: boolean;
12
+ loginEnvironment: boolean;
13
+ }
14
+ /** Append explicit capability denies AFTER resolving the legacy all-or-nothing grant.
15
+ * An unrelated ON permission must never erase an individual OFF. Pure, bounded tool list.
16
+ */
17
+ export declare function resolveNativeCapabilityDenies(required: {
18
+ capabilities?: Partial<NativeCapabilities>;
19
+ denied: readonly string[];
20
+ }, _optional?: Record<string, never>): readonly string[];
21
+ /** Hosts explicitly grant native fallbacks; omitted preserves the standalone CLI contract.
22
+ * Pure, O(t) for t configured denies. Security/path denies always survive the grant.
23
+ * @example resolveNativeToolDenies({ enabled: true, denied: ['Bash', 'Read(/secret)'] }, {});
24
+ */
25
+ export declare function resolveNativeToolDenies(required: {
26
+ enabled: boolean | undefined;
27
+ denied?: readonly string[];
28
+ }, _optional?: Record<string, never>): readonly string[];
29
+ //# sourceMappingURL=native-tool-policy.d.ts.map
@@ -0,0 +1,36 @@
1
+ /** Native fallback tools, independent of a host's catalog and identity policy. */
2
+ export const NATIVE_FALLBACK_TOOLS = Object.freeze([
3
+ 'Bash', 'Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'BashOutput', 'KillShell',
4
+ ]);
5
+ const CAPABILITY_TOOLS = {
6
+ shell: ['Bash', 'BashOutput', 'KillShell'],
7
+ fileWrite: ['Edit', 'Write', 'MultiEdit', 'NotebookEdit'],
8
+ subagents: ['Task', 'Agent'],
9
+ web: ['WebFetch', 'WebSearch'],
10
+ workflows: ['CronCreate', 'CronDelete', 'CronList', 'EnterWorktree', 'ExitWorktree', 'RemoteTrigger', 'Workflow'],
11
+ };
12
+ /** Append explicit capability denies AFTER resolving the legacy all-or-nothing grant.
13
+ * An unrelated ON permission must never erase an individual OFF. Pure, bounded tool list.
14
+ */
15
+ export function resolveNativeCapabilityDenies(required, _optional = {}) {
16
+ const denied = new Set(required.denied);
17
+ for (const key of Object.keys(CAPABILITY_TOOLS)) {
18
+ if (required.capabilities?.[key] === false)
19
+ for (const tool of CAPABILITY_TOOLS[key])
20
+ denied.add(tool);
21
+ }
22
+ return [...denied];
23
+ }
24
+ /** Hosts explicitly grant native fallbacks; omitted preserves the standalone CLI contract.
25
+ * Pure, O(t) for t configured denies. Security/path denies always survive the grant.
26
+ * @example resolveNativeToolDenies({ enabled: true, denied: ['Bash', 'Read(/secret)'] }, {});
27
+ */
28
+ export function resolveNativeToolDenies(required, _optional = {}) {
29
+ const denied = required.denied ?? [];
30
+ if (required.enabled === undefined)
31
+ return denied;
32
+ if (required.enabled)
33
+ return denied.filter(tool => !NATIVE_FALLBACK_TOOLS.includes(tool));
34
+ return [...new Set([...denied, ...NATIVE_FALLBACK_TOOLS])];
35
+ }
36
+ //# sourceMappingURL=native-tool-policy.js.map