shapewall 0.3.2 → 0.6.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 (119) hide show
  1. package/CHANGELOG.md +357 -0
  2. package/NOTICE +7 -0
  3. package/README.md +50 -4
  4. package/THIRD_PARTY.md +39 -0
  5. package/dist/agent/package-lock.json +2 -2
  6. package/dist/client/assets/BoardChat-DdwBcb2N.js +27 -0
  7. package/dist/client/assets/BuzzDialog-DpUcnU6S.js +1 -0
  8. package/dist/client/assets/ChecksPanel-CngYV4yz.js +1 -0
  9. package/dist/client/assets/History-CD0saQA5.js +1 -0
  10. package/dist/client/assets/LocalSettings-MZy2baig.js +1 -0
  11. package/dist/client/assets/{Management-DmTh1-tA.js → Management-CSvZ-SHO.js} +1 -1
  12. package/dist/client/assets/QuickConnect-foLh2QUm.js +1 -0
  13. package/dist/client/assets/ShareDialog-DPWDftoL.js +2 -0
  14. package/dist/client/assets/app-update-dialog-CtiXpTRD.js +1 -0
  15. package/dist/client/assets/{circle-x-3UxAvczM.js → circle-x-CteRBtXC.js} +1 -1
  16. package/dist/client/assets/index-Cxz1UVcV.css +2 -0
  17. package/dist/client/assets/index-uUZVBYUS.js +37 -0
  18. package/dist/client/assets/play-BjRNIGSf.js +1 -0
  19. package/dist/client/assets/{refresh-cw-BRHNyCnY.js → refresh-cw-r_tZiFfB.js} +1 -1
  20. package/dist/client/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  21. package/dist/client/assets/{runtime-Bft6x_6E.js → runtime-Bvq10IhH.js} +1 -1
  22. package/dist/client/assets/ui-zQpn-PdL.js +41 -0
  23. package/dist/client/build-info.json +1 -1
  24. package/dist/client/index.html +4 -3
  25. package/dist/client/sw.js +2 -2
  26. package/dist/console/assets/{LocalAccountsApp-IvHd9zWN.js → LocalAccountsApp-DIdy1KnN.js} +1 -1
  27. package/dist/console/assets/{LocalConsole-DOyLou56.js → LocalConsole-DfcQztF-.js} +1 -1
  28. package/dist/console/assets/{app-update-dialog-Da46CJpv.js → app-update-dialog-ttl9lF5A.js} +1 -1
  29. package/dist/console/assets/console-OqAjD0kV.js +55 -0
  30. package/dist/console/assets/console-kvjrAArQ.css +2 -0
  31. package/dist/console/build-info.json +1 -1
  32. package/dist/console/console.html +2 -2
  33. package/docs/agent-hardening.md +192 -0
  34. package/docs/agent-recipes.md +23 -0
  35. package/docs/agent-workflow.md +5 -0
  36. package/docs/agents.md +74 -6
  37. package/docs/config.md +1 -1
  38. package/docs/deployment.md +2 -0
  39. package/docs/design-system.md +20 -15
  40. package/docs/hosted.md +815 -3
  41. package/docs/where-to-run.md +123 -0
  42. package/package.json +2 -1
  43. package/src/agent/agent-logos.js +81 -0
  44. package/src/agent/backends/acp.js +528 -25
  45. package/src/agent/branch-mode.js +17 -3
  46. package/src/agent/card-hash.js +65 -0
  47. package/src/agent/config.js +27 -2
  48. package/src/agent/context.js +41 -0
  49. package/src/agent/exec-paths.js +105 -0
  50. package/src/agent/icon-store.js +100 -0
  51. package/src/agent/identity.js +77 -0
  52. package/src/agent/owner-mcp.js +19 -3
  53. package/src/agent/routes.js +82 -22
  54. package/src/agent/run.js +14 -2
  55. package/src/agent/settings-routes.js +233 -14
  56. package/src/agent/starter/cli.js +6 -1
  57. package/src/agent/test-timing.js +14 -0
  58. package/src/agent/tools.js +4 -2
  59. package/src/agent/turn-changes.js +70 -8
  60. package/src/agent/user-settings.js +51 -3
  61. package/src/capture/element-map.js +61 -4
  62. package/src/cli/args.js +13 -0
  63. package/src/cli/commands.js +20 -5
  64. package/src/cli/help.js +36 -1
  65. package/src/hosted/admin.js +7 -0
  66. package/src/hosted/agent-approvals.js +28 -3
  67. package/src/hosted/agent-link.js +1032 -0
  68. package/src/hosted/agent-policy.js +10 -3
  69. package/src/hosted/agent-presence.js +81 -0
  70. package/src/hosted/agent-routes.js +135 -0
  71. package/src/hosted/agents.js +1199 -0
  72. package/src/hosted/app.js +94 -4
  73. package/src/hosted/board-routes.js +134 -3
  74. package/src/hosted/chat-frames.js +256 -0
  75. package/src/hosted/chat-job.js +204 -0
  76. package/src/hosted/chat-permissions.js +191 -0
  77. package/src/hosted/chat-routes.js +1009 -0
  78. package/src/hosted/chat-store.js +460 -0
  79. package/src/hosted/comment-files.js +8 -1
  80. package/src/hosted/comments.js +1 -1
  81. package/src/hosted/console-routes.js +58 -1
  82. package/src/hosted/db.js +165 -0
  83. package/src/hosted/device-routes.js +64 -8
  84. package/src/hosted/device.js +35 -4
  85. package/src/hosted/events.js +8 -6
  86. package/src/hosted/membership.js +9 -1
  87. package/src/hosted/pages.js +2 -0
  88. package/src/hosted/permissions.js +38 -0
  89. package/src/hosted/presence.js +18 -1
  90. package/src/hosted/projects.js +60 -2
  91. package/src/hosted/ratelimit.js +8 -0
  92. package/src/hosted/tenancy.js +18 -0
  93. package/src/hosted/token-api.js +118 -15
  94. package/src/hosted/token-events.js +7 -2
  95. package/src/hosted/tokens.js +24 -7
  96. package/src/hosted/turn-hub.js +152 -0
  97. package/src/mcp.js +10 -2
  98. package/src/remote/agent-connect.js +433 -0
  99. package/src/remote/agent-fix.js +611 -0
  100. package/src/remote/agent-job.js +216 -0
  101. package/src/remote/agent-link.js +904 -0
  102. package/src/remote/agent-policy-file.js +242 -0
  103. package/src/remote/credentials.js +35 -1
  104. package/src/remote/login.js +12 -2
  105. package/src/store.js +5 -0
  106. package/dist/client/assets/BoardChat-BeRp6007.js +0 -27
  107. package/dist/client/assets/BuzzDialog-CrYy48hh.js +0 -1
  108. package/dist/client/assets/ChecksPanel-CB820mhj.js +0 -1
  109. package/dist/client/assets/History-Ba909bGJ.js +0 -1
  110. package/dist/client/assets/LocalSettings-ChMi9Zir.js +0 -1
  111. package/dist/client/assets/QuickConnect-CrVweWZB.js +0 -1
  112. package/dist/client/assets/ShareDialog-DO2HhY6g.js +0 -2
  113. package/dist/client/assets/app-update-dialog-C09ODdUQ.js +0 -1
  114. package/dist/client/assets/index-BIjfZKnp.js +0 -37
  115. package/dist/client/assets/index-CXtuJi1K.css +0 -2
  116. package/dist/client/assets/shield-check-DMpniYP6.js +0 -1
  117. package/dist/client/assets/ui-mhL9gsne.js +0 -41
  118. package/dist/console/assets/console-CIBv7cXU.js +0 -55
  119. package/dist/console/assets/console-Fp4k9iyx.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,134 @@ 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
