@1agh/maude 2.2.1 → 2.3.1

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 (74) 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/client/panels/ChatPanel.jsx +19 -4
  33. package/apps/studio/client/panels/PermissionPrompt.jsx +11 -6
  34. package/apps/studio/client/panels/acp-runtime.js +95 -7
  35. package/apps/studio/client/v2/ai/Advanced.jsx +4 -3
  36. package/apps/studio/client/v2/ai/AgentNotice.jsx +138 -0
  37. package/apps/studio/client/v2/ai/AgentOffer.jsx +110 -0
  38. package/apps/studio/client/v2/ai/AgentPicker.jsx +121 -0
  39. package/apps/studio/client/v2/ai/Composer.jsx +4 -0
  40. package/apps/studio/client/v2/ai/ConnectSheet.jsx +13 -0
  41. package/apps/studio/client/v2/ai/Feed.jsx +8 -0
  42. package/apps/studio/client/v2/ai/NeedsYouSlot.jsx +24 -1
  43. package/apps/studio/client/v2/ai/Suggest.jsx +5 -1
  44. package/apps/studio/client/v2/ai/advanced-model.js +17 -6
  45. package/apps/studio/client/v2/ai/agents-model.js +333 -0
  46. package/apps/studio/client/v2/ai/agents-store.js +223 -0
  47. package/apps/studio/client/v2/ai/ai.css +63 -0
  48. package/apps/studio/client/v2/ai/needs-you.js +1 -1
  49. package/apps/studio/client/v2/fold/fold-store.js +1 -0
  50. package/apps/studio/client/v2/settings/agent-keys.js +88 -0
  51. package/apps/studio/client/v2/settings/agents-card.jsx +408 -0
  52. package/apps/studio/client/v2/settings/connections-model.js +1 -1
  53. package/apps/studio/client/v2/settings/connections-section.jsx +4 -0
  54. package/apps/studio/client/v2/settings/settings-cards.js +2 -1
  55. package/apps/studio/client/v2/settings/settings-model.js +1 -0
  56. package/apps/studio/client/v2/settings/settings.css +7 -0
  57. package/apps/studio/client/v2/shell/served-routes.js +1 -0
  58. package/apps/studio/cloud-build.ts +5 -0
  59. package/apps/studio/dist/client.bundle.js +604 -604
  60. package/apps/studio/dist/styles.css +1 -1
  61. package/apps/studio/generation/keys.ts +197 -11
  62. package/apps/studio/outbox/policy.ts +8 -2
  63. package/apps/studio/outbox/types.ts +5 -0
  64. package/apps/studio/routes/agents.ts +479 -0
  65. package/apps/studio/routes/index.ts +3 -0
  66. package/apps/studio/scripts/acp-conformance-local.ts +95 -0
  67. package/apps/studio/scripts/acp-e2e-local.ts +1026 -0
  68. package/apps/studio/server.ts +9 -0
  69. package/apps/studio/sync/writer-registry.ts +12 -0
  70. package/apps/studio/whats-new.json +10 -0
  71. package/apps/studio/ws.ts +3 -0
  72. package/cli/commands/codex.mjs +36 -2
  73. package/cli/lib/harness/codex-runtime.mjs +98 -11
  74. package/package.json +9 -8
