forked from nexu-io/open-design
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdetection.ts
More file actions
484 lines (465 loc) · 17.2 KB
/
Copy pathdetection.ts
File metadata and controls
484 lines (465 loc) · 17.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
import { execAgentFile } from './invocation.js';
import { AGENT_DEFS } from './registry.js';
import {
DEFAULT_MODEL_OPTION,
getRememberedLiveModels,
mergeFallbackModelMetadata,
rememberLiveModels,
} from './models.js';
import { applyAgentLaunchEnv, resolveAgentLaunch } from './launch.js';
import { spawnEnvForAgent } from './env.js';
import { probeAgentAuthStatus } from './auth.js';
import { agentCapabilities } from './capabilities.js';
import { installMetaForAgent } from './metadata.js';
import { resolveAmrOpenCodeExecutable } from './executables.js';
import { resolveAmrProfile } from '../integrations/vela.js';
import {
buildAuthDiagnostic,
buildCompatibilityDiagnostic,
buildExecutableDiagnostic,
buildNotInvocableDiagnostic,
buildVersionDiagnostic,
type NotInvocableCause,
} from './diagnostics.js';
import type {
AgentDiagnostic,
DetectedAgent,
RuntimeAgentDef,
RuntimeCapabilityMap,
RuntimeModelSource,
RuntimeModelOption,
} from './types.js';
type FetchedRuntimeModels = {
models: RuntimeModelOption[];
source: RuntimeModelSource;
};
export interface DetectedRuntimeVersions {
agentCliVersion?: string;
runtimeCompanionName?: string;
runtimeCompanionVersion?: string;
}
// Detection already pays the bounded `--version` probe cost used by Settings.
// Keep the result as daemon-lifetime provenance so run telemetry can name the
// exact executable family without spawning another process on every turn.
const detectedRuntimeVersions = new Map<string, DetectedRuntimeVersions>();
export function getDetectedRuntimeVersions(
agentId: string | null | undefined,
): DetectedRuntimeVersions | null {
if (!agentId) return null;
const remembered = detectedRuntimeVersions.get(agentId);
return remembered ? { ...remembered } : null;
}
function configuredEnvForAgent(
configuredEnvByAgent: Record<string, Record<string, string>>,
agentId: string,
): Record<string, string> {
const configAgentId = agentId === 'byok-opencode' ? 'opencode' : agentId;
return configuredEnvByAgent?.[configAgentId] ?? {};
}
function amrModelScopeFromEnv(env: NodeJS.ProcessEnv): string {
return resolveAmrProfile(env);
}
function withRememberedAmrModels(
def: RuntimeAgentDef,
env: NodeJS.ProcessEnv,
modelResult: FetchedRuntimeModels,
): FetchedRuntimeModels {
if (def.id !== 'amr' || modelResult.models.length > 0) return modelResult;
const rememberedModels = getRememberedLiveModels(def.id, amrModelScopeFromEnv(env));
if (rememberedModels.length === 0) return modelResult;
return { models: rememberedModels, source: 'live' };
}
async function fetchModels(
def: RuntimeAgentDef,
resolvedBin: string,
env: NodeJS.ProcessEnv,
): Promise<FetchedRuntimeModels> {
if (typeof def.fetchModels === 'function') {
try {
const parsed = await def.fetchModels(resolvedBin, env);
if (!parsed || parsed.length === 0) {
return { models: def.fallbackModels, source: 'fallback' };
}
return { models: mergeFallbackModelMetadata(def, parsed), source: 'live' };
} catch {
return { models: def.fallbackModels, source: 'fallback' };
}
}
if (!def.listModels) {
return { models: def.fallbackModels, source: 'fallback' };
}
try {
const { stdout } = await execAgentFile(resolvedBin, def.listModels.args, {
env,
timeout: def.listModels.timeoutMs ?? 5000,
// Models lists from popular CLIs (e.g. opencode) easily exceed the
// default 1MB buffer once you include every openrouter model. Bump
// it so we don't truncate the listing.
maxBuffer: 8 * 1024 * 1024,
});
const parsed = def.listModels.parse(String(stdout));
// Empty / null parse result means the CLI didn't actually return a
// usable list (e.g. cursor-agent's "No models available"); fall back
// to the static hint so the picker isn't stuck on Default-only.
if (!parsed || parsed.length === 0) {
return { models: def.fallbackModels, source: 'fallback' };
}
return { models: mergeFallbackModelMetadata(def, parsed), source: 'live' };
} catch {
return { models: def.fallbackModels, source: 'fallback' };
}
}
type VersionProbeOutcome =
| { kind: 'not-invocable'; cause: NotInvocableCause }
| { kind: 'spawned'; version: string | null };
/**
* Run the agent's `--version` probe and classify the result. The probe
* has two distinct failure modes the catch arm has to discriminate:
*
* - **Not invocable.** The OS rejected the spawn outright, OR the
* wrapper script spawned but its underlying interpreter / target
* failed. We split permission failures (EACCES / exit 126) from
* missing-target failures (ENOENT / ENOTDIR / exit 127) so Settings can
* offer permission-specific copy instead of treating every failure as a
* broken shim. We still mark the agent unavailable so Settings does not
* advertise a ghost entry (issue #658, lefarcen review P2 on PR #1301).
*
* - **Spawned but `--version` was unhappy.** The binary itself ran
* (any other rejection: timeout, generic non-zero exit, stderr
* noise) so the CLI is invocable; we just can't read a version
* string. Adapters whose `--version` flag is unsupported land
* here and must keep working with `version: null`.
*
* `child_process.execFile` reports OS-level rejections with a string
* `err.code` (`'ENOENT'`, `'EACCES'`, `'ENOTDIR'`) and non-zero exit
* codes with a *numeric* `err.code` equal to the exit status, so the
* two arms below are unambiguous.
*/
async function probeVersionAtPath(
def: RuntimeAgentDef,
resolved: string,
env: NodeJS.ProcessEnv,
): Promise<VersionProbeOutcome> {
try {
const { stdout } = await execAgentFile(resolved, def.versionArgs, {
env,
timeout: def.versionProbeTimeoutMs ?? 3000,
});
const rawVersion = String(stdout).trim().split('\n')[0]?.trim() || null;
const version = rawVersion && def.versionPolicy?.parse
? def.versionPolicy.parse(rawVersion)
: rawVersion;
return { kind: 'spawned', version };
} catch (err) {
const code = (err as NodeJS.ErrnoException)?.code;
if (typeof code === 'string') {
if (code === 'EACCES') {
return { kind: 'not-invocable', cause: 'not-executable' };
}
if (code === 'ENOENT' || code === 'ENOTDIR') {
return { kind: 'not-invocable', cause: 'missing-target' };
}
} else if (typeof code === 'number' && (code === 126 || code === 127)) {
return {
kind: 'not-invocable',
cause: code === 126 ? 'not-executable' : 'missing-target',
};
}
return { kind: 'spawned', version: null };
}
}
async function probeAmrOpenCodeVersion(
def: RuntimeAgentDef,
env: NodeJS.ProcessEnv,
): Promise<string | null> {
if (def.id !== 'amr') return null;
const companion = resolveAmrOpenCodeExecutable(env);
if (!companion) return null;
try {
const { stdout } = await execAgentFile(companion, ['--version'], {
env,
timeout: def.versionProbeTimeoutMs ?? 3000,
});
return String(stdout).trim().split('\n')[0] || null;
} catch {
return null;
}
}
function unavailableAgent(
def: RuntimeAgentDef,
diagnostics: AgentDiagnostic[] = [],
detected?: { path?: string; version?: string | null },
): DetectedAgent {
return {
...stripFns(def),
models: def.fallbackModels ?? [DEFAULT_MODEL_OPTION],
modelsSource: 'fallback',
available: false,
...(detected?.path ? { path: detected.path } : {}),
...(detected && 'version' in detected ? { version: detected.version ?? null } : {}),
...(diagnostics.length > 0 ? { diagnostics } : {}),
...installMetaForAgent(def.id),
};
}
// Probe the agent's `--help` once and record which advertised flags the
// installed CLI supports, so buildArgs can consult the cache. Extracted from
// the main probe so it can run concurrently with model + auth probing instead
// of blocking them. Returns the capability map (or null when the agent
// declares no help/capability metadata or the probe failed).
async function probeCapabilities(
def: RuntimeAgentDef,
launchPath: string,
env: NodeJS.ProcessEnv,
): Promise<RuntimeCapabilityMap | null> {
if (!def.helpArgs || !def.capabilityFlags) return null;
try {
const { stdout } = await execAgentFile(launchPath, def.helpArgs, {
env,
timeout: 5000,
maxBuffer: 4 * 1024 * 1024,
});
const caps: RuntimeCapabilityMap = {};
for (const [flag, key] of Object.entries(def.capabilityFlags)) {
caps[key] = String(stdout).includes(flag);
}
return caps;
} catch {
// If --help fails, leave caps empty so buildArgs falls back to the safe
// baseline (no optional flags).
return {};
}
}
async function probe(
def: RuntimeAgentDef,
configuredEnv: Record<string, string> = {},
): Promise<DetectedAgent> {
detectedRuntimeVersions.delete(def.id);
// Detection must probe the exact path the runtime will spawn, not just the
// PATH-visible shim. This is load-bearing for Codex under nvm/fnm/mise:
// the discovered `codex` entry is often a `#!/usr/bin/env node` wrapper
// that is not invocable from a GUI-launched app's stripped PATH, while the
// launch resolver can still upgrade it to the packaged native Codex binary.
// If detection probes the shim but chat/run spawns the native binary, the
// UI incorrectly reports "not installed" until the user pins CODEX_BIN by
// hand even though the real launch path is healthy.
const launch = resolveAgentLaunch(def, configuredEnv);
if (!launch.selectedPath || !launch.launchPath) {
return unavailableAgent(def, [buildExecutableDiagnostic(def, configuredEnv)]);
}
const probeEnv = applyAgentLaunchEnv(
spawnEnvForAgent(
def.id,
{
...process.env,
...(def.env || {}),
},
configuredEnv,
undefined,
{ resolvedBin: launch.selectedPath },
),
launch,
);
const outcome = await probeVersionAtPath(def, launch.launchPath, probeEnv);
if (outcome.kind === 'not-invocable') {
return unavailableAgent(def, [
buildNotInvocableDiagnostic(def, launch, outcome.cause),
]);
}
if (def.versionPolicy?.requireVersion && !outcome.version) {
return unavailableAgent(def, [buildVersionDiagnostic(def, outcome.version)]);
}
let runtimeCompanionVersion: string | undefined;
if (def.compatibilityProbe) {
try {
if (def.compatibilityProbe.preflight && !def.compatibilityProbe.preflight(probeEnv)) {
return unavailableAgent(def, [buildCompatibilityDiagnostic(def)], {
path: launch.selectedPath,
version: outcome.version,
});
}
const { stdout } = await execAgentFile(
launch.launchPath,
def.compatibilityProbe.args,
{
env: probeEnv,
timeout: def.compatibilityProbe.timeoutMs ?? 5000,
maxBuffer: 1024 * 1024,
},
);
runtimeCompanionVersion = def.compatibilityProbe.parse(String(stdout));
} catch {
return unavailableAgent(def, [buildCompatibilityDiagnostic(def)], {
path: launch.selectedPath,
version: outcome.version,
});
}
}
const versionDiagnostic =
def.versionPolicy &&
outcome.version &&
!def.versionPolicy.supportedVersions.includes(outcome.version)
? buildVersionDiagnostic(def, outcome.version)
: null;
// The version probe must finish first (it gates availability), but the
// three post-version probes are independent reads — run them concurrently
// so a single agent's detection wall is max(help, models, auth) ≈ 5s rather
// than the sum ≈ 15s. `--help` capabilities are cached on `agentCapabilities`
// for buildArgs to consult.
const [caps, modelResult, auth, amrOpenCodeVersion] = await Promise.all([
probeCapabilities(def, launch.launchPath, probeEnv),
fetchModels(def, launch.launchPath, probeEnv),
probeAgentAuthStatus(def, launch.launchPath, probeEnv),
probeAmrOpenCodeVersion(def, probeEnv),
]);
const surfacedModelResult = withRememberedAmrModels(def, probeEnv, modelResult);
if (caps) {
agentCapabilities.set(def.id, caps);
}
const authDiagnostic = auth ? buildAuthDiagnostic(def, auth) : null;
const runtimeVersions: DetectedRuntimeVersions = {
...(outcome.version ? { agentCliVersion: outcome.version } : {}),
...(amrOpenCodeVersion
? {
runtimeCompanionName: 'opencode',
runtimeCompanionVersion: amrOpenCodeVersion,
}
: {}),
...(runtimeCompanionVersion
? {
runtimeCompanionName: def.id === 'deepseek-harness'
? '@open-design/dsh-runtime'
: 'runtime-profile',
runtimeCompanionVersion,
}
: {}),
};
if (Object.keys(runtimeVersions).length > 0) {
detectedRuntimeVersions.set(def.id, runtimeVersions);
}
return {
...stripFns(def),
models: surfacedModelResult.models,
modelsSource: surfacedModelResult.source,
available: true,
path: launch.selectedPath,
version: outcome.version,
...(auth
? {
authStatus: auth.status,
...(auth.message ? { authMessage: auth.message } : {}),
}
: {}),
...(versionDiagnostic || authDiagnostic
? {
diagnostics: [versionDiagnostic, authDiagnostic].filter(
(diagnostic): diagnostic is AgentDiagnostic => diagnostic !== null,
),
}
: {}),
...installMetaForAgent(def.id),
};
}
function stripFns(
def: RuntimeAgentDef,
): Omit<DetectedAgent, 'models' | 'modelsSource' | 'available' | 'path' | 'version'> {
// Drop the buildArgs / listModels closures but keep declarative metadata
// (reasoningOptions, streamFormat, name, bin, etc.). `models` is
// populated separately by `fetchModels`, so we strip the static
// `fallbackModels` slot here too. `helpArgs` / `capabilityFlags` /
// `fallbackBins` / `maxPromptArgBytes` / `env` are probe-or-spawn-only
// metadata and shouldn't bleed into the API response either.
// Runtime timeout fields are spawn-time hints for chat-run watchdogs and
// are not part of the public AgentInfo contract — strip them here so the
// runtime registry stays the only consumer.
const {
buildArgs,
listModels,
fetchModels,
fallbackModels,
helpArgs,
capabilityFlags,
fallbackBins,
versionProbeTimeoutMs,
versionPolicy,
compatibilityProbe,
maxPromptArgBytes,
env,
inactivityTimeoutMs,
firstOutputTimeoutMs,
authProbe,
...rest
} = def;
return rest;
}
export async function detectAgent(
def: RuntimeAgentDef,
configuredEnv: Record<string, string> = {},
): Promise<DetectedAgent> {
try {
return await probe(def, configuredEnv);
} catch {
// Fault isolation (issue #2297): one adapter's probe blowing up
// — e.g. a synchronous filesystem throw during PATH walking on a
// packaged Windows daemon, or an async rejection from one of the
// post-launch probes — must not collapse the whole agent picker.
// Without this guard the bare `Promise.all` rejected and the
// `/api/agents` catch arm returned `[]`, so the UI silently lost
// every CLI option and fell back to BYOK / Cloud only.
return unavailableAgent(def);
}
}
function rememberDetectedLiveModels(
def: RuntimeAgentDef,
configuredEnv: Record<string, string>,
agent: DetectedAgent,
): void {
if (def.id === 'amr' && agent.models.length === 0) return;
const scope = def.id === 'amr'
? amrModelScopeFromEnv({
...process.env,
...(def.env || {}),
...configuredEnv,
})
: null;
rememberLiveModels(agent.id, agent.models, scope);
}
export async function detectAgents(
configuredEnvByAgent: Record<string, Record<string, string>> = {},
) {
const results = await Promise.all(
AGENT_DEFS.map((def) => detectAgent(def, configuredEnvForAgent(configuredEnvByAgent, def.id))),
);
// Refresh the validation cache from whatever we just surfaced to the UI
// so /api/chat can accept any model the user could have just picked,
// including ones that only showed up after a CLI re-auth.
for (const [index, agent] of results.entries()) {
const def = AGENT_DEFS[index];
if (!def) continue;
rememberDetectedLiveModels(def, configuredEnvForAgent(configuredEnvByAgent, def.id), agent);
}
return results;
}
// Streaming variant: yields each agent the moment its probe settles, in
// completion order rather than registry order, so the UI can paint a card
// as soon as it resolves instead of waiting for the slowest CLI. The model
// validation cache is refreshed per-agent (same effect as the batch path,
// just incrementally). `detectAgents` keeps the array contract for callers
// that don't care about incremental delivery (cache warm, analytics, chat).
export async function* detectAgentsStream(
configuredEnvByAgent: Record<string, Record<string, string>> = {},
): AsyncGenerator<DetectedAgent> {
const tagged = AGENT_DEFS.map((def, index) =>
detectAgent(def, configuredEnvForAgent(configuredEnvByAgent, def.id)).then((agent) => {
rememberDetectedLiveModels(def, configuredEnvForAgent(configuredEnvByAgent, def.id), agent);
return { index, agent };
}),
);
const pending = new Set(tagged.keys());
while (pending.size > 0) {
const { index, agent } = await Promise.race(
tagged.filter((_, i) => pending.has(i)),
);
pending.delete(index);
yield agent;
}
}