shapewall 0.3.3 → 0.7.0

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 (157) hide show
  1. package/CHANGELOG.md +501 -0
  2. package/README.md +87 -4
  3. package/THIRD_PARTY.md +15 -0
  4. package/dist/agent/package-lock.json +594 -2
  5. package/dist/client/assets/BoardChat-WS8mAIW6.js +27 -0
  6. package/dist/client/assets/{BuzzDialog-Ix9qJvim.js → BuzzDialog-B-Mlr6wF.js} +1 -1
  7. package/dist/client/assets/ChecksPanel-Dx1ZLBR6.js +1 -0
  8. package/dist/client/assets/History-sXhmpcvs.js +1 -0
  9. package/dist/client/assets/LocalSettings-CtGzz9F3.js +1 -0
  10. package/dist/client/assets/{Management-NVFDtSZB.js → Management-CGHe8Wt9.js} +1 -1
  11. package/dist/client/assets/QuickConnect-DEk84E4A.js +1 -0
  12. package/dist/client/assets/{ShareDialog-By0ETg6n.js → ShareDialog-CGGx-AYK.js} +2 -2
  13. package/dist/client/assets/{app-update-dialog-RGIw24iZ.js → app-update-dialog-_bVp8hnC.js} +1 -1
  14. package/dist/client/assets/{circle-x-B6KfScOE.js → circle-x-BWoHA1QY.js} +1 -1
  15. package/dist/client/assets/index-Bm-Xd3YN.js +37 -0
  16. package/dist/client/assets/index-C7Ostk3K.css +2 -0
  17. package/dist/client/assets/play-BzQ3tRTv.js +1 -0
  18. package/dist/client/assets/{refresh-cw-vkgvCCfR.js → refresh-cw-BYBMyDKT.js} +1 -1
  19. package/dist/client/assets/{runtime-Bft6x_6E.js → runtime-Bvq10IhH.js} +1 -1
  20. package/dist/client/assets/ui-CAY6myRA.js +41 -0
  21. package/dist/client/build-info.json +1 -1
  22. package/dist/client/index.html +3 -3
  23. package/dist/client/sw.js +2 -2
  24. package/dist/console/assets/LocalAccountsApp-CWRguRRL.js +1 -0
  25. package/dist/console/assets/LocalConsole--I2SaIpr.js +2 -0
  26. package/dist/console/assets/LocalUsage-BmpCZ36k.js +1 -0
  27. package/dist/console/assets/app-update-dialog-B8M9plaT.js +1 -0
  28. package/dist/console/assets/app-version-muKrQqbL.js +1 -0
  29. package/dist/console/assets/console-CrhTsPbz.css +2 -0
  30. package/dist/console/assets/console-DxapQ9oS.js +11 -0
  31. package/dist/console/assets/local-agents-CoqD4dSN.js +6 -0
  32. package/dist/console/assets/minus-DDQ0ydcM.js +1 -0
  33. package/dist/console/assets/tailnet-C5Flwl_d.js +2 -0
  34. package/dist/console/assets/theme-DCd0qh4l.js +1 -0
  35. package/dist/console/assets/ui-Bry1mnCY.js +41 -0
  36. package/dist/console/assets/usage-CIPWnHaS.css +1 -0
  37. package/dist/console/assets/usage-CqVjMb7m.js +5 -0
  38. package/dist/console/assets/usage-D1G0GgE3.js +56 -0
  39. package/dist/console/build-info.json +1 -1
  40. package/dist/console/console.html +8 -2
  41. package/docs/agent-hardening.md +206 -0
  42. package/docs/agent-recipes.md +23 -0
  43. package/docs/agent-workflow.md +5 -0
  44. package/docs/agents.md +49 -6
  45. package/docs/architecture.md +10 -4
  46. package/docs/deployment.md +39 -17
  47. package/docs/design-system.md +56 -7
  48. package/docs/hosted.md +1800 -46
  49. package/docs/images/board-overview.png +0 -0
  50. package/docs/images/journeys.png +0 -0
  51. package/docs/images/live-comment.png +0 -0
  52. package/docs/images/phone-comment.png +0 -0
  53. package/docs/images/phone-overview.png +0 -0
  54. package/docs/images/variant.png +0 -0
  55. package/docs/where-to-run.md +119 -3
  56. package/package.json +6 -1
  57. package/src/agent/backends/acp.js +745 -44
  58. package/src/agent/branch-mode.js +17 -3
  59. package/src/agent/card-hash.js +65 -0
  60. package/src/agent/context.js +41 -0
  61. package/src/agent/exec-paths.js +105 -0
  62. package/src/agent/routes.js +23 -2
  63. package/src/agent/run.js +11 -1
  64. package/src/agent/starter/cli.js +6 -1
  65. package/src/agent/turn-changes.js +70 -8
  66. package/src/agent/usage-log.js +251 -0
  67. package/src/cli/args.js +37 -0
  68. package/src/cli/commands.js +20 -5
  69. package/src/cli/help.js +73 -3
  70. package/src/cli/init.js +2 -1
  71. package/src/cli/serve.js +20 -5
  72. package/src/cli.js +8 -0
  73. package/src/hosted/access-cli.js +99 -1
  74. package/src/hosted/activity-core.js +232 -0
  75. package/src/hosted/activity.js +375 -0
  76. package/src/hosted/admin.js +87 -13
  77. package/src/hosted/agent-approvals.js +29 -4
  78. package/src/hosted/agent-link.js +1032 -0
  79. package/src/hosted/agent-policy.js +10 -3
  80. package/src/hosted/agent-presence.js +63 -22
  81. package/src/hosted/agent-routes.js +135 -0
  82. package/src/hosted/agents.js +1206 -0
  83. package/src/hosted/app.js +178 -12
  84. package/src/hosted/auth-routes.js +156 -15
  85. package/src/hosted/auth.js +123 -20
  86. package/src/hosted/board-routes.js +129 -5
  87. package/src/hosted/chat-frames.js +246 -0
  88. package/src/hosted/chat-job.js +204 -0
  89. package/src/hosted/chat-permissions.js +203 -0
  90. package/src/hosted/chat-routes.js +1009 -0
  91. package/src/hosted/chat-store.js +477 -0
  92. package/src/hosted/comment-files.js +11 -1
  93. package/src/hosted/comments.js +1 -1
  94. package/src/hosted/console-routes.js +122 -34
  95. package/src/hosted/db.js +295 -0
  96. package/src/hosted/device-routes.js +88 -10
  97. package/src/hosted/device.js +54 -4
  98. package/src/hosted/events.js +3 -3
  99. package/src/hosted/guards.js +337 -27
  100. package/src/hosted/http.js +6 -3
  101. package/src/hosted/membership.js +22 -3
  102. package/src/hosted/operator-access.js +418 -0
  103. package/src/hosted/operator.js +106 -2
  104. package/src/hosted/ops-cli.js +238 -3
  105. package/src/hosted/pages.js +4 -0
  106. package/src/hosted/passkey-policy.js +75 -0
  107. package/src/hosted/permissions.js +52 -6
  108. package/src/hosted/presence.js +31 -2
  109. package/src/hosted/projects.js +30 -2
  110. package/src/hosted/public.js +4 -4
  111. package/src/hosted/ratelimit.js +14 -0
  112. package/src/hosted/retention.js +18 -2
  113. package/src/hosted/server.js +123 -11
  114. package/src/hosted/shares.js +2 -2
  115. package/src/hosted/step-up-settings.js +68 -0
  116. package/src/hosted/step-up.js +135 -0
  117. package/src/hosted/tailnet-identity.js +24 -0
  118. package/src/hosted/tailnet-routes.js +342 -0
  119. package/src/hosted/tailnet.js +220 -0
  120. package/src/hosted/tailscale.js +75 -9
  121. package/src/hosted/tenancy.js +66 -1
  122. package/src/hosted/token-api.js +119 -20
  123. package/src/hosted/token-events.js +5 -3
  124. package/src/hosted/tokens.js +29 -6
  125. package/src/hosted/turn-hub.js +152 -0
  126. package/src/hosted/usage-core.js +624 -0
  127. package/src/hosted/usage-layout.js +724 -0
  128. package/src/hosted/usage-routes.js +375 -0
  129. package/src/hosted/usage-shape.js +256 -0
  130. package/src/hosted/usage.js +641 -0
  131. package/src/remote/agent-connect.js +469 -0
  132. package/src/remote/agent-fix.js +611 -0
  133. package/src/remote/agent-job.js +216 -0
  134. package/src/remote/agent-link.js +906 -0
  135. package/src/remote/agent-policy-file.js +242 -0
  136. package/src/remote/credentials.js +35 -1
  137. package/src/remote/login.js +44 -9
  138. package/src/remote/share.js +1 -1
  139. package/src/remote/tailnet-cli.js +547 -0
  140. package/src/server/app.js +15 -0
  141. package/src/server/pairing-routes.js +34 -5
  142. package/src/server/tailscale.js +97 -4
  143. package/src/tailnet-proof.js +766 -0
  144. package/dist/client/assets/BoardChat-DxehB761.js +0 -27
  145. package/dist/client/assets/ChecksPanel-pA_ueIaJ.js +0 -1
  146. package/dist/client/assets/History-C9N32kCv.js +0 -1
  147. package/dist/client/assets/LocalSettings-DawtKnvi.js +0 -1
  148. package/dist/client/assets/QuickConnect-DO1TjS1t.js +0 -1
  149. package/dist/client/assets/index-CsqLdqGx.css +0 -2
  150. package/dist/client/assets/index-DnZarJ3U.js +0 -37
  151. package/dist/client/assets/shield-check-QzwGhz0t.js +0 -1
  152. package/dist/client/assets/ui-DI-FGWWK.js +0 -41
  153. package/dist/console/assets/LocalAccountsApp-VOCZg8dg.js +0 -1
  154. package/dist/console/assets/LocalConsole-CMwAW-mF.js +0 -1
  155. package/dist/console/assets/app-update-dialog-Cw6UDqNP.js +0 -1
  156. package/dist/console/assets/console-DgfWmUEx.js +0 -55
  157. package/dist/console/assets/console-Lis0vvdL.css +0 -2