@@ -0,0 +1,479 @@
1
+ // /_api/agents — universal ACP (plan B1 discovery half = F2, B5 auth half + B6 server half = F7;
2
+ // contract .ai/plans/notes/universal-acp-contract.md, DDR-252): which ACP agents this Mac has, which
3
+ // of them the person connected to the Studio chat, and the routes that connect, sign in, disconnect
4
+ // and silence the one-time offer.
5
+ //
6
+ // GET /_api/agents[?refresh=1]
7
+ // → { agents: [Row], offerAgents: [id] }
8
+ // Row = { id, label, vendor, installed, realBin, version, fit, policy, offerable, (F2)
9
+ // connected, connectedAt, auth, offerDismissed, offer, health, connectNote, state }
10
+ // auth 'signed-in' | 'signed-out' | 'not-needed' | 'unknown'
11
+ // health 'ok' | 'unavailable' (acp/agents/health.ts: caught breaking Maude's limits this run)
12
+ // state the Settings › AI agents list word: 'connected' | 'sign-in' | 'untested' |
13
+ // 'unavailable' | 'available'
14
+ // offer Studio may show the one-time offer for this agent; offerAgents = the ids with offer
15
+ // (the UI draws ONE shared line from it)
16
+ // POST /_api/agents/:id/connect body { consent?: boolean }
17
+ // POST /_api/agents/:id/signin → { ok } · GET /signin-status → { auth, inFlight, … }
18
+ // POST /_api/agents/:id/signin-cancel
19
+ // POST /_api/agents/:id/disconnect · POST /_api/agents/:id/dismiss-offer
20
+ // POST /_api/agents/:id/key body { key, optIn? } → { ok, keySet, keyLast4 } (B7)
21
+ // POST /_api/agents/:id/key-remove → { ok, keySet: false }
22
+ // Own API key (DDR-252 § BYOK), in the 0600 key store (generation/keys.ts, `chat` scope). The
23
+ // key is NEVER echoed: rows and answers carry only `keySet` + `keyLast4`. Rows also carry
24
+ // `acceptsKey` (the agent takes one: Codex, Gemini, and Claude behind the opt-in) and, for
25
+ // Claude, `billing: 'api-key' | null`. A stored key counts as signed in: a row whose CLI says
26
+ // `signed-out` reads `signed-in` once a key is stored (the agent will authenticate with it), so
27
+ // `auth` keeps its vocabulary and the list says Connected, not Sign in. Claude's key needs
28
+ // `optIn: true` (the Advanced confirm card: "billed to your API account"); removing it turns
29
+ // the opt-in off. POST, not PUT/DELETE: the route table speaks GET/POST/PATCH.
30
+ //
31
+ // Claude keeps its own `/_api/claude/*` routes untouched. Here Claude is reported from the same
32
+ // readiness probe the chat panel uses (`probeAcpAvailabilityAuthed`), so the two cannot disagree, and
33
+ // its sign-in / status / cancel verbs delegate to the same functions those routes call. Connect,
34
+ // disconnect and dismiss are refused for it: Claude is the chat, not a connectable extra.
35
+ //
36
+ // PRIVILEGED: `origin: 'main'`, in neither canvas allowlist; every table spec sits behind the CSRF
37
+ // + loopback-Host double gate (`guardTableRoute`). About this Mac, not a canvas: `none` in
38
+ // test/_acl-route-classes.ts, `read`/`local` in sync/writer-registry.ts, refused in a cell (a cell
39
+ // runs no local AI; the `:id` paths match no manifest entry and are refused default-closed). The
40
+ // writes are refused in a read-only session, as Claude's own sign-in is.
41
+
42
+ import {
43
+ type AgentAuthState,
44
+ agentAuthStatus,
45
+ agentSigninState,
46
+ cancelAgentSignin,
47
+ startAgentSignin,
48
+ } from '../acp/agents/auth.ts';
49
+ import { agentById, CATALOG } from '../acp/agents/catalog.ts';
50
+ import { acceptsChatKey } from '../acp/agents/chat-key.ts';
51
+ import { createConnectConformance } from '../acp/agents/conformance.ts';
52
+ import type { AgentDescriptor, AgentId } from '../acp/agents/descriptor.ts';
53
+ import {
54
+ type DiscoveredAgent,
55
+ type DiscoverOptions,
56
+ discoverAgents,
57
+ } from '../acp/agents/discover.ts';
58
+ import { agentHealth } from '../acp/agents/health.ts';
59
+ import { type AgentStateStore, createAgentStateStore } from '../acp/agents/state.ts';
60
+ import {
61
+ cancelSignin,
62
+ getClaudeAuthStatus,
63
+ isSigninInFlight,
64
+ startSignin,
65
+ } from '../acp/login-state.ts';
66
+ import { forgetCodexApiLogin } from '../acp/policy/codex-home.ts';
67
+ import { probeAcpAvailabilityAuthed } from '../acp/probe.ts';
68
+ import {
69
+ type ChatKeyStatus,
70
+ chatKeyStatus,
71
+ clearChatKey,
72
+ clearClaudeApiKey,
73
+ setChatKey,
74
+ setClaudeApiKey,
75
+ } from '../generation/keys.ts';
76
+ import { personRequest } from '../shell/api-key.ts';
77
+ import type { RouteSpec } from './table.ts';
78
+
79
+ export type { AgentAuthState };
80
+
81
+ /** The conformance probe's answer (acp/agents/conformance.ts `createConnectConformance`). */
82
+ export interface ConformanceResult {
83
+ pass: boolean;
84
+ /** A short, human sentence for the Connect step when it fails. */
85
+ detail?: string;
86
+ }
87
+
88
+ export interface AgentsRouteDeps {
89
+ /** The discovery to ask; defaults to the real one. Tests hand it a stub. */
90
+ discover?: (opts?: DiscoverOptions) => Promise<DiscoveredAgent[]>;
91
+ /** The catalog `:id` is looked up in; defaults to the real one. */
92
+ catalog?: readonly AgentDescriptor[];
93
+ /** The connected / dismissed store; defaults to this profile's `agents.json`, opened lazily. */
94
+ store?: AgentStateStore;
95
+ /**
96
+ * The conformance probe a connect must pass. Default: the real probe for a bridge-enforced agent
97
+ * (`createConnectConformance`); anything else does not pass.
98
+ */
99
+ conformance?: (d: AgentDescriptor, realBin: string) => Promise<ConformanceResult>;
100
+ authStatus?: (d: AgentDescriptor, realBin: string) => Promise<AgentAuthState>;
101
+ startSignin?: typeof startAgentSignin;
102
+ signinState?: typeof agentSigninState;
103
+ cancelSignin?: typeof cancelAgentSignin;
104
+ /** 'ok', or 'unavailable' when this run caught the agent breaking Maude's limits (acp/agents/health.ts). */
105
+ health?: (id: string) => string;
106
+ /** B7 — the chat-key store; defaults to generation/keys.ts. Never returns a key. */
107
+ keys?: {
108
+ status(id: string): ChatKeyStatus;
109
+ set(id: string, key: unknown): ChatKeyStatus;
110
+ clear(id: string): void;
111
+ setClaude(key: unknown, optIn: unknown): ChatKeyStatus;
112
+ clearClaude(): void;
113
+ };
114
+ /** Claude's side, from the same functions `/_api/claude/*` and `/_api/acp/status` use. */
115
+ claude?: {
116
+ available(): Promise<{ available: boolean; billing?: 'api-key' }>;
117
+ authLoggedIn(): Promise<boolean | null>;
118
+ startSignin(): { ok: boolean; reason?: string };
119
+ cancelSignin(): void;
120
+ signinInFlight(): boolean;
121
+ };
122
+ }
123
+
124
+ const noStore = { 'Cache-Control': 'no-store' };
125
+
126
+ const json = (body: unknown, status = 200) => Response.json(body, { status, headers: noStore });
127
+
128
+ /**
129
+ * Security review 2026-11-12 (defender M5) — connecting an agent, storing or removing a key and the
130
+ * Claude API-key opt-in are the person's acts, never a key-holding helper's: the same check spend
131
+ * approval uses (`personRequest`, shell/api-key.ts). Null = a person; else the 403 answer.
132
+ */
133
+ const notPerson = (req: Request): Response | null =>
134
+ personRequest(req) ? null : json({ ok: false, reason: 'person-only' }, 403);
135
+
136
+ const defaultClaude: NonNullable<AgentsRouteDeps['claude']> = {
137
+ available: probeAcpAvailabilityAuthed,
138
+ authLoggedIn: async () => (await getClaudeAuthStatus())?.loggedIn ?? null,
139
+ startSignin,
140
+ cancelSignin,
141
+ signinInFlight: isSigninInFlight,
142
+ };
143
+
144
+ const defaultKeys: NonNullable<AgentsRouteDeps['keys']> = {
145
+ status: chatKeyStatus,
146
+ set: setChatKey,
147
+ clear: clearChatKey,
148
+ setClaude: (key, optIn) => setClaudeApiKey(key, optIn),
149
+ clearClaude: () => clearClaudeApiKey(),
150
+ };
151
+
152
+ /**
153
+ * F6b — the real probe (acp/agents/conformance.ts): a bridge-enforced agent connects only when it
154
+ * stays inside Maude's limits in a scratch world, and not at all when the person's own config makes
155
+ * Maude refuse it (opencode plugins). Cached per binary for the server run. Tests inject a fake.
156
+ */
157
+ let lazyConformance: ReturnType<typeof createConnectConformance> | undefined;
158
+ const defaultConformance = (d: AgentDescriptor, realBin: string): Promise<ConformanceResult> => {
159
+ if (!lazyConformance) lazyConformance = createConnectConformance();
160
+ return lazyConformance(d, realBin);
161
+ };
162
+
163
+ /** The Settings word for a row (the plan's list: Connected · Sign in · Untested version · Unavailable). */
164
+ export function agentListState(args: {
165
+ installed: boolean;
166
+ fit: DiscoveredAgent['fit'];
167
+ connected: boolean;
168
+ auth: AgentAuthState;
169
+ }): 'connected' | 'sign-in' | 'untested' | 'unavailable' | 'available' {
170
+ if (!args.installed || args.fit === 'too-old') return 'unavailable';
171
+ if (args.fit === 'untested') return 'untested';
172
+ if (args.auth === 'signed-out') return 'sign-in';
173
+ return args.connected ? 'connected' : 'available';
174
+ }
175
+
176
+ async function readBody(req: Request): Promise<Record<string, unknown>> {
177
+ try {
178
+ const text = await req.text();
179
+ if (!text || text.length > 4096) return {};
180
+ const v = JSON.parse(text);
181
+ return v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
182
+ } catch {
183
+ return {};
184
+ }
185
+ }
186
+
187
+ export function createAgentsRoutes(deps: AgentsRouteDeps = {}): RouteSpec[] {
188
+ const catalog = deps.catalog ?? CATALOG;
189
+ const lookup = (id: string) => (deps.catalog ? catalog.find((d) => d.id === id) : agentById(id));
190
+ const discover = (opts?: DiscoverOptions) =>
191
+ deps.discover
192
+ ? deps.discover(opts)
193
+ : discoverAgents(deps.catalog ? { ...opts, catalog: deps.catalog } : opts);
194
+ let lazyStore: AgentStateStore | undefined;
195
+ const store = (): AgentStateStore => {
196
+ if (deps.store) return deps.store;
197
+ if (!lazyStore) lazyStore = createAgentStateStore();
198
+ return lazyStore;
199
+ };
200
+ const conformance = deps.conformance ?? defaultConformance;
201
+ const authOf = deps.authStatus ?? agentAuthStatus;
202
+ const start = deps.startSignin ?? startAgentSignin;
203
+ const signinState = deps.signinState ?? agentSigninState;
204
+ const cancel = deps.cancelSignin ?? cancelAgentSignin;
205
+ const health =
206
+ deps.health ?? ((id: string) => (agentHealth(id as AgentId).available ? 'ok' : 'unavailable'));
207
+ const claude = deps.claude ?? defaultClaude;
208
+ const keys = deps.keys ?? defaultKeys;
209
+ /** A store that cannot be read is "no key" — never a 500 for the whole list. */
210
+ const keyOf = (d: AgentDescriptor | undefined): ChatKeyStatus => {
211
+ if (!d || !acceptsChatKey(d)) return { set: false, last4: null };
212
+ try {
213
+ return keys.status(d.id);
214
+ } catch {
215
+ return { set: false, last4: null };
216
+ }
217
+ };
218
+
219
+ /** The discovered row of one agent (cached discovery), or null. */
220
+ const rowOf = async (id: string): Promise<DiscoveredAgent | null> =>
221
+ (await discover()).find((r) => r.id === id) ?? null;
222
+
223
+ /** Resolve `:id` to its descriptor + row, or the refusing response. */
224
+ const target = async (
225
+ params: Record<string, string>
226
+ ): Promise<{ d: AgentDescriptor; row: DiscoveredAgent } | Response> => {
227
+ const d = lookup(params.id ?? '');
228
+ if (!d) return json({ ok: false, reason: 'unknown-agent' }, 404);
229
+ const row = await rowOf(d.id);
230
+ if (!row) return json({ ok: false, reason: 'unknown-agent' }, 404);
231
+ return { d, row };
232
+ };
233
+
234
+ /** A write: main origin, refused in a read-only session. `path` stays a literal in each call. */
235
+ const write = (spec: Pick<RouteSpec, 'path' | 'handle'>): RouteSpec => ({
236
+ method: 'POST',
237
+ origin: 'main',
238
+ readOnly: 'refused',
239
+ ...spec,
240
+ });
241
+
242
+ return [
243
+ {
244
+ method: 'GET',
245
+ path: '/_api/agents',
246
+ origin: 'main',
247
+ readOnly: 'allowed',
248
+ handle: async (req) => {
249
+ const force = new URL(req.url).searchParams.get('refresh') === '1';
250
+ try {
251
+ const rows = await discover({ force });
252
+ const state = store().read();
253
+ const claudeAvail = rows.some((r) => r.id === 'claude' && r.installed)
254
+ ? await claude.available()
255
+ : { available: false };
256
+ const agents = await Promise.all(
257
+ rows.map(async (row) => {
258
+ const d = lookup(row.id);
259
+ const rec = state.connected[row.id];
260
+ let auth: AgentAuthState = 'unknown';
261
+ if (row.id === 'claude') {
262
+ if (row.installed)
263
+ auth = claudeAvail.available
264
+ ? 'signed-in'
265
+ : (await claude.authLoggedIn()) === false
266
+ ? 'signed-out'
267
+ : 'unknown';
268
+ } else if (d && row.installed && row.realBin && row.fit === 'ok') {
269
+ auth = await authOf(d, row.realBin);
270
+ } else if (d?.auth.gate === 'none') {
271
+ auth = 'not-needed';
272
+ }
273
+ // B7 — a stored key signs the agent in (it authenticates with it at session start).
274
+ const key = keyOf(d);
275
+ if (key.set && row.id !== 'claude' && auth === 'signed-out') auth = 'signed-in';
276
+ const connected = row.id === 'claude' ? claudeAvail.available : rec !== undefined;
277
+ const offerDismissed = state.offerDismissed[row.id] === true;
278
+ const healthy = health(row.id) === 'ok';
279
+ const offer =
280
+ healthy &&
281
+ row.id !== 'claude' &&
282
+ row.offerable &&
283
+ !connected &&
284
+ !offerDismissed &&
285
+ rows.some((r) => r.id !== 'claude' && r.installed);
286
+ return {
287
+ ...row,
288
+ connected,
289
+ connectedAt: rec?.at ?? null,
290
+ auth,
291
+ offerDismissed,
292
+ offer,
293
+ health: healthy ? 'ok' : 'unavailable',
294
+ connectNote: d?.connectNote ?? null,
295
+ acceptsKey: d ? acceptsChatKey(d) : false,
296
+ keySet: key.set,
297
+ keyLast4: key.last4,
298
+ ...(row.id === 'claude'
299
+ ? {
300
+ billing:
301
+ claudeAvail.available && claudeAvail.billing === 'api-key'
302
+ ? 'api-key'
303
+ : null,
304
+ }
305
+ : {}),
306
+ state: healthy
307
+ ? agentListState({ installed: row.installed, fit: row.fit, connected, auth })
308
+ : 'unavailable',
309
+ };
310
+ })
311
+ );
312
+ return json({ agents, offerAgents: agents.filter((a) => a.offer).map((a) => a.id) });
313
+ } catch (err) {
314
+ return json(
315
+ { ok: false, error: err instanceof Error ? err.message : 'Could not look for agents.' },
316
+ 500
317
+ );
318
+ }
319
+ },
320
+ },
321
+
322
+ write({
323
+ path: '/_api/agents/:id/connect',
324
+ handle: async (req, params) => {
325
+ const refused = notPerson(req);
326
+ if (refused) return refused;
327
+ const t = await target(params);
328
+ if (t instanceof Response) return t;
329
+ const { d, row } = t;
330
+ if (d.id === 'claude') return json({ ok: false, reason: 'use-claude-routes' }, 409);
331
+ if (!row.installed || !row.realBin)
332
+ return json({ ok: false, reason: 'not-installed' }, 409);
333
+ if (row.fit === 'too-old') return json({ ok: false, reason: 'version-too-old' }, 409);
334
+ if (row.fit !== 'ok') return json({ ok: false, reason: 'untested-version' }, 409);
335
+ if (d.policy === 'unrestricted' && (await readBody(req)).consent !== true)
336
+ return json({ ok: false, reason: 'consent-required' }, 409);
337
+ if (d.auth.gate === 'session-new' && !keyOf(d).set) {
338
+ const auth = await authOf(d, row.realBin);
339
+ if (auth === 'signed-out') return json({ ok: false, needsSignin: true });
340
+ }
341
+ let result: ConformanceResult;
342
+ try {
343
+ result = await conformance(d, row.realBin);
344
+ } catch (err) {
345
+ result = { pass: false, detail: err instanceof Error ? err.message : undefined };
346
+ }
347
+ if (!result.pass)
348
+ return json({
349
+ ok: false,
350
+ reason: 'conformance-failed',
351
+ ...(result.detail ? { detail: result.detail } : {}),
352
+ });
353
+ const at = Date.now();
354
+ store().markConnected(d.id, row.version, at);
355
+ return json({ ok: true, connected: true, at, version: row.version });
356
+ },
357
+ }),
358
+
359
+ write({
360
+ path: '/_api/agents/:id/signin',
361
+ handle: async (_req, params) => {
362
+ const t = await target(params);
363
+ if (t instanceof Response) return t;
364
+ const { d, row } = t;
365
+ if (d.id === 'claude') {
366
+ const r = claude.startSignin();
367
+ return json(r, r.ok ? 200 : 409);
368
+ }
369
+ if (!row.installed || !row.realBin)
370
+ return json({ ok: false, reason: 'not-installed' }, 409);
371
+ const r = start(d, row.realBin);
372
+ return json(r, r.ok ? 200 : 409);
373
+ },
374
+ }),
375
+
376
+ {
377
+ method: 'GET',
378
+ path: '/_api/agents/:id/signin-status',
379
+ origin: 'main',
380
+ readOnly: 'allowed',
381
+ handle: async (_req, params) => {
382
+ const t = await target(params);
383
+ if (t instanceof Response) return t;
384
+ const { d, row } = t;
385
+ if (d.id === 'claude') {
386
+ const loggedIn = row.installed ? await claude.authLoggedIn() : null;
387
+ return json({
388
+ auth: loggedIn === null ? 'unknown' : loggedIn ? 'signed-in' : 'signed-out',
389
+ inFlight: claude.signinInFlight(),
390
+ startedAt: null,
391
+ lastExit: null,
392
+ });
393
+ }
394
+ const sign = signinState(d.id);
395
+ const auth: AgentAuthState =
396
+ row.installed && row.realBin ? await authOf(d, row.realBin) : 'unknown';
397
+ return json({ auth, ...sign });
398
+ },
399
+ },
400
+
401
+ write({
402
+ path: '/_api/agents/:id/signin-cancel',
403
+ handle: async (_req, params) => {
404
+ const d = lookup(params.id ?? '');
405
+ if (!d) return json({ ok: false, reason: 'unknown-agent' }, 404);
406
+ if (d.id === 'claude') claude.cancelSignin();
407
+ else cancel(d.id);
408
+ return json({ ok: true });
409
+ },
410
+ }),
411
+
412
+ write({
413
+ path: '/_api/agents/:id/disconnect',
414
+ handle: async (_req, params) => {
415
+ const d = lookup(params.id ?? '');
416
+ if (!d) return json({ ok: false, reason: 'unknown-agent' }, 404);
417
+ if (d.id === 'claude') return json({ ok: false, reason: 'use-claude-routes' }, 409);
418
+ store().disconnect(d.id);
419
+ return json({ ok: true });
420
+ },
421
+ }),
422
+
423
+ write({
424
+ path: '/_api/agents/:id/dismiss-offer',
425
+ handle: async (_req, params) => {
426
+ const d = lookup(params.id ?? '');
427
+ if (!d) return json({ ok: false, reason: 'unknown-agent' }, 404);
428
+ if (d.id === 'claude') return json({ ok: false, reason: 'use-claude-routes' }, 409);
429
+ store().dismissOffer(d.id);
430
+ return json({ ok: true });
431
+ },
432
+ }),
433
+
434
+ // B7 — own API key. The answer carries presence + last four only; nothing here logs the body.
435
+ write({
436
+ path: '/_api/agents/:id/key',
437
+ handle: async (req, params) => {
438
+ const refused = notPerson(req);
439
+ if (refused) return refused;
440
+ const d = lookup(params.id ?? '');
441
+ if (!d) return json({ ok: false, reason: 'unknown-agent' }, 404);
442
+ if (!acceptsChatKey(d)) return json({ ok: false, reason: 'no-api-key' }, 409);
443
+ const body = await readBody(req);
444
+ if (d.id === 'claude' && body.optIn !== true)
445
+ return json({ ok: false, reason: 'opt-in-required' }, 409);
446
+ let status: ChatKeyStatus;
447
+ try {
448
+ status = d.id === 'claude' ? keys.setClaude(body.key, true) : keys.set(d.id, body.key);
449
+ } catch (err) {
450
+ const invalid = err instanceof Error && err.message === 'invalid key';
451
+ return json(
452
+ { ok: false, reason: invalid ? 'invalid-key' : 'store-failed' },
453
+ invalid ? 400 : 500
454
+ );
455
+ }
456
+ return json({ ok: true, keySet: status.set, keyLast4: status.last4 });
457
+ },
458
+ }),
459
+
460
+ write({
461
+ path: '/_api/agents/:id/key-remove',
462
+ handle: async (req, params) => {
463
+ const refused = notPerson(req);
464
+ if (refused) return refused;
465
+ const d = lookup(params.id ?? '');
466
+ if (!d) return json({ ok: false, reason: 'unknown-agent' }, 404);
467
+ if (!acceptsChatKey(d)) return json({ ok: false, reason: 'no-api-key' }, 409);
468
+ try {
469
+ if (d.id === 'claude') keys.clearClaude();
470
+ else keys.clear(d.id);
471
+ if (d.id === 'codex') forgetCodexApiLogin(); // S1 (M2): Codex's key login goes with the key
472
+ } catch {
473
+ return json({ ok: false, reason: 'store-failed' }, 500);
474
+ }
475
+ return json({ ok: true, keySet: false, keyLast4: null });
476
+ },
477
+ }),
478
+ ];
479
+ }
@@ -17,6 +17,7 @@
17
17
  import { resolveAccess } from '../access/scope.ts';