+ // Claude Code's tools that only read. Everything else is removed from the
80
+ // session, so no allow rule and no mode can run it.
81
+ const CLAUDE_READ_TOOLS = ['Read', 'Grep', 'Glob']
82
+ const CLAUDE_ACTING_TOOLS = [
83
+ 'Bash',
84
+ 'BashOutput',
85
+ 'KillShell',
86
+ 'Edit',
87
+ 'MultiEdit',
88
+ 'Write',
89
+ 'NotebookEdit',
90
+ 'Agent',
91
+ 'Task',
92
+ 'WebFetch',
93
+ 'WebSearch',
94
+ 'Skill',
95
+ ]
96
+ // What goes with session/new.
97
+ export function readOnlySession(kind) {
98
+ if (kind !== 'claude') return {}
99
+ return {
100
+ _meta: {
101
+ claudeCode: {
102
+ options: {
103
+ // No settings files: the person's and the project's allow rules,
104
+ // hooks and plugins do not apply to this session.
105
+ settingSources: [],
106
+ // No MCP servers from .mcp.json, settings or plugins.
107
+ strictMcpConfig: true,
108
+ tools: CLAUDE_READ_TOOLS,
109
+ disallowedTools: CLAUDE_ACTING_TOOLS,
110
+ allowDangerouslySkipPermissions: false,
111
+ },
112
+ },
113
+ },
114
+ }
115
+ }
116
+ // What goes in the agent's environment.
117
+ export function readOnlyEnv(kind) {
118
+ // Codex: its read-only sandbox (no writes, no network), with approvals on request.
119
+ if (kind === 'codex') return { INITIAL_AGENT_MODE: 'read-only' }
120
+ // goose: chat only, no tool calls, whatever GOOSE_MODE the person set.
121
+ if (kind === 'goose') return { GOOSE_MODE: 'chat' }
122
+ return {}
123
+ }
124
+
125
+ // ---- Edits from a hosted board (`remoteEdit`) --------------------------------
126
+ // What `shapewall agent connect --approvals ...` runs for a fix: the agent may
127
+ // ask to edit files of the project and, when the machine lists some, to run
128
+ // exactly those commands. Every request is checked here first, on the
129
+ // machine, whatever anyone answers later:
130
+ // - an edit: a file inside the turn's folder (after symlinks), not in .git
131
+ // or Shapewall's store, not a settings file unless the machine allows it
132
+ // by name, and one whose whole result can be worked out and shown
133
+ // - a command: one of the machine's listed commands, character for character
134
+ // - anything else: refused
135
+ // What passes becomes a card (or, where the machine and the server's rule
136
+ // both say so, is allowed at once), through the turn's `gate`. A turn with no
137
+ // gate changes nothing. The agent's own settings are left out as for a
138
+ // read-only session, and it keeps only its reading and editing tools.
139
+ //
140
+ // Claude Code never gets its shell tool here, whatever commands the machine
141
+ // lists: with it, Claude Code runs commands it takes to be read-only (ls,
142
+ // cat, ...) without asking anyone, and those read outside the project. That
143
+ // was seen with the real adapter (docs/agent-hardening.md), so
144
+ // `agent connect` does not offer commands for Claude Code at all. Listed
145
+ // commands reach an agent only through Shapewall's own terminal
146
+ // (onTerminalCreate) or a permission request, both checked here.
147
+ const CLAUDE_EDIT_TOOLS = ['Edit', 'Write', 'MultiEdit']
148
+ export function remoteEditSession(kind) {
149
+ if (kind !== 'claude') return {}
150
+ const tools = [...CLAUDE_READ_TOOLS, ...CLAUDE_EDIT_TOOLS]
151
+ return {
152
+ _meta: {
153
+ claudeCode: {
154
+ options: {
155
+ settingSources: [],
156
+ strictMcpConfig: true,
157
+ tools,
158
+ disallowedTools: CLAUDE_ACTING_TOOLS.filter((tool) => !tools.includes(tool)),
159
+ allowDangerouslySkipPermissions: false,
160
+ },
161
+ },
162
+ },
163
+ }
164
+ }
165
+ // The two answers a card from a hosted board has.
166
+ export const REMOTE_OPTIONS = [
167
+ { optionId: 'allow', name: 'Allow', kind: 'allow_once' },
168
+ { optionId: 'deny', name: 'Deny', kind: 'reject_once' },
169
+ ]
170
+ export const REMOTE_REFUSALS = {
171
+ kind: "Refused on the agent's machine: only file edits and listed commands can be asked from a hosted board",
172
+ outside: "Refused on the agent's machine: outside the project, or in a folder agents may not write",
173
+ sensitive:
174
+ "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",
175
+ never: "Refused on the agent's machine: Git's own files, node_modules and files Git ignores are never part of a fix",
176
+ unknown: "Refused on the agent's machine: the whole change could not be worked out, so it cannot be shown",
177
+ large: "Refused on the agent's machine: too large to show in full",
178
+ command: "Refused on the agent's machine: not one of the commands it allows",
179
+ policy: "Refused on the agent's machine: it does not take this from the board",
180
+ option: "Refused on the agent's machine: the agent offered no way to allow it once",
181
+ }
182
+ const sha256 = (text) => createHash('sha256').update(String(text)).digest('hex')
183
+ // The most a card's diff may weigh to be relayed to a hosted board.
184
+ const REMOTE_DIFF_MAX = 80 * 1024
185
+
52
186
  const STDERR_KEEP = 4000
