@1agh/maude 2.2.1 → 2.3.2

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 (91) hide show
  1. package/apps/studio/acp/agents/auth.ts +241 -0
  2. package/apps/studio/acp/agents/catalog.ts +308 -0
  3. package/apps/studio/acp/agents/chat-key.ts +64 -0
  4. package/apps/studio/acp/agents/conformance.ts +1853 -0
  5. package/apps/studio/acp/agents/consent.ts +92 -0
  6. package/apps/studio/acp/agents/descriptor.ts +188 -0
  7. package/apps/studio/acp/agents/discover.ts +491 -0
  8. package/apps/studio/acp/agents/e2e-model.ts +58 -0
  9. package/apps/studio/acp/agents/health.ts +46 -0
  10. package/apps/studio/acp/agents/link-scan.ts +230 -0
  11. package/apps/studio/acp/agents/spawn.ts +164 -0
  12. package/apps/studio/acp/agents/state.ts +132 -0
  13. package/apps/studio/acp/ask-queue.ts +13 -4
  14. package/apps/studio/acp/bootstrap-brief.ts +16 -3
  15. package/apps/studio/acp/bridge.ts +709 -99
  16. package/apps/studio/acp/env.ts +43 -1
  17. package/apps/studio/acp/index.ts +428 -43
  18. package/apps/studio/acp/may-scope.ts +244 -21
  19. package/apps/studio/acp/policy/agent-home.ts +202 -0
  20. package/apps/studio/acp/policy/bridge-gate.ts +68 -0
  21. package/apps/studio/acp/policy/codex-home.ts +228 -0
  22. package/apps/studio/acp/policy/enforce.ts +620 -0
  23. package/apps/studio/acp/policy/gate-types.ts +41 -0
  24. package/apps/studio/acp/policy/launch-codex.ts +351 -0
  25. package/apps/studio/acp/policy/launch-copilot.ts +119 -0
  26. package/apps/studio/acp/policy/launch-gemini.ts +120 -0
  27. package/apps/studio/acp/policy/launch-opencode.ts +131 -0
  28. package/apps/studio/acp/policy/opencode-user-config.ts +240 -0
  29. package/apps/studio/acp/probe.ts +78 -14
  30. package/apps/studio/acp/transcript.ts +14 -0
  31. package/apps/studio/acp/write-scope.ts +62 -2
  32. package/apps/studio/annotations-layer.tsx +8 -0
  33. package/apps/studio/bin/_capture-init.js +5 -0
  34. package/apps/studio/bin/screenshot.sh +7 -1
  35. package/apps/studio/bridge/dgn-protocol.ts +3 -2
  36. package/apps/studio/canvas-shell.tsx +54 -0
  37. package/apps/studio/client/panels/ChatPanel.jsx +19 -4
  38. package/apps/studio/client/panels/PermissionPrompt.jsx +11 -6
  39. package/apps/studio/client/panels/SyncConsentDialog.jsx +4 -1
  40. package/apps/studio/client/panels/acp-runtime.js +95 -7
  41. package/apps/studio/client/v2/ai/Advanced.jsx +4 -3
  42. package/apps/studio/client/v2/ai/AgentNotice.jsx +138 -0
  43. package/apps/studio/client/v2/ai/AgentOffer.jsx +110 -0
  44. package/apps/studio/client/v2/ai/AgentPicker.jsx +121 -0
  45. package/apps/studio/client/v2/ai/Composer.jsx +4 -0
  46. package/apps/studio/client/v2/ai/ConnectSheet.jsx +13 -0
  47. package/apps/studio/client/v2/ai/Feed.jsx +8 -0
  48. package/apps/studio/client/v2/ai/NeedsYouSlot.jsx +24 -1
  49. package/apps/studio/client/v2/ai/Suggest.jsx +5 -1
  50. package/apps/studio/client/v2/ai/advanced-model.js +17 -6
  51. package/apps/studio/client/v2/ai/agents-model.js +333 -0
  52. package/apps/studio/client/v2/ai/agents-store.js +223 -0
  53. package/apps/studio/client/v2/ai/ai.css +63 -0
  54. package/apps/studio/client/v2/ai/needs-you.js +1 -1
  55. package/apps/studio/client/v2/empty/empty-host.jsx +11 -2
  56. package/apps/studio/client/v2/empty/use-empty-canvas.js +22 -7
  57. package/apps/studio/client/v2/fold/fold-store.js +1 -0
  58. package/apps/studio/client/v2/preview/preview-chrome-host.jsx +1 -0
  59. package/apps/studio/client/v2/settings/agent-keys.js +88 -0
  60. package/apps/studio/client/v2/settings/agents-card.jsx +408 -0
  61. package/apps/studio/client/v2/settings/connections-model.js +1 -1
  62. package/apps/studio/client/v2/settings/connections-section.jsx +4 -0
  63. package/apps/studio/client/v2/settings/settings-cards.js +2 -1
  64. package/apps/studio/client/v2/settings/settings-model.js +1 -0
  65. package/apps/studio/client/v2/settings/settings.css +7 -0
  66. package/apps/studio/client/v2/shell/served-routes.js +1 -0
  67. package/apps/studio/client/v2/undo/zoom-undo.jsx +19 -2
  68. package/apps/studio/cloud-build.ts +5 -0
  69. package/apps/studio/comments/reveal.ts +13 -0
  70. package/apps/studio/comments-overlay.tsx +36 -0
  71. package/apps/studio/dist/client.bundle.js +535 -535
  72. package/apps/studio/dist/comment-mount.js +2 -2
  73. package/apps/studio/dist/styles.css +1 -1
  74. package/apps/studio/editing/annotation-count.ts +25 -0
  75. package/apps/studio/editing/empty-report.ts +8 -3
  76. package/apps/studio/editing/empty-reporter.tsx +10 -1
  77. package/apps/studio/generation/keys.ts +197 -11
  78. package/apps/studio/outbox/policy.ts +8 -2
  79. package/apps/studio/outbox/types.ts +5 -0
  80. package/apps/studio/routes/agents.ts +479 -0
  81. package/apps/studio/routes/index.ts +3 -0
  82. package/apps/studio/scripts/acp-conformance-local.ts +95 -0
  83. package/apps/studio/scripts/acp-e2e-local.ts +1026 -0
  84. package/apps/studio/server.ts +9 -0
  85. package/apps/studio/sync/index.ts +9 -1
  86. package/apps/studio/sync/writer-registry.ts +12 -0
  87. package/apps/studio/whats-new.json +19 -0
  88. package/apps/studio/ws.ts +3 -0
  89. package/cli/commands/codex.mjs +36 -2
  90. package/cli/lib/harness/codex-runtime.mjs +98 -11
  91. package/package.json +9 -8