18
18
  import { createAgentRuns } from '../agent-runs.ts';
19
19
  import { type AgentRouteDeps, agentRouteSpecs } from './agent.ts';
20
+ import { createAgentsRoutes } from './agents.ts';
20
21
  import { type AiRouteDeps, createAiRoutes } from './ai.ts';
21
22
  import { type AnnotationRouteDeps, createAnnotationRoutes } from './annotations.ts';
22
23
  import { type AssetDetailsRouteDeps, createAssetDetailsRoutes } from './asset-details.ts';
@@ -232,6 +233,8 @@ export function allSpecs(deps: RouteDeps): RouteSpec[] {
232
233
  ...(deps.export ? createExportRoutes(deps.export) : []),
233
234
  // S7.4 — GET /_api/comp-media (routes/video.ts): the comp's words, speech and beats derived from
234
235
  // its cut. It needs only the design root and its name, which the present and ai deps already carry.
236
+ // F2 — GET /_api/agents (routes/agents.ts): which ACP agents this Mac has (privileged, main origin)
237
+ ...createAgentsRoutes(),
235
238
  ...createVideoRoutes({
236
239
  designRoot: deps.present.designRoot,
237
240
  designRel: deps.ai.designRel,
@@ -0,0 +1,95 @@
1
+ #!/usr/bin/env bun
2
+ // Run the ACP conformance probe (acp/agents/conformance.ts) against the agents installed on THIS
3
+ // machine. Local only, never in CI: it needs the real codex / opencode binaries. Offline (loopback
4
+ // scripted model), scratch HOME, no credentials.
5
+ //
6
+ // bun apps/studio/scripts/acp-conformance-local.ts [codex|opencode ...]
7
+ // [--codex-bin <path>] probe another codex binary (e.g. a scratch @openai/codex install)
8
+ // [--bin <path>] the agent binary to probe (gemini: its bundle/gemini.js, with
9
+ // PROBE_PATH naming a PATH that has node)
10
+ // [--git none|project|both] opencode project outside git / its own git repo (default both)
11
+ // [--frames <dir>] write every frame + model request per run
12
+ // [--keep] keep the scratch worlds
13
+ // [--json] print the raw results
14
+ // [--control] POSITIVE CONTROL: undo the F6b isolation after the launch policy
15
+ // (Codex: the person's own CODEX_HOME back; opencode: no MCP
16
+ // disables, no OPENCODE_PURE; Copilot / Gemini: the person's own
17
+ // home back, no Maude system settings) to show the planted MCP server and
18
+ // hooks/plugins really run when nothing stops them. Expect FAILs.
19
+
20
+ import { mkdirSync } from 'node:fs';
21
+ import { join } from 'node:path';
22
+
23
+ import { agentById, COPILOT_ENFORCEMENT, GEMINI_ENFORCEMENT } from '../acp/agents/catalog.ts';
24
+ import {
25
+ type ConformanceOptions,
26
+ type ConformanceResult,
27
+ runConformance,
28
+ } from '../acp/agents/conformance.ts';
29
+ import type { AgentDescriptor } from '../acp/agents/descriptor.ts';
30
+ import { discoverAgents } from '../acp/agents/discover.ts';
31
+
32
+ const argv = process.argv.slice(2);
33
+ const flag = (n: string) => {
34
+ const i = argv.indexOf(n);
35
+ return i >= 0 ? argv[i + 1] : undefined;
36
+ };
37
+ const valued = new Set(['--codex-bin', '--bin', '--git', '--frames']);
38
+ const ids = argv.filter((a, i) => !a.startsWith('--') && !valued.has(argv[i - 1] ?? ''));
39
+ const wanted = ids.length ? ids : ['codex', 'opencode'];
40
+ const gitModes =
41
+ (flag('--git') ?? 'both') === 'both' ? ['none', 'project'] : [flag('--git') as string];
42
+ const frames = flag('--frames');
43
+ const control: ConformanceOptions['extraEnv'] = argv.includes('--control')
44
+ ? (w, env): Record<string, string> => {
45
+ if (env.OPENCODE_CONFIG_CONTENT) {
46
+ const cfg = JSON.parse(env.OPENCODE_CONFIG_CONTENT);
47
+ cfg.mcp = {};
48
+ return { OPENCODE_CONFIG_CONTENT: JSON.stringify(cfg), OPENCODE_PURE: '0' };
49
+ }
50
+ // B8 — the person's own Copilot / Gemini home back, and no Maude system settings.
51
+ if (env.COPILOT_HOME) return { COPILOT_HOME: join(w.home, '.copilot') };
52
+ if (env.GEMINI_CLI_HOME) {
53
+ return { GEMINI_CLI_HOME: w.home, GEMINI_CLI_SYSTEM_SETTINGS_PATH: join(w.base, 'none') };
54
+ }
55
+ return { CODEX_HOME: w.codexHome };
56
+ }
57
+ : undefined;
58
+ if (frames) mkdirSync(frames, { recursive: true });
59
+
60
+ const rows = await discoverAgents({ force: true });
61
+ const results: { label: string; result: ConformanceResult }[] = [];
62
+ for (const id of wanted) {
63
+ const found = agentById(id);
64
+ if (!found) throw new Error(`unknown agent ${id}`);
65
+ // B8 — an agent still 'unrestricted' in the catalog is probed with its candidate enforcement.
66
+ const candidate = { gemini: GEMINI_ENFORCEMENT, copilot: COPILOT_ENFORCEMENT }[id];
67
+ const d: AgentDescriptor =
68
+ !found.enforcement && candidate ? { ...found, enforcement: candidate } : found;
69
+ const row = rows.find((r) => r.id === id);
70
+ const bin = (id === 'codex' ? flag('--codex-bin') : undefined) ?? flag('--bin') ?? row?.realBin;
71
+ if (!bin) {
72
+ console.log(`${id}: not installed`);
73
+ continue;
74
+ }
75
+ const modes = id === 'codex' ? ['none'] : gitModes;
76
+ for (const git of modes) {
77
+ const label = `${id} ${git === 'project' ? '(project is a git repo)' : '(no git)'}${control ? ' [CONTROL: isolation undone]' : ''}`;
78
+ const t = Date.now();
79
+ const result = await runConformance(d, bin, {
80
+ git: git as 'none' | 'project',
81
+ keepScratch: argv.includes('--keep'),
82
+ framesLog: frames ? join(frames, `${id}-${git}.ndjson`) : undefined,
83
+ extraEnv: control,
84
+ // A node-script agent (Gemini CLI) needs its runtime on PATH: PROBE_PATH replaces the default.
85
+ path: process.env.PROBE_PATH,
86
+ });
87
+ results.push({ label, result });
88
+ console.log(
89
+ `\n${label} — ${bin} v${result.agentVersion ?? '?'} — ${result.pass ? 'PASS' : 'FAIL'} in ${Math.round((Date.now() - t) / 1000)} s`
90
+ );
91
+ for (const c of result.checks)
92
+ console.log(` ${c.ok ? 'ok ' : 'FAIL'} ${c.name}: ${c.detail}`);
93
+ }
94
+ }
95
+ if (argv.includes('--json')) console.log(JSON.stringify(results, null, 2));