53
187
  // The most an approval card shows (and so the most that can be approved).
54
188
  export const DETAIL_MAX = 4096
@@ -431,11 +565,11 @@ export function authError(label, argv) {
431
565
 
432
566
  // What the person's turn looks like to the agent: on a new session, the
433
567
  // preamble and the thread so far (as quoted data); then the new message.
434
- export function promptBlocks({ messages, fresh, image, thread }) {
568
+ export function promptBlocks({ messages, fresh, image, thread, preamble = null }) {
435
569
  const blocks = []
436
570
  const last = messages.at(-1)
437
571
  if (fresh) {
438
- blocks.push({ type: 'text', text: ACP_PREAMBLE })
572
+ blocks.push({ type: 'text', text: preamble || ACP_PREAMBLE })
439
573
  const earlier = messages
440
574
  .slice(0, -1)
441
575
  .map((message) => ({
@@ -493,11 +627,26 @@ function shownPath(root, file) {
493
627
 
494
628
  // One agent process and its ACP session (one chat thread).
495
629
  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 })
630
+ constructor({
631
+ argv,
632
+ label,
633
+ env,
634
+ sandbox,
635
+ limits,
636
+ log,
637
+ thread,
638
+ onGone,
639
+ mcpServers = [],
640
+ extraEnv = {},
641
+ readOnly = false,
642
+ remoteEdit = null,
643
+ preamble = null,
644
+ }) {
645
+ Object.assign(this, { argv, label, sandbox, limits, log, thread, onGone, mcpServers, readOnly, remoteEdit, preamble })
498
646
  // `extraEnv`: set by Shapewall itself, never by the agent (branch mode's
499
647
  // GIT_CEILING_DIRECTORIES), for the agent and the terminals it runs.
500
- this.env = { ...agentEnv(env), ...extraEnv }
648
+ // Read only: the variables that put the agent's own sandbox in force win over the person's.
649
+ this.env = { ...agentEnv(env), ...extraEnv, ...(readOnly ? readOnlyEnv(acpAgentKind(argv)) : {}) }
501
650
  this.root = sandbox.root
502
651
  this.state = 'starting'
503
652
  this.stderr = ''
@@ -514,6 +663,12 @@ class AcpProcess {
514
663
  return this.child?.pid ?? null
515
664
  }
516
665
 
666
+ // A connected agent (read only, or taking edits from a hosted board): its
667
+ // session must be in a mode that asks before it acts.
668
+ get asks() {
669
+ return this.readOnly || Boolean(this.remoteEdit)
670
+ }
671
+
517
672
  async start(signal) {
518
673
  let child
519
674
  // The process starts in a fresh empty folder, not the project: `npx` and
@@ -576,13 +731,23 @@ class AcpProcess {
576
731
  try {
577
732
  const init = await this.connection.agent.request('initialize', {
578
733
  protocolVersion: PROTOCOL_VERSION,
579
- clientCapabilities: { fs: { readTextFile: true, writeTextFile: true }, terminal: true },
734
+ // Read only: the agent is offered no way to write or run through Shapewall.
735
+ clientCapabilities: {
736
+ fs: { readTextFile: true, writeTextFile: !this.readOnly },
737
+ // Edits from a hosted board: a terminal only when the machine lists commands.
738
+ terminal: !this.readOnly && !(this.remoteEdit && !this.remoteEdit.commands.length),
739
+ },
580
740
  clientInfo: { name: 'shapewall', title: 'Shapewall', version: VERSION },
581
741
  })
582
742
  this.agentInfo = init?.agentInfo || null
583
743
  this.image = Boolean(init?.agentCapabilities?.promptCapabilities?.image)
584
744
  this.authMethods = Array.isArray(init?.authMethods) ? init.authMethods : []
585
- const session = await this.connection.agent.request('session/new', { cwd: this.root, mcpServers: this.mcpServers })
745
+ const session = await this.connection.agent.request('session/new', {
746
+ cwd: this.root,
747
+ mcpServers: this.mcpServers,
748
+ // Read only: the agent's own controls are set so that it cannot act (readOnlySession).
749
+ ...(this.readOnly ? readOnlySession(acpAgentKind(this.argv)) : this.remoteEdit ? remoteEditSession(acpAgentKind(this.argv)) : {}),
750
+ })
586
751
  this.sessionId = session.sessionId
587
752
  this.choices = sessionChoices(session)
588
753
  this.configOptions = Array.isArray(session.configOptions) ? session.configOptions : []
@@ -590,6 +755,7 @@ class AcpProcess {
590
755
  // As the session started, before any chat's choices: what a new chat starts from.
591
756
  this.startOptions = sessionOptions(this.configOptions, this.modes)
592
757
  this.state = 'ready'
758
+ if (this.asks) await this.askingMode()
593
759
  } catch (error) {
594
760
  throw this.startError(error)
595
761
  } finally {
@@ -605,6 +771,8 @@ class AcpProcess {
605
771
  return new AgentError('agent_start', `${this.label} did not answer within ${Math.round(this.limits.startMs / 1000)} seconds.`)
606
772
  }
607
773
  this.kill('start_failed')
774
+ // Read only, and the agent's mode cannot be trusted to ask: said as it is.
775
+ if (error instanceof AgentError && error.code === 'agent_unsafe_mode') return error
608
776
  if (authFailure(error)) return this.authError()
609
777
  if (this.exited) return this.exitError()
610
778
  return new AgentError('agent_start', `${this.label} did not start an ACP session (${cut(errorText(error) || 'no answer', 300)}).`)
@@ -712,10 +880,11 @@ class AcpProcess {
712
880
 
713
881
  // Starts session/prompt. Returns the events and a finish() for when the
714
882
  // reader stops early.
715
- prompt(blocks, signal) {
883
+ prompt(blocks, signal, gate = null) {
716
884
  clearTimeout(this.idleTimer)
717
885
  const queue = eventQueue()
718
- const turn = { queue, permissions: new Map(), cancelled: false, settled: false, text: '' }
886
+ // `gate`: who decides this turn's requests (edits from a hosted board).
887
+ const turn = { queue, permissions: new Map(), cancelled: false, settled: false, text: '', gate, chain: Promise.resolve() }
719
888
  this.turn = turn
720
889
  this.fresh = false
721
890
  const onAbort = () => this.cancel(turn)
@@ -773,6 +942,247 @@ class AcpProcess {
773
942
  turn.killTimer.unref?.()
774
943
  }
775
944
 
945
+ // Read only: the session's mode, when it has one, must be one that asks
946
+ // before it acts (the requests are then refused here). A session set to
947
+ // act without asking (bypass, accept edits, auto, ...) is switched to the
948
+ // first mode that asks; if there is none, it does not start.
949
+ // The session's mode as the agent reports it: { id, current, values }, or
950
+ // null when it reports none (neither a "mode" config option nor modes).
951
+ modeState() {
952
+ const config = this.configOptions.find((option) => option?.category === 'mode' && typeof option.currentValue === 'string')
953
+ const current = config ? config.currentValue : this.modes?.currentModeId
954
+ if (typeof current !== 'string') return null
955
+ const values = config
956
+ ? optionValues(config.options)
957
+ : optionValues((this.modes?.availableModes || []).map((item) => ({ value: item?.id, name: item?.name })))
958
+ return { id: config ? config.id : MODE_OPTION_ID, current, values }
959
+ }
960
+ // Read only: is this mode one a connected agent may run in? A known
961
+ // agent: exactly the modes known to ask (or to be read-only by the
962
+ // agent's own sandbox). Any other: a mode whose name does not say it acts
963
+ // without asking.
964
+ modeAllowed(item) {
965
+ const wanted = READ_ONLY_MODES[acpAgentKind(this.argv)]
966
+ return wanted ? wanted.includes(item.value) : !UNSAFE_VALUE_RE.test(`${item.value} ${item.name}`)
967
+ }
968
+ // The mode when it is not allowed (see modeAllowed), else null.
969
+ unsafeMode() {
970
+ const state = this.modeState()
971
+ if (!state) return null
972
+ const name = state.values.find((item) => item.value === state.current)?.name || state.current
973
+ return this.modeAllowed({ value: state.current, name }) ? null : state
974
+ }
975
+ // Read only, fail closed: the session must report a mode, and it must be
976
+ // one that asks. Anything else is switched to one, or the agent does not
977
+ // start. Nothing is assumed about an agent that says nothing.
978
+ async askingMode() {
979
+ if (!this.modeState())
980
+ throw new AgentError(
981
+ 'agent_unsafe_mode',
982
+ `${this.label} reports no session mode, so Shapewall cannot tell that it asks before it acts. It is not started read-only.`,
983
+ )
984
+ const unsafe = this.unsafeMode()
985
+ if (!unsafe) return
986
+ const safe = unsafe.values.filter((item) => this.modeAllowed(item))
987
+ const wanted = READ_ONLY_MODES[acpAgentKind(this.argv)] || []
988
+ // The agent's own asking mode first; never "plan" by choice: a planning
989
+ // mode answers with a plan to approve, not an answer.
990
+ const pick =
991
+ wanted.map((value) => safe.find((item) => item.value === value)).find(Boolean) ||
992
+ safe.find((item) => /^(default|ask)$/i.test(item.value)) ||
993
+ safe.find((item) => !/plan/i.test(item.value)) ||
994
+ safe[0]
995
+ const refuse = () =>
996
+ new AgentError(
997
+ 'agent_unsafe_mode',
998
+ `${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.`,
999
+ )
1000
+ if (!pick) throw refuse()
1001
+ try {
1002
+ if (unsafe.id === MODE_OPTION_ID) {
1003
+ await this.connection.agent.request('session/set_mode', { sessionId: this.sessionId, modeId: pick.value })
1004
+ this.modes = { ...this.modes, currentModeId: pick.value }
1005
+ } else {
1006
+ const result = await this.connection.agent.request('session/set_config_option', {
1007
+ sessionId: this.sessionId,
1008
+ configId: unsafe.id,
1009
+ value: pick.value,
1010
+ })
1011
+ if (Array.isArray(result?.configOptions)) this.configOptions = result.configOptions
1012
+ else this.configOptions = this.configOptions.map((item) => (item.id === unsafe.id ? { ...item, currentValue: pick.value } : item))
1013
+ }
1014
+ } catch {
1015
+ throw refuse()
1016
+ }
1017
+ if (this.unsafeMode()) throw refuse()
1018
+ this.log(`acp: ${this.label} switched from mode "${cut(unsafe.current, 40)}" to "${cut(pick.value, 40)}" (read only)`)
1019
+ }
1020
+
1021
+ // Read only: what the agent asked for is refused here, and the answer
1022
+ // says so (a card nobody can answer). Returns the card's state.
1023
+ refuse({ title, kind, detail = null, note = READ_ONLY_NOTE }) {
1024
+ const turn = this.turn
1025
+ if (turn && !turn.cancelled)
1026
+ turn.queue.push({
1027
+ type: 'permission',
1028
+ id: `perm_${randomBytes(6).toString('hex')}`,
1029
+ title: cut(title, 120),
1030
+ kind,
1031
+ detail: `${detail ? `${cut(detail, 300)}\n` : ''}[${note}]`,
1032
+ diff: null,
1033
+ options: [],
1034
+ expiresAt: null,
1035
+ state: 'denied',
1036
+ chosen: null,
1037
+ })
1038
+ return 'denied'
1039
+ }
1040
+
1041
+ // ---- Edits from a hosted board ---------------------------------------------
1042
+
1043
+ // What an edit would leave in its file: { file, rel, current, next }, or
1044
+ // null when that cannot be worked out in full. From a whole new content
1045
+ // (Write), from old/new pairs every one of which the file holds now
1046
+ // (Edit, MultiEdit), or from one ACP diff whose old text is the file as it
1047
+ // is now. `file` is the real path, inside this turn's folder. Throws when
1048
+ // the path is outside it (or in .git, or in Shapewall's store).
1049
+ editResult(file, call, known, input) {
1050
+ const real = this.sandbox.resolve(path.resolve(this.root, file), { write: true })
1051
+ const rel = path.relative(this.root, real)
1052
+ const current = this.currentText(real)
1053
+ const text = (value) => (typeof value === 'string' && value.length <= DIFF_INPUT_MAX ? value : null)
1054
+ let next = null
1055
+ if (input) {
1056
+ const edits = Array.isArray(input.edits) ? input.edits : [input]
1057
+ const pairs = edits.map((edit) => ({
1058
+ oldText: text(edit?.old_string ?? edit?.old_str ?? edit?.oldText),
1059
+ newText: text(edit?.new_string ?? edit?.new_str ?? edit?.newText),
1060
+ all: edit?.replace_all === true,
1061
+ }))
1062
+ if (pairs.length && pairs.every((pair) => pair.oldText !== null && pair.newText !== null)) {
1063
+ next = current
1064
+ for (const pair of pairs) {
1065
+ if (next === null || !pair.oldText || !next.includes(pair.oldText)) return null
1066
+ next = pair.all ? next.split(pair.oldText).join(pair.newText) : next.replace(pair.oldText, () => pair.newText)
1067
+ }
1068
+ } else next = text(input.content ?? input.file_text ?? input.text)
1069
+ }
1070
+ if (next === null) {
1071
+ const sent = Array.isArray(call?.content) ? diffContent(call.content) : known?.diffs
1072
+ if (sent?.length !== 1) return null
1073
+ const only = sent[0]
1074
+ let same = false
1075
+ try {
1076
+ same = this.sandbox.resolve(path.resolve(this.root, only.path), { write: true }) === real
1077
+ } catch {
1078
+ same = false
1079
+ }
1080
+ if (!same || (only.oldText ?? null) !== current) return null
1081
+ next = only.newText
1082
+ }
1083
+ return { file: real, rel, current, next }
1084
+ }
1085
+
1086
+ // One request of a turn that takes edits from a hosted board, decided:
1087
+ // refused here, allowed at once (the machine and the server's rule both
1088
+ // say so), or asked on the board. Resolves true when it may go ahead.
1089
+ // `request`: { kind: 'edit', file, call, known, input } or
1090
+ // { kind: 'command', command }. One at a time per turn, so each edit is
1091
+ // worked out against the file as the one before left it.
1092
+ remoteRequest(request, signal) {
1093
+ const turn = this.turn
1094
+ if (!turn || turn.cancelled) return Promise.resolve(false)
1095
+ const run = turn.chain.then(() => this.remoteDecide(turn, request, signal))
1096
+ turn.chain = run.catch(() => {})
1097
+ return run
1098
+ }
1099
+
1100
+ async remoteDecide(turn, request, signal) {
1101
+ const still = () => this.turn === turn && !turn.cancelled && !signal?.aborted && this.state === 'ready' && !this.stoppingPromise
1102
+ if (!still()) return false
1103
+ const refuse = (title, kind, detail, note) => {
1104
+ this.refuse({ title, kind, detail, note })
1105
+ return false
1106
+ }
1107
+ // No gate: this turn was not started to change anything.
1108
+ if (!turn.gate) return refuse(request.kind === 'edit' ? 'Edit a file' : 'Run a command', 'other', null, REMOTE_REFUSALS.policy)
1109
+ let card
1110
+ let approved = null
1111
+ let guarded = false
1112
+ if (request.kind === 'edit') {
1113
+ const shown = showable(relativeTo(this.root, String(request.file || '')))
1114
+ let result
1115
+ try {
1116
+ // An earlier edit of this file that was allowed may still be on its way to disk.
1117
+ for (let tries = 0; ; tries += 1) {
1118
+ result = this.editResult(request.file, request.call, request.known, request.input)
1119
+ const before = result ? turn.gate.expected?.(result.rel.split(path.sep).join('/')) : null
1120
+ if (!before || tries >= 40 || sha256(result.current ?? '') === before) break
1121
+ await new Promise((resolve) => setTimeout(resolve, 50))
1122
+ }
1123
+ } catch {
1124
+ return refuse('Edit a file', 'edit', shown, REMOTE_REFUSALS.outside)
1125
+ }
1126
+ if (!still()) return false
1127
+ if (!result) return refuse('Edit a file', 'edit', shown, REMOTE_REFUSALS.unknown)
1128
+ const rel = result.rel.split(path.sep).join('/')
1129
+ if (!rel || rel.startsWith('..')) return refuse('Edit a file', 'edit', shown, REMOTE_REFUSALS.outside)
1130
+ // What Shapewall's commit would leave out is not asked for at all: an
1131
+ // edit that was allowed and then silently dropped would be a lie.
1132
+ let never = neverCommitted(rel)
1133
+ try {
1134
+ never = never || Boolean(await turn.gate.ignored?.(rel))
1135
+ } catch {
1136
+ never = true
1137
+ }
1138
+ if (!still()) return false
1139
+ if (never) return refuse(`Edit ${rel}`, 'edit', rel, REMOTE_REFUSALS.never)
1140
+ // Files that run something (exec-paths.js): only when this machine named the file,
1141
+ // and then never without a person's answer.
1142
+ guarded = this.sandbox.sensitive(result.file) || runsSomething(rel)
1143
+ if (guarded && !this.remoteEdit.allowPaths.includes(rel)) return refuse(`Edit ${rel}`, 'edit', rel, REMOTE_REFUSALS.sensitive)
1144
+ const diff = diffForFiles([{ path: rel, oldText: result.current, newText: result.next, outside: false }])
1145
+ if (!diff || diff.truncated || Buffer.byteLength(JSON.stringify(diff)) > REMOTE_DIFF_MAX)
1146
+ return refuse(`Edit ${rel}`, 'edit', rel, REMOTE_REFUSALS.large)
1147
+ card = { title: `${result.current === null ? 'Create' : 'Edit'} ${rel}`, kind: 'edit', detail: rel, diff }
1148
+ approved = { rel, hash: sha256(result.next) }
1149
+ } else {
1150
+ const command = typeof request.command === 'string' ? request.command.trim() : ''
1151
+ if (!command || !this.remoteEdit.commands.includes(command))
1152
+ return refuse('Run a command', 'execute', showable(command), REMOTE_REFUSALS.command)
1153
+ card = { title: 'Run a command', kind: 'execute', detail: command, diff: null }
1154
+ }
1155
+ let verdict = 'deny'
1156
+ try {
1157
+ verdict = await turn.gate.decide(
1158
+ request.kind === 'edit' ? { kind: 'edit', path: approved.rel, guarded } : { kind: 'command', command: card.detail },
1159
+ )
1160
+ } catch {
1161
+ verdict = 'deny'
1162
+ }
1163
+ // A file that runs something is never allowed without asking, whatever the rules say.
1164
+ if (guarded && verdict === 'allow') verdict = 'ask'
1165
+ if (!still()) return false
1166
+ if (verdict === 'allow') {
1167
+ // Allowed without asking: the card says so, and nobody is waited for.
1168
+ turn.queue.push({
1169
+ type: 'permission',
1170
+ id: `perm_${randomBytes(12).toString('hex')}`,
1171
+ ...card,
1172
+ options: [],
1173
+ expiresAt: null,
1174
+ state: 'approved',
1175
+ chosen: 'Allowed automatically',
1176
+ })
1177
+ } else if (verdict === 'ask') {
1178
+ const { state } = await this.ask({ ...card, options: REMOTE_OPTIONS }, signal)
1179
+ if (state !== 'approved' || !still()) return false
1180
+ } else return refuse(card.title, card.kind, card.detail, REMOTE_REFUSALS.policy)
1181
+ // `auto`: nobody looked at this one (the fix is then held back from any remote: agent-fix.js).
1182
+ if (approved) turn.gate.approved?.(approved.rel, approved.hash, { auto: verdict === 'allow' })
1183
+ return true
1184
+ }
1185
+
776
1186
  // The composer's option menus, as sessionOptions lists them.
777
1187
  options() {
778
1188
  return sessionOptions(this.configOptions, this.modes)
@@ -840,11 +1250,14 @@ class AcpProcess {
840
1250
  if (params?.sessionId === this.sessionId && params.update?.sessionUpdate === 'config_option_update') {
841
1251
  // The agent changed its own model or effort (or confirmed ours): the composer shows it.
842
1252
  if (Array.isArray(params.update.configOptions)) this.configOptions = params.update.configOptions
1253
+ if (this.asks && this.unsafeMode()) this.kill('unsafe_mode')
843
1254
  return
844
1255
  }
845
1256
  if (params?.sessionId === this.sessionId && params.update?.sessionUpdate === 'current_mode_update') {
846
1257
  if (this.modes && typeof params.update.currentModeId === 'string')
847
1258
  this.modes = { ...this.modes, currentModeId: params.update.currentModeId }
1259
+ // Read only: an agent that switches itself to a mode that acts without asking stops.
1260
+ if (this.asks && this.unsafeMode()) this.kill('unsafe_mode')
848
1261
  return
849
1262
  }
850
1263
  const turn = this.turn
@@ -979,6 +1392,37 @@ class AcpProcess {
979
1392
  if (detail && target && outsideProject(this.root, target)) {
980
1393
  detail = `${detail}\n[Outside the project: ${showable(path.resolve(this.root, target))}]`
981
1394
  }
1395
+ // Read only: refused here, whatever it is. The agent hears its own
1396
+ // "reject" option (or a cancel) and goes on answering.
1397
+ if (this.readOnly) {
1398
+ this.refuse({ title: call.title || known.title || 'Use a tool', kind: call.kind || known.kind || 'other', detail })
1399
+ const reject = options.find((item) => item.kind === 'reject_once') || options.find((item) => item.kind === 'reject_always')
1400
+ return reject ? { outcome: { outcome: 'selected', optionId: reject.optionId } } : { outcome: { outcome: 'cancelled' } }
1401
+ }
1402
+ // Edits from a hosted board: checked and decided here (remoteRequest).
1403
+ // The agent only ever hears "once": its "always" options are not used.
1404
+ if (this.remoteEdit) {
1405
+ const kind = call.kind || known.kind || 'other'
1406
+ const reject = options.find((item) => item.kind === 'reject_once') || options.find((item) => item.kind === 'reject_always')
1407
+ const no = () => (reject ? { outcome: { outcome: 'selected', optionId: reject.optionId } } : { outcome: { outcome: 'cancelled' } })
1408
+ const allow = options.find((item) => item.kind === 'allow_once')
1409
+ const file = [input?.file_path, input?.path, input?.filePath].find((value) => typeof value === 'string' && value)
1410
+ const command = typeof input?.command === 'string' ? input.command : null
1411
+ let request = null
1412
+ if (kind === 'edit' && file) request = { kind: 'edit', file, call, known, input }
1413
+ else if (kind === 'execute' && command !== null && !file) request = { kind: 'command', command }
1414
+ if (!request || !allow) {
1415
+ this.refuse({
1416
+ title: request ? (request.kind === 'edit' ? 'Edit a file' : 'Run a command') : 'Use a tool',
1417
+ kind,
1418
+ detail,
1419
+ note: request ? REMOTE_REFUSALS.option : REMOTE_REFUSALS.kind,
1420
+ })
1421
+ return no()
1422
+ }
1423
+ const ok = await this.remoteRequest(request, signal)
1424
+ return ok ? { outcome: { outcome: 'selected', optionId: allow.optionId } } : no()
1425
+ }
982
1426
  const { state, option } = await this.ask(
983
1427
  {
984
1428
  title: call.title || known.title || 'Use a tool',
@@ -1065,7 +1509,37 @@ class AcpProcess {
1065
1509
 
1066
1510
  async onWrite(params, signal) {
1067
1511
  this.ownSession(params)
1512
+ if (this.readOnly) {
1513
+ this.refuse({ title: 'Write a file', kind: 'edit', detail: showable(relativeTo(this.root, String(params?.path || ''))) })
1514
+ throw new RequestError(-32000, READ_ONLY_REFUSAL)
1515
+ }
1068
1516
  const turn = this.turn
1517
+ // Edits from a hosted board: the same checks and the same card as an
1518
+ // edit the agent makes with its own tool; then the write, through the sandbox.
1519
+ if (this.remoteEdit) {
1520
+ const ok =
1521
+ typeof params?.path === 'string' && typeof params?.content === 'string'
1522
+ ? await this.remoteRequest(
1523
+ { kind: 'edit', file: params.path, call: null, known: null, input: { content: params.content } },
1524
+ signal,
1525
+ )
1526
+ : false
1527
+ if (!ok) throw new RequestError(-32000, 'This file was not written: the edit was refused or not allowed.')
1528
+ try {
1529
+ const file = this.sandbox.write(params)
1530
+ this.turn?.queue.push({
1531
+ type: 'tool',
1532
+ id: `acp-write-${randomBytes(4).toString('hex')}`,
1533
+ name: 'edit',
1534
+ label: 'Wrote a file',
1535
+ state: 'done',
1536
+ detail: relativeTo(this.root, file),
1537
+ })
1538
+ return {}
1539
+ } catch (error) {
1540
+ throw sandboxRefusal(error)
1541
+ }
1542
+ }
1069
1543
  let target
1070
1544
  try {
1071
1545
  target = this.sandbox.resolve(params?.path, { write: true })
@@ -1116,6 +1590,14 @@ class AcpProcess {
1116
1590
 
1117
1591
  async onTerminalCreate(params, signal) {
1118
1592
  this.ownSession(params)
1593
+ if (this.readOnly) {
1594
+ this.refuse({
1595
+ title: 'Run a command',
1596
+ kind: 'execute',
1597
+ detail: showable(formatCommand([String(params?.command || ''), ...(Array.isArray(params?.args) ? params.args.map(String) : [])])),
1598
+ })
1599
+ throw new RequestError(-32000, READ_ONLY_REFUSAL)
1600
+ }
1119
1601
  const turn = this.turn
1120
1602
  if (this.terminals.size >= this.limits.terminalsMax) throw new RequestError(-32000, 'Too many terminals are open; release one first.')
1121
1603
  const command = typeof params.command === 'string' ? params.command : ''
@@ -1147,19 +1629,30 @@ class AcpProcess {
1147
1629
  ...Object.entries(extraEnv).map(([name, value]) => `env ${name}=${showable(value)}`),
1148
1630
  ...(ignored.length ? [`env ignored: ${ignored.join(', ')}`] : []),
1149
1631
  ]
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}).`)
1632
+ if (this.remoteEdit) {
1633
+ // From a hosted board: one of the machine's listed commands, exactly,
1634
+ // in the project folder, with no environment of the agent's choosing.
1635
+ if (cwd !== this.root || Object.keys(extraEnv).length || ignored.length) {
1636
+ this.refuse({ title: 'Run a command', kind: 'execute', detail: shown, note: REMOTE_REFUSALS.command })
1637
+ throw new RequestError(-32000, 'Refused: a command from a hosted board runs in the project folder, with no extra environment.')
1638
+ }
1639
+ const ok = await this.remoteRequest({ kind: 'command', command: formatCommand([command, ...args]) }, signal)
1640
+ if (!ok) throw new RequestError(-32000, 'This command was refused or not allowed.')
1641
+ } else {
1642
+ const { state } = await this.ask(
1643
+ {
1644
+ title: 'Run a command',
1645
+ kind: 'execute',
1646
+ detail: lines.join('\n'),
1647
+ options: [
1648
+ { optionId: 'run', name: 'Run', kind: 'allow_once' },
1649
+ { optionId: 'deny', name: "Don't run", kind: 'reject_once' },
1650
+ ],
1651
+ },
1652
+ signal,
1653
+ )
1654
+ if (state !== 'approved') throw new RequestError(-32000, `The person did not allow this command (${state}).`)
1655
+ }
1163
1656
  // Approval can resolve immediately before teardown. Recheck after that
1164
1657
  // await so no terminal group appears after stopOwned took its snapshot.
1165
1658
  if (!turn || this.turn !== turn || turn.cancelled || signal?.aborted || this.state !== 'ready' || this.stoppingPromise)
@@ -1311,6 +1804,10 @@ export function createAcpBackend(
1311
1804
  limits: limit,
1312
1805
  log,
1313
1806
  thread,
1807
+ // Read only (settings.readOnly, `shapewall agent connect`): see the top of this file.
1808
+ readOnly: settings.readOnly === true,
1809
+ // Edits from a hosted board (settings.remoteEdit: { commands, allowPaths }).
1810
+ remoteEdit: settings.readOnly !== true && settings.remoteEdit ? settings.remoteEdit : null,
1314
1811
  mcpServers: mcpServersFor?.(thread) || [],
1315
1812
  onGone: (item) => {
1316
1813
  if (item.stopped || !item.pid) processPool?.agents.delete(item)
@@ -1363,7 +1860,9 @@ export function createAcpBackend(
1363
1860
  // `workdir`: { root, env, protect, sensitivePaths } for a turn that works
1364
1861
  // in a folder of its own (branch mode): the thread's agent runs there,
1365
1862
  // started afresh when its session was in another folder.
1366
- async *stream({ messages, signal, thread = 'default', choices = null, workdir = null }) {
1863
+ // `gate`: { decide, approved, expected } for a turn that takes edits
1864
+ // from a hosted board (AcpProcess.remoteRequest).
1865
+ async *stream({ messages, signal, thread = 'default', choices = null, workdir = null, gate = null, preamble = null }) {
1367
1866
  if (signal?.aborted) return
1368
1867
  await preparing.get(thread)?.catch(() => {})
1369
1868
  let agent = processes.get(thread)
@@ -1390,7 +1889,11 @@ export function createAcpBackend(
1390
1889
  yield { type: 'status', text: `${settings.label} is working` }
1391
1890
  const image = agent.image && settings.vision !== false
1392
1891
  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)
1892
+ const turn = agent.prompt(
1893
+ promptBlocks({ messages, fresh: agent.fresh, image, thread, preamble: preamble || settings.preamble || null }),
1894
+ signal,
1895
+ gate,
1896
+ )
1394
1897
  try {
1395
1898
  for await (const event of turn.events) yield event
1396
1899
  } catch (error) {