@@ -16,11 +16,16 @@
16
16
  // - The client side Shapewall offers: text files inside the project root only
17
17
  // (src/agent/acp/sandbox.js), and terminals where every command needs the
18
18
  // person's approval in the panel. Nothing else.
19
+ // - Read only (`readOnly`, what `shapewall agent connect` runs for a hosted
20
+ // board): no writes and no terminals are offered, every request for
21
+ // permission is refused on the spot with a note in the answer, and a
22
+ // session whose mode acts without asking is switched to one that asks, or
23
+ // not started at all. Nobody is asked: there is nobody at this machine.
19
24
 
20
25
  import fs from 'node:fs'
21
26
  import os from 'node:os'
22
27
  import path from 'node:path'
23
- import { randomBytes } from 'node:crypto'
28
+ import { createHash, randomBytes } from 'node:crypto'
24
29
  import { spawn } from 'node:child_process'
25
30
  import { Readable, Writable } from 'node:stream'
26
31
  import { PROTOCOL_VERSION, RequestError, client, ndJsonStream } from '@agentclientprotocol/sdk'
@@ -29,6 +34,7 @@ import { createSandbox, SandboxError } from '../acp/sandbox.js'
29
34
  import { ACP_PREAMBLE, NEXT_STEPS_PROMPT, NO_IMAGES_NOTE, quoteData } from '../context.js'
30
35
  import { AgentError } from '../errors.js'
31
36
  import { showable } from '../showable.js'
37
+ import { neverCommitted, runsSomething } from '../exec-paths.js'
32
38
  import { diffForCard, diffForFiles } from '../text-diff.js'
33
39
  import { findProgram } from '../../watch.js'
34
40
  import { redact } from './openai.js'
@@ -49,6 +55,176 @@ export const ACP_DEFAULTS = {
49
55
  terminalBytesMax: 1024 * 1024,
50
56
  }
51
57
 
58
+ // What a read-only agent is told, and what its answer shows, when it asks
59
+ // to change a file or run a command.
60
+ export const READ_ONLY_REFUSAL = 'Refused: this agent reads and answers only. It cannot change files or run commands from a hosted board.'
61
+
62
+ // The same on the refused request's card, in a few words.
63
+ export const READ_ONLY_NOTE = 'Refused: read and answer only'
64
+
65
+ // ---- Read only, by the agent's own controls ---------------------------------
66
+ // Refusing what an agent asks for is not enough: a tool it is set up to run
67
+ // without asking never asks. So each known agent is also started in a way
68
+ // that makes its own sandbox refuse edits and commands, and that leaves the
69
+ // person's allow rules out. What each adapter takes was read from its source
70
+ // (docs/agent-hardening.md says which agents were proven this way).
71
+
72
+ // The session modes a known agent may run in, read only: modes known to ask
73
+ // before acting, or enforced read-only by the agent itself.
74
+ export const READ_ONLY_MODES = {
75
+ claude: ['default', 'plan'],
76
+ codex: ['read-only'],
77
+ goose: ['chat'],
78
+ }
79
+ // The adapter versions the read-only and edit sessions were proven with,
80
+ // against the real adapter (docs/agent-hardening.md). Another version is
81
+ // used as it is, with a plain warning: an adapter changes what it starts a
82
+ // session with (0.106.0 starts in the mode "auto" where 0.93.0 started in
83
+ // "default"), and only a tested version is known to keep what is promised.
84
+ export const TESTED_ADAPTERS = {
85
+ claude: { name: '@agentclientprotocol/claude-agent-acp', versions: ['0.93.0', '0.106.0'] },
86
+ }
87
+ const versionParts = (text) => {
88
+ const found = /^(\d+)\.(\d+)\.(\d+)/.exec(String(text || ''))
89
+ return found ? found.slice(1).map(Number) : null
90
+ }
91
+ const versionOrder = (a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]
92
+ // What an adapter says it is (initialize's agentInfo), for a log line or an
93
+ // error: "@agentclientprotocol/claude-agent-acp 0.106.0", or '' when it says nothing.
94
+ export function adapterName(agentInfo) {
95
+ const name = showable(String(agentInfo?.name || agentInfo?.title || '')).slice(0, 80)
96
+ const version = showable(String(agentInfo?.version || '')).slice(0, 40)
97
+ return [name, version].filter(Boolean).join(' ')
98
+ }
99
+ // { state, versions, install }: 'tested', 'newer' (than every tested one) or
100
+ // 'untested' (older, in between, another package, or no version said); null
101
+ // for an agent with no tested list.
102
+ export function adapterStatus(kind, agentInfo) {
103
+ const known = TESTED_ADAPTERS[kind]
104
+ if (!known) return null
105
+ const out = { versions: known.versions, install: `npm install -g ${known.name}@${known.versions.at(-1)}` }
106
+ const version = versionParts(agentInfo?.version)
107
+ if (agentInfo?.name !== known.name || !version) return { ...out, state: 'untested' }
108
+ if (known.versions.includes(version.join('.'))) return { ...out, state: 'tested' }
109
+ return { ...out, state: known.versions.every((item) => versionOrder(version, versionParts(item)) > 0) ? 'newer' : 'untested' }
110
+ }
111
+ // One plain line about an adapter that is not a tested one, or null.
112
+ export function adapterWarning(kind, agentInfo, label) {
113
+ const status = adapterStatus(kind, agentInfo)
114
+ if (!status || status.state === 'tested') return null
115
+ const said = adapterName(agentInfo) || 'an adapter that does not say its version'
116
+ const tested = `${TESTED_ADAPTERS[kind].name} ${status.versions.join(' and ')}`
117
+ const what = status.state === 'newer' ? 'which is newer than the versions' : 'which is not a version'
118
+ return `${label} runs through ${said}, ${what} Shapewall ${VERSION} was tested with (${tested}). It is used as it is. If chats fail or behave oddly, install a tested one: ${status.install}`
119
+ }
120
+
121
+ // Claude Code's tools that only read. Everything else is removed from the
122
+ // session, so no allow rule and no mode can run it.
123
+ const CLAUDE_READ_TOOLS = ['Read', 'Grep', 'Glob']
124
+ const CLAUDE_ACTING_TOOLS = [
125
+ 'Bash',
126
+ 'BashOutput',
127
+ 'KillShell',
128
+ 'Edit',
129
+ 'MultiEdit',
130
+ 'Write',
131
+ 'NotebookEdit',
132
+ 'Agent',
133
+ 'Task',
134
+ 'WebFetch',
135
+ 'WebSearch',
136
+ 'Skill',
137
+ ]
138
+ // What goes with session/new.
139
+ export function readOnlySession(kind) {
140
+ if (kind !== 'claude') return {}
141
+ return {
142
+ _meta: {
143
+ claudeCode: {
144
+ options: {
145
+ // No settings files: the person's and the project's allow rules,
146
+ // hooks and plugins do not apply to this session.
147
+ settingSources: [],
148
+ // No MCP servers from .mcp.json, settings or plugins.
149
+ strictMcpConfig: true,
150
+ tools: CLAUDE_READ_TOOLS,
151
+ disallowedTools: CLAUDE_ACTING_TOOLS,
152
+ allowDangerouslySkipPermissions: false,
153
+ },
154
+ },
155
+ },
156
+ }
157
+ }
158
+ // What goes in the agent's environment.
159
+ export function readOnlyEnv(kind) {
160
+ // Codex: its read-only sandbox (no writes, no network), with approvals on request.
161
+ if (kind === 'codex') return { INITIAL_AGENT_MODE: 'read-only' }
162
+ // goose: chat only, no tool calls, whatever GOOSE_MODE the person set.
163
+ if (kind === 'goose') return { GOOSE_MODE: 'chat' }
164
+ return {}
165
+ }
166
+
167
+ // ---- Edits from a hosted board (`remoteEdit`) --------------------------------
168
+ // What `shapewall agent connect --approvals ...` runs for a fix: the agent may
169
+ // ask to edit files of the project and, when the machine lists some, to run
170
+ // exactly those commands. Every request is checked here first, on the
171
+ // machine, whatever anyone answers later:
172
+ // - an edit: a file inside the turn's folder (after symlinks), not in .git
173
+ // or Shapewall's store, not a settings file unless the machine allows it
174
+ // by name, and one whose whole result can be worked out and shown
175
+ // - a command: one of the machine's listed commands, character for character
176
+ // - anything else: refused
177
+ // What passes becomes a card (or, where the machine and the server's rule
178
+ // both say so, is allowed at once), through the turn's `gate`. A turn with no
179
+ // gate changes nothing. The agent's own settings are left out as for a
180
+ // read-only session, and it keeps only its reading and editing tools.
181
+ //
182
+ // Claude Code never gets its shell tool here, whatever commands the machine
183
+ // lists: with it, Claude Code runs commands it takes to be read-only (ls,
184
+ // cat, ...) without asking anyone, and those read outside the project. That
185
+ // was seen with the real adapter (docs/agent-hardening.md), so
186
+ // `agent connect` does not offer commands for Claude Code at all. Listed
187
+ // commands reach an agent only through Shapewall's own terminal
188
+ // (onTerminalCreate) or a permission request, both checked here.
189
+ const CLAUDE_EDIT_TOOLS = ['Edit', 'Write', 'MultiEdit']
190
+ export function remoteEditSession(kind) {
191
+ if (kind !== 'claude') return {}
192
+ const tools = [...CLAUDE_READ_TOOLS, ...CLAUDE_EDIT_TOOLS]
193
+ return {
194
+ _meta: {
195
+ claudeCode: {
196
+ options: {
197
+ settingSources: [],
198
+ strictMcpConfig: true,
199
+ tools,
200
+ disallowedTools: CLAUDE_ACTING_TOOLS.filter((tool) => !tools.includes(tool)),
201
+ allowDangerouslySkipPermissions: false,
202
+ },
203
+ },
204
+ },
205
+ }
206
+ }
207
+ // The two answers a card from a hosted board has.
208
+ export const REMOTE_OPTIONS = [
209
+ { optionId: 'allow', name: 'Allow', kind: 'allow_once' },
210
+ { optionId: 'deny', name: 'Deny', kind: 'reject_once' },
211
+ ]
212
+ export const REMOTE_REFUSALS = {
213
+ kind: "Refused on the agent's machine: only file edits and listed commands can be asked from a hosted board",
214
+ outside: "Refused on the agent's machine: outside the project, or in a folder agents may not write",
215
+ sensitive:
216
+ "Refused on the agent's machine: a file that runs on install, build, test or CI (settings, scripts, manifests, tests), which it does not let a connected agent edit",
217
+ never: "Refused on the agent's machine: Git's own files, node_modules and files Git ignores are never part of a fix",
218
+ unknown: "Refused on the agent's machine: the whole change could not be worked out, so it cannot be shown",
219
+ large: "Refused on the agent's machine: too large to show in full",
220
+ command: "Refused on the agent's machine: not one of the commands it allows",
221
+ policy: "Refused on the agent's machine: it does not take this from the board",
222
+ option: "Refused on the agent's machine: the agent offered no way to allow it once",
223
+ }
224
+ const sha256 = (text) => createHash('sha256').update(String(text)).digest('hex')
225
+ // The most a card's diff may weigh to be relayed to a hosted board.
226
+ const REMOTE_DIFF_MAX = 80 * 1024
227
+
52
228
  const STDERR_KEEP = 4000
