shapewall 0.3.3 → 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 (98) hide show
  1. package/CHANGELOG.md +249 -0
  2. package/README.md +49 -3
  3. package/dist/agent/package-lock.json +2 -2
  4. package/dist/client/assets/BoardChat-DdwBcb2N.js +27 -0
  5. package/dist/client/assets/{BuzzDialog-Ix9qJvim.js → BuzzDialog-DpUcnU6S.js} +1 -1
  6. package/dist/client/assets/ChecksPanel-CngYV4yz.js +1 -0
  7. package/dist/client/assets/History-CD0saQA5.js +1 -0
  8. package/dist/client/assets/LocalSettings-MZy2baig.js +1 -0
  9. package/dist/client/assets/{Management-NVFDtSZB.js → Management-CSvZ-SHO.js} +1 -1
  10. package/dist/client/assets/QuickConnect-foLh2QUm.js +1 -0
  11. package/dist/client/assets/{ShareDialog-By0ETg6n.js → ShareDialog-DPWDftoL.js} +2 -2
  12. package/dist/client/assets/{app-update-dialog-RGIw24iZ.js → app-update-dialog-CtiXpTRD.js} +1 -1
  13. package/dist/client/assets/{circle-x-B6KfScOE.js → circle-x-CteRBtXC.js} +1 -1
  14. package/dist/client/assets/index-Cxz1UVcV.css +2 -0
  15. package/dist/client/assets/index-uUZVBYUS.js +37 -0
  16. package/dist/client/assets/play-BjRNIGSf.js +1 -0
  17. package/dist/client/assets/{refresh-cw-vkgvCCfR.js → refresh-cw-r_tZiFfB.js} +1 -1
  18. package/dist/client/assets/{runtime-Bft6x_6E.js → runtime-Bvq10IhH.js} +1 -1
  19. package/dist/client/assets/ui-zQpn-PdL.js +41 -0
  20. package/dist/client/build-info.json +1 -1
  21. package/dist/client/index.html +3 -3
  22. package/dist/client/sw.js +2 -2
  23. package/dist/console/assets/{LocalAccountsApp-VOCZg8dg.js → LocalAccountsApp-DIdy1KnN.js} +1 -1
  24. package/dist/console/assets/{LocalConsole-CMwAW-mF.js → LocalConsole-DfcQztF-.js} +1 -1
  25. package/dist/console/assets/{app-update-dialog-Cw6UDqNP.js → app-update-dialog-ttl9lF5A.js} +1 -1
  26. package/dist/console/assets/console-OqAjD0kV.js +55 -0
  27. package/dist/console/assets/console-kvjrAArQ.css +2 -0
  28. package/dist/console/build-info.json +1 -1
  29. package/dist/console/console.html +2 -2
  30. package/docs/agent-hardening.md +192 -0
  31. package/docs/agent-recipes.md +23 -0
  32. package/docs/agent-workflow.md +5 -0
  33. package/docs/agents.md +14 -6
  34. package/docs/hosted.md +804 -11
  35. package/docs/where-to-run.md +37 -2
  36. package/package.json +1 -1
  37. package/src/agent/backends/acp.js +528 -25
  38. package/src/agent/branch-mode.js +17 -3
  39. package/src/agent/card-hash.js +65 -0
  40. package/src/agent/context.js +41 -0
  41. package/src/agent/exec-paths.js +105 -0
  42. package/src/agent/routes.js +2 -2
  43. package/src/agent/run.js +11 -1
  44. package/src/agent/starter/cli.js +6 -1
  45. package/src/agent/turn-changes.js +70 -8
  46. package/src/cli/args.js +13 -0
  47. package/src/cli/commands.js +20 -5
  48. package/src/cli/help.js +36 -1
  49. package/src/hosted/admin.js +7 -0
  50. package/src/hosted/agent-approvals.js +28 -3
  51. package/src/hosted/agent-link.js +1032 -0
  52. package/src/hosted/agent-policy.js +10 -3
  53. package/src/hosted/agent-presence.js +63 -22
  54. package/src/hosted/agent-routes.js +135 -0
  55. package/src/hosted/agents.js +1199 -0
  56. package/src/hosted/app.js +89 -5
  57. package/src/hosted/board-routes.js +127 -3
  58. package/src/hosted/chat-frames.js +256 -0
  59. package/src/hosted/chat-job.js +204 -0
  60. package/src/hosted/chat-permissions.js +191 -0
  61. package/src/hosted/chat-routes.js +1009 -0
  62. package/src/hosted/chat-store.js +460 -0
  63. package/src/hosted/comment-files.js +8 -1
  64. package/src/hosted/comments.js +1 -1
  65. package/src/hosted/console-routes.js +11 -0
  66. package/src/hosted/db.js +165 -0
  67. package/src/hosted/device-routes.js +64 -8
  68. package/src/hosted/device.js +35 -4
  69. package/src/hosted/events.js +3 -3
  70. package/src/hosted/membership.js +9 -1
  71. package/src/hosted/pages.js +2 -0
  72. package/src/hosted/permissions.js +38 -0
  73. package/src/hosted/presence.js +17 -0
  74. package/src/hosted/projects.js +29 -2
  75. package/src/hosted/ratelimit.js +8 -0
  76. package/src/hosted/tenancy.js +18 -0
  77. package/src/hosted/token-api.js +118 -19
  78. package/src/hosted/token-events.js +5 -3
  79. package/src/hosted/tokens.js +21 -5
  80. package/src/hosted/turn-hub.js +152 -0
  81. package/src/remote/agent-connect.js +433 -0
  82. package/src/remote/agent-fix.js +611 -0
  83. package/src/remote/agent-job.js +216 -0
  84. package/src/remote/agent-link.js +904 -0
  85. package/src/remote/agent-policy-file.js +242 -0
  86. package/src/remote/credentials.js +35 -1
  87. package/src/remote/login.js +12 -2
  88. package/dist/client/assets/BoardChat-DxehB761.js +0 -27
  89. package/dist/client/assets/ChecksPanel-pA_ueIaJ.js +0 -1
  90. package/dist/client/assets/History-C9N32kCv.js +0 -1
  91. package/dist/client/assets/LocalSettings-DawtKnvi.js +0 -1
  92. package/dist/client/assets/QuickConnect-DO1TjS1t.js +0 -1
  93. package/dist/client/assets/index-CsqLdqGx.css +0 -2
  94. package/dist/client/assets/index-DnZarJ3U.js +0 -37
  95. package/dist/client/assets/shield-check-QzwGhz0t.js +0 -1
  96. package/dist/client/assets/ui-DI-FGWWK.js +0 -41
  97. package/dist/console/assets/console-DgfWmUEx.js +0 -55
  98. package/dist/console/assets/console-Lis0vvdL.css +0 -2
