@1agh/maude 2.2.0 → 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 (79) 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/canvas-pages-view.tsx +3 -2
  33. package/apps/studio/canvas-theme-pill.tsx +125 -72
  34. package/apps/studio/client/panels/ChatPanel.jsx +19 -4
  35. package/apps/studio/client/panels/PermissionPrompt.jsx +11 -6
  36. package/apps/studio/client/panels/acp-runtime.js +95 -7
  37. package/apps/studio/client/v2/ai/Advanced.jsx +4 -3
  38. package/apps/studio/client/v2/ai/AgentNotice.jsx +138 -0
  39. package/apps/studio/client/v2/ai/AgentOffer.jsx +110 -0
  40. package/apps/studio/client/v2/ai/AgentPicker.jsx +121 -0
  41. package/apps/studio/client/v2/ai/Composer.jsx +4 -0
  42. package/apps/studio/client/v2/ai/ConnectSheet.jsx +13 -0
  43. package/apps/studio/client/v2/ai/Feed.jsx +8 -0
  44. package/apps/studio/client/v2/ai/NeedsYouSlot.jsx +24 -1
  45. package/apps/studio/client/v2/ai/Suggest.jsx +5 -1
  46. package/apps/studio/client/v2/ai/advanced-model.js +17 -6
  47. package/apps/studio/client/v2/ai/agents-model.js +333 -0
  48. package/apps/studio/client/v2/ai/agents-store.js +223 -0
  49. package/apps/studio/client/v2/ai/ai.css +63 -0
  50. package/apps/studio/client/v2/ai/needs-you.js +1 -1
  51. package/apps/studio/client/v2/fold/fold-store.js +1 -0
  52. package/apps/studio/client/v2/left-panel/left-panel.css +8 -0
  53. package/apps/studio/client/v2/settings/agent-keys.js +88 -0
  54. package/apps/studio/client/v2/settings/agents-card.jsx +408 -0
  55. package/apps/studio/client/v2/settings/connections-model.js +1 -1
  56. package/apps/studio/client/v2/settings/connections-section.jsx +4 -0
  57. package/apps/studio/client/v2/settings/settings-cards.js +2 -1
  58. package/apps/studio/client/v2/settings/settings-model.js +1 -0
  59. package/apps/studio/client/v2/settings/settings.css +7 -0
  60. package/apps/studio/client/v2/shell/served-routes.js +1 -0
  61. package/apps/studio/cloud-build.ts +5 -0
  62. package/apps/studio/dist/client.bundle.js +604 -604
  63. package/apps/studio/dist/styles.css +1 -1
  64. package/apps/studio/ds/board/board.css +4 -78
  65. package/apps/studio/ds/board/ds-bar.tsx +15 -9
  66. package/apps/studio/generation/keys.ts +197 -11
  67. package/apps/studio/outbox/policy.ts +8 -2
  68. package/apps/studio/outbox/types.ts +5 -0
  69. package/apps/studio/routes/agents.ts +479 -0
  70. package/apps/studio/routes/index.ts +3 -0
  71. package/apps/studio/scripts/acp-conformance-local.ts +95 -0
  72. package/apps/studio/scripts/acp-e2e-local.ts +1026 -0
  73. package/apps/studio/server.ts +9 -0
  74. package/apps/studio/sync/writer-registry.ts +12 -0
  75. package/apps/studio/whats-new.json +19 -0
  76. package/apps/studio/ws.ts +3 -0
  77. package/cli/commands/codex.mjs +36 -2
  78. package/cli/lib/harness/codex-runtime.mjs +98 -11
  79. package/package.json +9 -8
@@ -9,7 +9,7 @@
9
9
  // auth precedence falls through to the user's Pro/Max subscription.
10
10
 
11
11
  import { randomBytes } from 'node:crypto';