@@ -0,0 +1,491 @@
1
+ // Agent discovery (F2 / plan B1, discovery half): which catalog agents are installed on this Mac,
2
+ // at which real path and version, and whether that version is one Maude has tested.
3
+ // Contract: .ai/plans/notes/universal-acp-contract.md (F2) · DDR-252.
4
+ //
5
+ // resolveAgentBin walk the login-shell PATH (the sidecar's own PATH already is that, sidecar.rs)
6
+ // for each `detect.bins` name; follow symlinks (realpath); when a hit is a SHELL
7
+ // script, READ it and follow its `exec` / `export X="<path>"` lines to the real
8
+ // binary. Nothing but the final version probe is ever executed, and that is the
9
+ // resolved real binary, never a wrapper. A wrapper that does not resolve to a
10
+ // non-wrapper is skipped and the search goes on down PATH.
11
+ // probeAgentVersion `<realBin> <versionArgs>` under a hard 5 s kill, scrubbed env, cached by
12
+ // realpath + mtime (+ the args), never on the boot path.
13
+ // discoverAgents lazy, process-cached, one row per CATALOG entry; `force` re-probes.
14
+ //
15
+ // A script whose shebang is a JS/Python runtime (`#!/usr/bin/env node`: an npm-installed agent) is a
16
+ // real entry, not a wrapper: it is launched by its shebang, so `CODEX_PATH` may point at it. Only
17
+ // shell scripts are read for a forward target.
18
+
19
+ import { closeSync, openSync, readSync, realpathSync, statSync } from 'node:fs';
20
+ import { homedir, tmpdir } from 'node:os';
21
+ import { basename, delimiter, isAbsolute, join } from 'node:path';
22
+ import { scrubAgentEnv } from '../env.ts';
23
+ import { resolveClaudePath } from '../probe.ts';
24
+ import { CATALOG, isOfferable } from './catalog.ts';
25
+ import { type AgentDescriptor, type AgentId, type VersionFit, versionFit } from './descriptor.ts';
26
+
27
+ type Env = Record<string, string | undefined>;
28
+
29
+ export const VERSION_PROBE_TIMEOUT_MS = 5000;
30
+ /** Wrapper-of-wrapper depth that is still plausible; anything deeper is a loop or a maze. */
31
+ const MAX_WRAPPER_DEPTH = 5;
32
+ /** A thin wrapper is a few lines; never read more than this of any script. */
33
+ const MAX_SCRIPT_BYTES = 64 * 1024;
34
+ const MAX_PROBE_OUTPUT_BYTES = 16 * 1024;
35
+ /** `?refresh=1` hammered in a loop must not turn into a subprocess storm. */
36
+ const REFRESH_THROTTLE_MS = 1000;
37
+
38
+ const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'ash', 'fish']);
39
+
40
+ // ---------------------------------------------------------------- PATH walk
41
+
42
+ function isExecutableFile(p: string): boolean {
43
+ try {
44
+ const st = statSync(p);
45
+ if (!st.isFile()) return false;
46
+ return process.platform === 'win32' || (st.mode & 0o111) !== 0;
47
+ } catch {
48
+ return false;
49
+ }
50
+ }
51
+
52
+ function safeRealpath(p: string): string | null {
53
+ try {
54
+ return realpathSync(p);
55
+ } catch {
56
+ return null;
57
+ }
58
+ }
59
+
60
+ /** Every executable file named `name` on `env.PATH`, in PATH order (first = what a shell would run). */
61
+ function pathHits(name: string, env: Env): string[] {
62
+ const pathVar = env.PATH ?? env.Path ?? '';
63
+ if (!pathVar) return [];
64
+ const exts =
65
+ process.platform === 'win32'
66
+ ? ['', ...(env.PATHEXT ?? '.EXE;.CMD;.BAT').split(';').filter(Boolean)]
67
+ : [''];
68
+ const out: string[] = [];
69
+ for (const dir of pathVar.split(delimiter)) {
70
+ if (!dir || !isAbsolute(dir)) continue; // an empty or relative entry means "cwd": never search it
71
+ for (const ext of exts) {
72
+ const candidate = join(dir, name + ext);
73
+ if (isExecutableFile(candidate)) out.push(candidate);
74
+ }
75
+ }
76
+ return out;
77
+ }
78
+
79
+ // ---------------------------------------------------------------- reading scripts
80
+
81
+ function readHead(path: string, max: number): string | null {
82
+ let fd: number | null = null;
83
+ try {
84
+ fd = openSync(path, 'r');
85
+ const buf = Buffer.alloc(max);
86
+ const n = readSync(fd, buf, 0, max, 0);
87
+ return buf.subarray(0, n).toString('utf8');
88
+ } catch {
89
+ return null;
90
+ } finally {
91
+ if (fd !== null) {
92
+ try {
93
+ closeSync(fd);
94
+ } catch {
95
+ /* nothing to do */
96
+ }
97
+ }
98
+ }
99
+ }
100
+
101
+ type EntryKind = 'binary' | 'runtime-script' | 'wrapper';
102
+
103
+ /** A file with no shebang is a binary; a shell shebang is a wrapper; any other interpreter is a runtime entry. */
104
+ function classify(head: string): EntryKind {
105
+ if (!head.startsWith('#!')) return 'binary';
106
+ const firstLine = head.slice(2, head.indexOf('\n') === -1 ? undefined : head.indexOf('\n'));
107
+ const words = firstLine.trim().split(/\s+/).filter(Boolean);
108
+ let interp = words[0] ?? '';
109
+ if (basename(interp) === 'env') {
110
+ // `#!/usr/bin/env -S node --flag` / `#!/usr/bin/env FOO=1 bash`
111
+ interp = words.slice(1).find((w) => !w.startsWith('-') && !w.includes('=')) ?? '';
112
+ }
113
+ return SHELLS.has(basename(interp)) ? 'wrapper' : 'runtime-script';
114
+ }
115
+
116
+ /** Split one shell line into words: '…' and "…" quoted, backslash escapes, stops at ; | & #. */
117
+ function shellWords(line: string): string[] {
118
+ const words: string[] = [];
119
+ let cur = '';
120
+ let has = false;
121
+ let quote: '"' | "'" | null = null;
122
+ for (let i = 0; i < line.length; i++) {
123
+ const c = line[i] as string;
124
+ if (quote) {
125
+ if (c === quote) quote = null;
126
+ else if (c === '\\' && quote === '"' && i + 1 < line.length) cur += line[++i];
127
+ else cur += c;
128
+ continue;
129
+ }
130
+ if (c === '"' || c === "'") {
131
+ quote = c;
132
+ has = true;
133
+ } else if (c === '\\' && i + 1 < line.length) {
134
+ cur += line[++i];
135
+ has = true;
136
+ } else if (/\s/.test(c)) {
137
+ if (has) words.push(cur);
138
+ cur = '';
139
+ has = false;
140
+ } else if (c === ';' || c === '|' || c === '&' || (c === '#' && !has)) {
141
+ break;
142
+ } else {
143
+ cur += c;
144
+ has = true;
145
+ }
146
+ }
147
+ if (has) words.push(cur);
148
+ return words;
149
+ }
150
+
151
+ /**
152
+ * Expand `~`, `$NAME` and `${NAME}` against the script's own assignments, then the environment.
153
+ * An unknown variable, a command substitution or a backtick makes the word unresolvable (null):
154
+ * guessing a path is how a wrapper would be pointed somewhere it does not go.
155
+ */
156
+ function expandWord(word: string, vars: Map<string, string>, env: Env): string | null {
157
+ if (word.includes('`') || word.includes('$(')) return null;
158
+ const home = env.HOME ?? homedir();
159
+ let w = word;
160
+ if (w === '~' || w.startsWith('~/')) w = home + w.slice(1);
161
+ let unknown = false;
162
+ w = w.replace(/\$\{(\w+)\}|\$(\w+)/g, (_m, a: string | undefined, b: string | undefined) => {
163
+ const name = (a ?? b) as string;
164
+ const v = vars.get(name) ?? (name === 'HOME' ? home : env[name]);
165
+ if (v === undefined) {
166
+ unknown = true;
167
+ return '';
168
+ }
169
+ return v;
170
+ });
171
+ return unknown ? null : w;
172
+ }
173
+
174
+ /**
175
+ * The forward targets a shell wrapper names, most direct first:
176
+ * 1. `exec <path> …` (through a leading `command`, `env`, `NAME=value`), when <path> is absolute
177
+ * after expansion. `exec maude codex "$@"` names a bare command: not a target.
178
+ * 2. an assigned or exported value (`export MAUDE_CODEX_REAL="$HOME/.local/bin/codex"`) that is
179
+ * an absolute path whose basename is one of the agent's bins: the wrapper's "real binary" knob.
180
+ */
181
+ export function wrapperTargets(text: string, bins: readonly string[], env: Env): string[] {
182
+ const vars = new Map<string, string>();
183
+ const execs: string[] = [];
184
+ const assigned: string[] = [];
185
+ for (const raw of text.split(/\r?\n/)) {
186
+ const line = raw.trim();
187
+ if (!line || line.startsWith('#')) continue;
188
+ const asg = /^(?:export\s+|readonly\s+|declare\s+-x\s+)?([A-Za-z_]\w*)=(.*)$/.exec(line);
189
+ if (asg) {
190
+ const word = shellWords(asg[2] as string)[0];
191
+ const value = word === undefined ? '' : expandWord(word, vars, env);
192
+ if (value !== null) {
193
+ vars.set(asg[1] as string, value);
194
+ if (isAbsolute(value) && bins.includes(basename(value))) assigned.push(value);
195
+ }
196
+ continue;
197
+ }
198
+ const ex = /^exec\s+(.*)$/.exec(line);
199
+ if (!ex) continue;
200
+ const words = shellWords(ex[1] as string);
201
+ let i = 0;
202
+ while (i < words.length) {
203
+ const w = words[i] as string;
204
+ if (w === 'command' || w === 'env' || w === '--') i++;
205
+ else if (w.startsWith('-') && i > 0 && (words[i - 1] === 'env' || words[i - 1] === 'command'))
206
+ i++; // env -i / command -p
207
+ else if (/^[A-Za-z_]\w*=/.test(w))
208
+ i++; // env FOO=bar
209
+ else break;
210
+ }
211
+ const head = words[i];
212
+ if (head === undefined) continue;
213
+ const expanded = expandWord(head, vars, env);
214
+ if (expanded !== null && isAbsolute(expanded)) execs.push(expanded);
215
+ }
216
+ return [...new Set([...execs, ...assigned])];
217
+ }
218
+
219
+ // ---------------------------------------------------------------- resolution
220
+
221
+ function resolveEntry(
222
+ candidate: string,
223
+ bins: readonly string[],
224
+ env: Env,
225
+ depth: number,
226
+ seen: Set<string>
227
+ ): string | null {
228
+ const real = safeRealpath(candidate);
229
+ if (!real || seen.has(real) || !isExecutableFile(real)) return null;
230
+ seen.add(real);
231
+ const head = readHead(real, 256);
232
+ if (head === null) return null;
233
+ if (classify(head) !== 'wrapper') return real;
234
+ if (depth >= MAX_WRAPPER_DEPTH) return null;
235
+ const text = readHead(real, MAX_SCRIPT_BYTES);
236
+ if (text === null) return null;
237
+ for (const target of wrapperTargets(text, bins, env)) {
238
+ const resolved = resolveEntry(target, bins, env, depth + 1, seen);
239
+ if (resolved) return resolved;
240
+ }
241
+ return null;
242
+ }
243
+
244
+ /** The first executable on `env.PATH` named `bin`: the `which` resolveClaudePath is handed. */
245
+ function whichOn(bin: string, env: Env): string | null {
246
+ return pathHits(bin, env)[0] ?? null;
247
+ }
248
+
249
+ /**
250
+ * The real binary of an agent, or null. Claude is whatever `resolveClaudePath()` finds (its
251
+ * `MAUDE_CLAUDE_BIN` override, SHA pin and E2E stubs included), only realpath'd: this module never
252
+ * re-derives it.
253
+ */
254
+ export function resolveAgentBin(d: AgentDescriptor, env: Env = process.env): string | null {
255
+ if (d.id === 'claude') {
256
+ // the process environment: resolveClaudePath's own lookup, untouched (the equality the contract asks for);
257
+ // an explicit env (tests, a different PATH) gets the same lookup over THAT env's PATH
258
+ const found =
259
+ env === process.env
260
+ ? resolveClaudePath(env)
261
+ : resolveClaudePath(env, (bin) => whichOn(bin, env));
262
+ return found ? (safeRealpath(found) ?? found) : null;
263
+ }
264
+ const seen = new Set<string>();
265
+ for (const name of d.detect.bins) {
266
+ for (const hit of pathHits(name, env)) {
267
+ const real = resolveEntry(hit, d.detect.bins, env, 0, seen);
268
+ if (real) return real;
269
+ }
270
+ }
271
+ return null;
272
+ }
273
+
274
+ // ---------------------------------------------------------------- version probe
275
+
276
+ const versionCache = new Map<string, Promise<string | null>>();
277
+
278
+ /** For tests, and for a "Check again" that should not trust any earlier answer. */
279
+ export function clearVersionCache(): void {
280
+ versionCache.clear();
281
+ }
282
+
283
+ async function readCapped(stream: ReadableStream<Uint8Array> | null | undefined): Promise<string> {
284
+ if (!stream) return '';
285
+ const chunks: Uint8Array[] = [];
286
+ let total = 0;
287
+ const reader = stream.getReader();
288
+ try {
289
+ while (total < MAX_PROBE_OUTPUT_BYTES) {
290
+ const { value, done } = await reader.read();
291
+ if (done) break;
292
+ chunks.push(value);
293
+ total += value.byteLength;
294
+ }
295
+ } catch {
296
+ /* a killed child closes its pipes abruptly */
297
+ } finally {
298
+ try {
299
+ await reader.cancel();
300
+ } catch {
301
+ /* nothing to do */
302
+ }
303
+ }
304
+ return Buffer.concat(chunks).toString('utf8');
305
+ }
306
+
307
+ /** SIGKILL the probe's whole process group (it was spawned detached), else just the child. */
308
+ function killGroup(proc: ReturnType<typeof Bun.spawn>): void {
309
+ if (process.platform !== 'win32' && proc.pid > 0) {
310
+ try {
311
+ process.kill(-proc.pid, 'SIGKILL');
312
+ return;
313
+ } catch {
314
+ /* the group is gone, or never formed: fall back to the child */
315
+ }
316
+ }
317
+ try {
318
+ proc.kill('SIGKILL');
319
+ } catch {
320
+ /* already gone */
321
+ }
322
+ }
323
+
324
+ async function runVersion(
325
+ d: AgentDescriptor,
326
+ realBin: string,
327
+ env: Env,
328
+ timeoutMs: number
329
+ ): Promise<string | null> {
330
+ let proc: ReturnType<typeof Bun.spawn>;
331
+ try {
332
+ proc = Bun.spawn([realBin, ...d.detect.versionArgs], {
333
+ env: scrubAgentEnv(env),
334
+ cwd: tmpdir(), // never the served project: a project-local config must not steer a probe
335
+ stdin: 'ignore',
336
+ stdout: 'pipe',
337
+ stderr: 'pipe',
338
+ // Security review 2026-11-12 — its own process group, so the timeout reaches a wrapper's
339
+ // grandchildren too (POSIX; Windows has no groups and keeps the direct kill)
340
+ detached: process.platform !== 'win32',
341
+ });
342
+ } catch {
343
+ return null;
344
+ }
345
+ let timedOut = false;
346
+ const killer = setTimeout(() => {
347
+ timedOut = true;
348
+ killGroup(proc);
349
+ }, timeoutMs);
350
+ let deadline: ReturnType<typeof setTimeout> | undefined;
351
+ try {
352
+ const work = (async () => {
353
+ const [out, err] = await Promise.all([
354
+ readCapped(proc.stdout as ReadableStream<Uint8Array>),
355
+ readCapped(proc.stderr as ReadableStream<Uint8Array>),
356
+ ]);
357
+ await proc.exited;
358
+ return `${out}\n${err}`;
359
+ })();
360
+ // a grandchild that keeps a pipe open must not outlive the kill
361
+ const late = new Promise<null>((resolve) => {
362
+ deadline = setTimeout(() => resolve(null), timeoutMs + 150);
363
+ });
364
+ const text = await Promise.race([work, late]);
365
+ if (timedOut || text === null || proc.exitCode !== 0) return null;
366
+ const m = d.detect.versionRe.exec(text);
367
+ return m?.[1] ?? null;
368
+ } finally {
369
+ clearTimeout(killer);
370
+ if (deadline) clearTimeout(deadline);
371
+ // still running (the late path): nothing of the probe outlives it
372
+ if (proc.exitCode === null && proc.signalCode === null) killGroup(proc);
373
+ }
374
+ }
375
+
376
+ export interface ProbeOptions {
377
+ /** Skip the realpath+mtime cache. */
378
+ force?: boolean;
379
+ timeoutMs?: number;
380
+ env?: Env;
381
+ }
382
+
383
+ /**
384
+ * The semver `realBin` reports, or null (no output match, a crash, a timeout). Cached by realpath +
385
+ * mtime (+ the args), so an in-place upgrade re-probes and nothing else does.
386
+ */
387
+ export function probeAgentVersion(
388
+ d: AgentDescriptor,
389
+ realBin: string,
390
+ opts: ProbeOptions = {}
391
+ ): Promise<string | null> {
392
+ const real = safeRealpath(realBin);
393
+ let mtime: number;
394
+ try {
395
+ mtime = statSync(real ?? realBin).mtimeMs;
396
+ } catch {
397
+ return Promise.resolve(null);
398
+ }
399
+ const key = [real ?? realBin, mtime, d.id, ...d.detect.versionArgs].join('\0');
400
+ if (!opts.force) {
401
+ const hit = versionCache.get(key);
402
+ if (hit) return hit;
403
+ }
404
+ const probe = runVersion(
405
+ d,
406
+ real ?? realBin,
407
+ opts.env ?? process.env,
408
+ opts.timeoutMs ?? VERSION_PROBE_TIMEOUT_MS
409
+ );
410
+ versionCache.set(key, probe);
411
+ return probe;
412
+ }
413
+
414
+ // ---------------------------------------------------------------- discovery
415
+
416
+ export interface DiscoveredAgent {
417
+ id: AgentId;
418
+ label: string;
419
+ vendor: string;
420
+ installed: boolean;
421
+ /** realpath of the agent's own binary (what `CODEX_PATH` etc. is set to), or null. */
422
+ realBin: string | null;
423
+ /** null when not installed or the version could not be read. */
424
+ version: string | null;
425
+ fit: VersionFit | null;
426
+ policy: AgentDescriptor['policy'];
427
+ /** May Studio proactively offer it: bridge-enforced, installed and a tested version. */
428
+ offerable: boolean;
429
+ }
430
+
431
+ export interface DiscoverOptions {
432
+ /** Re-probe everything (throttled to once a second on the process-wide path). */
433
+ force?: boolean;
434
+ /** Lookup environment; absent = the process environment and the process-wide cache. */
435
+ env?: Env;
436
+ catalog?: readonly AgentDescriptor[];
437
+ timeoutMs?: number;
438
+ /** Called as each row settles, so a fast agent is not held back behind a slow probe. */
439
+ onRow?: (row: DiscoveredAgent) => void;
440
+ }
441
+
442
+ async function discoverOne(
443
+ d: AgentDescriptor,
444
+ env: Env,
445
+ opts: DiscoverOptions
446
+ ): Promise<DiscoveredAgent> {
447
+ const realBin = resolveAgentBin(d, env);
448
+ const version = realBin
449
+ ? await probeAgentVersion(d, realBin, { force: opts.force, timeoutMs: opts.timeoutMs, env })
450
+ : null;
451
+ const fit = version ? versionFit(d, version) : null;
452
+ const row: DiscoveredAgent = {
453
+ id: d.id,
454
+ label: d.label,
455
+ vendor: d.vendor,
456
+ installed: realBin !== null,
457
+ realBin,
458
+ version,
459
+ fit,
460
+ policy: d.policy,
461
+ offerable: isOfferable(d) && realBin !== null && fit === 'ok',
462
+ };
463
+ opts.onRow?.(row);
464
+ return row;
465
+ }
466
+
467
+ let processWide: { promise: Promise<DiscoveredAgent[]>; doneAt: number } | null = null;
468
+
469
+ /** One row per catalog entry, probed in parallel (one hanging agent never delays another). */
470
+ export function discoverAgents(opts: DiscoverOptions = {}): Promise<DiscoveredAgent[]> {
471
+ const run = (env: Env, catalog: readonly AgentDescriptor[]) =>
472
+ Promise.all(catalog.map((d) => discoverOne(d, env, opts)));
473
+ if (opts.env || opts.catalog) {
474
+ return run(opts.env ?? process.env, opts.catalog ?? CATALOG);
475
+ }
476
+ const cached = processWide;
477
+ if (cached && (!opts.force || Date.now() - cached.doneAt < REFRESH_THROTTLE_MS)) {
478
+ return cached.promise;
479
+ }
480
+ const entry = {
481
+ promise: run(process.env, CATALOG).finally(() => {
482
+ entry.doneAt = Date.now();
483
+ }),
484
+ doneAt: Number.POSITIVE_INFINITY, // in flight: a force during it joins it
485
+ };
486
+ processWide = entry;
487
+ entry.promise.catch(() => {
488
+ if (processWide === entry) processWide = null; // a failure is not remembered
489
+ });
490
+ return entry.promise;
491
+ }
@@ -0,0 +1,58 @@
1
+ // E2E ONLY — point a non-Claude agent the real server spawns at a loopback scripted model.
2
+ //
3
+ // The local end-to-end run (scripts/acp-e2e-local.ts) drives the REAL server with the REAL agent
4
+ // binaries and must reach the agent's real model path offline, with no account. The production
5
+ // launch policy names no model endpoint, so this switch adds the same model wiring the conformance
6
+ // probe uses (acp/agents/conformance.ts `profileFor(d).injectModel`), after the launch policy, and
7
+ // nothing else: no permission, no MCP server, no hook.
8
+ //
9
+ // Narrow on purpose:
10
+ // • `e2eSwitch` — a release build ignores it whatever its env holds (release-build.ts);
11
+ // • only `http://127.0.0.1:<port>` (no path, no user info) — never a remote endpoint;
12
+ // • never Claude (its model path is the person's own `claude`);
13
+ // • the switch itself is dropped from the agent's env.
14
+
15
+ import { e2eSwitch, IS_RELEASE_BUILD } from '../../release-build.ts';
16
+ import { profileFor } from './conformance.ts';
17
+ import type { AgentDescriptor } from './descriptor.ts';
18
+
19
+ export const E2E_AGENT_MODEL_SWITCH = 'MAUDE_E2E_AGENT_MODEL_URL';
20
+
21
+ /** The loopback model origin the switch names, or null (unset, release build, not loopback http). */
22
+ export function e2eAgentModelUrl(
23
+ env: Readonly<Record<string, string | undefined>>,
24
+ release: boolean = IS_RELEASE_BUILD
25
+ ): string | null {
26
+ const v = e2eSwitch(env as Record<string, string | undefined>, E2E_AGENT_MODEL_SWITCH, release);
27
+ if (!v) return null;
28
+ let u: URL;
29
+ try {
30
+ u = new URL(v);
31
+ } catch {
32
+ return null;
33
+ }
34
+ if (u.protocol !== 'http:' || u.hostname !== '127.0.0.1' || !u.port) return null;
35
+ if (u.username || u.password || u.search || u.hash || (u.pathname !== '/' && u.pathname !== ''))
36
+ return null;
37
+ return `http://127.0.0.1:${u.port}`;
38
+ }
39
+
40
+ /**
41
+ * Apply the switch to one spawn's env (mutated). True when the agent's model now points at the
42
+ * loopback model. The switch never reaches the agent, applied or not.
43
+ */
44
+ export function applyE2eAgentModel(
45
+ d: AgentDescriptor,
46
+ spawnEnv: Record<string, string>,
47
+ env: Readonly<Record<string, string | undefined>> = process.env,
48
+ release: boolean = IS_RELEASE_BUILD
49
+ ): boolean {
50
+ delete spawnEnv[E2E_AGENT_MODEL_SWITCH];
51
+ if (d.policy === 'claude-meta') return false;
52
+ const url = e2eAgentModelUrl(env, release);
53
+ if (!url) return false;
54
+ const profile = profileFor(d);
55
+ if (!profile) return false;
56
+ profile.injectModel(spawnEnv, url);
57
+ return true;
58
+ }
@@ -0,0 +1,46 @@
1
+ // Agent health for this server run (universal ACP, contract rule 12, DDR-252).
2
+ //
3
+ // When the bridge's tripwire sees a completed tool call that broke an agent's launch policy, the
4
+ // session ends and the agent is marked unavailable here: no chat may start it again until the
5
+ // server restarts (or Settings › "Check again" clears it once the conformance probe is green).
6
+ // In memory on purpose: the evidence is this run's frames, and a planted file must never be able
7
+ // to mark an agent healthy.
8
+
9
+ import type { AgentId } from './descriptor.ts';
10
+
11
+ export interface AgentHealth {
12
+ id: AgentId;
13
+ available: boolean;
14
+ /** Why it is unavailable (the tripwire's reason), when it is. */
15
+ reason?: string;
16
+ /** ms since epoch the agent was marked unavailable. */
17
+ since?: number;
18
+ }
19
+
20
+ const unavailable = new Map<AgentId, { reason: string; since: number }>();
21
+
22
+ /** Rule 12 — the launch policy did not hold: no chat starts this agent again this run. */
23
+ export function markAgentUnavailable(id: AgentId, reason: string, now = Date.now()): void {
24
+ if (!unavailable.has(id)) unavailable.set(id, { reason, since: now });
25
+ }
26
+
27
+ export function agentHealth(id: AgentId): AgentHealth {
28
+ const u = unavailable.get(id);
29
+ return u ? { id, available: false, reason: u.reason, since: u.since } : { id, available: true };
30
+ }
31
+
32
+ /** Every agent marked unavailable this run (the agents route lists them in Settings). */
33
+ export function unavailableAgents(): AgentHealth[] {
34
+ return [...unavailable.entries()].map(([id, u]) => ({
35
+ id,
36
+ available: false,
37
+ reason: u.reason,
38
+ since: u.since,
39
+ }));
40
+ }
41
+
42
+ /** Tests, and a "Check again" whose conformance probe passed. No id → every agent. */
43
+ export function clearAgentHealth(id?: AgentId): void {
44
+ if (id === undefined) unavailable.clear();
45
+ else unavailable.delete(id);
46
+ }