@@ -0,0 +1,433 @@
1
+ // `shapewall agent connect --remote URL`: makes the coding agent on this
2
+ // machine (Claude Code, Codex, goose, Gemini CLI) an agent of a hosted
3
+ // project. Run it in the project's folder, on the machine that has the code.
4
+ //
5
+ // The first run asks for an approval in the browser (the device login, for
6
+ // an agent): an admin types the code, names the agent, picks its icon, the
7
+ // project and who may use it. The server makes the agent's own token, which
8
+ // is saved here (credentials.js, 0600) and never printed. Then this starts
9
+ // nothing but a link (agent-link.js): members chat with the agent from the
10
+ // board, it reads the project and answers. It does not edit and it runs no
11
+ // command: this machine refuses both, whatever the server sends.
12
+ //
13
+ // The command that runs is this machine's own: a saved agent, or one of the
14
+ // known agents found on PATH. Nothing from the server names it.
15
+
16
+ import fs from 'node:fs'
17
+ import os from 'node:os'
18
+ import path from 'node:path'
19
+ import { KNOWN_AGENTS, detectAgents } from '../agent/acp/detect.js'
20
+ import { acpAgentKind } from '../agent/acp/command.js'
21
+ import { createBackend } from '../agent/backends/index.js'
22
+ import { agentSettings } from '../agent/config.js'
23
+ import { REMOTE_FIX_PREAMBLE, REMOTE_PREAMBLE } from '../agent/context.js'
24
+ import { authFiles, findConfigFile, loadConfig } from '../config.js'
25
+ import { AGENT_SLUG_RE, forgetAgentCredential, readAgentCredential, saveAgentCredential } from './credentials.js'
26
+ import { fixRoot, sweepFixes } from './agent-fix.js'
27
+ import { fatalLinkError, runAgentLink } from './agent-link.js'
28
+ import {
29
+ POLICY_APPROVALS,
30
+ POLICY_AUDIENCES,
31
+ POLICY_AUTO_KINDS,
32
+ cleanAllowPath,
33
+ cleanBase,
34
+ cleanCommand,
35
+ cleanRemote,
36
+ describeMachinePolicy,
37
+ policyFile,
38
+ readMachinePolicy,
39
+ saveMachinePolicy,
40
+ } from './agent-policy-file.js'
41
+ import { createRemote, remoteOrigin } from './remote.js'
42
+ import { safeOut, terminalSafe } from './terminal.js'
43
+
44
+ const VERSION = JSON.parse(fs.readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version
45
+ const TOKEN_RE = /^swp_[A-Za-z0-9_-]{43}$/
46
+
47
+ // The project folder: where the config is, else where the command runs.
48
+ function projectFor(flags, cwd) {
49
+ const file = findConfigFile(flags.config, cwd)
50
+ if (fs.existsSync(file)) return loadConfig(flags.config, { cwd })
51
+ return { file: null, dir: cwd, outputDir: path.join(cwd, '.shapewall'), agent: null, boards: [] }
52
+ }
53
+
54
+ // Which local agent runs: --agent names a known one (claude, codex, goose,
55
+ // gemini) or a saved agent's id; without it, this project's saved agent,
56
+ // else the first known agent found on PATH. Always this machine's command.
57
+ // The agents `agent connect` offers: the ones whose own controls were
58
+ // proven, with the real adapter, to keep a read-only session from editing,
59
+ // running commands and reading outside the project (docs/agent-hardening.md
60
+ // says how). An agent that could not be proven that way is not offered:
61
+ // refusing what it asks for is not enough when it does not ask.
62
+ export const CONNECT_PROVEN = ['claude']
63
+ const NOT_PROVEN = {
64
+ codex:
65
+ 'Codex cannot be connected in this release. Started read-only it changes no files, but its sandbox still runs shell commands and reads files outside the project without asking, and what it reads can leave this machine in an answer.',
66
+ goose: 'goose cannot be connected in this release: its chat-only mode could not be verified to keep every tool off.',
67
+ gemini: 'Gemini CLI cannot be connected in this release: its read-only behaviour has not been verified.',
68
+ }
69
+
70
+ export function connectSettings(config, flags, env = process.env) {
71
+ const wanted = typeof flags.agent === 'string' ? flags.agent.trim() : ''
72
+ const known = KNOWN_AGENTS.find((agent) => agent.id === wanted)
73
+ const found = detectAgents(env)
74
+ const fromKnown = (agent) => {
75
+ if (!CONNECT_PROVEN.includes(agent.id))
76
+ throw new Error(`${NOT_PROVEN[agent.id]} Connect Claude Code (--agent claude), or use "shapewall watch --remote" for this agent.`)
77
+ const here = found.find((item) => item.id === agent.id)
78
+ if (!here)
79
+ throw new Error(
80
+ `${agent.label} is not installed on this machine (no "${agent.adapter}" on PATH).${agent.install ? ` Install it: ${agent.install}` : ''}`,
81
+ )
82
+ if (here.state !== 'ready')
83
+ throw new Error(
84
+ `${agent.label} is here, but its ACP adapter is not.${here.install ? ` Install it: ${here.install}` : ''} (docs/agents.md)`,
85
+ )
86
+ return agentSettings(config, env, { acp: agent.command })
87
+ }
88
+ let settings
89
+ if (known) settings = fromKnown(known)
90
+ else if (wanted) settings = agentSettings(config, env, { profileId: wanted })
91
+ else {
92
+ settings = agentSettings(config, env)
93
+ if (!(settings.configured && settings.backend === 'acp')) {
94
+ // Only an agent that is offered: another one found first is passed over.
95
+ const first = found.find((item) => item.state === 'ready' && CONNECT_PROVEN.includes(item.id))
96
+ if (!first)
97
+ throw new Error(
98
+ 'No agent that can be connected was found on this machine. Install Claude Code with its ACP adapter (npm install -g @agentclientprotocol/claude-agent-acp, docs/agents.md). Codex, goose and Gemini CLI are not offered by agent connect in this release.',
99
+ )
100
+ settings = fromKnown(KNOWN_AGENTS.find((agent) => agent.id === first.id))
101
+ }
102
+ }
103
+ if (settings.backend !== 'acp')
104
+ throw new Error('agent connect runs a coding agent on this machine (Claude Code, Codex, goose, Gemini CLI), not a model endpoint.')
105
+ if (!settings.configured) throw new Error(settings.problem || 'That agent is not set up on this machine.')
106
+ // A saved agent or this project's own: the same rule, by what its command starts.
107
+ const kind = acpAgentKind(settings.acp.argv)
108
+ if (!CONNECT_PROVEN.includes(kind))
109
+ throw new Error(
110
+ `${NOT_PROVEN[kind] || `${settings.label} cannot be connected in this release: Shapewall cannot make an agent it does not know read-only by the agent's own controls.`} Connect Claude Code (--agent claude).`,
111
+ )
112
+ return settings
113
+ }
114
+
115
+ // What stands in the way of a read-only session, in the agent's own
116
+ // settings. A connected Claude Code session is started without the person's
117
+ // and the project's settings files (their allow rules, hooks and MCP servers
118
+ // do not apply) and with only its reading tools. What Shapewall cannot leave
119
+ // out is the machine's managed settings: when those allow acting tools or
120
+ // run hooks, the agent is not started. Returns { refuse: [...], notes: [...] }.
121
+ const ACTING_RULE_RE = /^(Bash|Edit|Write|MultiEdit|NotebookEdit|WebFetch|WebSearch|Task|Agent|mcp__|Read\(\s*(\/|~))/
122
+ export function profileProblems(kind, root, env = process.env, { managedFile = '/etc/claude-code/managed-settings.json' } = {}) {
123
+ const out = { refuse: [], notes: [] }
124
+ if (kind !== 'claude') return out
125
+ const read = (file) => {
126
+ try {
127
+ return JSON.parse(fs.readFileSync(file, 'utf8'))
128
+ } catch {
129
+ return null
130
+ }
131
+ }
132
+ const acting = (data) =>
133
+ Array.isArray(data?.permissions?.allow) ? data.permissions.allow.filter((rule) => ACTING_RULE_RE.test(String(rule))) : []
134
+ const hooks = (data) => (data?.hooks && typeof data.hooks === 'object' ? Object.keys(data.hooks).length : 0)
135
+ const managed = read(managedFile)
136
+ if (managed) {
137
+ if (acting(managed).length)
138
+ out.refuse.push(
139
+ `${managedFile} lets Claude Code use ${acting(managed).length} acting tool rule${acting(managed).length === 1 ? '' : 's'} without asking (permissions.allow), and a session cannot leave managed settings out.`,
140
+ )
141
+ if (hooks(managed))
142
+ out.refuse.push(`${managedFile} runs hooks (commands) around every session, and a session cannot leave managed settings out.`)
143
+ if (/bypass|accept|dontask|auto/i.test(String(managed.permissions?.defaultMode || '')))
144
+ out.notes.push(
145
+ `${managedFile} sets the default mode "${managed.permissions.defaultMode}": this session is switched to one that asks, or it does not start.`,
146
+ )
147
+ }
148
+ const home = env.HOME || os.homedir()
149
+ const files = [
150
+ path.join(env.CLAUDE_CONFIG_DIR || path.join(home, '.claude'), 'settings.json'),
151
+ path.join(root, '.claude', 'settings.json'),
152
+ path.join(root, '.claude', 'settings.local.json'),
153
+ ]
154
+ const found = files.filter((file) => {
155
+ const data = read(file)
156
+ return data && (acting(data).length || hooks(data) || data.permissions?.defaultMode)
157
+ })
158
+ if (found.length)
159
+ out.notes.push(
160
+ `Left out of this session: the allow rules, hooks and default mode in ${found.map((file) => (file.startsWith(root) ? path.relative(root, file) : file.replace(home, '~'))).join(', ')}.`,
161
+ )
162
+ return out
163
+ }
164
+
165
+ // What the flags change in this machine's policy for the connection:
166
+ // { changes } to save, or throws with how to say it. Lists grow one entry a
167
+ // run ("none" empties one), so a service file carries no policy: the file does.
168
+ // Agents whose listed commands were proven, with the real adapter, to be
169
+ // the only commands they run. None yet: Claude Code, started with its shell
170
+ // tool, runs commands it takes to be read-only without asking (acp.js).
171
+ export const COMMANDS_PROVEN = []
172
+ const NO_COMMANDS =
173
+ 'Commands cannot be allowed for Claude Code in this release: started with its shell tool it runs commands it takes to be read-only (ls, cat) without asking, and those can read outside the project. Edits work without it.'
174
+
175
+ export function policyChanges(flags, saved, kind = null) {
176
+ const changes = {}
177
+ const commandsOk = kind === null || COMMANDS_PROVEN.includes(kind)
178
+ if (flags.audience !== undefined) {
179
+ if (!POLICY_AUDIENCES.includes(flags.audience))
180
+ throw new Error(
181
+ '--audience: "owner" (ask the server to keep it to the person who connects it, and refuse other jobs here) or "server" (as set on the server)',
182
+ )
183
+ changes.audience = flags.audience
184
+ }
185
+ if (flags.approvals !== undefined) {
186
+ if (!POLICY_APPROVALS.includes(flags.approvals))
187
+ throw new Error(
188
+ '--approvals: "none" (read and answer only, the default), "owner" (the person who connected it may allow edits from the board) or "admins" (whoever the server lets answer, admins by default)',
189
+ )
190
+ changes.approvals = flags.approvals
191
+ }
192
+ const approvals = changes.approvals ?? saved.approvals
193
+ const needsApprovals = (flag) => {
194
+ if (approvals === 'none') throw new Error(`--${flag} needs --approvals owner or --approvals admins: this agent reads and answers only.`)
195
+ }
196
+ if (flags['allow-command'] !== undefined) {
197
+ needsApprovals('allow-command')
198
+ if (flags['allow-command'] === 'none') changes.commands = []
199
+ else if (!commandsOk) throw new Error(`--allow-command: ${NO_COMMANDS}`)
200
+ else {
201
+ const command = cleanCommand(flags['allow-command'])
202
+ if (!command)
203
+ throw new Error(
204
+ '--allow-command: one exact command on one line, at most 200 characters, such as "npm test" ("none" removes them all)',
205
+ )
206
+ changes.commands = [...new Set([...saved.commands, command])]
207
+ }
208
+ }
209
+ if (flags['allow-path'] !== undefined) {
210
+ needsApprovals('allow-path')
211
+ if (flags['allow-path'] === 'none') changes.allowPaths = []
212
+ else {
213
+ const file = cleanAllowPath(flags['allow-path'])
214
+ if (!file) throw new Error('--allow-path: a file path inside the project, such as package.json ("none" removes them all)')
215
+ changes.allowPaths = [...new Set([...saved.allowPaths, file])]
216
+ }
217
+ }
218
+ if (flags.auto !== undefined) {
219
+ const kinds = flags.auto === 'none' ? [] : String(flags.auto).split(',')
220
+ if (kinds.some((kind) => !POLICY_AUTO_KINDS.includes(kind)))
221
+ throw new Error('--auto: "none" (every request waits for a person, the default), "edits", "commands" or "edits,commands"')
222
+ if (kinds.length) needsApprovals('auto')
223
+ if (kinds.includes('commands') && !(changes.commands ?? saved.commands).length)
224
+ throw new Error('--auto commands needs at least one --allow-command: there is no command to allow.')
225
+ changes.auto = kinds
226
+ }
227
+ if (flags.base !== undefined) {
228
+ if (flags.base !== 'head' && !cleanBase(flags.base))
229
+ throw new Error('--base: a branch name, such as main ("head": the commit the checkout is on)')
230
+ changes.base = flags.base === 'head' ? null : flags.base
231
+ }
232
+ if (flags['git-remote'] !== undefined) {
233
+ if (flags['git-remote'] !== 'none' && !cleanRemote(flags['git-remote']))
234
+ throw new Error('--git-remote: a remote name, such as origin ("none": never push)')
235
+ changes.remote = flags['git-remote'] === 'none' ? null : flags['git-remote']
236
+ }
237
+ return changes
238
+ }
239
+
240
+ export async function agentConnect(
241
+ flags,
242
+ print,
243
+ err,
244
+ { env = process.env, cwd = process.cwd(), fetchImpl = fetch, signal = null, sleep } = {},
245
+ ) {
246
+ const out = safeOut(print)
247
+ const log = safeOut(err)
248
+ const origin = remoteOrigin(flags, env)
249
+ const slug = flags.as === undefined ? 'default' : String(flags.as)
250
+ if (!AGENT_SLUG_RE.test(slug)) throw new Error('--as: a short name for this connection (lower-case letters, digits and dashes)')
251
+ const concurrency = flags.concurrency === undefined ? 2 : Number(flags.concurrency)
252
+ if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 4) throw new Error('--concurrency must be 1 to 4')
253
+ const config = projectFor(flags, cwd)
254
+ const settings = connectSettings(config, flags, env)
255
+ const kind = acpAgentKind(settings.acp.argv) || 'custom'
256
+ const label = terminalSafe(settings.label)
257
+ // Checked before anything is asked of anyone: a wrong flag changes nothing.
258
+ // A value in the file that is not understood reads as the narrowest setting, and is said.
259
+ const policyNow = readMachinePolicy(origin, slug, env, {
260
+ warn: (text) => log(`Not understood, so read as the narrowest setting: ${text}`),
261
+ })
262
+ const changes = policyChanges(flags, policyNow, kind)
263
+
264
+ // ---- The agent's token: its own, never the saved login's ----
265
+ let token = env.SHAPEWALL_TOKEN || ''
266
+ let source = token ? 'env' : null
267
+ if (typeof flags['token-file'] === 'string') {
268
+ token = fs.readFileSync(flags['token-file'], 'utf8').trim()
269
+ source = 'file'
270
+ }
271
+ if (!token) {
272
+ const saved = readAgentCredential(origin, slug, env)
273
+ if (saved) {
274
+ token = saved.token
275
+ source = 'agent'
276
+ }
277
+ }
278
+ if (!token) {
279
+ const { login } = await import('./login.js')
280
+ const suggested = typeof flags.name === 'string' && flags.name.trim() ? flags.name.trim() : settings.label
281
+ out(`Connecting ${label} in ${config.dir} to ${origin}.`)
282
+ out('An admin of the workspace approves it in the browser: they name the agent, pick its project and who may use it.')
283
+ token = await login(flags, print, {
284
+ env,
285
+ fetchImpl,
286
+ signal,
287
+ ...(sleep ? { sleep } : {}),
288
+ purpose: 'agent',
289
+ agent: { kind, name: suggested },
290
+ onApproved: (result) => {
291
+ const file = saveAgentCredential(
292
+ origin,
293
+ slug,
294
+ {
295
+ token: result.token,
296
+ tokenName: result.tokenName || null,
297
+ workspace: result.workspace || null,
298
+ project: result.project || null,
299
+ agent: result.agent || null,
300
+ scopes: Array.isArray(result.scopes) ? result.scopes : [],
301
+ expiresAt: result.expiresAt || null,
302
+ savedAt: new Date().toISOString(),
303
+ },
304
+ env,
305
+ )
306
+ out(
307
+ `Approved as "${result.agent?.name || result.tokenName}" for ${result.workspace?.name || 'the workspace'} / ${result.project?.name || 'the project'}.`,
308
+ )
309
+ out(`Its token is saved in ${file} (only you can read it). Run the same command to connect again.`)
310
+ return result.token
311
+ },
312
+ })
313
+ source = 'agent'
314
+ }
315
+ if (!TOKEN_RE.test(token))
316
+ throw new Error('That is not a project token (swp_...). Run "shapewall agent connect" without it to get one approved.')
317
+
318
+ // ---- This machine's own rules ----
319
+ const saved = Object.keys(changes).length ? saveMachinePolicy(origin, slug, changes, env) : policyNow
320
+ // Commands in the file (written by hand, or for another agent) are not in effect for an agent they were not proven with.
321
+ const policy = COMMANDS_PROVEN.includes(kind) ? saved : { ...saved, commands: [], auto: saved.auto.filter((item) => item !== 'commands') }
322
+ if (saved.commands.length && !policy.commands.length) log(`Not in effect: the commands in ${policyFile(env)}. ${NO_COMMANDS}`)
323
+ const edits = policy.approvals !== 'none'
324
+ if (edits) {
325
+ // Said now rather than at the first fix: where fixes are made must be outside the project.
326
+ try {
327
+ fixRoot(config.dir, env)
328
+ } catch (error) {
329
+ throw new Error(error.message.replace(/^On the agent's machine, t/, 'T').replace(/ there /, ' '), { cause: error })
330
+ }
331
+ // What an earlier run left behind (it was killed mid-fix): removed, and its branch names are free again.
332
+ const swept = sweepFixes(config.dir, env)
333
+ if (swept.length) log(`Removed ${swept.length} unfinished fix cop${swept.length === 1 ? 'y' : 'ies'} an earlier run left behind.`)
334
+ }
335
+ const profile = profileProblems(kind, config.dir, env)
336
+ if (profile.refuse.length)
337
+ throw new Error(`${label} is not started read-only on this machine. ${profile.refuse.join(' ')} See docs/agent-hardening.md.`)
338
+ for (const line of profile.notes) log(line)
339
+
340
+ const backend = createBackend(
341
+ // Read and answer only (src/agent/backends/acp.js readOnly), with the
342
+ // connected agent's own first words. Images are not sent to it yet.
343
+ { ...settings, readOnly: true, preamble: REMOTE_PREAMBLE, vision: false },
344
+ {
345
+ env,
346
+ root: config.dir,
347
+ protect: [config.outputDir],
348
+ sensitivePaths: () => authFiles(config),
349
+ limits: { processesMax: Math.max(concurrency, 2) },
350
+ log: (line) => log(line),
351
+ },
352
+ )
353
+ if (!backend) throw new Error('That agent could not be set up on this machine.')
354
+ // The same agent, started for fixes: it may ask to edit files of the
355
+ // project (and to run the listed commands), each request checked here and
356
+ // answered on the board (acp.js remoteEdit). Only when this machine said so.
357
+ const editBackend = edits
358
+ ? createBackend(
359
+ {
360
+ ...settings,
361
+ readOnly: false,
362
+ remoteEdit: { commands: policy.commands, allowPaths: policy.allowPaths },
363
+ preamble: REMOTE_FIX_PREAMBLE,
364
+ vision: false,
365
+ },
366
+ {
367
+ env,
368
+ // Each fix gives its own folder (a worktree) as the turn's workdir; this root is never written.
369
+ root: config.dir,
370
+ protect: [config.outputDir],
371
+ sensitivePaths: () => authFiles(config),
372
+ limits: { processesMax: Math.max(concurrency, 2) },
373
+ log: (line) => log(line),
374
+ },
375
+ )
376
+ : null
377
+
378
+ const controller = new AbortController()
379
+ const stop = () => controller.abort()
380
+ signal?.addEventListener('abort', stop, { once: true })
381
+ process.once('SIGINT', stop)
382
+ process.once('SIGTERM', stop)
383
+ const remote = createRemote({ origin, token, source, fetchImpl })
384
+ let ended = null
385
+ try {
386
+ ended = await runAgentLink({
387
+ origin,
388
+ token,
389
+ source,
390
+ backend,
391
+ editBackend,
392
+ fix: edits ? { config, env, fetchImpl } : null,
393
+ hello: { kind, machine: os.hostname().split('.')[0] || 'this computer', version: VERSION, maxTurns: concurrency },
394
+ policy,
395
+ remote,
396
+ takeover: Boolean(flags.takeover),
397
+ signal: controller.signal,
398
+ fetchImpl,
399
+ log: (line) => log(line),
400
+ onReady: (said) => {
401
+ const agent = said?.agent || {}
402
+ log(
403
+ `Connected: ${terminalSafe(agent.name || label)} (${label}) is online for ${terminalSafe(agent.workspace?.name || 'the workspace')} / ${terminalSafe(agent.project?.name || 'the project')}.`,
404
+ )
405
+ log(`Works in ${config.dir}. Used by: ${terminalSafe(agent.audience || 'the person who connected it')}.`)
406
+ for (const line of describeMachinePolicy(policy)) log(terminalSafe(line))
407
+ if (policy.audience === 'owner')
408
+ log(`This machine refuses questions the server says are not from the person who connected it (${policyFile(env)}).`)
409
+ log('Members chat with it from the Agents panel of the board. Ctrl+C stops it.')
410
+ },
411
+ })
412
+ } catch (error) {
413
+ if (!fatalLinkError(error)) throw error
414
+ // Another process holds this agent's link: the server says which machine, since when.
415
+ if (error.code === 'already_connected') throw new Error(terminalSafe(error.message), { cause: error })
416
+ // A saved token the server refuses is of no more use: the next run asks for a new approval.
417
+ const forgot = error.status === 401 && source === 'agent' && forgetAgentCredential(origin, slug, env)
418
+ throw new Error(
419
+ error.status === 401
420
+ ? `This agent's token was revoked or has expired, or the person who connected it is no longer an admin there.${forgot ? ' The saved token was removed: run the same command again for a new approval.' : ''}`
421
+ : `This token is not a connected agent's (${error.message}). Run "shapewall agent connect --remote ${origin}" without SHAPEWALL_TOKEN or --token-file to get one approved.`,
422
+ { cause: error },
423
+ )
424
+ } finally {
425
+ process.removeListener('SIGINT', stop)
426
+ process.removeListener('SIGTERM', stop)
427
+ signal?.removeEventListener('abort', stop)
428
+ backend.close?.()
429
+ editBackend?.close?.()
430
+ }
431
+ log(ended?.takenOver ? 'Another "shapewall agent connect" took over this agent (--takeover). This one stopped.' : 'Disconnected.')
432
+ return 0
433
+ }