12
- import { rmSync, statSync } from 'node:fs';
12
+ import { existsSync, rmSync, statSync } from 'node:fs';
13
13
  import { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises';
14
14
  import { delimiter, dirname, isAbsolute, join, resolve } from 'node:path';
15
15
 
@@ -22,6 +22,7 @@ import {
22
22
  ndJsonStream,
23
23
  PROTOCOL_VERSION,
24
24
  type PromptResponse,
25
+ RequestError,
25
26
  type RequestPermissionRequest,
26
27
  type RequestPermissionResponse,
27
28
  type SessionConfigOption,
@@ -35,6 +36,10 @@ import { HANDOFF_RUN_VERBS } from '../handoff/write-scopes.ts';
35
36
  import { DEV_SERVER_ROOT } from '../paths.ts';
36
37
  import { readUiPrefs } from '../ui-prefs.ts';
37
38
  import { relayAdapterLine } from './adapter-stderr.ts';
39
+ import { CLAUDE } from './agents/catalog.ts';
40
+ import { type AgentDescriptor, isRefusedConfigValue, type PolicyCtx } from './agents/descriptor.ts';
41
+ import { applyE2eAgentModel } from './agents/e2e-model.ts';
42
+ import { agentSpawn } from './agents/spawn.ts';
38
43
  import {
39
44
  type AudienceLeak,
40
45
  audienceLeak,
@@ -54,7 +59,7 @@ import {
54
59
  foldSnapshot,
55
60
  sameTasks,
56
61
  } from './background-tasks.ts';
57
- import { chatSpawnEnv, scrubAgentEnv, teamsSpawnEnv } from './env.ts';
62
+ import { scrubAgentEnv } from './env.ts';
58
63
  import {
59
64
  type AiMay,
60
65
  assetsRootsFor,
@@ -77,7 +82,11 @@ import {
77
82
  readVerdict,
78
83
  } from './may-scope.ts';
79
84
  import { type SdkPluginConfig, suppressionFor } from './plugin-bootstrap.ts';
85
+ import { FORBIDDEN_METHOD_ERROR, type GateResult, isRefusedMode } from './policy/enforce.ts';
86
+ import type { PermissionGate } from './policy/gate-types.ts';
80
87
  import {
88
+ type AgentInfo,
89
+ agentInfoOf,
81
90
  resolveAdapterEntry,
82
91
  resolveAgentClaudeExecutable,
83
92
  resolveAgentRuntime,
@@ -99,6 +108,31 @@ import {
99
108
  export interface AcpBridgeOptions {
100
109
  /** Absolute repo root the ACP session runs in (where `.design/` + the CLI operate). */
101
110
  repoRoot: string;
111
+ /**
112
+ * F3 (universal ACP, DDR-252) — which agent this bridge spawns. Absent → Claude, exactly as
113
+ * before the descriptor existed (test/acp-agent-spawn.test.ts pins it byte for byte).
114
+ */
115
+ agent?: AgentDescriptor;
116
+ /**
117
+ * F3 — another agent's real binary, from discovery (acp/agents/discover.ts, F2): `CODEX_PATH`
118
+ * for an adapter, argv[0] for a native-ACP agent. Claude ignores it and resolves its own
119
+ * (`resolveClaudePath`, the trusted `MAUDE_CLAUDE_BIN` override).
120
+ */
121
+ agentBin?: string;
122
+ /**
123
+ * B3 — the permission gate of an agent that is not Claude (acp/policy/bridge-gate.ts over
124
+ * enforce.ts, contract rules 1–13). Every `session/request_permission` of such an agent goes
125
+ * through it and never reaches the Claude-shaped gates. A non-Claude agent with none is refused
126
+ * everything (fail closed).
127
+ */
128
+ permissionGate?: PermissionGate;
129
+ /**
130
+ * B3 rule 12 — the tripwire saw a completed tool call that broke the agent's launch policy. The
131
+ * bridge stops itself right after; the caller marks the agent unavailable and tells the panel.
132
+ */
133
+ onPolicyViolation?: (reason: string) => void;
134
+ /** B3 — a one-line note for the panel (a "AI may" restart that could not keep the session). */
135
+ onNote?: (note: { kind: string; message: string }) => void;
102
136
  /**
103
137
  * P8 c7 (decision maude/v2-p8-c7-ai-may-enforced) — the project's design root, whose `assets/` folder
104
138
  * "Use Assets and footage" covers (acp/may-scope.ts). Absent → `<repoRoot>/.design`.
@@ -309,6 +343,24 @@ export interface BridgeUsage {
309
343
  rateLimit?: unknown;
310
344
  }
311
345
 
346
+ /**
347
+ * B4 — the studio brief as the first block of a non-Claude agent's first prompt (no system-prompt
348
+ * channel). Marked as Maude's, so the agent does not read it as the person's words.
349
+ */
350
+ export function studioBriefPreamble(brief: string): string {
351
+ return `<maude-studio-brief>\nEnvironment facts from the Maude studio (not the person's message):\n${brief}\n</maude-studio-brief>`;
352
+ }
353
+
354
+ /**
355
+ * B3 — the Claude tool name an ACP `kind` stands for, for an agent that sends no name (the read
356
+ * tracker and the writer-verb hold know Claude's names). A kind not listed is tracked as nothing.
357
+ */
358
+ const KIND_AS_TOOL_NAME: Readonly<Record<string, string>> = Object.freeze({
359
+ read: 'Read',
360
+ search: 'Grep',
361
+ execute: 'Bash',
362
+ });
363
+
312
364
  /** Flatten a `SessionConfigSelect.options` — a flat option array OR grouped
313
365
  * (`SessionConfigSelectGroup[]`) — into one list of `{value,name}` leaves. */
314
366
  function flattenSelectOptions(options: unknown): Array<{ value: string; name?: string | null }> {
@@ -785,6 +837,30 @@ export function newSessionParams(
785
837
  };
786
838
  }
787
839
 
840
+ /**
841
+ * F3 — session/new params for `descriptor`. Claude ('claude-meta') gets `newSessionParams`
842
+ * unchanged. Any other agent gets no `_meta.claudeCode` at all (it would ignore it, and a reader
843
+ * would take it for a policy that holds): its policy is the launch policy + the bridge gate.
844
+ */
845
+ export function newSessionParamsFor(
846
+ descriptor: AgentDescriptor,
847
+ ...args: Parameters<typeof newSessionParams>
848
+ ): { cwd: string; mcpServers: never[]; _meta?: Record<string, unknown> } {
849
+ if (descriptor.policy === 'claude-meta') return newSessionParams(...args);
850
+ return { cwd: args[0], mcpServers: [] };
851
+ }
852
+
853
+ /** F3 (rule 10) — a mode outside the agent's `enforcement.pinMode.allow` (S1: an allowlist). */
854
+ export class ModeRefusedError extends Error {
855
+ constructor(
856
+ readonly modeId: string,
857
+ label: string
858
+ ) {
859
+ super(`Maude keeps ${label} out of the "${modeId}" mode in this chat.`);
860
+ this.name = 'ModeRefusedError';
861
+ }
862
+ }
863
+
788
864
  // Milestone B (DDR-125 F2 retirement) — how long a permission request waits
789
865
  // for a human decision before the bridge settles it itself. Generous (a
790
866
  // person reading a tool-call card and clicking a button, not a network hop)
@@ -1016,7 +1092,32 @@ export class AcpBridge {
1016
1092
  /** re-check 2 M-c — which repo files git does not track (private for the audience gate). */
1017
1093
  private readonly repoPrivacy: RepoPrivacy;
1018
1094
 
1095
+ /** F3 — the agent this bridge spawns (default Claude). */
1096
+ private readonly agent: AgentDescriptor;
1097
+ /**
1098
+ * F3 — from `initialize`: whether the agent can load a persisted session at all. A promise,
1099
+ * because `ensureStarted` lets a second caller through once `conn` exists — before the
1100
+ * handshake has answered — so a session may be established while `initialize` is in flight.
1101
+ */
1102
+ private canLoadSession: Promise<boolean> = Promise.resolve(false);
1103
+ /**
1104
+ * B4 — from `initialize`: the agent takes a client system prompt on session/new and session/load
1105
+ * (`agentCapabilities.sessionCapabilities.systemPrompt`, codex-acp). Else the studio brief rides
1106
+ * the first prompt of each new session as a preamble (`briefPending`). Claude never uses either:
1107
+ * its brief rides `_meta` (newSessionParams).
1108
+ */
1109
+ private canSystemPrompt: Promise<boolean> = Promise.resolve(false);
1110
+ /** B4 — new sessions whose first prompt still owes the studio-brief preamble. */
1111
+ private readonly briefPending = new Set<string>();
1112
+ /** B3 rule 13 — why the running turn ended on a Maude refusal ("Codex stopped: …"), if it did. */
1113
+ private turnRefusal: string | null = null;
1114
+ /** B3 rule 12 — the tripwire fired once; everything after is teardown. */
1115
+ private violated = false;
1116
+ /** Review S1 — the mode/config pins ran for this session; an agent-side move to a refused value after this ends it. */
1117
+ private pinsApplied = false;
1118
+
1019
1119
  constructor(private readonly opts: AcpBridgeOptions) {
1120
+ this.agent = opts.agent ?? CLAUDE;
1020
1121
  this.scopeRoot = pinScopeRoot(opts.repoRoot);
1021
1122
  const instance = randomBytes(6).toString('hex');
1022
1123
  this.scratch = chatScratchDir(opts.repoRoot, opts.chatId, instance);
@@ -1081,12 +1182,93 @@ export class AcpBridge {
1081
1182
 
1082
1183
  /** The last-advertised mode roster + current mode (read-only snapshot). */
1083
1184
  get modes(): SessionModeState | null {
1084
- return this.lastModes;
1185
+ return this.visibleModes();
1186
+ }
1187
+
1188
+ /** F3 — which agent this bridge runs (the `caps` frame names it). */
1189
+ get agentInfo(): AgentInfo {
1190
+ return agentInfoOf(this.agent);
1191
+ }
1192
+
1193
+ /**
1194
+ * B3 — who an error came from, for a non-Claude agent ("Codex reported: …", with the vendor's
1195
+ * status page). Null for Claude: its errors read as they always have.
1196
+ */
1197
+ get agentAttribution(): { id: string; label: string; vendor: string; statusUrl?: string } | null {
1198
+ const d = this.agent;
1199
+ if (d.policy === 'claude-meta') return null;
1200
+ return {
1201
+ id: d.id,
1202
+ label: d.label,
1203
+ vendor: d.vendor,
1204
+ ...(d.statusUrl ? { statusUrl: d.statusUrl } : {}),
1205
+ };
1206
+ }
1207
+
1208
+ /** F3 (rule 10) — true when the descriptor refuses `modeId` (the panel says why). */
1209
+ refusesMode(modeId: string): boolean {
1210
+ return isRefusedMode(this.agent, modeId);
1211
+ }
1212
+
1213
+ /**
1214
+ * S1 — true when the descriptor refuses `value` for config option `configId`: a refused mode
1215
+ * through the `mode` option (rule 10), or a value outside a `pinConfig` allowlist (Copilot's
1216
+ * `allow_all`).
1217
+ */
1218
+ refusesConfig(configId: string, value: string | boolean): boolean {
1219
+ if (configId === 'mode' && typeof value === 'string' && this.refusesMode(value)) return true;
1220
+ return isRefusedConfigValue(this.agent, configId, value);
1221
+ }
1222
+
1223
+ /** The roster the panel may offer: a refused mode is never listed (rule 10). */
1224
+ private visibleModes(): SessionModeState | null {
1225
+ const m = this.lastModes;
1226
+ if (!m || !this.agent.enforcement?.pinMode) return m;
1227
+ return { ...m, availableModes: m.availableModes.filter((x) => !this.refusesMode(x.id)) };
1228
+ }
1229
+
1230
+ /**
1231
+ * The config options the panel may offer: a refused mode leaves the `mode` select too, a refused
1232
+ * value leaves a pinned option's select (grouped or flat), and a pinned BOOLEAN option whose `true`
1233
+ * is refused is not listed at all (S1: Copilot's `allow_all`).
1234
+ */
1235
+ private visibleConfigOptions(): SessionConfigOption[] {
1236
+ const e = this.agent.enforcement;
1237
+ if (!e?.pinMode && !e?.pinConfig) return this.lastConfigOptions;
1238
+ const keep = (id: string, x: { value?: unknown }) =>
1239
+ typeof x.value !== 'string' || !this.refusesConfig(id, x.value);
1240
+ const out: SessionConfigOption[] = [];
1241
+ for (const o of this.lastConfigOptions) {
1242
+ if (o.type === 'boolean') {
1243
+ if (!this.refusesConfig(o.id, true)) out.push(o);
1244
+ continue;
1245
+ }
1246
+ if (o.type !== 'select' || !Array.isArray(o.options)) {
1247
+ out.push(o);
1248
+ continue;
1249
+ }
1250
+ const options = (o.options as Array<{ value?: unknown; options?: unknown }>)
1251
+ .map((x) =>
1252
+ Array.isArray(x.options)
1253
+ ? {
1254
+ ...x,
1255
+ options: (x.options as Array<{ value?: unknown }>).filter((y) => keep(o.id, y)),
1256
+ }
1257
+ : x
1258
+ )
1259
+ .filter((x) => (Array.isArray(x.options) ? x.options.length > 0 : keep(o.id, x)));
1260
+ out.push({ ...o, options } as SessionConfigOption);
1261
+ }
1262
+ return out;
1263
+ }
1264
+
1265
+ private emitCaps(): void {
1266
+ this.opts.onCaps?.(this.visibleModes(), this.visibleConfigOptions());
1085
1267
  }
1086
1268
 
1087
1269
  /** The last-advertised generic config-option set (read-only snapshot). */
1088
1270
  get configOptions(): SessionConfigOption[] {
1089
- return this.lastConfigOptions;
1271
+ return this.visibleConfigOptions();
1090
1272
  }
1091
1273
 
1092
1274
  /** The last-seen usage snapshot (read-only), or null before the first `usage_update`. */
@@ -1156,6 +1338,7 @@ export class AcpBridge {
1156
1338
  * validates `modeId` against `this.modes` before invoking this.
1157
1339
  */
1158
1340
  async setMode(chatId: string, modeId: string): Promise<void> {
1341
+ if (this.refusesMode(modeId)) throw new ModeRefusedError(modeId, this.agent.label);
1159
1342
  await this.ensureStarted();
1160
1343
  const sessionId = await this.sessionFor(chatId);
1161
1344
  if (!this.conn) throw new Error('ACP adapter not ready');
@@ -1169,12 +1352,15 @@ export class AcpBridge {
1169
1352
  * every listener sees the side effects, not just the option that changed.
1170
1353
  */
1171
1354
  async setConfigOption(chatId: string, configId: string, value: string): Promise<void> {
1355
+ if (this.refusesConfig(configId, value)) {
1356
+ throw new ModeRefusedError(value, this.agent.label);
1357
+ }
1172
1358
  await this.ensureStarted();
1173
1359
  const sessionId = await this.sessionFor(chatId);
1174
1360
  if (!this.conn) throw new Error('ACP adapter not ready');
1175
1361
  const response = await this.conn.setSessionConfigOption({ sessionId, configId, value });
1176
1362
  this.lastConfigOptions = response.configOptions;
1177
- this.opts.onCaps?.(this.lastModes, this.lastConfigOptions);
1363
+ this.emitCaps();
1178
1364
  }
1179
1365
 
1180
1366
  /** True when `value` is currently offered for the select-type option `configId`. */
@@ -1194,6 +1380,49 @@ export class AcpBridge {
1194
1380
  * (e.g. an effort level unsupported by the model claude resolved to) is
1195
1381
  * silently skipped, leaving the session's own default in place.
1196
1382
  */
1383
+ /**
1384
+ * F3 (rule 10) — a descriptor that pins a mode gets it right after session/new or load, when the
1385
+ * session reports another one. A pin the agent refuses ends the session start: a bridge-enforced
1386
+ * agent in an unpinned mode (Codex `agent`: Guardian auto-review) is not a session to run.
1387
+ */
1388
+ private async pinModeOnce(sessionId: string): Promise<void> {
1389
+ const pin = this.agent.enforcement?.pinMode;
1390
+ if (!pin || !this.conn) return;
1391
+ if (this.lastModes?.currentModeId === pin.modeId) return;
1392
+ await this.conn.setSessionMode({ sessionId, modeId: pin.modeId });
1393
+ this.lastModes = this.lastModes
1394
+ ? { ...this.lastModes, currentModeId: pin.modeId }
1395
+ : { currentModeId: pin.modeId, availableModes: [] };
1396
+ }
1397
+
1398
+ /**
1399
+ * S1 — the `pinConfig` counterpart of pinModeOnce: a session that starts on a refused value of a
1400
+ * pinned option (Copilot `allow_all` on) is moved to the first allowed value. A move the agent
1401
+ * refuses ends the session start, like a refused mode pin.
1402
+ */
1403
+ private async pinConfigOnce(sessionId: string): Promise<void> {
1404
+ const pins = this.agent.enforcement?.pinConfig;
1405
+ if (!pins || !this.conn) return;
1406
+ for (const [configId, pin] of Object.entries(pins)) {
1407
+ const o = this.lastConfigOptions.find((x) => x.id === configId);
1408
+ if (!o || !this.refusesConfig(configId, o.currentValue)) continue;
1409
+ const res =
1410
+ o.type === 'boolean'
1411
+ ? await this.conn.setSessionConfigOption({
1412
+ sessionId,
1413
+ configId,
1414
+ type: 'boolean',
1415
+ value: pin.allow[0] === 'true' || pin.allow[0] === 'on',
1416
+ })
1417
+ : await this.conn.setSessionConfigOption({ sessionId, configId, value: pin.allow[0] });
1418
+ this.lastConfigOptions = res.configOptions;
1419
+ const now = this.lastConfigOptions.find((x) => x.id === configId);
1420
+ if (now && this.refusesConfig(configId, now.currentValue)) {
1421
+ throw new ModeRefusedError(String(now.currentValue), this.agent.label);
1422
+ }
1423
+ }
1424
+ }
1425
+
1197
1426
  private async applyDesiredConfigOnce(sessionId: string): Promise<void> {
1198
1427
  if (!this.conn) return;
1199
1428
  try {
@@ -1215,6 +1444,7 @@ export class AcpBridge {
1215
1444
  }
1216
1445
  if (
1217
1446
  this.desiredModeId &&
1447
+ !this.refusesMode(this.desiredModeId) &&
1218
1448
  this.lastModes?.availableModes.some((m) => m.id === this.desiredModeId)
1219
1449
  ) {
1220
1450
  await this.conn.setSessionMode({ sessionId, modeId: this.desiredModeId });
@@ -1282,7 +1512,11 @@ export class AcpBridge {
1282
1512
  if (inFlight) return inFlight;
1283
1513
 
1284
1514
  const promise = (
1285
- existing ? this.reestablishForMay(chatId, existing) : this.establishSession(chatId)
1515
+ existing
1516
+ ? this.agent.policy === 'claude-meta'
1517
+ ? this.reestablishForMay(chatId, existing)
1518
+ : this.restartForMay(chatId, existing)
1519
+ : this.establishSession(chatId)
1286
1520
  ).finally(() => {
1287
1521
  this.sessionPromises.delete(chatId);
1288
1522
  });
@@ -1325,6 +1559,41 @@ export class AcpBridge {
1325
1559
  return this.establishSession(chatId, closed ? sessionId : null);
1326
1560
  }
1327
1561
 
1562
+ /**
1563
+ * B3 (F3 hand-back) — an agent that is not Claude carries the "AI may" switches in its LAUNCH
1564
+ * policy (Codex's network/permission profile, opencode's permission block, MAUDE_NO_EGRESS): env
1565
+ * at spawn, which no session call can change. A switch change therefore restarts the agent
1566
+ * process with the new policy and resumes the chat's session through `loadSession` when the agent
1567
+ * can; otherwise it starts a new session and says so in one line (the history stays in the chat).
1568
+ * Only between turns (`sessionFor` never comes here under a running one).
1569
+ */
1570
+ private async restartForMay(chatId: string, sessionId: string): Promise<string> {
1571
+ const proc = this.proc;
1572
+ this.conn = null;
1573
+ this.proc = null;
1574
+ try {
1575
+ proc?.kill();
1576
+ } catch {
1577
+ /* already gone */
1578
+ }
1579
+ this.denyAllPendingPermissions();
1580
+ this.sessions.clear();
1581
+ this.sessionMay.clear();
1582
+ this.sessionGatedRules.clear();
1583
+ this.briefPending.clear();
1584
+ await this.ensureStarted();
1585
+ const canLoad = await this.canLoadSession;
1586
+ const next = await this.establishSession(chatId, canLoad ? sessionId : null);
1587
+ if (next !== sessionId) {
1588
+ await this.appendTranscript({ role: 'bootstrap', kind: 'may-restart-new-session' });
1589
+ this.opts.onNote?.({
1590
+ kind: 'may-restart-new-session',
1591
+ message: `${this.agent.label} restarted with the new "AI may" settings in a new session: it no longer sees the earlier messages of this chat.`,
1592
+ });
1593
+ }
1594
+ return next;
1595
+ }
1596
+
1328
1597
  /** `resume`: undefined → the id persisted for this chat; null → never resume (a fresh session). */
1329
1598
  private async establishSession(chatId: string, resume?: string | null): Promise<string> {
1330
1599
  if (!this.conn) throw new Error('ACP adapter not started');
@@ -1339,23 +1608,50 @@ export class AcpBridge {
1339
1608
  }
1340
1609
  const may = { ...this.may };
1341
1610
  const gated = this.audienceGatedNow();
1342
- const params = newSessionParams(this.opts.repoRoot, this.opts.studioBrief, this.opts.plugins, {
1343
- readRoots: this.readRoots,
1344
- onlyVerbs: scoped === null ? null : HANDOFF_RUN_VERBS,
1345
- may,
1346
- assetsRoots: this.assetsRoots,
1347
- credentials: this.credentialPaths,
1348
- audienceGated: gated,
1349
- });
1611
+ const params = newSessionParamsFor(
1612
+ this.agent,
1613
+ this.opts.repoRoot,
1614
+ this.opts.studioBrief,
1615
+ this.opts.plugins,
1616
+ {
1617
+ readRoots: this.readRoots,
1618
+ onlyVerbs: scoped === null ? null : HANDOFF_RUN_VERBS,
1619
+ may,
1620
+ assetsRoots: this.assetsRoots,
1621
+ credentials: this.credentialPaths,
1622
+ audienceGated: gated,
1623
+ }
1624
+ );
1625
+ // B4 — a non-Claude agent that takes a client system prompt gets the studio brief there, on
1626
+ // session/new and session/load alike (codex-acp: `systemPrompt: {mode, content}`).
1627
+ const briefInPrompt =
1628
+ this.agent.policy !== 'claude-meta' &&
1629
+ !!this.opts.studioBrief &&
1630
+ (await this.canSystemPrompt);
1631
+ const sessionParams = briefInPrompt
1632
+ ? {
1633
+ ...params,
1634
+ systemPrompt: {
1635
+ mode: 'append',
1636
+ content: [{ type: 'text', text: this.opts.studioBrief as string }],
1637
+ },
1638
+ }
1639
+ : params;
1350
1640
  const persistedId = resume === undefined ? await this.readPersistedSessionId() : resume;
1351
1641
  let sessionId: string | undefined;
1352
1642
  let modes: SessionModeState | null | undefined;
1353
1643
  let configOptions: SessionConfigOption[] | null | undefined;
1354
- if (persistedId) {
1644
+ // F3 — an agent that did not advertise `loadSession` would never answer it: go straight to a
1645
+ // new session instead of waiting LOAD_SESSION_TIMEOUT_MS for nothing.
1646
+ const canLoad = persistedId ? await this.canLoadSession : false;
1647
+ if (persistedId && !canLoad) {
1648
+ await this.appendTranscript({ role: 'bootstrap', kind: 'resume-unsupported' });
1649
+ }
1650
+ if (persistedId && canLoad) {
1355
1651
  try {
1356
1652
  this.replaying = true;
1357
1653
  const result = await withTimeout(
1358
- this.conn.loadSession({ ...params, sessionId: persistedId }),
1654
+ this.conn.loadSession({ ...sessionParams, sessionId: persistedId }),
1359
1655
  LOAD_SESSION_TIMEOUT_MS
1360
1656
  );
1361
1657
  if (result === TIMED_OUT) {
@@ -1377,8 +1673,12 @@ export class AcpBridge {
1377
1673
  }
1378
1674
 
1379
1675
  if (sessionId === undefined) {
1380
- const created = await this.conn.newSession(params);
1676
+ const created = await this.conn.newSession(sessionParams);
1381
1677
  this.sessions.set(chatId, created.sessionId);
1678
+ // B4 — otherwise the brief rides this new session's first prompt (a loaded one already has it).
1679
+ if (this.agent.policy !== 'claude-meta' && this.opts.studioBrief && !briefInPrompt) {
1680
+ this.briefPending.add(created.sessionId);
1681
+ }
1382
1682
  await this.writePersistedSessionId(created.sessionId);
1383
1683
  sessionId = created.sessionId;
1384
1684
  modes = created.modes;
@@ -1401,10 +1701,14 @@ export class AcpBridge {
1401
1701
  }).dropped
1402
1702
  )
1403
1703
  );
1704
+ this.pinsApplied = false; // a new or resumed session: its pins run again below
1404
1705
  this.lastModes = modes ?? null;
1405
1706
  this.lastConfigOptions = configOptions ?? [];
1707
+ await this.pinModeOnce(sessionId);
1708
+ await this.pinConfigOnce(sessionId);
1709
+ this.pinsApplied = true;
1406
1710
  await this.applyDesiredConfigOnce(sessionId);
1407
- this.opts.onCaps?.(this.lastModes, this.lastConfigOptions);
1711
+ this.emitCaps();
1408
1712
  return sessionId;
1409
1713
  }
1410
1714
 
@@ -1441,84 +1745,269 @@ export class AcpBridge {
1441
1745
  }
1442
1746
  }
1443
1747
 
1444
- private async start(): Promise<void> {
1445
- const adapterEntry = resolveAdapterEntry();
1446
- if (!adapterEntry) {
1447
- throw new Error('The Claude agent bridge is not installed in this build.');
1748
+ /**
1749
+ * F3 — the agent's argv and its whole env, built once (acp/agents/spawn.ts). Claude's errors and
1750
+ * its spawn are exactly as before the descriptor existed; another agent's name its label.
1751
+ */
1752
+ private spawnPlan(): { cmd: string[]; env: Record<string, string> } {
1753
+ const d = this.agent;
1754
+ let adapterEntry: string | undefined;
1755
+ let agentBin: string;
1756
+ if (d.id === CLAUDE.id) {
1757
+ adapterEntry = resolveAdapterEntry() ?? undefined;
1758
+ if (!adapterEntry) {
1759
+ throw new Error('The Claude agent bridge is not installed in this build.');
1760
+ }
1761
+ const claudePath = resolveClaudePath();
1762
+ if (!claudePath) {
1763
+ throw new Error("Claude Code isn't connected — run `claude` in a terminal and `/login`.");
1764
+ }
1765
+ // #148 — a Windows npm `claude.cmd` shim can't be spawned by Node without a shell.
1766
+ const agentClaude = resolveAgentClaudeExecutable(claudePath);
1767
+ if (!agentClaude) {
1768
+ throw new Error(
1769
+ 'Claude Code is installed as an npm `claude.cmd` shim the chat cannot start — reinstall it with the native installer.'
1770
+ );
1771
+ }
1772
+ // DDR-123 guardrail #2 — pin the adapter to the user's OWN `claude` CLI
1773
+ // (CLAUDE_CODE_EXECUTABLE, the descriptor's agentBinEnv). Without it the adapter falls back
1774
+ // to the ~210 MB native binary of @anthropic-ai/claude-agent-sdk, which the desktop bundle
1775
+ // deliberately does not stage (stage-resources.mjs) — and the turn would leave the user's
1776
+ // subscription.
1777
+ agentBin = agentClaude;
1778
+ } else {
1779
+ if (d.launch.kind === 'adapter-js') {
1780
+ adapterEntry = resolveAdapterEntry(d.launch) ?? undefined;
1781
+ if (!adapterEntry) {
1782
+ throw new Error(`The ${d.label} agent bridge is not installed in this build.`);
1783
+ }
1784
+ }
1785
+ const bin = this.opts.agentBin;
1786
+ if (!bin || !existsSync(bin)) {
1787
+ throw new Error(`${d.label} isn't installed on this Mac — connect it in Settings.`);
1788
+ }
1789
+ agentBin = bin;
1448
1790
  }
1449
- const claudePath = resolveClaudePath();
1450
- if (!claudePath) {
1451
- throw new Error("Claude Code isn't connected — run `claude` in a terminal and `/login`.");
1791
+ if (d.policy === 'bridge-enforced' && !d.enforcement) {
1792
+ throw new Error(`${d.label} has no Maude policy to run under.`);
1452
1793
  }
1453
- // #148 — a Windows npm `claude.cmd` shim can't be spawned by Node without a shell.
1454
- const agentClaude = resolveAgentClaudeExecutable(claudePath);
1455
- if (!agentClaude) {
1456
- throw new Error(
1457
- 'Claude Code is installed as an npm `claude.cmd` shim the chat cannot start — reinstall it with the native installer.'
1458
- );
1794
+
1795
+ // Model + effort are no longer env-at-spawn (Task A3) — `applyDesiredConfigOnce` live-applies
1796
+ // the persisted picks once the session exists. No respawn on a config change.
1797
+ // V2-8.9 re-check 2 H-a — a ports getter that throws hands the helpers none (fail closed).
1798
+ let ownPorts: readonly number[] = [];
1799
+ try {
1800
+ ownPorts = this.opts.ownPorts?.() ?? [];
1801
+ } catch {
1802
+ ownPorts = [];
1459
1803
  }
1804
+ const plan = agentSpawn({
1805
+ descriptor: d,
1806
+ // DDR-123 guardrail #1 — strip ANTHROPIC_API_KEY (and every other vendor's key, rule 14) so
1807
+ // the child stays on the user's own sign-in. This is the whole compliance story; do not
1808
+ // weaken it. The shell's per-spawn secrets (MAUDE_TOKEN_* …) go with it (V2-3.6 M4).
1809
+ scrubbed: scrubAgentEnv(process.env, d.envAllow),
1810
+ agentBin,
1811
+ adapterEntry,
1812
+ // RCA-G1 — a runnable JS runtime; on a node/bun-less machine our own compiled self, which
1813
+ // must run with BUN_BE_BUN=1 (else the handshake below never completes → "Working…").
1814
+ runtime: d.launch.kind === 'adapter-js' ? resolveAgentRuntime() : undefined,
1815
+ policyCtx: this.policyCtx(agentBin),
1816
+ actor: {
1817
+ sessionRoot: this.opts.repoRoot,
1818
+ readRoots: this.readRoots,
1819
+ ownPorts,
1820
+ // V2-8.9 M2 — owner-only, never through a planted link; a failure leaves TMPDIR alone.
1821
+ tmpdir: ensureChatScratch(this.scratch) ? this.scratch : null,
1822
+ grantsFile: this.opts.grantsFile,
1823
+ },
1824
+ // S11.13 — Settings › Advanced › teams (prefs.json experimentalTeams), read at each spawn.
1825
+ teams: readUiPrefs().experimentalTeams === true,
1826
+ chatId: this.opts.chatId,
1827
+ delimiter,
1828
+ });
1829
+ // E2E only (scripts/acp-e2e-local.ts) — a loopback scripted model for a non-Claude agent; a
1830
+ // release build ignores the switch (acp/agents/e2e-model.ts).
1831
+ applyE2eAgentModel(d, plan.env);
1832
+ return plan;
1833
+ }
1460
1834
 
1461
- // DDR-123 guardrail #1 — strip ANTHROPIC_API_KEY so the child stays on the
1462
- // user's subscription. This is the whole compliance story; do not weaken it.
1463
- const env = scrubAgentEnv(process.env);
1464
- // DDR-123 guardrail #2 — pin the adapter to the user's OWN `claude` CLI.
1465
- // `claude-agent-acp`'s `claudeCliPath()` honors CLAUDE_CODE_EXECUTABLE and
1466
- // ONLY otherwise falls back to the ~210 MB native Claude binary shipped as a
1467
- // platform-specific OPTIONAL dep of @anthropic-ai/claude-agent-sdk. The
1468
- // desktop bundle deliberately stages just the adapter's JS closure (not that
1469
- // native binary — see apps/desktop/scripts/stage-resources.mjs), so without
1470
- // this pin the packaged adapter would throw "native binary not found". Driving
1471
- // the user's installed CLI is also the documented intent: it keeps the turn on
1472
- // their subscription rather than the SDK's embedded runtime.
1473
- env.CLAUDE_CODE_EXECUTABLE = agentClaude;
1474
- // Least-privilege: the adapter child never talks to the dev-server's GitHub
1475
- // token bridge (only apps/studio/github/token.ts does). scrubAgentEnv above
1476
- // drops its loopback handle (MAUDE_TOKEN_*) with every other shell secret —
1477
- // one strip for the bridge, the probe and login-state alike (V2-3.6 M4).
1478
- // Model + effort are no longer env-at-spawn (Task A3) — the adapter starts
1479
- // on its own default and `establishSession`/`applyDesiredConfigOnce` live-
1480
- // applies the user's persisted picks via `setSessionConfigOption` once the
1481
- // session (and its advertised options) exist. No respawn on a config change.
1482
-
1483
- // RCA-G1 — resolve a runnable JS runtime. On a node/bun-less machine this
1484
- // falls back to our own compiled self, which must be spawned with
1485
- // BUN_BE_BUN=1 to behave as `bun` (else it re-runs the embedded server and
1486
- // the handshake below never completes → "Working…" forever). Set on `env`
1487
- // AFTER scrubAgentEnv (which doesn't touch BUN_BE_BUN).
1488
- const runtime = resolveAgentRuntime();
1489
- if (runtime.bunBeBun) env.BUN_BE_BUN = '1';
1490
- // V2-2.4b (decision:maude/v2-2.4b-actor-env-marker) — the adapter hands its env to `claude`,
1491
- // and `claude` to every design-plugin hook: `maude design hook` reads this to tell a Maude chat
1492
- // run from a terminal Claude Code (the run's actor, and who brackets it — acp/index.ts does).
1493
- env.MAUDE_AGENT_ACTOR = 'maude-chat';
1494
- // gate-b-sec2 (decision v2-gate-b-sec2-session-root): the project this chat's maude verbs are
1495
- // held to — `maude design` refuses a --root / cwd / CLAUDE_PROJECT_DIR naming another one.
1496
- env.MAUDE_SESSION_ROOT = this.opts.repoRoot;
1497
- // V2-8.9 H2 — the read boundary of this chat for the verbs that read a path they are given
1498
- // (cli/lib/confine-read.mjs): the fixed roots now, the consented folders live from the store.
1499
- env.MAUDE_READ_ROOTS = this.readRoots.join(delimiter);
1500
- // V2-8.9 re-check 2 H-a — the ports of THIS session's own server (main, canvas, capture): the
1501
- // browser helpers open no other loopback port (bin/_url-guard.mjs). Plain ports only; none →
1502
- // unset, and the helpers refuse every page (fail closed). Scrubbed + bash-guarded like the rest.
1835
+ /** A getter the caller passes in, read now; a throw is `fallback` (each call site picks the safe side). */
1836
+ private live<T>(get: (() => T) | undefined, fallback: T): T {
1503
1837
  try {
1504
- const ports = (this.opts.ownPorts?.() ?? []).filter(
1505
- (p) => Number.isInteger(p) && p > 0 && p < 65536
1506
- );
1507
- if (ports.length) env.MAUDE_OWN_PORTS = [...new Set(ports)].join(',');
1838
+ return get ? get() : fallback;
1839
+ } catch {
1840
+ return fallback;
1841
+ }
1842
+ }
1843
+
1844
+ /**
1845
+ * B3 — one `session/request_permission` of an agent that is not Claude, end to end, through the
1846
+ * gate (acp/policy/gate-types.ts). It never falls through to the Claude-shaped gates below, which
1847
+ * key on Claude tool names this agent does not send.
1848
+ * • refuse → the request's `reject_once` (else `cancelled`), no card; with `rejectEndsTurn` the
1849
+ * turn ends with the refusal notice (rule 13).
1850
+ * • allow → granted once, after the audience hold (H1): a write is checked like Claude's
1851
+ * in-project write, a `maude design` writer verb like Claude's Bash one; a read carries
1852
+ * nothing anywhere and passes.
1853
+ * • ask → the person's card with only `allow_once` / `reject_once` (rule 9); the answer goes
1854
+ * back through the gate, which remembers an approval for the tripwire.
1855
+ * No gate wired, or a gate that throws → refused (fail closed).
1856
+ */
1857
+ private agentPermission(params: RequestPermissionRequest): Promise<RequestPermissionResponse> {
1858
+ const gate = this.opts.permissionGate;
1859
+ // The request names its call: the writer-verb hold below finds it by kind even when the agent
1860
+ // streamed no tool_call first.
1861
+ const tc = params.toolCall as { toolCallId?: unknown; kind?: unknown } | undefined;
1862
+ if (typeof tc?.toolCallId === 'string' && !this.toolNames.has(tc.toolCallId)) {
1863
+ this.rememberToolName({
1864
+ sessionUpdate: 'tool_call',
1865
+ toolCallId: tc.toolCallId,
1866
+ kind: tc.kind,
1867
+ } as unknown as SessionUpdate);
1868
+ }
1869
+ const refuse = (): Promise<RequestPermissionResponse> => {
1870
+ const reject = (params.options ?? []).find((o) => o.kind === 'reject_once');
1871
+ return Promise.resolve({
1872
+ outcome: reject
1873
+ ? { outcome: 'selected', optionId: reject.optionId }
1874
+ : { outcome: 'cancelled' },
1875
+ });
1876
+ };
1877
+ if (!gate) return refuse();
1878
+ let result: GateResult;
1879
+ try {
1880
+ result = gate.decide({
1881
+ req: params,
1882
+ descriptor: this.agent,
1883
+ ctx: this.policyCtx(this.opts.agentBin ?? ''),
1884
+ state: {
1885
+ stopped: this.stopped,
1886
+ grantRoots: this.live(this.opts.readRoots, []),
1887
+ // S8.10 — a scoped run: a getter that throws is a run scoped to nothing (fail closed);
1888
+ // no getter at all is no run scope.
1889
+ onlyPaths: this.opts.writeOnlyRoots
1890
+ ? this.live<readonly string[] | null>(this.opts.writeOnlyRoots, [])
1891
+ : null,
1892
+ },
1893
+ });
1508
1894
  } catch {
1509
- /* no list: the helpers open nothing */
1895
+ return refuse();
1896
+ }
1897
+ if (result.decision === 'reject') {
1898
+ this.noteRefusal(gate.refusalNotice(result));
1899
+ return Promise.resolve(
1900
+ result.optionId
1901
+ ? { outcome: { outcome: 'selected', optionId: result.optionId } }
1902
+ : { outcome: { outcome: 'cancelled' } }
1903
+ );
1510
1904
  }
1511
- // V2-8.9 M2 — the agent's temp folder is this chat's own scratch (inside its read boundary), not
1512
- // the shared /tmp. Owner-only, never through a planted link (re-check 2 L3); a failure leaves
1513
- // TMPDIR as it was (reads there then ask).
1514
- if (ensureChatScratch(this.scratch)) env.TMPDIR = `${this.scratch}/`;
1515
- if (this.opts.grantsFile) env.MAUDE_GRANTS_FILE = this.opts.grantsFile;
1516
- const proc = Bun.spawn([runtime.bin, adapterEntry], {
1905
+ const card = (info?: PermissionScopeInfo) =>
1906
+ this.askPerson(
1907
+ { ...params, options: result.strippedOptions },
1908
+ { stripAlways: true, info }
1909
+ ).then((res) => {
1910
+ const answered = gate.answer(
1911
+ result,
1912
+ res.outcome.outcome === 'selected' ? res.outcome.optionId : null
1913
+ );
1914
+ if (!this.grants(answered, result)) this.noteRefusal(gate.cardRefusalNotice());
1915
+ return answered;
1916
+ });
1917
+ if (result.decision === 'ask') {
1918
+ return card(
1919
+ result.reason === 'write-outside'
1920
+ ? {
1921
+ outOfProjectWrite: true,
1922
+ resolvedPaths: result.shown.paths,
1923
+ scopeRoot: this.scopeRoot,
1924
+ reason: 'outside',
1925
+ }
1926
+ : undefined
1927
+ );
1928
+ }
1929
+ // allow_once — the audience hold (H1) before it is granted
1930
+ const auto: RequestPermissionResponse = {
1931
+ outcome: { outcome: 'selected', optionId: result.optionId as string },
1932
+ };
1933
+ if (result.reason === 'write-inside') {
1934
+ const targets = result.shown.paths.filter((p) => p !== result.shown.cwd);
1935
+ // S5.10 — a folder AI may read is never a write path, whichever chat it is attached to.
1936
+ // (no getter = no grants; a getter that throws = unknown → the card)
1937
+ const readOnly = this.opts.readOnlyRoots ? this.live(this.opts.readOnlyRoots, null) : [];
1938
+ if (
1939
+ readOnly === null ||
1940
+ targets.some((t) => readOnly.some((r) => t === r || isInsideRoot(t, r)))
1941
+ ) {
1942
+ return card({
1943
+ outOfProjectWrite: true,
1944
+ resolvedPaths: targets,
1945
+ scopeRoot: this.scopeRoot,
1946
+ reason: 'read-only-grant',
1947
+ });
1948
+ }
1949
+ const held = this.audienceHold(targets);
1950
+ if (!held) return Promise.resolve(auto);
1951
+ return held.then((info) => {
1952
+ if (this.stopped) return { outcome: { outcome: 'cancelled' } };
1953
+ return info ? card(info) : auto;
1954
+ });
1955
+ }
1956
+ if (result.reason === 'shell-auto-verb' || result.reason === 'shell-read-inside') {
1957
+ const verb = this.writerVerbHold({ ...params, options: result.strippedOptions });
1958
+ if (!verb) return Promise.resolve(auto);
1959
+ return verb.then((res) => {
1960
+ if (!this.grants(res, result)) this.noteRefusal(gate.cardRefusalNotice());
1961
+ return res;
1962
+ });
1963
+ }
1964
+ return Promise.resolve(auto);
1965
+ }
1966
+
1967
+ /** True when `res` picked an `allow_once` option the gate offered. */
1968
+ private grants(res: RequestPermissionResponse, result: GateResult): boolean {
1969
+ if (res.outcome.outcome !== 'selected') return false;
1970
+ const id = res.outcome.optionId;
1971
+ return result.strippedOptions.some((o) => o.optionId === id && o.kind === 'allow_once');
1972
+ }
1973
+
1974
+ /** B3 rule 13 — the first refusal of a turn is the one the panel names. */
1975
+ private noteRefusal(notice: string | null): void {
1976
+ if (notice && this.turnRefusal === null && this.pendingTurns.size > 0)
1977
+ this.turnRefusal = notice;
1978
+ }
1979
+
1980
+ /** B3 rule 12 — the launch policy did not hold: end the session, keep the frames, tell the caller. */
1981
+ private policyViolated(reason: string): void {
1982
+ if (this.violated) return;
1983
+ this.violated = true;
1984
+ console.error(`[acp-agent:${this.agent.id}] launch policy not enforced: ${reason}`);
1985
+ try {
1986
+ this.opts.onPolicyViolation?.(reason);
1987
+ } finally {
1988
+ void this.stop();
1989
+ }
1990
+ }
1991
+
1992
+ /** F3 — the session scope a launch policy and the bridge gate are built from (PolicyCtx). */
1993
+ private policyCtx(agentBin: string): PolicyCtx {
1994
+ return {
1995
+ scopeRoot: this.scopeRoot,
1996
+ readRoots: this.readRoots,
1997
+ writeRoots: [this.scopeRoot, this.scratch],
1998
+ credentialPaths: this.credentialPaths,
1999
+ may: { ...this.may },
2000
+ designRoots: this.designRoots,
2001
+ agentBin,
2002
+ };
2003
+ }
2004
+
2005
+ private async start(): Promise<void> {
2006
+ const { cmd, env } = this.spawnPlan();
2007
+ const proc = Bun.spawn(cmd, {
1517
2008
  cwd: this.opts.repoRoot,
1518
2009
  windowsHide: true, // #141 — never a console window for the adapter on Windows
1519
- // V2-1.15 §5.4 — this chat's id and no other's (a stale MAUDE_CHAT_ID is dropped).
1520
- // S11.13 — Settings › Advanced › teams (prefs.json experimentalTeams), read at each spawn.
1521
- env: chatSpawnEnv(teamsSpawnEnv(env, readUiPrefs()), this.opts.chatId),
2010
+ env,
1522
2011
  stdin: 'pipe',
1523
2012
  stdout: 'pipe',
1524
2013
  stderr: 'pipe',
@@ -1579,11 +2068,37 @@ export class AcpBridge {
1579
2068
  this.lastModes = this.lastModes
1580
2069
  ? { ...this.lastModes, currentModeId: u.currentModeId }
1581
2070
  : { currentModeId: u.currentModeId, availableModes: [] };
1582
- this.opts.onCaps?.(this.lastModes, this.lastConfigOptions);
2071
+ // Review S1 — the AGENT moved itself to a refused mode (a slash command, a prompt):
2072
+ // hiding it from the picker is not enough, end the session like any other breach.
2073
+ if (
2074
+ this.pinsApplied &&
2075
+ this.agent.enforcement?.pinMode &&
2076
+ this.refusesMode(u.currentModeId)
2077
+ ) {
2078
+ this.policyViolated(`switched itself to the refused mode ${u.currentModeId}`);
2079
+ return;
2080
+ }
2081
+ this.emitCaps();
1583
2082
  return;
1584
2083
  }
1585
2084
  if (u.sessionUpdate === 'config_option_update') {
1586
2085
  this.lastConfigOptions = u.configOptions ?? [];
2086
+ // Review S1 — an agent-side move to a refused config value (Copilot `allow_all`, a refused
2087
+ // mode in the `mode` option) ends the session; the pin is not a picker filter only.
2088
+ if (
2089
+ this.pinsApplied &&
2090
+ (this.agent.enforcement?.pinMode || this.agent.enforcement?.pinConfig)
2091
+ ) {
2092
+ const bad = this.lastConfigOptions.find(
2093
+ (o) =>
2094
+ (typeof o.currentValue === 'string' || typeof o.currentValue === 'boolean') &&
2095
+ this.refusesConfig(o.id, o.currentValue as string | boolean)
2096
+ );
2097
+ if (bad) {
2098
+ this.policyViolated(`set ${bad.id} to a refused value (${String(bad.currentValue)})`);
2099
+ return;
2100
+ }
2101
+ }
1587
2102
  // The adapter mirrors the current mode as a "mode"-id select option
1588
2103
  // inside configOptions (claude-agent-acp's MODE_CONFIG_ID) but doesn't
1589
2104
  // always pair that with a current_mode_update — e.g. `setSessionMode`
@@ -1595,7 +2110,7 @@ export class AcpBridge {
1595
2110
  ? { ...this.lastModes, currentModeId: modeOpt.currentValue }
1596
2111
  : { currentModeId: modeOpt.currentValue, availableModes: [] };
1597
2112
  }
1598
- this.opts.onCaps?.(this.lastModes, this.lastConfigOptions);
2113
+ this.emitCaps();
1599
2114
  return;
1600
2115
  }
1601
2116
  if (u.sessionUpdate === 'session_info_update') {
@@ -1618,12 +2133,29 @@ export class AcpBridge {
1618
2133
  // transcript and already rendered client-side, so forwarding/re-appending
1619
2134
  // it here would duplicate every message in the panel and the jsonl file.
1620
2135
  if (this.replaying) return;
2136
+ // B3 rule 12 — the tripwire: a completed tool call that broke the launch policy ends the
2137
+ // session. Evidence, never a gate (the permission request already went through the gate);
2138
+ // the frame is still delivered and kept below. Not on replayed history: a resumed session's
2139
+ // calls were judged when they ran, and approvals made then are not remembered now.
2140
+ let violation: string | null = null;
2141
+ if (this.agent.policy !== 'claude-meta' && !this.violated) {
2142
+ try {
2143
+ const v = this.opts.permissionGate?.observe(
2144
+ u,
2145
+ this.policyCtx(this.opts.agentBin ?? '')
2146
+ );
2147
+ if (v?.violated) violation = v.reason;
2148
+ } catch {
2149
+ /* an observer that throws proves nothing either way */
2150
+ }
2151
+ }
1621
2152
  // Claim the transcript line FIRST, then hand the same number to both
1622
2153
  // consumers. Deriving it separately in each would let them disagree,
1623
2154
  // which is exactly the desync the seam exists to prevent.
1624
2155
  const seq = ++this.transcriptLines;
1625
2156
  this.opts.onUpdate(u, seq);
1626
2157
  void this.appendTranscript({ role: 'agent', update: u }, seq);
2158
+ if (violation) this.policyViolated(violation);
1627
2159
  },
1628
2160
  // V2-8.9 round B A1 — every way this resolves is reported (`onPermissionDecided`): a shell verb's
1629
2161
  // run-stage window reopens only on a grant.
@@ -1643,6 +2175,9 @@ export class AcpBridge {
1643
2175
  // transparency callback (every request, however it resolves);
1644
2176
  // `onPermissionRequest` is the actual UI hook the client answers.
1645
2177
  this.opts.onPermission?.(params);
2178
+ // F3 → F5 — an agent that is not Claude goes through the bridge-enforced gate first
2179
+ // (acp/policy/enforce.ts); the Claude-shaped gates below key on Claude tool names.
2180
+ if (this.agent.policy !== 'claude-meta') return this.agentPermission(params);
1646
2181
  // P8 c7 (decision maude/v2-p8-c7-ai-may-enforced) — an "AI may" switch the person turned off
1647
2182
  // refuses the call here, against the CURRENT state, with no card: the person already said no.
1648
2183
  // Before the write gate, so an off switch is never auto-approved as an in-project write.
@@ -1750,8 +2285,36 @@ export class AcpBridge {
1750
2285
  },
1751
2286
  };
1752
2287
 
2288
+ // B3 rule 11 — a non-Claude agent is never offered file or terminal access (`fs:false`, no
2289
+ // `terminal`), so one asking anyway is a protocol violation: a JSON-RPC error, logged. Claude's
2290
+ // client is left exactly as it was.
2291
+ if (this.agent.policy !== 'claude-meta') {
2292
+ const forbidden = (method: string) => (): never => {
2293
+ console.error(`[acp-agent:${this.agent.id}] refused ${method}: not offered to this agent`);
2294
+ throw new RequestError(FORBIDDEN_METHOD_ERROR.code, FORBIDDEN_METHOD_ERROR.message, {
2295
+ method,
2296
+ });
2297
+ };
2298
+ Object.assign(client, {
2299
+ readTextFile: forbidden('fs/read_text_file'),
2300
+ writeTextFile: forbidden('fs/write_text_file'),
2301
+ createTerminal: forbidden('terminal/create'),
2302
+ terminalOutput: forbidden('terminal/output'),
2303
+ releaseTerminal: forbidden('terminal/release'),
2304
+ waitForTerminalExit: forbidden('terminal/wait_for_exit'),
2305
+ killTerminal: forbidden('terminal/kill'),
2306
+ });
2307
+ }
1753
2308
  const conn = new ClientSideConnection(() => client, stream);
1754
2309
  this.conn = conn;
2310
+ let settleLoad: (can: boolean) => void = () => {};
2311
+ this.canLoadSession = new Promise<boolean>((r) => {
2312
+ settleLoad = r;
2313
+ });
2314
+ let settleSystemPrompt: (can: boolean) => void = () => {};
2315
+ this.canSystemPrompt = new Promise<boolean>((r) => {
2316
+ settleSystemPrompt = r;
2317
+ });
1755
2318
 
1756
2319
  // RCA-G1 — bound the handshake. If the spawned "adapter" is actually a
1757
2320
  // mis-launched runtime that never speaks ACP (the exact node-less bug: a
@@ -1781,8 +2344,15 @@ export class AcpBridge {
1781
2344
  },
1782
2345
  }),
1783
2346
  INITIALIZE_TIMEOUT_MS
1784
- );
2347
+ ).catch((err: unknown) => {
2348
+ // A handshake that fails must not leave a session start waiting on the answer forever.
2349
+ settleLoad(false);
2350
+ settleSystemPrompt(false);
2351
+ throw err;
2352
+ });
1785
2353
  if (initResult === TIMED_OUT) {
2354
+ settleLoad(false);
2355
+ settleSystemPrompt(false);
1786
2356
  this.conn = null;
1787
2357
  try {
1788
2358
  proc.kill();
@@ -1792,9 +2362,18 @@ export class AcpBridge {
1792
2362
  this.proc = null;
1793
2363
  throw new Error(
1794
2364
  `AI editing couldn't start: the agent runtime didn't respond within ${INITIALIZE_TIMEOUT_MS / 1000}s. ` +
1795
- `Check that Claude Code is installed and signed in (Help ▸ Check AI editing readiness).`
2365
+ (this.agent.id === CLAUDE.id
2366
+ ? `Check that Claude Code is installed and signed in (Help ▸ Check AI editing readiness).`
2367
+ : `Check that ${this.agent.label} is installed and signed in.`)
1796
2368
  );
1797
2369
  }
2370
+ // F3 — resume only an agent that said it can (`loadSession`); others start a new session.
2371
+ settleLoad(initResult.agentCapabilities?.loadSession === true);
2372
+ // B4 — `sessionCapabilities.systemPrompt` (an ACP draft codex-acp ships; not in this SDK's types).
2373
+ const sessionCaps = (
2374
+ initResult.agentCapabilities as { sessionCapabilities?: unknown } | undefined
2375
+ )?.sessionCapabilities as { systemPrompt?: unknown } | null | undefined;
2376
+ settleSystemPrompt(!!sessionCaps?.systemPrompt && typeof sessionCaps.systemPrompt === 'object');
1798
2377
  // Sessions are created lazily per chat (sessionFor) — not here.
1799
2378
  }
1800
2379
 
@@ -1802,11 +2381,14 @@ export class AcpBridge {
1802
2381
  async prompt(
1803
2382
  text: string,
1804
2383
  chatId: string
1805
- ): Promise<{ stopReason: PromptResponse['stopReason'] }> {
2384
+ ): Promise<{ stopReason: PromptResponse['stopReason']; refusal?: string }> {
1806
2385
  await this.ensureStarted();
1807
- const conn = this.conn;
1808
- if (!conn) throw new Error('ACP adapter not ready');
2386
+ if (!this.conn) throw new Error('ACP adapter not ready');
1809
2387
  const sessionId = await this.sessionFor(chatId);
2388
+ // B3 — read the connection AFTER the session: an "AI may" restart of a non-Claude agent
2389
+ // (`restartForMay`) replaced it while the session was being re-established.
2390
+ const conn = this.conn as ClientSideConnection | null;
2391
+ if (!conn) throw new Error('ACP adapter not ready');
1810
2392
  this.currentSession = sessionId;
1811
2393
 
1812
2394
  // Audit record (feature-acp-context-hardening, BREAKER guard): the brief
@@ -1857,7 +2439,16 @@ export class AcpBridge {
1857
2439
  // is racing anymore (an unhandled rejection).
1858
2440
  try {
1859
2441
  this.pendingTurns.add(turn);
1860
- const promptCall = conn.prompt({ sessionId, prompt: [{ type: 'text', text }] });
2442
+ this.turnRefusal = null;
2443
+ // B4 — a new session of an agent with no system-prompt channel gets the studio brief as a
2444
+ // preamble block of its FIRST prompt only. The transcript keeps the person's own text (above)
2445
+ // and the brief as its `bootstrap` line, so the panel never shows the brief as theirs.
2446
+ const blocks: Array<{ type: 'text'; text: string }> = [];
2447
+ if (this.briefPending.delete(sessionId) && this.opts.studioBrief) {
2448
+ blocks.push({ type: 'text', text: studioBriefPreamble(this.opts.studioBrief) });
2449
+ }
2450
+ blocks.push({ type: 'text', text });
2451
+ const promptCall = conn.prompt({ sessionId, prompt: blocks });
1861
2452
  promptCall.catch(() => {}); // a forced-reject race must not surface as an unhandled rejection
1862
2453
  response = await Promise.race([promptCall, forced]);
1863
2454
  } finally {
@@ -1865,7 +2456,11 @@ export class AcpBridge {
1865
2456
  resolveSettled();
1866
2457
  }
1867
2458
  await this.appendTranscript({ role: 'stop', stopReason: response.stopReason });
1868
- return { stopReason: response.stopReason };
2459
+ const refusal = this.turnRefusal;
2460
+ this.turnRefusal = null;
2461
+ return refusal
2462
+ ? { stopReason: response.stopReason, refusal }
2463
+ : { stopReason: response.stopReason };
1869
2464
  }
1870
2465
 
1871
2466
  /**
@@ -1939,9 +2534,21 @@ export class AcpBridge {
1939
2534
  // declared as an open `unknown`-valued record, and `claudeCode.toolName` is
1940
2535
  // an adapter-INTERNAL convention (like the `_meta` payloads newSessionParams
1941
2536
  // sends the other way), not part of the ACP schema.
1942
- const view = u as { toolCallId?: unknown; _meta?: { claudeCode?: { toolName?: unknown } } };
2537
+ const view = u as {
2538
+ toolCallId?: unknown;
2539
+ kind?: unknown;
2540
+ _meta?: { claudeCode?: { toolName?: unknown } };
2541
+ };
1943
2542
  const id = view.toolCallId;
1944
- const name = view._meta?.claudeCode?.toolName;
2543
+ // B3 — an agent that is not Claude sends no tool name, only the ACP `kind`. The read tracker
2544
+ // (H1) and the writer-verb hold key on Claude's names, so the kind stands in for one; a
2545
+ // `_meta` name such an agent sends is never trusted.
2546
+ const name =
2547
+ this.agent.policy === 'claude-meta'
2548
+ ? view._meta?.claudeCode?.toolName
2549
+ : typeof view.kind === 'string'
2550
+ ? KIND_AS_TOOL_NAME[view.kind]
2551
+ : undefined;
1945
2552
  if (typeof id !== 'string' || !id || typeof name !== 'string' || !name) return;
1946
2553
  if (!this.toolNames.has(id) && this.toolNames.size >= MAX_TRACKED_TOOL_NAMES) {
1947
2554
  const oldest = this.toolNames.keys().next().value;
@@ -2546,7 +3153,10 @@ export class AcpBridge {
2546
3153
  }
2547
3154
 
2548
3155
  private async drainStderr(proc: Spawned): Promise<void> {
2549
- const log = (line: string) => console.error('[acp-adapter]', line);
3156
+ // B3 — another agent's lines are named after it, so a log reader can tell who reported what.
3157
+ const tag =
3158
+ this.agent.policy === 'claude-meta' ? '[acp-adapter]' : `[acp-agent:${this.agent.id}]`;
3159
+ const log = (line: string) => console.error(tag, line);
2550
3160
  const lines = createLineSplitter((line) =>
2551
3161
  relayAdapterLine(line, log, (snap) => this.setBackground(proc, snap))
2552
3162
  );