53
229
  // The most an approval card shows (and so the most that can be approved).
54
230
  export const DETAIL_MAX = 4096
@@ -431,11 +607,11 @@ export function authError(label, argv) {
431
607
 
432
608
  // What the person's turn looks like to the agent: on a new session, the
433
609
  // preamble and the thread so far (as quoted data); then the new message.
434
- export function promptBlocks({ messages, fresh, image, thread }) {
610
+ export function promptBlocks({ messages, fresh, image, thread, preamble = null }) {
435
611
  const blocks = []
436
612
  const last = messages.at(-1)
437
613
  if (fresh) {
438
- blocks.push({ type: 'text', text: ACP_PREAMBLE })
614
+ blocks.push({ type: 'text', text: preamble || ACP_PREAMBLE })
439
615
  const earlier = messages
440
616
  .slice(0, -1)
441
617
  .map((message) => ({
@@ -493,11 +669,26 @@ function shownPath(root, file) {
493
669
 
494
670
  // One agent process and its ACP session (one chat thread).
495
671
  class AcpProcess {
496
- constructor({ argv, label, env, sandbox, limits, log, thread, onGone, mcpServers = [], extraEnv = {} }) {
497
- Object.assign(this, { argv, label, sandbox, limits, log, thread, onGone, mcpServers })
672
+ constructor({
673
+ argv,
674
+ label,
675
+ env,
676
+ sandbox,
677
+ limits,
678
+ log,
679
+ thread,
680
+ onGone,
681
+ mcpServers = [],
682
+ extraEnv = {},
683
+ readOnly = false,
684
+ remoteEdit = null,
685
+ preamble = null,
686
+ }) {
687
+ Object.assign(this, { argv, label, sandbox, limits, log, thread, onGone, mcpServers, readOnly, remoteEdit, preamble })
498
688
  // `extraEnv`: set by Shapewall itself, never by the agent (branch mode's
499
689
  // GIT_CEILING_DIRECTORIES), for the agent and the terminals it runs.
500
- this.env = { ...agentEnv(env), ...extraEnv }
690
+ // Read only: the variables that put the agent's own sandbox in force win over the person's.
691
+ this.env = { ...agentEnv(env), ...extraEnv, ...(readOnly ? readOnlyEnv(acpAgentKind(argv)) : {}) }
501
692
  this.root = sandbox.root
502
693
  this.state = 'starting'
503
694
  this.stderr = ''
@@ -514,6 +705,12 @@ class AcpProcess {
514
705
  return this.child?.pid ?? null
515
706
  }
516
707
 
708
+ // A connected agent (read only, or taking edits from a hosted board): its
709
+ // session must be in a mode that asks before it acts.
710
+ get asks() {
711
+ return this.readOnly || Boolean(this.remoteEdit)
712
+ }
713
+
517
714
  async start(signal) {
518
715
  let child
519
716
  // The process starts in a fresh empty folder, not the project: `npx` and
@@ -544,6 +741,12 @@ class AcpProcess {
544
741
  child.stderr.on('data', (chunk) => {
545
742
  this.stderr = (this.stderr + chunk.toString('utf8')).slice(-STDERR_KEEP)
546
743
  })
744
+ // Everything it wrote has been read (lastWords waits for this).
745
+ this.stderrClosed = new Promise((resolve) => {
746
+ child.stderr.once('end', resolve)
747
+ child.stderr.once('close', resolve)
748
+ child.stderr.once('error', resolve)
749
+ })
547
750
  child.stdin.on('error', () => {})
548
751
  // A later error (a failed kill) must not take the server down.
549
752
  child.on('error', () => {})
@@ -576,13 +779,23 @@ class AcpProcess {
576
779
  try {
577
780
  const init = await this.connection.agent.request('initialize', {
578
781
  protocolVersion: PROTOCOL_VERSION,
579
- clientCapabilities: { fs: { readTextFile: true, writeTextFile: true }, terminal: true },
782
+ // Read only: the agent is offered no way to write or run through Shapewall.
783
+ clientCapabilities: {
784
+ fs: { readTextFile: true, writeTextFile: !this.readOnly },
785
+ // Edits from a hosted board: a terminal only when the machine lists commands.
786
+ terminal: !this.readOnly && !(this.remoteEdit && !this.remoteEdit.commands.length),
787
+ },
580
788
  clientInfo: { name: 'shapewall', title: 'Shapewall', version: VERSION },
581
789
  })
582
790
  this.agentInfo = init?.agentInfo || null
583
791
  this.image = Boolean(init?.agentCapabilities?.promptCapabilities?.image)
584
792
  this.authMethods = Array.isArray(init?.authMethods) ? init.authMethods : []
585
- const session = await this.connection.agent.request('session/new', { cwd: this.root, mcpServers: this.mcpServers })
793
+ const session = await this.connection.agent.request('session/new', {
794
+ cwd: this.root,
795
+ mcpServers: this.mcpServers,
796
+ // Read only: the agent's own controls are set so that it cannot act (readOnlySession).
797
+ ...(this.readOnly ? readOnlySession(acpAgentKind(this.argv)) : this.remoteEdit ? remoteEditSession(acpAgentKind(this.argv)) : {}),
798
+ })
586
799
  this.sessionId = session.sessionId
587
800
  this.choices = sessionChoices(session)
588
801
  this.configOptions = Array.isArray(session.configOptions) ? session.configOptions : []
@@ -590,8 +803,17 @@ class AcpProcess {
590
803
  // As the session started, before any chat's choices: what a new chat starts from.
591
804
  this.startOptions = sessionOptions(this.configOptions, this.modes)
592
805
  this.state = 'ready'
806
+ if (this.asks) await this.askingMode()
593
807
  } catch (error) {
594
- throw this.startError(error)
808
+ // Its output closed: the exit follows in a moment, and says more (the code, its last words) than the request that failed.
809
+ if (!this.exited && !this.killedFor && (child.stdout.readableEnded || child.stdout.destroyed))
810
+ await Promise.race([this.exitedPromise, new Promise((resolve) => setTimeout(resolve, 500))])
811
+ // What happened is settled now, before it is stopped: stopping it is an exit of our own making.
812
+ const was = { why: this.killedFor, exited: Boolean(this.exited) }
813
+ this.kill('start_failed')
814
+ // Its answer and its stderr are two pipes: the failed request can be read before the words that explain it.
815
+ await this.lastWords()
816
+ throw this.startError(error, was)
595
817
  } finally {
596
818
  clearTimeout(timer)
597
819
  signal?.removeEventListener('abort', onAbort)
@@ -599,15 +821,82 @@ class AcpProcess {
599
821
  return this
600
822
  }
601
823
 
602
- startError(error) {
603
- if (this.killedFor === 'start_timeout') {
604
- this.kill('start_failed')
605
- return new AgentError('agent_start', `${this.label} did not answer within ${Math.round(this.limits.startMs / 1000)} seconds.`)
606
- }
824
+ // Waits, for a bounded moment, until all of a stopped agent's stderr has
825
+ // been read: the pipe closes when the process is gone, and everything it
826
+ // wrote comes before that. An agent that does not stop (it ignores the
827
+ // signal) delays the error by `ms` at most.
828
+ async lastWords(ms = 750) {
829
+ if (!this.stderrClosed) return
830
+ let timer
831
+ await Promise.race([
832
+ this.stderrClosed,
833
+ new Promise((resolve) => {
834
+ timer = setTimeout(resolve, ms)
835
+ }),
836
+ ])
837
+ clearTimeout(timer)
838
+ }
839
+
840
+ // `was`: why it had been stopped, and whether it had exited, before start() stopped it itself.
841
+ startError(error, { why = null, exited = false } = {}) {
607
842
  this.kill('start_failed')
843
+ if (why === 'start_timeout')
844
+ return this.startFailure(`${this.label} did not answer within ${Math.round(this.limits.startMs / 1000)} seconds`)
845
+ // Stopped while it started (an unsafe mode, a cancel): said as that, not as the request that then failed.
846
+ if (why) return this.stoppedError(why)
847
+ // Read only, and the agent's mode cannot be trusted to ask: said as it is.
848
+ if (error instanceof AgentError && error.code === 'agent_unsafe_mode') {
849
+ const said = adapterName(this.agentInfo)
850
+ if (said) error.message = `${error.message} Its adapter: ${said}.`
851
+ return error
852
+ }
608
853
  if (authFailure(error)) return this.authError()
609
- if (this.exited) return this.exitError()
610
- return new AgentError('agent_start', `${this.label} did not start an ACP session (${cut(errorText(error) || 'no answer', 300)}).`)
854
+ if (exited) return this.exitError({ starting: true })
855
+ return this.startFailure(`${this.label} did not start an ACP session (${cut(errorText(error) || 'no answer', 300)})`)
856
+ }
857
+
858
+ // The agent's last words on stderr, for a message: a few lines, with
859
+ // anything that looks like a key removed and the home folder not spelled out.
860
+ stderrTail(max = 300, lines = 3) {
861
+ const home = os.homedir()
862
+ const tail = redact(this.stderr.trim().split('\n').slice(-lines).join(' ').trim())
863
+ return cut(home.length > 1 ? tail.split(home).join('~') : tail, max)
864
+ }
865
+
866
+ // What to try, after a start that failed: a tested adapter version when
867
+ // this one is not, else where to look.
868
+ startHint() {
869
+ const status = adapterStatus(acpAgentKind(this.argv), this.agentInfo)
870
+ if (status && status.state !== 'tested' && this.agentInfo)
871
+ return `This adapter version is not one Shapewall ${VERSION} was tested with (${status.versions.join(', ')}); a tested one: ${status.install}`
872
+ return 'To see more, run "shapewall doctor" in the project folder on the machine the agent runs on (docs/agents.md).'
873
+ }
874
+
875
+ // A start that failed, with everything known about why: what happened, the
876
+ // adapter and its version, its last output and what to try. Never just
877
+ // "did not start".
878
+ startFailure(what, code = 'agent_start') {
879
+ const tail = this.stderrTail()
880
+ const home = os.homedir()
881
+ const text = `${what}${this.via()}.${tail ? ` Its last output: ${tail}` : ''} ${this.startHint()}`.replace(/\s+/g, ' ')
882
+ // The agent's own error text may name files: the home folder is not spelled out in a chat.
883
+ return new AgentError(code, home.length > 1 ? text.split(home).join('~') : text)
884
+ }
885
+
886
+ // Stopped by Shapewall before it was ready, and why.
887
+ stoppedError(why = this.killedFor) {
888
+ if (why === 'unsafe_mode')
889
+ return this.startFailure(
890
+ `${this.label} moved to the mode "${this.unsafeWas ?? '?'}", which acts without asking, while it started. A connected agent must ask before it acts, so it was stopped`,
891
+ 'agent_unsafe_mode',
892
+ )
893
+ const reasons = {
894
+ aborted: 'the request was cancelled',
895
+ cleared: 'the thread was cleared',
896
+ shutdown: 'Shapewall is stopping',
897
+ evicted: 'another thread needed its place',
898
+ }
899
+ return this.startFailure(`${this.label} did not start: ${reasons[why] || `it was stopped while starting (${why || this.state})`}`)
611
900
  }
612
901
 
613
902
  // Not logged in: the fix goes to the chat and to the server log.
@@ -617,10 +906,13 @@ class AcpProcess {
617
906
  return error
618
907
  }
619
908
 
620
- exitError() {
621
- const tail = this.stderr.trim().split('\n').slice(-3).join(' ').trim()
909
+ // `starting`: it went away before its session was ready (the adapter, its
910
+ // version and what to try are said too).
911
+ exitError({ starting = false } = {}) {
912
+ const tail = this.stderrTail()
622
913
  const how = this.exited?.signal ? `signal ${this.exited.signal}` : `code ${this.exited?.code ?? '?'}`
623
- return new AgentError('agent_exited', `${this.label} stopped (${how})${tail ? `: ${cut(tail, 300)}` : '.'}`)
914
+ if (starting) return this.startFailure(`${this.label} stopped while it started (${how})`, 'agent_exited')
915
+ return new AgentError('agent_exited', `${this.label} stopped (${how})${tail ? `: ${tail}` : '.'}`)
624
916
  }
625
917
 
626
918
  gone(code, signalName) {
@@ -632,7 +924,15 @@ class AcpProcess {
632
924
  // Whatever a running turn was waiting for will not come.
633
925
  if (this.turn) {
634
926
  for (const permission of this.turn.permissions.values()) permission.settle('cancelled')
635
- this.turn.queue.end(this.turn.cancelled ? null : this.exitError())
927
+ // Stopped here for a mode that acts without asking: the chat hears that, not "signal SIGTERM".
928
+ const why =
929
+ this.killedFor === 'unsafe_mode'
930
+ ? new AgentError(
931
+ 'agent_unsafe_mode',
932
+ `${this.label} moved to the mode "${this.unsafeWas ?? '?'}", which acts without asking. A connected agent must ask before it acts, so it was stopped${this.via()}.`,
933
+ )
934
+ : this.exitError()
935
+ this.turn.queue.end(this.turn.cancelled ? null : why)
636
936
  }
637
937
  try {
638
938
  this.connection?.close()
@@ -712,10 +1012,11 @@ class AcpProcess {
712
1012
 
713
1013
  // Starts session/prompt. Returns the events and a finish() for when the
714
1014
  // reader stops early.
715
- prompt(blocks, signal) {
1015
+ prompt(blocks, signal, gate = null) {
716
1016
  clearTimeout(this.idleTimer)
717
1017
  const queue = eventQueue()
718
- const turn = { queue, permissions: new Map(), cancelled: false, settled: false, text: '' }
1018
+ // `gate`: who decides this turn's requests (edits from a hosted board).
1019
+ const turn = { queue, permissions: new Map(), cancelled: false, settled: false, text: '', gate, chain: Promise.resolve() }
719
1020
  this.turn = turn
720
1021
  this.fresh = false
721
1022
  const onAbort = () => this.cancel(turn)
@@ -773,6 +1074,266 @@ class AcpProcess {
773
1074
  turn.killTimer.unref?.()
774
1075
  }
775
1076
 
1077
+ // Read only: the session's mode, when it has one, must be one that asks
1078
+ // before it acts (the requests are then refused here). A session set to
1079
+ // act without asking (bypass, accept edits, auto, ...) is switched to the
1080
+ // first mode that asks; if there is none, it does not start.
1081
+ // The session's mode as the agent reports it: { id, current, values }, or
1082
+ // null when it reports none (neither a "mode" config option nor modes).
1083
+ modeState() {
1084
+ const config = this.configOptions.find((option) => option?.category === 'mode' && typeof option.currentValue === 'string')
1085
+ const current = config ? config.currentValue : this.modes?.currentModeId
1086
+ if (typeof current !== 'string') return null
1087
+ const values = config
1088
+ ? optionValues(config.options)
1089
+ : optionValues((this.modes?.availableModes || []).map((item) => ({ value: item?.id, name: item?.name })))
1090
+ return { id: config ? config.id : MODE_OPTION_ID, current, values }
1091
+ }
1092
+ // Read only: is this mode one a connected agent may run in? A known
1093
+ // agent: exactly the modes known to ask (or to be read-only by the
1094
+ // agent's own sandbox). Any other: a mode whose name does not say it acts
1095
+ // without asking.
1096
+ modeAllowed(item) {
1097
+ const wanted = READ_ONLY_MODES[acpAgentKind(this.argv)]
1098
+ return wanted ? wanted.includes(item.value) : !UNSAFE_VALUE_RE.test(`${item.value} ${item.name}`)
1099
+ }
1100
+ // A mode's display name, as the agent lists it.
1101
+ modeName(id) {
1102
+ return this.modeState()?.values.find((item) => item.value === id)?.name || id
1103
+ }
1104
+ // The mode when it is not allowed (see modeAllowed), else null.
1105
+ unsafeMode() {
1106
+ const state = this.modeState()
1107
+ if (!state) return null
1108
+ return this.modeAllowed({ value: state.current, name: this.modeName(state.current) }) ? null : state
1109
+ }
1110
+ // A connected agent's session moved to a mode that acts without asking:
1111
+ // it stops, and the log and the chat say which mode.
1112
+ unsafeStop(mode) {
1113
+ if (this.unsafeWas === undefined) {
1114
+ this.unsafeWas = cut(showable(mode), 40)
1115
+ this.log(`acp: ${this.label} moved to the mode "${this.unsafeWas}", which acts without asking, so it was stopped${this.via()}`)
1116
+ }
1117
+ this.kill('unsafe_mode')
1118
+ }
1119
+ // " (through <adapter> <version>)" for a message, or ''.
1120
+ via() {
1121
+ const said = adapterName(this.agentInfo)
1122
+ return said ? ` (through ${said})` : ''
1123
+ }
1124
+ // Read only, fail closed: the session must report a mode, and it must be
1125
+ // one that asks. Anything else is switched to one, or the agent does not
1126
+ // start. Nothing is assumed about an agent that says nothing.
1127
+ async askingMode() {
1128
+ if (!this.modeState())
1129
+ throw new AgentError(
1130
+ 'agent_unsafe_mode',
1131
+ `${this.label} reports no session mode, so Shapewall cannot tell that it asks before it acts. It is not started read-only.`,
1132
+ )
1133
+ const unsafe = this.unsafeMode()
1134
+ if (!unsafe) return
1135
+ const safe = unsafe.values.filter((item) => this.modeAllowed(item))
1136
+ const wanted = READ_ONLY_MODES[acpAgentKind(this.argv)] || []
1137
+ // The agent's own asking mode first; never "plan" by choice: a planning
1138
+ // mode answers with a plan to approve, not an answer.
1139
+ const pick =
1140
+ wanted.map((value) => safe.find((item) => item.value === value)).find(Boolean) ||
1141
+ safe.find((item) => /^(default|ask)$/i.test(item.value)) ||
1142
+ safe.find((item) => !/plan/i.test(item.value)) ||
1143
+ safe[0]
1144
+ const refuse = () =>
1145
+ new AgentError(
1146
+ 'agent_unsafe_mode',
1147
+ `${this.label} is set to act without asking on this machine (mode "${cut(unsafe.current, 40)}"), and could not be switched to a mode that asks. A connected agent reads and answers only: it is not started.`,
1148
+ )
1149
+ if (!pick) throw refuse()
1150
+ try {
1151
+ if (unsafe.id === MODE_OPTION_ID) {
1152
+ await this.connection.agent.request('session/set_mode', { sessionId: this.sessionId, modeId: pick.value })
1153
+ this.modes = { ...this.modes, currentModeId: pick.value }
1154
+ } else {
1155
+ const result = await this.connection.agent.request('session/set_config_option', {
1156
+ sessionId: this.sessionId,
1157
+ configId: unsafe.id,
1158
+ value: pick.value,
1159
+ })
1160
+ if (Array.isArray(result?.configOptions)) this.configOptions = result.configOptions
1161
+ else this.configOptions = this.configOptions.map((item) => (item.id === unsafe.id ? { ...item, currentValue: pick.value } : item))
1162
+ }
1163
+ } catch {
1164
+ throw refuse()
1165
+ }
1166
+ if (this.unsafeMode()) throw refuse()
1167
+ this.log(
1168
+ `acp: ${this.label} switched from mode "${cut(unsafe.current, 40)}" to "${cut(pick.value, 40)}" (${this.readOnly ? 'read only' : 'edits are asked on the board'})`,
1169
+ )
1170
+ }
1171
+
1172
+ // Read only: what the agent asked for is refused here, and the answer
1173
+ // says so (a card nobody can answer). Returns the card's state.
1174
+ refuse({ title, kind, detail = null, note = READ_ONLY_NOTE }) {
1175
+ const turn = this.turn
1176
+ if (turn && !turn.cancelled)
1177
+ turn.queue.push({
1178
+ type: 'permission',
1179
+ id: `perm_${randomBytes(6).toString('hex')}`,
1180
+ title: cut(title, 120),
1181
+ kind,
1182
+ detail: `${detail ? `${cut(detail, 300)}\n` : ''}[${note}]`,
1183
+ diff: null,
1184
+ options: [],
1185
+ expiresAt: null,
1186
+ state: 'denied',
1187
+ chosen: null,
1188
+ })
1189
+ return 'denied'
1190
+ }
1191
+
1192
+ // ---- Edits from a hosted board ---------------------------------------------
1193
+
1194
+ // What an edit would leave in its file: { file, rel, current, next }, or
1195
+ // null when that cannot be worked out in full. From a whole new content
1196
+ // (Write), from old/new pairs every one of which the file holds now
1197
+ // (Edit, MultiEdit), or from one ACP diff whose old text is the file as it
1198
+ // is now. `file` is the real path, inside this turn's folder. Throws when
1199
+ // the path is outside it (or in .git, or in Shapewall's store).
1200
+ editResult(file, call, known, input) {
1201
+ const real = this.sandbox.resolve(path.resolve(this.root, file), { write: true })
1202
+ const rel = path.relative(this.root, real)
1203
+ const current = this.currentText(real)
1204
+ const text = (value) => (typeof value === 'string' && value.length <= DIFF_INPUT_MAX ? value : null)
1205
+ let next = null
1206
+ if (input) {
1207
+ const edits = Array.isArray(input.edits) ? input.edits : [input]
1208
+ const pairs = edits.map((edit) => ({
1209
+ oldText: text(edit?.old_string ?? edit?.old_str ?? edit?.oldText),
1210
+ newText: text(edit?.new_string ?? edit?.new_str ?? edit?.newText),
1211
+ all: edit?.replace_all === true,
1212
+ }))
1213
+ if (pairs.length && pairs.every((pair) => pair.oldText !== null && pair.newText !== null)) {
1214
+ next = current
1215
+ for (const pair of pairs) {
1216
+ if (next === null || !pair.oldText || !next.includes(pair.oldText)) return null
1217
+ next = pair.all ? next.split(pair.oldText).join(pair.newText) : next.replace(pair.oldText, () => pair.newText)
1218
+ }
1219
+ } else next = text(input.content ?? input.file_text ?? input.text)
1220
+ }
1221
+ if (next === null) {
1222
+ const sent = Array.isArray(call?.content) ? diffContent(call.content) : known?.diffs
1223
+ if (sent?.length !== 1) return null
1224
+ const only = sent[0]
1225
+ let same = false
1226
+ try {
1227
+ same = this.sandbox.resolve(path.resolve(this.root, only.path), { write: true }) === real
1228
+ } catch {
1229
+ same = false
1230
+ }
1231
+ if (!same || (only.oldText ?? null) !== current) return null
1232
+ next = only.newText
1233
+ }
1234
+ return { file: real, rel, current, next }
1235
+ }
1236
+
1237
+ // One request of a turn that takes edits from a hosted board, decided:
1238
+ // refused here, allowed at once (the machine and the server's rule both
1239
+ // say so), or asked on the board. Resolves true when it may go ahead.
1240
+ // `request`: { kind: 'edit', file, call, known, input } or
1241
+ // { kind: 'command', command }. One at a time per turn, so each edit is
1242
+ // worked out against the file as the one before left it.
1243
+ remoteRequest(request, signal) {
1244
+ const turn = this.turn
1245
+ if (!turn || turn.cancelled) return Promise.resolve(false)
1246
+ const run = turn.chain.then(() => this.remoteDecide(turn, request, signal))
1247
+ turn.chain = run.catch(() => {})
1248
+ return run
1249
+ }
1250
+
1251
+ async remoteDecide(turn, request, signal) {
1252
+ const still = () => this.turn === turn && !turn.cancelled && !signal?.aborted && this.state === 'ready' && !this.stoppingPromise
1253
+ if (!still()) return false
1254
+ const refuse = (title, kind, detail, note) => {
1255
+ this.refuse({ title, kind, detail, note })
1256
+ return false
1257
+ }
1258
+ // No gate: this turn was not started to change anything.
1259
+ if (!turn.gate) return refuse(request.kind === 'edit' ? 'Edit a file' : 'Run a command', 'other', null, REMOTE_REFUSALS.policy)
1260
+ let card
1261
+ let approved = null
1262
+ let guarded = false
1263
+ if (request.kind === 'edit') {
1264
+ const shown = showable(relativeTo(this.root, String(request.file || '')))
1265
+ let result
1266
+ try {
1267
+ // An earlier edit of this file that was allowed may still be on its way to disk.
1268
+ for (let tries = 0; ; tries += 1) {
1269
+ result = this.editResult(request.file, request.call, request.known, request.input)
1270
+ const before = result ? turn.gate.expected?.(result.rel.split(path.sep).join('/')) : null
1271
+ if (!before || tries >= 40 || sha256(result.current ?? '') === before) break
1272
+ await new Promise((resolve) => setTimeout(resolve, 50))
1273
+ }
1274
+ } catch {
1275
+ return refuse('Edit a file', 'edit', shown, REMOTE_REFUSALS.outside)
1276
+ }
1277
+ if (!still()) return false
1278
+ if (!result) return refuse('Edit a file', 'edit', shown, REMOTE_REFUSALS.unknown)
1279
+ const rel = result.rel.split(path.sep).join('/')
1280
+ if (!rel || rel.startsWith('..')) return refuse('Edit a file', 'edit', shown, REMOTE_REFUSALS.outside)
1281
+ // What Shapewall's commit would leave out is not asked for at all: an
1282
+ // edit that was allowed and then silently dropped would be a lie.
1283
+ let never = neverCommitted(rel)
1284
+ try {
1285
+ never = never || Boolean(await turn.gate.ignored?.(rel))
1286
+ } catch {
1287
+ never = true
1288
+ }
1289
+ if (!still()) return false
1290
+ if (never) return refuse(`Edit ${rel}`, 'edit', rel, REMOTE_REFUSALS.never)
1291
+ // Files that run something (exec-paths.js): only when this machine named the file,
1292
+ // and then never without a person's answer.
1293
+ guarded = this.sandbox.sensitive(result.file) || runsSomething(rel)
1294
+ if (guarded && !this.remoteEdit.allowPaths.includes(rel)) return refuse(`Edit ${rel}`, 'edit', rel, REMOTE_REFUSALS.sensitive)
1295
+ const diff = diffForFiles([{ path: rel, oldText: result.current, newText: result.next, outside: false }])
1296
+ if (!diff || diff.truncated || Buffer.byteLength(JSON.stringify(diff)) > REMOTE_DIFF_MAX)
1297
+ return refuse(`Edit ${rel}`, 'edit', rel, REMOTE_REFUSALS.large)
1298
+ card = { title: `${result.current === null ? 'Create' : 'Edit'} ${rel}`, kind: 'edit', detail: rel, diff }
1299
+ approved = { rel, hash: sha256(result.next) }
1300
+ } else {
1301
+ const command = typeof request.command === 'string' ? request.command.trim() : ''
1302
+ if (!command || !this.remoteEdit.commands.includes(command))
1303
+ return refuse('Run a command', 'execute', showable(command), REMOTE_REFUSALS.command)
1304
+ card = { title: 'Run a command', kind: 'execute', detail: command, diff: null }
1305
+ }
1306
+ let verdict = 'deny'
1307
+ try {
1308
+ verdict = await turn.gate.decide(
1309
+ request.kind === 'edit' ? { kind: 'edit', path: approved.rel, guarded } : { kind: 'command', command: card.detail },
1310
+ )
1311
+ } catch {
1312
+ verdict = 'deny'
1313
+ }
1314
+ // A file that runs something is never allowed without asking, whatever the rules say.
1315
+ if (guarded && verdict === 'allow') verdict = 'ask'
1316
+ if (!still()) return false
1317
+ if (verdict === 'allow') {
1318
+ // Allowed without asking: the card says so, and nobody is waited for.
1319
+ turn.queue.push({
1320
+ type: 'permission',
1321
+ id: `perm_${randomBytes(12).toString('hex')}`,
1322
+ ...card,
1323
+ options: [],
1324
+ expiresAt: null,
1325
+ state: 'approved',
1326
+ chosen: 'Allowed automatically',
1327
+ })
1328
+ } else if (verdict === 'ask') {
1329
+ const { state } = await this.ask({ ...card, options: REMOTE_OPTIONS }, signal)
1330
+ if (state !== 'approved' || !still()) return false
1331
+ } else return refuse(card.title, card.kind, card.detail, REMOTE_REFUSALS.policy)
1332
+ // `auto`: nobody looked at this one (the fix is then held back from any remote: agent-fix.js).
1333
+ if (approved) turn.gate.approved?.(approved.rel, approved.hash, { auto: verdict === 'allow' })
1334
+ return true
1335
+ }
1336
+
776
1337
  // The composer's option menus, as sessionOptions lists them.
777
1338
  options() {
778
1339
  return sessionOptions(this.configOptions, this.modes)
@@ -840,11 +1401,26 @@ class AcpProcess {
840
1401
  if (params?.sessionId === this.sessionId && params.update?.sessionUpdate === 'config_option_update') {
841
1402
  // The agent changed its own model or effort (or confirmed ours): the composer shows it.
842
1403
  if (Array.isArray(params.update.configOptions)) this.configOptions = params.update.configOptions
1404
+ const unsafe = this.asks ? this.unsafeMode() : null
1405
+ if (unsafe) this.unsafeStop(unsafe.current)
843
1406
  return
844
1407
  }
845
1408
  if (params?.sessionId === this.sessionId && params.update?.sessionUpdate === 'current_mode_update') {
846
- if (this.modes && typeof params.update.currentModeId === 'string')
847
- this.modes = { ...this.modes, currentModeId: params.update.currentModeId }
1409
+ const id = params.update.currentModeId
1410
+ if (typeof id !== 'string') return
1411
+ if (this.modes) this.modes = { ...this.modes, currentModeId: id }
1412
+ // An agent that reports its mode both ways (a "mode" config option and
1413
+ // modes) has one mode: this is it. The option's own update may come
1414
+ // later, or only with the answer to the request that changed it
1415
+ // (claude-agent-acp 0.106.0 sends this first when asked to switch), and
1416
+ // until then the option would still name the mode the session left.
1417
+ const option = this.configOptions.find((item) => item?.category === 'mode' && typeof item.currentValue === 'string')
1418
+ if (option && optionValues(option.options).some((item) => item.value === id))
1419
+ this.configOptions = this.configOptions.map((item) => (item === option ? { ...item, currentValue: id } : item))
1420
+ // Read only: an agent that switches itself to a mode that acts without
1421
+ // asking stops. The mode it names is checked itself, and so is what the
1422
+ // session's state then says.
1423
+ if (this.asks && (!this.modeAllowed({ value: id, name: this.modeName(id) }) || this.unsafeMode())) this.unsafeStop(id)
848
1424
  return
849
1425
  }
850
1426
  const turn = this.turn
@@ -979,6 +1555,37 @@ class AcpProcess {
979
1555
  if (detail && target && outsideProject(this.root, target)) {
980
1556
  detail = `${detail}\n[Outside the project: ${showable(path.resolve(this.root, target))}]`
981
1557
  }
1558
+ // Read only: refused here, whatever it is. The agent hears its own
1559
+ // "reject" option (or a cancel) and goes on answering.
1560
+ if (this.readOnly) {
1561
+ this.refuse({ title: call.title || known.title || 'Use a tool', kind: call.kind || known.kind || 'other', detail })
1562
+ const reject = options.find((item) => item.kind === 'reject_once') || options.find((item) => item.kind === 'reject_always')
1563
+ return reject ? { outcome: { outcome: 'selected', optionId: reject.optionId } } : { outcome: { outcome: 'cancelled' } }
1564
+ }
1565
+ // Edits from a hosted board: checked and decided here (remoteRequest).
1566
+ // The agent only ever hears "once": its "always" options are not used.
1567
+ if (this.remoteEdit) {
1568
+ const kind = call.kind || known.kind || 'other'
1569
+ const reject = options.find((item) => item.kind === 'reject_once') || options.find((item) => item.kind === 'reject_always')
1570
+ const no = () => (reject ? { outcome: { outcome: 'selected', optionId: reject.optionId } } : { outcome: { outcome: 'cancelled' } })
1571
+ const allow = options.find((item) => item.kind === 'allow_once')
1572
+ const file = [input?.file_path, input?.path, input?.filePath].find((value) => typeof value === 'string' && value)
1573
+ const command = typeof input?.command === 'string' ? input.command : null
1574
+ let request = null
1575
+ if (kind === 'edit' && file) request = { kind: 'edit', file, call, known, input }
1576
+ else if (kind === 'execute' && command !== null && !file) request = { kind: 'command', command }
1577
+ if (!request || !allow) {
1578
+ this.refuse({
1579
+ title: request ? (request.kind === 'edit' ? 'Edit a file' : 'Run a command') : 'Use a tool',
1580
+ kind,
1581
+ detail,
1582
+ note: request ? REMOTE_REFUSALS.option : REMOTE_REFUSALS.kind,
1583
+ })
1584
+ return no()
1585
+ }
1586
+ const ok = await this.remoteRequest(request, signal)
1587
+ return ok ? { outcome: { outcome: 'selected', optionId: allow.optionId } } : no()
1588
+ }
982
1589
  const { state, option } = await this.ask(
983
1590
  {
984
1591
  title: call.title || known.title || 'Use a tool',
@@ -1065,7 +1672,37 @@ class AcpProcess {
1065
1672
 
1066
1673
  async onWrite(params, signal) {
1067
1674
  this.ownSession(params)
1675
+ if (this.readOnly) {
1676
+ this.refuse({ title: 'Write a file', kind: 'edit', detail: showable(relativeTo(this.root, String(params?.path || ''))) })
1677
+ throw new RequestError(-32000, READ_ONLY_REFUSAL)
1678
+ }
1068
1679
  const turn = this.turn
1680
+ // Edits from a hosted board: the same checks and the same card as an
1681
+ // edit the agent makes with its own tool; then the write, through the sandbox.
1682
+ if (this.remoteEdit) {
1683
+ const ok =
1684
+ typeof params?.path === 'string' && typeof params?.content === 'string'
1685
+ ? await this.remoteRequest(
1686
+ { kind: 'edit', file: params.path, call: null, known: null, input: { content: params.content } },
1687
+ signal,
1688
+ )
1689
+ : false
1690
+ if (!ok) throw new RequestError(-32000, 'This file was not written: the edit was refused or not allowed.')
1691
+ try {
1692
+ const file = this.sandbox.write(params)
1693
+ this.turn?.queue.push({
1694
+ type: 'tool',
1695
+ id: `acp-write-${randomBytes(4).toString('hex')}`,
1696
+ name: 'edit',
1697
+ label: 'Wrote a file',
1698
+ state: 'done',
1699
+ detail: relativeTo(this.root, file),
1700
+ })
1701
+ return {}
1702
+ } catch (error) {
1703
+ throw sandboxRefusal(error)
1704
+ }
1705
+ }
1069
1706
  let target
1070
1707
  try {
1071
1708
  target = this.sandbox.resolve(params?.path, { write: true })
@@ -1116,6 +1753,14 @@ class AcpProcess {
1116
1753
 
1117
1754
  async onTerminalCreate(params, signal) {
1118
1755
  this.ownSession(params)
1756
+ if (this.readOnly) {
1757
+ this.refuse({
1758
+ title: 'Run a command',
1759
+ kind: 'execute',
1760
+ detail: showable(formatCommand([String(params?.command || ''), ...(Array.isArray(params?.args) ? params.args.map(String) : [])])),
1761
+ })
1762
+ throw new RequestError(-32000, READ_ONLY_REFUSAL)
1763
+ }
1119
1764
  const turn = this.turn
1120
1765
  if (this.terminals.size >= this.limits.terminalsMax) throw new RequestError(-32000, 'Too many terminals are open; release one first.')
1121
1766
  const command = typeof params.command === 'string' ? params.command : ''
@@ -1147,19 +1792,30 @@ class AcpProcess {
1147
1792
  ...Object.entries(extraEnv).map(([name, value]) => `env ${name}=${showable(value)}`),
1148
1793
  ...(ignored.length ? [`env ignored: ${ignored.join(', ')}`] : []),
1149
1794
  ]
1150
- const { state } = await this.ask(
1151
- {
1152
- title: 'Run a command',
1153
- kind: 'execute',
1154
- detail: lines.join('\n'),
1155
- options: [
1156
- { optionId: 'run', name: 'Run', kind: 'allow_once' },
1157
- { optionId: 'deny', name: "Don't run", kind: 'reject_once' },
1158
- ],
1159
- },
1160
- signal,
1161
- )
1162
- if (state !== 'approved') throw new RequestError(-32000, `The person did not allow this command (${state}).`)
1795
+ if (this.remoteEdit) {
1796
+ // From a hosted board: one of the machine's listed commands, exactly,
1797
+ // in the project folder, with no environment of the agent's choosing.
1798
+ if (cwd !== this.root || Object.keys(extraEnv).length || ignored.length) {
1799
+ this.refuse({ title: 'Run a command', kind: 'execute', detail: shown, note: REMOTE_REFUSALS.command })
1800
+ throw new RequestError(-32000, 'Refused: a command from a hosted board runs in the project folder, with no extra environment.')
1801
+ }
1802
+ const ok = await this.remoteRequest({ kind: 'command', command: formatCommand([command, ...args]) }, signal)
1803
+ if (!ok) throw new RequestError(-32000, 'This command was refused or not allowed.')
1804
+ } else {
1805
+ const { state } = await this.ask(
1806
+ {
1807
+ title: 'Run a command',
1808
+ kind: 'execute',
1809
+ detail: lines.join('\n'),
1810
+ options: [
1811
+ { optionId: 'run', name: 'Run', kind: 'allow_once' },
1812
+ { optionId: 'deny', name: "Don't run", kind: 'reject_once' },
1813
+ ],
1814
+ },
1815
+ signal,
1816
+ )
1817
+ if (state !== 'approved') throw new RequestError(-32000, `The person did not allow this command (${state}).`)
1818
+ }
1163
1819
  // Approval can resolve immediately before teardown. Recheck after that
1164
1820
  // await so no terminal group appears after stopOwned took its snapshot.
1165
1821
  if (!turn || this.turn !== turn || turn.cancelled || signal?.aborted || this.state !== 'ready' || this.stoppingPromise)
@@ -1311,6 +1967,10 @@ export function createAcpBackend(
1311
1967
  limits: limit,
1312
1968
  log,
1313
1969
  thread,
1970
+ // Read only (settings.readOnly, `shapewall agent connect`): see the top of this file.
1971
+ readOnly: settings.readOnly === true,
1972
+ // Edits from a hosted board (settings.remoteEdit: { commands, allowPaths }).
1973
+ remoteEdit: settings.readOnly !== true && settings.remoteEdit ? settings.remoteEdit : null,
1314
1974
  mcpServers: mcpServersFor?.(thread) || [],
1315
1975
  onGone: (item) => {
1316
1976
  if (item.stopped || !item.pid) processPool?.agents.delete(item)
@@ -1332,6 +1992,7 @@ export function createAcpBackend(
1332
1992
  } catch (error) {
1333
1993
  agent.kill('start_failed')
1334
1994
  await agent.stoppingPromise
1995
+ startFailed(agent, error)
1335
1996
  throw error
1336
1997
  } finally {
1337
1998
  starting.delete(agent)
@@ -1344,11 +2005,32 @@ export function createAcpBackend(
1344
2005
  await agent.stoppingPromise
1345
2006
  throw new AgentError('agent_start', 'The server is stopping.')
1346
2007
  }
1347
- if (agent.state !== 'ready') throw agent.exited ? agent.exitError() : new AgentError('agent_start', `${settings.label} did not start.`)
2008
+ if (agent.state !== 'ready') {
2009
+ // Ready a moment ago, and gone or stopped since: said with the cause.
2010
+ const gone = Boolean(agent.exited)
2011
+ const why = agent.killedFor
2012
+ agent.kill('start_failed')
2013
+ await agent.lastWords()
2014
+ const error = gone ? agent.exitError({ starting: true }) : agent.stoppedError(why)
2015
+
2016
+ startFailed(agent, error)
2017
+ throw error
2018
+ }
1348
2019
  processes.set(thread, agent)
1349
2020
  return agent
1350
2021
  }
1351
2022
 
2023
+ // A start that failed goes to the log with its cause, as it goes to the
2024
+ // chat: the message, and more of the agent's last output than a chat shows.
2025
+ // Not when the person or Shapewall stopped it, and not twice for a login
2026
+ // (authError logs its own line).
2027
+ const startFailed = (agent, error) => {
2028
+ if (['aborted', 'cleared', 'shutdown', 'evicted', 'doctor'].includes(agent.killedFor) || error?.code === 'agent_auth') return
2029
+ log(`acp: ${error?.message || `${settings.label} did not start`}`)
2030
+ const tail = agent.stderrTail(1500, 12)
2031
+ if (tail) log(`acp: ${settings.label} last output: ${tail}`)
2032
+ }
2033
+
1352
2034
  return {
1353
2035
  id: 'acp',
1354
2036
  tools: 'own',
@@ -1363,7 +2045,9 @@ export function createAcpBackend(
1363
2045
  // `workdir`: { root, env, protect, sensitivePaths } for a turn that works
1364
2046
  // in a folder of its own (branch mode): the thread's agent runs there,
1365
2047
  // started afresh when its session was in another folder.
1366
- async *stream({ messages, signal, thread = 'default', choices = null, workdir = null }) {
2048
+ // `gate`: { decide, approved, expected } for a turn that takes edits
2049
+ // from a hosted board (AcpProcess.remoteRequest).
2050
+ async *stream({ messages, signal, thread = 'default', choices = null, workdir = null, gate = null, preamble = null }) {
1367
2051
  if (signal?.aborted) return
1368
2052
  await preparing.get(thread)?.catch(() => {})
1369
2053
  let agent = processes.get(thread)
@@ -1390,7 +2074,11 @@ export function createAcpBackend(
1390
2074
  yield { type: 'status', text: `${settings.label} is working` }
1391
2075
  const image = agent.image && settings.vision !== false
1392
2076
  if (!image && messages.at(-1)?.content?.some((part) => part.type === 'image')) yield { type: 'notice', text: NO_IMAGES_NOTE }
1393
- const turn = agent.prompt(promptBlocks({ messages, fresh: agent.fresh, image, thread }), signal)
2077
+ const turn = agent.prompt(
2078
+ promptBlocks({ messages, fresh: agent.fresh, image, thread, preamble: preamble || settings.preamble || null }),
2079
+ signal,
2080
+ gate,
2081
+ )
1394
2082
  try {
1395
2083
  for await (const event of turn.events) yield event
1396
2084
  } catch (error) {
@@ -1470,7 +2158,10 @@ export function createAcpBackend(
1470
2158
 
1471
2159
  // `shapewall doctor`: starts the agent, does the initialize handshake, and
1472
2160
  // stops it again. Never sends a prompt (that would spend the subscription).
1473
- export async function acpHandshake(settings, { env = process.env, root, timeoutMs = 30000, processPool = null } = {}) {
2161
+ // `agent connect` does the same before it goes online, with the session a
2162
+ // connected agent gets (settings.readOnly, settings.remoteEdit): a session
2163
+ // that cannot be opened is said at once, with why, not at the first question.
2164
+ export async function acpHandshake(settings, { env = process.env, root, timeoutMs = 30000, processPool = null, log = () => {} } = {}) {
1474
2165
  const sandbox = createSandbox({ root })
1475
2166
  const agent = new AcpProcess({
1476
2167
  argv: settings.acp.argv,
@@ -1478,8 +2169,10 @@ export async function acpHandshake(settings, { env = process.env, root, timeoutM
1478
2169
  env,
1479
2170
  sandbox,
1480
2171
  limits: { ...ACP_DEFAULTS, startMs: timeoutMs },
1481
- log: () => {},
2172
+ log,
1482
2173
  thread: 'doctor',
2174
+ readOnly: settings.readOnly === true,
2175
+ remoteEdit: settings.readOnly !== true && settings.remoteEdit ? settings.remoteEdit : null,
1483
2176
  onGone: (item) => {
1484
2177
  if (item.stopped || !item.pid) processPool?.agents.delete(item)
1485
2178
  poolChanged(processPool)
@@ -1488,9 +2181,17 @@ export async function acpHandshake(settings, { env = process.env, root, timeoutM
1488
2181
  try {
1489
2182
  await reserveProcessSlot(processPool, agent)
1490
2183
  await agent.start()
1491
- return { ok: true, agentInfo: agent.agentInfo, image: agent.image, choices: agent.choices }
2184
+ // Stopped between its answer and now (a mode that acts without asking): not a session.
2185
+ if (agent.state !== 'ready') {
2186
+ const gone = Boolean(agent.exited)
2187
+ const why = agent.killedFor
2188
+ agent.kill('doctor')
2189
+ await agent.lastWords()
2190
+ throw gone ? agent.exitError({ starting: true }) : agent.stoppedError(why)
2191
+ }
2192
+ return { ok: true, agentInfo: agent.agentInfo, image: agent.image, choices: agent.choices, mode: agent.modeState()?.current ?? null }
1492
2193
  } catch (error) {
1493
- return { ok: false, code: error.code, message: error.message }
2194
+ return { ok: false, code: error.code, message: error.message, agentInfo: agent.agentInfo || null, stderr: agent.stderrTail(1500, 12) }
1494
2195
  } finally {
1495
2196
  agent.kill('doctor')
1496
2197
  await agent.stoppingPromise