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,1199 @@
1
+ // Agents on a hosted server. A project API token that may take work (the
2
+ // claim scope) is an agent: something a board lists by name, with a face,
3
+ // a state, and rules about who may send it work. The row in `agents`
4
+ // (migration 12) hangs that on the token; the token keeps the secret, the
5
+ // scopes, the name and revocation, exactly as before.
6
+ //
7
+ // state online (heard from in the last 90 seconds; a connected
8
+ // agent: while its link is open), busy (online and holding a
9
+ // comment it took, or answering in a chat), offline, revoked
10
+ // (its token was revoked, expired, or its maker is no longer an
11
+ // admin)
12
+ // connected an agent whose token has the "agent" scope: a machine runs
13
+ // `shapewall agent connect` for it and holds a link
14
+ // (src/hosted/agent-link.js). It says what it is and can do
15
+ // when the link opens (hello): its kind, its machine, whether it
16
+ // chats, and what its own machine allows. That is display and a
17
+ // narrowing only: the server never widens anything from it.
18
+ // audience who may send it work: "owner" (the person who connected it,
19
+ // the default for a new agent), "members" (the owner and named
20
+ // members) or "trusted" (everyone the project's agent policy
21
+ // trusts; what tokens from before 0.4.0 keep). The agent policy
22
+ // still decides who may send work to an agent at all: an
23
+ // audience only narrows that.
24
+ // routing a comment is addressed to one agent or to none ("any agent").
25
+ // Only the addressed agent's token may take it, and an agent
26
+ // only takes comments sent by someone in its audience.
27
+ //
28
+ // One function per setting. setIdentity, setDefault, setAudience,
29
+ // setApprovalRule and revoke below are the only code that changes those
30
+ // settings: each checks the role (src/hosted/permissions.js), validates,
31
+ // writes, and records an audit event with before and after. The console
32
+ // routes (src/hosted/agent-routes.js) are thin callers, so a CLI command or
33
+ // an admin tool can call the same functions later. `actor` is who asks:
34
+ // { userId, role, audit(action, target, detail) }.
35
+ //
36
+ // Every query goes through the tenant handle `t` (src/hosted/tenancy.js).
37
+
38
+ import { logoForAgent } from '../agent/agent-logos.js'
39
+ import { cleanAgentName, isAgentTint, isBuiltInIcon } from '../agent/identity.js'
40
+ import { agentPolicy, trustedMember } from './agent-policy.js'
41
+ import { newId } from './crypto.js'
42
+ import { HttpError } from './http.js'
43
+ import {
44
+ AGENT_AUDIENCES,
45
+ APPROVAL_ROLES,
46
+ APPROVAL_RULES,
47
+ approvalAutoAvailable,
48
+ approvalRuleFor,
49
+ canAnswerApproval,
50
+ canChangeApprovalRoles,
51
+ canChangeApprovalRule,
52
+ canManageAgents,
53
+ effectiveApprovalRule,
54
+ roleAtLeast,
55
+ tokenCreatorOk,
56
+ } from './permissions.js'
57
+
58
+ // What runs behind an agent, as far as the server was told. "watcher" is a
59
+ // `shapewall watch --remote` (or MCP client) whose command is unknown; the
60
+ // known ones show their product mark (src/agent/agent-logos.js).
61
+ export const AGENT_KINDS = ['watcher', 'claude', 'codex', 'goose', 'gemini', 'custom']
62
+ // What a connected agent may say it is (hello): never "watcher".
63
+ export const LINK_KINDS = ['claude', 'codex', 'goose', 'gemini', 'custom']
64
+ export const LINK_TURNS_MAX = 4
65
+ export const AUDIENCE_USERS_MAX = 50
66
+ export const AGENT_ID_RE = /^ag_[a-f0-9]{24}$/
67
+ // On a comment as the server hands it around (src/hosted/app.js
68
+ // dispatchView): { agent_id, dispatch_by }, what claimCheck goes by. A
69
+ // symbol key, so it never reaches JSON.
70
+ export const COMMENT_ROUTING = Symbol('commentRouting')
71
+
72
+ const SELECT = `SELECT a.*, k.name AS name, k.prefix AS token_prefix, k.scopes AS token_scopes, k.revoked_at AS token_revoked_at,
73
+ k.expires_at AS token_expires_at, k.created_by AS token_created_by, k.last_used_at AS token_last_used_at,
74
+ p.name AS project_name, u.handle AS creator_handle, u.display_name AS creator_name, m.role AS creator_role
75
+ FROM agents a JOIN api_tokens k ON k.id = a.token_id AND k.workspace_id = a.workspace_id
76
+ JOIN projects p ON p.id = a.project_id AND p.workspace_id = a.workspace_id
77
+ LEFT JOIN users u ON u.id = k.created_by
78
+ LEFT JOIN memberships m ON m.user_id = k.created_by AND m.workspace_id = a.workspace_id
79
+ WHERE a.workspace_id = :ws`
80
+
81
+ const parseList = (text) => {
82
+ try {
83
+ const value = JSON.parse(text || '[]')
84
+ return Array.isArray(value) ? value.filter((item) => typeof item === 'string') : []
85
+ } catch {
86
+ return []
87
+ }
88
+ }
89
+ const personName = (person) => person?.displayName || person?.handle || 'someone who left'
90
+ const listNames = (names) => (names.length <= 1 ? names.join('') : `${names.slice(0, -1).join(', ')} and ${names.at(-1)}`)
91
+
92
+ // What a connected agent reported about itself, cleaned: display only.
93
+ const parseCaps = (text) => {
94
+ try {
95
+ const value = JSON.parse(text || '{}')
96
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {}
97
+ } catch {
98
+ return {}
99
+ }
100
+ }
101
+
102
+ // `links`: the open links of connected agents (src/hosted/agent-link.js):
103
+ // { of(workspaceId, agentId) -> { connectedAt, streams } | null,
104
+ // turns(workspaceId, agentId) -> how many chat turns it is answering }.
105
+ export function createAgentStore(t, { now = () => new Date(), presence = null, handleFor = () => null, links = null } = {}) {
106
+ const iso = () => now().toISOString()
107
+ // Reads repeat within one request (a list of comments asks per comment);
108
+ // every write starts over.
109
+ let memo = new Map()
110
+ const forget = () => {
111
+ memo = new Map()
112
+ }
113
+ const once = (key, make) => {
114
+ if (!memo.has(key)) memo.set(key, make())
115
+ return memo.get(key)
116
+ }
117
+
118
+ // ---- Rows ----
119
+
120
+ // A token with the claim scope that has no agent row yet was made while an
121
+ // older build ran on this database: it becomes an agent the first time it
122
+ // is looked for, with the audience such tokens had (the agent policy's).
123
+ // `audit(action, target, detail)`: hears `agent_first_seen` for each one,
124
+ // whoever's request found it (a token's call, the board, the console).
125
+ // Two requests may find the same token at once: the insert gives way to
126
+ // the row that is already there.
127
+ function ensure(projectId, audit = null) {
128
+ const missing = t.all(
129
+ `SELECT k.id, k.name, k.created_by, k.created_at, k.last_used_at FROM api_tokens k WHERE k.workspace_id = :ws AND k.project_id = :project
130
+ AND k.scopes LIKE '%"claim"%' AND NOT EXISTS (SELECT 1 FROM agents a WHERE a.token_id = k.id)`,
131
+ { project: projectId },
132
+ )
133
+ let made = 0
134
+ for (const token of missing) {
135
+ const id = insert({ projectId, tokenId: token.id, userId: token.created_by, at: token.created_at, inherited: true })
136
+ if (!id) continue
137
+ made += 1
138
+ audit?.('agent_first_seen', id, { project: projectId, token: token.id, name: token.name, kind: 'watcher' })
139
+ }
140
+ if (missing.length) forget()
141
+ return made
142
+ }
143
+ // Returns the new agent's id, or null when the token already had one.
144
+ function insert({
145
+ projectId,
146
+ tokenId,
147
+ userId,
148
+ at = iso(),
149
+ inherited = false,
150
+ machine = null,
151
+ kind = 'watcher',
152
+ lastSeenAt = null,
153
+ icon = null,
154
+ tint = null,
155
+ }) {
156
+ const id = newId('ag')
157
+ const result = t.run(
158
+ `INSERT INTO agents (workspace_id, project_id, id, token_id, kind, icon, tint, machine, audience, audience_inherited, created_by,
159
+ created_at, approved_by, approved_at, last_seen_at)
160
+ VALUES (:ws, :project, :id, :token, :kind, :icon, :tint, :machine, :audience, :inherited, :user, :at, :user, :at, :seen)
161
+ ON CONFLICT(token_id) DO NOTHING`,
162
+ {
163
+ project: projectId,
164
+ id,
165
+ token: tokenId,
166
+ kind,
167
+ icon,
168
+ tint,
169
+ machine,
170
+ audience: inherited ? 'trusted' : 'owner',
171
+ inherited: inherited ? 1 : 0,
172
+ user: userId || null,
173
+ at,
174
+ seen: lastSeenAt,
175
+ },
176
+ )
177
+ forget()
178
+ return Number(result.changes) ? id : null
179
+ }
180
+ // A new token with the claim scope: its agent, for the person who made it
181
+ // only until they say otherwise. `machine`: the label `shapewall login` sent.
182
+ // Audit entries about an agent carry its name: the log reads without a
183
+ // lookup, and still makes sense after the agent is gone.
184
+ function create(actor, { projectId, tokenId, name = null, machine = null, kind = 'watcher', icon = null, tint = null }) {
185
+ const label = cleanMachine(machine)
186
+ const id = insert({
187
+ projectId,
188
+ tokenId,
189
+ userId: actor.userId,
190
+ machine: label,
191
+ kind: AGENT_KINDS.includes(kind) ? kind : 'custom',
192
+ icon: isBuiltInIcon(icon) ? icon : null,
193
+ tint: isAgentTint(tint) ? tint : null,
194
+ })
195
+ actor.audit('agent_created', id, {
196
+ project: projectId,
197
+ token: tokenId,
198
+ name,
199
+ kind,
200
+ audience: 'owner',
201
+ ...(label ? { machine: label } : {}),
202
+ })
203
+ return id
204
+ }
205
+ const rows = (projectId = null) =>
206
+ once(`rows:${projectId || ''}`, () =>
207
+ projectId
208
+ ? t.all(`${SELECT} AND a.project_id = :project ORDER BY a.created_at, a.id`, { project: projectId })
209
+ : t.all(`${SELECT} ORDER BY a.created_at, a.id`),
210
+ )
211
+ const live = (row, at = iso()) =>
212
+ Boolean(row) &&
213
+ !row.token_revoked_at &&
214
+ !(row.token_expires_at && row.token_expires_at <= at) &&
215
+ Boolean(row.token_created_by) &&
216
+ tokenCreatorOk(row.creator_role)
217
+ const get = (projectId, agentId) =>
218
+ (AGENT_ID_RE.test(String(agentId || '')) ? rows(projectId).find((row) => row.id === agentId) : null) || null
219
+ function need(projectId, agentId) {
220
+ const row = get(projectId, agentId)
221
+ if (!row) throw new HttpError(404, 'unknown_agent', 'No such agent.')
222
+ return row
223
+ }
224
+ // The agent of a token, or null. A claim-scoped token from an older build
225
+ // becomes an agent here, on first sight (`audit` hears of it, see ensure).
226
+ function forToken(projectId, tokenId, { audit = null } = {}) {
227
+ const find = () => rows(projectId).find((row) => row.token_id === tokenId) || null
228
+ const found = find()
229
+ if (found) return found
230
+ ensure(projectId, audit)
231
+ return find()
232
+ }
233
+ // Which agent a token is, for the face on a reply it wrote (revoked or not).
234
+ const idForToken = (projectId, tokenId) => (tokenId ? rows(projectId).find((row) => row.token_id === tokenId)?.id || null : null)
235
+ const defaultId = (projectId) =>
236
+ once(
237
+ `default:${projectId}`,
238
+ () =>
239
+ t.get('SELECT default_agent_id FROM projects WHERE workspace_id = :ws AND id = :project', { project: projectId })
240
+ ?.default_agent_id || null,
241
+ )
242
+ // The project's default agent while it can still take work, else null
243
+ // (a revoked default falls back to "any agent").
244
+ function defaultAgent(projectId) {
245
+ const row = get(projectId, defaultId(projectId))
246
+ return live(row) ? row : null
247
+ }
248
+
249
+ // ---- State ----
250
+
251
+ // Which comments each agent holds right now: token id -> [{ board, number }].
252
+ const held = (projectId) =>
253
+ once(`held:${projectId}`, () => {
254
+ const out = new Map()
255
+ for (const claim of t.all(
256
+ `SELECT c.token_id, c.board_id, c.comment_number FROM agent_claims c
257
+ JOIN comments m ON m.workspace_id = c.workspace_id AND m.project_id = c.project_id AND m.board_id = c.board_id AND m.number = c.comment_number
258
+ WHERE c.workspace_id = :ws AND c.project_id = :project AND c.ended_at IS NULL AND m.status = 'open' AND m.agent_status IN ('queued', 'working')
259
+ ORDER BY c.created_at`,
260
+ { project: projectId },
261
+ )) {
262
+ if (!out.has(claim.token_id)) out.set(claim.token_id, [])
263
+ out.get(claim.token_id).push({ board: claim.board_id, number: claim.comment_number })
264
+ }
265
+ return out
266
+ })
267
+ // Comments sent to an agent (or to any, under '') that nothing took yet:
268
+ // agent id -> [{ board, number }]. Open, vouched for, the run approved.
269
+ const waiting = (projectId) =>
270
+ once(`waiting:${projectId}`, () => {
271
+ const out = new Map()
272
+ const liveIds = new Set(
273
+ rows(projectId)
274
+ .filter((row) => live(row))
275
+ .map((row) => row.id),
276
+ )
277
+ for (const comment of t.all(
278
+ `SELECT board_id, number, agent_id FROM comments WHERE workspace_id = :ws AND project_id = :project AND status = 'open'
279
+ AND agent_status IS NULL AND dispatch_hash IS NOT NULL AND run_approved = 1 ORDER BY dispatch_at, number`,
280
+ { project: projectId },
281
+ )) {
282
+ const key = comment.agent_id && liveIds.has(comment.agent_id) ? comment.agent_id : ''
283
+ if (!out.has(key)) out.set(key, [])
284
+ out.get(key).push({ board: comment.board_id, number: comment.number })
285
+ }
286
+ return out
287
+ })
288
+ // A connected agent: its token may hold a link.
289
+ const linked = (row) => parseList(row.token_scopes).includes('agent')
290
+ // What it said about itself the last time its link opened (hello).
291
+ const capsOf = (row) => parseCaps(row.capabilities)
292
+ const linkOf = (row) => (linked(row) ? links?.of(t.workspaceId, row.id) || null : null)
293
+ function stateOf(row) {
294
+ if (!live(row)) return { state: 'revoked', lastSeenAt: latestOf(row.last_seen_at, row.token_last_used_at) }
295
+ const heard = presence?.ofAgent(t.workspaceId, row.id) || { online: false, lastSeenAt: null }
296
+ const lastSeenAt = latestOf(heard.lastSeenAt, row.last_seen_at, row.token_last_used_at)
297
+ // A connected agent is online exactly while its link is open: a call to
298
+ // the token API alone does not make it reachable.
299
+ const online = linked(row) ? Boolean(linkOf(row)) : heard.online
300
+ if (!online) return { state: 'offline', lastSeenAt }
301
+ const busy = held(row.project_id).get(row.token_id)?.length || (links?.turns(t.workspaceId, row.id) || 0) > 0
302
+ return { state: busy ? 'busy' : 'online', lastSeenAt }
303
+ }
304
+ // The link opened and the agent said what it is (POST /api/v1/agent/hello):
305
+ // kind, machine and capabilities, validated by the caller. Display, and
306
+ // what the machine's own policy narrows; never a widening.
307
+ function hello(row, { kind, machine, capabilities }) {
308
+ const label = cleanMachine(machine)
309
+ t.run(
310
+ 'UPDATE agents SET kind = :kind, machine = :machine, capabilities = :caps, last_seen_at = :at WHERE workspace_id = :ws AND id = :id',
311
+ {
312
+ kind: LINK_KINDS.includes(kind) ? kind : 'custom',
313
+ machine: label || row.machine || null,
314
+ caps: JSON.stringify(capabilities || {}),
315
+ at: iso(),
316
+ id: row.id,
317
+ },
318
+ )
319
+ forget()
320
+ return get(row.project_id, row.id)
321
+ }
322
+ // What the agent's machine said it allows (hello), as the approval rules
323
+ // read it. Nothing here is ever more than the machine said.
324
+ function machinePolicy(row) {
325
+ const policy = linked(row) ? capsOf(row).policy || {} : {}
326
+ const approvals = ['owner', 'admins'].includes(policy.approvals) ? policy.approvals : 'none'
327
+ const commands =
328
+ approvals !== 'none' && Array.isArray(policy.commands) ? policy.commands.filter((item) => typeof item === 'string') : []
329
+ const auto =
330
+ approvals !== 'none' && Array.isArray(policy.auto)
331
+ ? policy.auto.filter((kind) => kind === 'edits' || (kind === 'commands' && commands.length > 0))
332
+ : []
333
+ return { audience: policy.audience === 'owner' ? 'owner' : 'server', approvals, commands, auto }
334
+ }
335
+ // On a machine that takes approvals from the person who connected it
336
+ // alone, "allow without asking" counts only when that same person set it:
337
+ // nobody else can take them out of the loop.
338
+ const ownerOnly = (row) => machinePolicy(row).approvals === 'owner'
339
+ const ruleStands = (row) =>
340
+ row.approval_rule !== 'auto' || !ownerOnly(row) || (Boolean(row.created_by) && row.approval_rule_by === row.created_by)
341
+ const approvalOf = (row) => {
342
+ const machine = machinePolicy(row)
343
+ return {
344
+ approvalRule: ruleStands(row) ? row.approval_rule : 'ask',
345
+ approvalChangeRole: row.approval_change_role,
346
+ approvalAnswerRole: row.approval_answer_role,
347
+ machineApprovals: machine.approvals,
348
+ machineAuto: machine.auto,
349
+ }
350
+ }
351
+ // The rule in effect for this agent's requests, per kind: what a fix is told.
352
+ const approvalRules = (row) => ({
353
+ edits: approvalRuleFor(approvalOf(row), 'edits'),
354
+ commands: approvalRuleFor(approvalOf(row), 'commands'),
355
+ // The person who connected the agent set the rule themself (a machine that said "owner" asks for this).
356
+ byOwner: row.approval_rule === 'auto' && Boolean(row.created_by) && row.approval_rule_by === row.created_by,
357
+ })
358
+ // Whether a machine takes edits from the board at all, and how its
359
+ // requests are answered: "none" (reads and answers), "ask" or "auto".
360
+ function editMode(row) {
361
+ const machine = machinePolicy(row)
362
+ if (machine.approvals === 'none') return 'none'
363
+ return approvalRules(row).edits === 'auto' ? 'auto' : 'ask'
364
+ }
365
+ // May this person answer this agent's permission cards, and if not, why
366
+ // (said on the card). Every rule must hold: the agent's answer role, its
367
+ // audience and the project's trust (the same as sending it work), and the
368
+ // level its own machine set ("owner": only the person who connected it).
369
+ function answerCheck(row, { userId, role, boardId = null }) {
370
+ const machine = machinePolicy(row)
371
+ const owner = people().get(row.created_by) || null
372
+ if (!live(row)) return { ok: false, reason: `${row.name} was revoked.` }
373
+ if (machine.approvals === 'none')
374
+ return { ok: false, reason: `${row.name} reads and answers only: its machine takes no approvals from the board.` }
375
+ const who =
376
+ machine.approvals === 'owner'
377
+ ? personName(owner)
378
+ : row.approval_answer_role === 'owner'
379
+ ? `an owner ${row.name} takes work from`
380
+ : `an admin ${row.name} takes work from`
381
+ const no = { ok: false, reason: `Waiting for ${who} to allow or deny this.` }
382
+ if (!userId || !canAnswerApproval(role, approvalOf(row))) return no
383
+ if (!inAudience(row, userId) || !trusted(row.project_id, boardId, userId)) return no
384
+ if (machine.approvals === 'owner' && row.created_by !== userId) return no
385
+ return { ok: true, reason: null, owner: Boolean(row.created_by) && row.created_by === userId }
386
+ }
387
+ // The link opened (hello): when the machine no longer allows "without
388
+ // asking", a stored "always allow" does not wait for it to come back. It
389
+ // is set to "ask" again, in the open. `audit(action, target, detail)`.
390
+ // Also says, when it changed, what the machine allows now.
391
+ function helloPolicy(before, after, audit) {
392
+ const was = machinePolicy(before)
393
+ const now = machinePolicy(after)
394
+ const shape = (policy) => ({ approvals: policy.approvals, commands: policy.commands.length, auto: policy.auto })
395
+ if (JSON.stringify(shape(was)) !== JSON.stringify(shape(now)))
396
+ audit?.('agent_edit_mode_changed', after.id, {
397
+ project: after.project_id,
398
+ name: after.name,
399
+ before: shape(was),
400
+ after: shape(now),
401
+ by: 'machine',
402
+ })
403
+ if (after.approval_rule === 'auto' && (!ruleStands(after) || !approvalAutoAvailable(approvalOf(after)))) {
404
+ t.run("UPDATE agents SET approval_rule = 'ask' WHERE workspace_id = :ws AND id = :id", { id: after.id })
405
+ audit?.('agent_approval_rule_changed', after.id, {
406
+ project: after.project_id,
407
+ name: after.name,
408
+ before: { rule: 'auto' },
409
+ after: { rule: 'ask' },
410
+ reason: 'the machine no longer allows requests without asking',
411
+ })
412
+ forget()
413
+ }
414
+ return get(after.project_id, after.id)
415
+ }
416
+ // A claim-scoped token was heard from: its agent is online, and its
417
+ // last-seen time is written down at most once a minute.
418
+ function seen(row) {
419
+ if (!row || !presence) return
420
+ const { save } = presence.seen(t.workspaceId, row.project_id, row.id, row.name)
421
+ if (save) t.run('UPDATE agents SET last_seen_at = :at WHERE workspace_id = :ws AND id = :id', { at: iso(), id: row.id })
422
+ }
423
+
424
+ // ---- Audience ----
425
+
426
+ const people = () =>
427
+ once('people', () => {
428
+ const out = new Map()
429
+ for (const row of t.all(
430
+ 'SELECT m.user_id, m.role, u.handle, u.display_name FROM memberships m JOIN users u ON u.id = m.user_id WHERE m.workspace_id = :ws',
431
+ ))
432
+ out.set(row.user_id, { userId: row.user_id, role: row.role, handle: row.handle, displayName: row.display_name })
433
+ return out
434
+ })
435
+ // The named members of a "members" audience who are still in the workspace.
436
+ const namedUsers = (row) => parseList(row.audience_users).filter((id) => id !== row.created_by && people().has(id))
437
+ // Whether this person is in the agent's audience. (Whether the agent
438
+ // policy lets them send work to an agent at all is `trusted` below: both
439
+ // must hold.)
440
+ // The agent's own machine said it takes work from its connector only
441
+ // (`shapewall agent connect --audience owner`): the last word, whatever
442
+ // the audience here says.
443
+ const machineOwnerOnly = (row) => linked(row) && capsOf(row).policy?.audience === 'owner'
444
+ function inAudience(row, userId) {
445
+ if (!row || !userId) return false
446
+ if (machineOwnerOnly(row)) return Boolean(row.created_by) && row.created_by === userId
447
+ if (row.audience === 'trusted') return true
448
+ if (row.created_by && row.created_by === userId) return true
449
+ return row.audience === 'members' && namedUsers(row).includes(userId)
450
+ }
451
+ const trusted = (projectId, boardId, userId) => trustedMember({ ...t, handleFor }, agentPolicy(t, projectId, boardId), userId)
452
+ // The audience in words and names, for whoever looks at the agent.
453
+ function audienceOf(row) {
454
+ const owner = people().get(row.created_by) || null
455
+ const named = row.audience === 'members' ? namedUsers(row).map((id) => people().get(id)) : []
456
+ const names = [personName(owner), ...named.map(personName)]
457
+ // Narrowed on the agent's machine: what is in effect, said plainly.
458
+ if (machineOwnerOnly(row) && row.audience !== 'owner')
459
+ return {
460
+ kind: row.audience,
461
+ effective: 'owner',
462
+ inherited: false,
463
+ text: `Only ${personName(owner)} (set on the agent's own machine)`,
464
+ people: owner ? [{ handle: owner.handle, displayName: owner.displayName }] : [],
465
+ }
466
+ return {
467
+ kind: row.audience,
468
+ effective: row.audience,
469
+ // Kept from before 0.4.0, never chosen.
470
+ inherited: Boolean(row.audience_inherited) && row.audience === 'trusted',
471
+ text:
472
+ row.audience === 'trusted'
473
+ ? "Everyone this project's agent policy trusts"
474
+ : row.audience === 'owner'
475
+ ? `Only ${personName(owner)}`
476
+ : listNames(names),
477
+ people: (row.audience === 'trusted' ? [] : [owner, ...named]).filter(Boolean).map((person) => ({
478
+ handle: person.handle,
479
+ displayName: person.displayName,
480
+ })),
481
+ }
482
+ }
483
+ // May this person send the agent work, and if not, why (said on the board).
484
+ function sendCheck(row, { userId, role, boardId = null }) {
485
+ if (!roleAtLeast(role, 'member')) return { ok: false, reason: 'Viewers cannot send work to an agent.' }
486
+ if (!live(row)) return { ok: false, reason: `${row.name} was revoked.` }
487
+ if (!trusted(row.project_id, boardId, userId))
488
+ return { ok: false, reason: "This project's agent policy does not let you send work to an agent. Ask an admin." }
489
+ if (inAudience(row, userId)) return { ok: true, reason: null }
490
+ const audience = audienceOf(row)
491
+ return {
492
+ ok: false,
493
+ reason:
494
+ row.audience === 'owner'
495
+ ? `${audience.text} can send work to ${row.name}. Ask them, or an admin, to share it.`
496
+ : `${row.name} takes work from ${audience.text} only. Ask an admin to add you.`,
497
+ }
498
+ }
499
+
500
+ // May this person chat with the agent right now, and if not, why (said
501
+ // in the picker and under the composer). Chat needs a connected agent
502
+ // that chats, the same rules as sending it work, and an open link.
503
+ function chatCheck(row, { userId, role, boardId = null }) {
504
+ if (!live(row)) return { ok: false, code: 'agent_revoked', reason: `${row.name} was revoked.` }
505
+ if (!linked(row) || capsOf(row).chat !== true)
506
+ return {
507
+ ok: false,
508
+ code: 'no_chat',
509
+ reason: `${row.name} takes comments only. Chat needs an agent connected with "shapewall agent connect".`,
510
+ }
511
+ const send = sendCheck(row, { userId, role, boardId })
512
+ if (!send.ok) return { ok: false, code: 'agent_audience', reason: send.reason.replace(/send work to/g, 'use') }
513
+ if (!linkOf(row)) return { ok: false, code: 'agent_offline', reason: `${row.name} is offline.` }
514
+ return { ok: true, code: null, reason: null }
515
+ }
516
+ // What a connected agent said it can do, for the board and the console.
517
+ function linkView(row) {
518
+ if (!linked(row)) return { connected: false }
519
+ const caps = capsOf(row)
520
+ const link = linkOf(row)
521
+ return {
522
+ connected: true,
523
+ connectedAt: link?.connectedAt || null,
524
+ chats: caps.chat === true,
525
+ version: typeof caps.version === 'string' ? caps.version : null,
526
+ // Read and answer only: the machine refuses edits and commands itself.
527
+ capabilities: {
528
+ chat: caps.chat === true,
529
+ edits: caps.edits === true,
530
+ commands: caps.commands === true,
531
+ images: caps.images === true,
532
+ },
533
+ policy: machinePolicy(row),
534
+ maxTurns: Number.isInteger(caps.maxTurns) ? caps.maxTurns : null,
535
+ }
536
+ }
537
+ // Edits from the board, as the board says it about this agent: whether
538
+ // its machine takes them, how requests are answered, and whether this
539
+ // person may press Fix and answer its cards (with the reason when not).
540
+ function editsView(row, viewer, { boardId = null } = {}) {
541
+ const mode = editMode(row)
542
+ const machine = machinePolicy(row)
543
+ const answer = mode === 'none' ? { ok: false, reason: null } : answerCheck(row, { ...viewer, boardId })
544
+ const chat = chatCheck(row, { ...viewer, boardId })
545
+ const fix =
546
+ mode === 'none'
547
+ ? {
548
+ ok: false,
549
+ reason: `${row.name} reads and answers only. Edits are switched on on its own machine (shapewall agent connect --approvals).`,
550
+ }
551
+ : chat.ok
552
+ ? { ok: true, reason: null }
553
+ : { ok: false, reason: chat.reason }
554
+ return {
555
+ mode,
556
+ text:
557
+ mode === 'none'
558
+ ? 'Reads and answers'
559
+ : mode === 'auto'
560
+ ? 'Edits on a branch, allowed without asking'
561
+ : `Edits on a branch, each allowed by ${machine.approvals === 'owner' ? 'the person who connected it' : row.approval_answer_role === 'owner' ? 'an owner' : 'an admin'}`,
562
+ commands: machine.commands.length,
563
+ answer: { ok: answer.ok, reason: answer.reason },
564
+ fix,
565
+ }
566
+ }
567
+
568
+ // ---- Routing ----
569
+
570
+ // The agent a comment is addressed to, while that agent can still take
571
+ // work; null means any agent. A comment addressed to a revoked agent is
572
+ // never stuck: any agent may take it.
573
+ function addressOf(projectId, row) {
574
+ const agent = row?.agent_id ? get(projectId, row.agent_id) : null
575
+ return live(agent) ? agent.id : null
576
+ }
577
+ // Addresses a comment a person just sent (or that was vouched for when it
578
+ // was written). `wanted`: an agent id, null for any agent, or undefined
579
+ // for the project's default agent when this person may use it (any agent
580
+ // otherwise). Throws when the named agent is not theirs to use.
581
+ function address(projectId, boardId, row, { userId, role }, wanted = undefined) {
582
+ let agent = null
583
+ if (wanted === undefined) {
584
+ const candidate = defaultAgent(projectId)
585
+ agent = candidate && inAudience(candidate, userId) ? candidate : null
586
+ } else if (wanted !== null) {
587
+ agent = get(projectId, wanted)
588
+ if (!live(agent)) throw new HttpError(404, 'unknown_agent', 'No such agent in this project. It may have been revoked.')
589
+ const check = sendCheck(agent, { userId, role, boardId })
590
+ if (!check.ok) throw new HttpError(403, 'agent_audience', check.reason)
591
+ }
592
+ t.run(
593
+ 'UPDATE comments SET agent_id = :agent WHERE workspace_id = :ws AND project_id = :project AND board_id = :board AND number = :number',
594
+ { project: projectId, board: boardId, number: row.number, agent: agent?.id || null },
595
+ )
596
+ forget()
597
+ return agent?.id || null
598
+ }
599
+ // "Let any agent take it": a comment that waits for one agent goes to
600
+ // whichever agent takes it first. Returns the agent it was waiting for.
601
+ function release(actor, projectId, boardId, row) {
602
+ const from = addressOf(projectId, row)
603
+ if (row.agent_id)
604
+ t.run(
605
+ 'UPDATE comments SET agent_id = NULL WHERE workspace_id = :ws AND project_id = :project AND board_id = :board AND number = :number',
606
+ { project: projectId, board: boardId, number: row.number },
607
+ )
608
+ forget()
609
+ if (from)
610
+ actor.audit('agent_queue_released', `${boardId}#${row.number}`, {
611
+ project: projectId,
612
+ from,
613
+ fromName: get(projectId, from)?.name || null,
614
+ to: null,
615
+ })
616
+ return from
617
+ }
618
+ // May this agent take this comment? The two rules a token cannot get
619
+ // around: a comment sent to another agent is not its to take, and it only
620
+ // takes work from people in its audience (the person whose vouch stands on
621
+ // the comment, `dispatch_by`).
622
+ function claimCheck(agent, projectId, row) {
623
+ if (!agent) return { ok: false, code: 'not_an_agent', message: 'This token is not an agent.' }
624
+ const addressed = addressOf(projectId, row)
625
+ if (addressed && addressed !== agent.id)
626
+ return { ok: false, code: 'addressed_elsewhere', message: 'This comment was sent to another agent.' }
627
+ if (!inAudience(agent, row.dispatch_by))
628
+ return { ok: false, code: 'agent_audience', message: "This comment was sent by someone outside this agent's audience." }
629
+ return { ok: true, code: null, message: null }
630
+ }
631
+
632
+ // Whether this agent's token holds the comment right now (it took it and
633
+ // has not finished). `row`: a comment row, or its COMMENT_ROUTING.
634
+ function holds(agent, projectId, row) {
635
+ if (!agent || !row) return false
636
+ const board = row.board_id
637
+ const number = row.number
638
+ return (held(projectId).get(agent.token_id) || []).some((item) => item.board === board && item.number === number)
639
+ }
640
+ // May this agent's token work on this comment at all (read it, reply, set
641
+ // a status, ask for an approval)? Yes while it holds it, whatever changed
642
+ // since: an audience governs new work, and never strands work under way.
643
+ // Otherwise the rule for taking it (claimCheck).
644
+ function workCheck(agent, projectId, row) {
645
+ if (holds(agent, projectId, row)) return { ok: true, code: null, message: null }
646
+ return claimCheck(agent, projectId, row)
647
+ }
648
+ // May this agent's token read a reply this person wrote? Only people in
649
+ // its audience (the same rule as sending it work): someone the agent
650
+ // policy trusts but this agent does not take work from cannot steer it
651
+ // through a reply. While it holds the comment, the person whose approval
652
+ // stands on it stays readable too.
653
+ function replyVisible(agent, projectId, row, userId) {
654
+ if (!agent || !userId) return false
655
+ return inAudience(agent, userId) || (userId === row?.dispatch_by && holds(agent, projectId, row))
656
+ }
657
+
658
+ // ---- Agents that are gone ----
659
+
660
+ // Every comment an agent holds, by the newest claim on it: [{ token_id,
661
+ // board, number }] for open comments that read queued or working.
662
+ function heldBy(projectId) {
663
+ const latest = new Map()
664
+ for (const claim of t.all(
665
+ `SELECT c.token_id, c.board_id, c.comment_number FROM agent_claims c
666
+ JOIN comments m ON m.workspace_id = c.workspace_id AND m.project_id = c.project_id AND m.board_id = c.board_id AND m.number = c.comment_number
667
+ WHERE c.workspace_id = :ws AND c.project_id = :project AND m.status = 'open' AND m.agent_status IN ('queued', 'working')
668
+ ORDER BY c.created_at, c.rowid`,
669
+ { project: projectId },
670
+ ))
671
+ latest.set(`${claim.board_id}#${claim.comment_number}`, {
672
+ token_id: claim.token_id,
673
+ board: claim.board_id,
674
+ number: claim.comment_number,
675
+ })
676
+ return [...latest.values()]
677
+ }
678
+ // An agent that can no longer take work lets go of everything: the
679
+ // comments it holds lose their working status and go to any agent (their
680
+ // claims end, their usage records close with the reason), the comments
681
+ // that waited for it go to any agent, and the project loses it as default.
682
+ // `audit` hears one agent_queue_released per comment. Safe to run again.
683
+ function releaseAgent(projectId, agent, { audit = null, reason = 'revoked', holding = null } = {}) {
684
+ const at = iso()
685
+ const where = 'workspace_id = :ws AND project_id = :project AND board_id = :board AND number = :number'
686
+ const mine = (holding || heldBy(projectId)).filter((item) => item.token_id === agent.token_id)
687
+ const said = (item, was) =>
688
+ audit?.('agent_queue_released', `${item.board}#${item.number}`, {
689
+ project: projectId,
690
+ from: agent.id,
691
+ fromName: agent.name,
692
+ to: null,
693
+ reason,
694
+ was,
695
+ })
696
+ for (const item of mine) {
697
+ t.run(
698
+ 'UPDATE agent_runs SET ended_at = :at, outcome = :reason WHERE workspace_id = :ws AND project_id = :project AND agent_id = :agent AND board_id = :board AND comment_number = :number AND ended_at IS NULL',
699
+ { project: projectId, agent: agent.id, board: item.board, number: item.number, at, reason },
700
+ )
701
+ t.run(`UPDATE comments SET agent_status = NULL, agent_status_at = NULL, agent_id = NULL WHERE ${where}`, {
702
+ project: projectId,
703
+ board: item.board,
704
+ number: item.number,
705
+ })
706
+ said(item, 'working')
707
+ }
708
+ t.run(
709
+ 'UPDATE agent_claims SET ended_at = :at WHERE workspace_id = :ws AND project_id = :project AND token_id = :token AND ended_at IS NULL',
710
+ { project: projectId, token: agent.token_id, at },
711
+ )
712
+ const queued = t
713
+ .all(
714
+ "SELECT board_id, number FROM comments WHERE workspace_id = :ws AND project_id = :project AND agent_id = :agent AND status = 'open' AND agent_status IS NULL",
715
+ { project: projectId, agent: agent.id },
716
+ )
717
+ .map((comment) => ({ board: comment.board_id, number: comment.number }))
718
+ for (const item of queued) {
719
+ t.run(`UPDATE comments SET agent_id = NULL WHERE ${where}`, { project: projectId, board: item.board, number: item.number })
720
+ said(item, 'waiting')
721
+ }
722
+ const wasDefault = defaultId(projectId) === agent.id
723
+ if (wasDefault) {
724
+ t.run('UPDATE projects SET default_agent_id = NULL WHERE workspace_id = :ws AND id = :project', { project: projectId })
725
+ audit?.('agent_default_changed', projectId, { before: agent.id, beforeName: agent.name, after: null, afterName: null, reason })
726
+ }
727
+ presence?.forgetAgent(t.workspaceId, agent.id)
728
+ forget()
729
+ return { comments: queued.length, held: mine.length, wasDefault }
730
+ }
731
+ // The same for every agent of the project that stopped being able to take
732
+ // work by another road: its token expired, was revoked with its maker's
733
+ // other grants, or its maker is no longer an admin. Run where such an
734
+ // agent would be seen (a token's call, the board's list, the console), so
735
+ // nothing reads "working" under an agent that is gone, and a revoked agent
736
+ // is never shown as the default.
737
+ function releaseGone(projectId, audit = null) {
738
+ const gone = rows(projectId).filter((row) => !live(row))
739
+ if (!gone.length) return 0
740
+ const holding = heldBy(projectId)
741
+ const addressed = new Set(
742
+ t
743
+ .all(
744
+ "SELECT DISTINCT agent_id FROM comments WHERE workspace_id = :ws AND project_id = :project AND agent_id IS NOT NULL AND status = 'open' AND agent_status IS NULL",
745
+ { project: projectId },
746
+ )
747
+ .map((row) => row.agent_id),
748
+ )
749
+ const open = new Set(
750
+ t
751
+ .all('SELECT DISTINCT token_id FROM agent_claims WHERE workspace_id = :ws AND project_id = :project AND ended_at IS NULL', {
752
+ project: projectId,
753
+ })
754
+ .map((row) => row.token_id),
755
+ )
756
+ const fallback = defaultId(projectId)
757
+ let released = 0
758
+ for (const agent of gone) {
759
+ const busy = holding.some((item) => item.token_id === agent.token_id)
760
+ if (!busy && !addressed.has(agent.id) && !open.has(agent.token_id) && fallback !== agent.id) continue
761
+ const reason = agent.token_revoked_at ? 'revoked' : agent.token_expires_at && agent.token_expires_at <= iso() ? 'expired' : 'inactive'
762
+ releaseAgent(projectId, agent, { audit, reason, holding })
763
+ released += 1
764
+ }
765
+ return released
766
+ }
767
+
768
+ // ---- Usage records (the groundwork of the usage dashboard) ----
769
+
770
+ // One row per comment an agent took: who asked, which agent, where, when.
771
+ // No comment text, no answer. The model, effort and token columns stay
772
+ // NULL: a watcher reports none of them.
773
+ function startRun({ projectId, boardId, number, agentId, claimId, askedBy }) {
774
+ t.run(
775
+ `INSERT INTO agent_runs (workspace_id, project_id, id, kind, agent_id, claim_id, board_id, comment_number, asked_by, started_at)
776
+ VALUES (:ws, :project, :id, 'fix', :agent, :claim, :board, :number, :asked, :at)`,
777
+ {
778
+ project: projectId,
779
+ id: newId('run'),
780
+ agent: agentId || null,
781
+ claim: claimId,
782
+ board: boardId,
783
+ number,
784
+ asked: askedBy || null,
785
+ at: iso(),
786
+ },
787
+ )
788
+ }
789
+ // Closes the record of every run whose claim ended, with how it ended:
790
+ // the status the agent left (done, needs-human, branch-ready), "resolved"
791
+ // when the comment was resolved meanwhile, "released" when the claim was
792
+ // dropped with nothing to show, "removed" when the comment is gone. A run
793
+ // whose claim was swept away and followed by another claim on the same
794
+ // comment is "stale": what the comment says now is the later run's doing.
795
+ function closeRuns(projectId) {
796
+ const ended = t.all(
797
+ `SELECT r.id, r.claim_id, r.board_id, r.comment_number, c.ended_at FROM agent_runs r
798
+ JOIN agent_claims c ON c.id = r.claim_id AND c.workspace_id = r.workspace_id
799
+ WHERE r.workspace_id = :ws AND r.project_id = :project AND r.ended_at IS NULL AND c.ended_at IS NOT NULL`,
800
+ { project: projectId },
801
+ )
802
+ for (const run of ended) {
803
+ const comment = t.get(
804
+ 'SELECT status, agent_status, resolved_at FROM comments WHERE workspace_id = :ws AND project_id = :project AND board_id = :board AND number = :number',
805
+ { project: projectId, board: run.board_id, number: run.comment_number },
806
+ )
807
+ const newest = t.get(
808
+ 'SELECT id FROM agent_claims WHERE workspace_id = :ws AND project_id = :project AND board_id = :board AND comment_number = :number ORDER BY created_at DESC, rowid DESC LIMIT 1',
809
+ { project: projectId, board: run.board_id, number: run.comment_number },
810
+ )
811
+ const outcome = !comment
812
+ ? 'removed'
813
+ : newest && newest.id !== run.claim_id
814
+ ? 'stale'
815
+ : comment.status === 'resolved'
816
+ ? 'resolved'
817
+ : ['done', 'needs-human', 'branch-ready'].includes(comment.agent_status)
818
+ ? comment.agent_status
819
+ : 'released'
820
+ const at =
821
+ comment?.status === 'resolved' && comment.resolved_at && comment.resolved_at < run.ended_at ? comment.resolved_at : run.ended_at
822
+ t.run('UPDATE agent_runs SET ended_at = :at, outcome = :outcome WHERE workspace_id = :ws AND id = :id', { id: run.id, at, outcome })
823
+ }
824
+ return ended.length
825
+ }
826
+
827
+ // ---- Views ----
828
+
829
+ const face = (row) => ({
830
+ icon: isBuiltInIcon(row.icon) ? row.icon : null,
831
+ tint: isAgentTint(row.tint) ? row.tint : null,
832
+ logo: logoForAgent(row.kind),
833
+ })
834
+ // An agent as a board member sees it. No token id, prefix or scope, and
835
+ // no account id: names, a face, a state, and what this viewer may do.
836
+ function boardView(row, viewer, { boardId = null } = {}) {
837
+ const check = sendCheck(row, { ...viewer, boardId })
838
+ const mine = (list) => (list || []).filter((item) => !boardId || item.board === boardId).map((item) => item.number)
839
+ const working = held(row.project_id).get(row.token_id) || []
840
+ const queued = waiting(row.project_id).get(row.id) || []
841
+ return {
842
+ id: row.id,
843
+ name: row.name,
844
+ kind: row.kind,
845
+ ...face(row),
846
+ machine: row.machine || null,
847
+ ...stateOf(row),
848
+ isDefault: defaultId(row.project_id) === row.id,
849
+ audience: audienceOf(row),
850
+ canSend: check.ok,
851
+ reason: check.reason,
852
+ // A connected agent: whether it chats, and whether this person may
853
+ // chat with it right now (with the reason when not).
854
+ link: linkView(row),
855
+ edits: editsView(row, viewer, { boardId }),
856
+ chat: (() => {
857
+ const chat = chatCheck(row, { ...viewer, boardId })
858
+ return { ok: chat.ok, code: chat.code, reason: chat.reason }
859
+ })(),
860
+ working: mine(working),
861
+ queued: mine(queued),
862
+ // What it holds on the project's other boards, as counts.
863
+ elsewhere: { working: working.length - mine(working).length, queued: queued.length - mine(queued).length },
864
+ }
865
+ }
866
+ // The agents of a project for its board: the ones that can take work.
867
+ function boardList(projectId, viewer, { boardId = null, audit = null } = {}) {
868
+ ensure(projectId, audit)
869
+ releaseGone(projectId, audit)
870
+ const agents = rows(projectId)
871
+ .filter((row) => live(row))
872
+ .map((row) => boardView(row, viewer, { boardId }))
873
+ return {
874
+ agents,
875
+ defaultAgentId: defaultAgent(projectId)?.id || null,
876
+ // Whether this person may send work to an agent at all (the agent policy).
877
+ canSend: roleAtLeast(viewer.role, 'member') && trusted(projectId, boardId, viewer.userId),
878
+ // Sent to any agent and not taken yet, on this board.
879
+ unassigned: (waiting(projectId).get('') || []).filter((item) => !boardId || item.board === boardId).map((item) => item.number),
880
+ }
881
+ }
882
+ // An agent as the console shows it to an admin: everything above plus its
883
+ // settings, its token (what the Tokens page shows of it) and who made it.
884
+ function consoleView(row) {
885
+ const working = held(row.project_id).get(row.token_id) || []
886
+ const queued = waiting(row.project_id).get(row.id) || []
887
+ const audience = audienceOf(row)
888
+ const approval = approvalOf(row)
889
+ const machine = machinePolicy(row)
890
+ return {
891
+ id: row.id,
892
+ name: row.name,
893
+ kind: row.kind,
894
+ ...face(row),
895
+ machine: row.machine || null,
896
+ ...stateOf(row),
897
+ projectId: row.project_id,
898
+ projectName: row.project_name,
899
+ isDefault: defaultId(row.project_id) === row.id,
900
+ audience: {
901
+ ...audience,
902
+ users: row.audience === 'members' ? namedUsers(row).map((id) => ({ userId: id, ...pick(people().get(id)) })) : [],
903
+ },
904
+ approval: {
905
+ rule: row.approval_rule,
906
+ effectiveRule: effectiveApprovalRule(approval),
907
+ autoAvailable: approvalAutoAvailable(approval),
908
+ changeRole: row.approval_change_role,
909
+ answerRole: row.approval_answer_role,
910
+ // What its own machine allows: the ceiling for everything above.
911
+ mode: editMode(row),
912
+ machine: { approvals: machine.approvals, commands: machine.commands, auto: machine.auto },
913
+ rules: { edits: approvalRules(row).edits, commands: approvalRules(row).commands },
914
+ // Who may switch "allow without asking" on: only the person who connected it, when its machine says "owner".
915
+ autoBy: ownerOnly(row) ? 'owner' : 'role',
916
+ },
917
+ counts: { working: working.length, queued: queued.length },
918
+ link: { ...linkView(row), streams: linkOf(row)?.streams || 0 },
919
+ createdAt: row.created_at,
920
+ createdBy: row.created_by
921
+ ? { userId: row.created_by, ...pick(people().get(row.created_by)), left: !people().has(row.created_by) }
922
+ : null,
923
+ token: {
924
+ id: row.token_id,
925
+ prefix: row.token_prefix,
926
+ scopes: parseList(row.token_scopes),
927
+ expiresAt: row.token_expires_at,
928
+ revokedAt: row.token_revoked_at,
929
+ },
930
+ }
931
+ }
932
+ // Every agent of the project (or, without one, of the workspace), live
933
+ // ones first.
934
+ function consoleList(projectId = null, { audit = null } = {}) {
935
+ const projects = projectId ? [projectId] : t.all('SELECT id FROM projects WHERE workspace_id = :ws').map((project) => project.id)
936
+ for (const id of projects) {
937
+ ensure(id, audit)
938
+ releaseGone(id, audit)
939
+ }
940
+ const all = rows(projectId).map(consoleView)
941
+ return [...all.filter((agent) => agent.state !== 'revoked'), ...all.filter((agent) => agent.state === 'revoked')]
942
+ }
943
+
944
+ // ---- Settings: one function each ----
945
+
946
+ const mayManage = (actor) => {
947
+ if (!canManageAgents(actor.role)) throw new HttpError(403, 'forbidden', 'Managing agents needs the admin role or higher.')
948
+ }
949
+ const after = (projectId, agentId) => {
950
+ forget()
951
+ return consoleView(need(projectId, agentId))
952
+ }
953
+
954
+ // Name, icon, tint and kind: how the agent looks on the board. `changes`
955
+ // holds only what changes. The name is the token's name (what the agent's
956
+ // replies are signed with from now on).
957
+ function setIdentity(actor, projectId, agentId, changes = {}) {
958
+ mayManage(actor)
959
+ const row = need(projectId, agentId)
960
+ if (!live(row)) throw new HttpError(409, 'agent_revoked', 'This agent was revoked.')
961
+ const before = { name: row.name, icon: row.icon || null, tint: row.tint || null, kind: row.kind }
962
+ const next = { ...before }
963
+ if (changes.name !== undefined) {
964
+ const { name, problem } = cleanAgentName(changes.name)
965
+ if (problem || !name) throw new HttpError(400, 'invalid_name', problem ? `Agent ${problem}.` : 'Agent name: 1 to 40 characters.')
966
+ next.name = name
967
+ }
968
+ if (changes.icon !== undefined) {
969
+ if (changes.icon !== null && !isBuiltInIcon(changes.icon))
970
+ throw new HttpError(400, 'invalid_icon', 'Choose one of the built-in icons.')
971
+ next.icon = changes.icon
972
+ }
973
+ if (changes.tint !== undefined) {
974
+ if (changes.tint !== null && !isAgentTint(changes.tint)) throw new HttpError(400, 'invalid_tint', 'Choose one of the tints.')
975
+ next.tint = changes.tint
976
+ }
977
+ if (changes.kind !== undefined) {
978
+ if (!AGENT_KINDS.includes(changes.kind)) throw new HttpError(400, 'invalid_kind', `Kind: ${AGENT_KINDS.join(', ')}.`)
979
+ next.kind = changes.kind
980
+ }
981
+ if (next.name !== before.name) {
982
+ t.run('UPDATE api_tokens SET name = :name WHERE workspace_id = :ws AND project_id = :project AND id = :id', {
983
+ name: next.name,
984
+ project: projectId,
985
+ id: row.token_id,
986
+ })
987
+ actor.audit('agent_renamed', row.id, { project: projectId, from: before.name, to: next.name })
988
+ }
989
+ const look = (value) => ({ icon: value.icon, tint: value.tint, kind: value.kind })
990
+ if (JSON.stringify(look(next)) !== JSON.stringify(look(before))) {
991
+ t.run('UPDATE agents SET icon = :icon, tint = :tint, kind = :kind WHERE workspace_id = :ws AND id = :id', {
992
+ ...look(next),
993
+ id: row.id,
994
+ })
995
+ actor.audit('agent_identity_changed', row.id, { project: projectId, name: next.name, before: look(before), after: look(next) })
996
+ }
997
+ return after(projectId, agentId)
998
+ }
999
+
1000
+ // The project's default agent: the one "Send to agent" names, and where a
1001
+ // trusted member's new comment goes. null: any agent.
1002
+ function setDefault(actor, projectId, agentId) {
1003
+ mayManage(actor)
1004
+ const row = agentId === null ? null : need(projectId, agentId)
1005
+ if (row && !live(row)) throw new HttpError(409, 'agent_revoked', 'A revoked agent cannot be the default.')
1006
+ const before = defaultId(projectId)
1007
+ if (before !== (row?.id || null)) {
1008
+ t.run('UPDATE projects SET default_agent_id = :agent WHERE workspace_id = :ws AND id = :project', {
1009
+ project: projectId,
1010
+ agent: row?.id || null,
1011
+ })
1012
+ actor.audit('agent_default_changed', projectId, {
1013
+ before,
1014
+ beforeName: get(projectId, before)?.name || null,
1015
+ after: row?.id || null,
1016
+ afterName: row?.name || null,
1017
+ })
1018
+ forget()
1019
+ }
1020
+ return row?.id || null
1021
+ }
1022
+
1023
+ // Who may send the agent work: { audience, users }. `users` (account ids
1024
+ // of workspace members) only with "members"; the person who connected the
1025
+ // agent is always in.
1026
+ function setAudience(actor, projectId, agentId, { audience, users = [] } = {}) {
1027
+ mayManage(actor)
1028
+ const row = need(projectId, agentId)
1029
+ if (!live(row)) throw new HttpError(409, 'agent_revoked', 'This agent was revoked.')
1030
+ if (!AGENT_AUDIENCES.includes(audience)) throw new HttpError(400, 'invalid_audience', `Audience: ${AGENT_AUDIENCES.join(', ')}.`)
1031
+ let named = []
1032
+ if (audience === 'members') {
1033
+ if (!Array.isArray(users) || users.length > AUDIENCE_USERS_MAX || users.some((id) => typeof id !== 'string'))
1034
+ throw new HttpError(400, 'invalid_audience', `Named members: at most ${AUDIENCE_USERS_MAX} people.`)
1035
+ named = [...new Set(users)].filter((id) => id !== row.created_by)
1036
+ const unknown = named.filter((id) => !roleAtLeast(people().get(id)?.role, 'member'))
1037
+ if (unknown.length)
1038
+ throw new HttpError(400, 'invalid_audience', 'Named members must be members of this workspace (viewers cannot send work).')
1039
+ }
1040
+ const shape = (kind, list) => ({ audience: kind, users: [...list].sort() })
1041
+ const before = shape(row.audience, row.audience === 'members' ? namedUsers(row) : [])
1042
+ const next = shape(audience, named)
1043
+ // Saving the same audience still counts as choosing it.
1044
+ if (JSON.stringify(before) !== JSON.stringify(next) || row.audience_inherited) {
1045
+ t.run(
1046
+ 'UPDATE agents SET audience = :audience, audience_users = :users, audience_inherited = 0 WHERE workspace_id = :ws AND id = :id',
1047
+ {
1048
+ audience,
1049
+ users: JSON.stringify(next.users),
1050
+ id: row.id,
1051
+ },
1052
+ )
1053
+ actor.audit('agent_audience_changed', row.id, { project: projectId, name: row.name, before, after: next })
1054
+ }
1055
+ return after(projectId, agentId)
1056
+ }
1057
+
1058
+ // The approval rule and who may change or answer it: { rule, changeRole,
1059
+ // answerRole }, only what changes. "auto" is refused until the agent's
1060
+ // machine can opt in (permissions.js approvalAutoAvailable).
1061
+ function setApprovalRule(actor, projectId, agentId, changes = {}) {
1062
+ mayManage(actor)
1063
+ const row = need(projectId, agentId)
1064
+ if (!live(row)) throw new HttpError(409, 'agent_revoked', 'This agent was revoked.')
1065
+ const before = { rule: row.approval_rule, changeRole: row.approval_change_role, answerRole: row.approval_answer_role }
1066
+ const next = { ...before }
1067
+ const current = approvalOf(row)
1068
+ if (changes.rule !== undefined && changes.rule !== before.rule) {
1069
+ if (!APPROVAL_RULES.includes(changes.rule))
1070
+ throw new HttpError(400, 'invalid_approval_rule', `Approval rule: ${APPROVAL_RULES.join(', ')}.`)
1071
+ if (!canChangeApprovalRule(actor.role, current))
1072
+ throw new HttpError(403, 'forbidden', `Changing this agent's approval rule needs the ${before.changeRole} role.`)
1073
+ // The machine takes approvals from the person who connected it alone:
1074
+ // then only that person may say "without asking". An admin cannot take them out of the loop.
1075
+ if (changes.rule === 'auto' && ownerOnly(row) && actor.userId !== row.created_by)
1076
+ throw new HttpError(
1077
+ 403,
1078
+ 'forbidden',
1079
+ `Only ${personName(people().get(row.created_by))} can let ${row.name} edit without asking: its machine takes approvals from the person who connected it alone.`,
1080
+ )
1081
+ if (changes.rule === 'auto' && !approvalAutoAvailable(current))
1082
+ throw new HttpError(
1083
+ 409,
1084
+ 'approval_auto_unavailable',
1085
+ "Allowing without asking needs the agent's own machine to say so first: shapewall agent connect --approvals owner --auto edits, on that machine.",
1086
+ )
1087
+ next.rule = changes.rule
1088
+ }
1089
+ for (const key of ['changeRole', 'answerRole']) {
1090
+ if (changes[key] === undefined || changes[key] === before[key]) continue
1091
+ if (!APPROVAL_ROLES.includes(changes[key])) throw new HttpError(400, 'invalid_approval_role', `Role: ${APPROVAL_ROLES.join(', ')}.`)
1092
+ if (!canChangeApprovalRoles(actor.role)) throw new HttpError(403, 'forbidden', 'Only an owner changes which role decides approvals.')
1093
+ next[key] = changes[key]
1094
+ }
1095
+ if (JSON.stringify(before) !== JSON.stringify(next)) {
1096
+ t.run(
1097
+ 'UPDATE agents SET approval_rule = :rule, approval_change_role = :changeRole, approval_answer_role = :answerRole, approval_rule_by = :by WHERE workspace_id = :ws AND id = :id',
1098
+ { ...next, id: row.id, by: next.rule !== before.rule ? actor.userId : row.approval_rule_by || null },
1099
+ )
1100
+ actor.audit('agent_approval_rule_changed', row.id, { project: projectId, name: row.name, before, after: next })
1101
+ }
1102
+ return after(projectId, agentId)
1103
+ }
1104
+
1105
+ // Revokes the agent's token. What it held and what waited for it go to
1106
+ // any agent; it stops being the default.
1107
+ function revoke(actor, projectId, agentId) {
1108
+ mayManage(actor)
1109
+ const row = need(projectId, agentId)
1110
+ const result = t.run(
1111
+ 'UPDATE api_tokens SET revoked_at = :at WHERE workspace_id = :ws AND project_id = :project AND id = :id AND revoked_at IS NULL',
1112
+ { at: iso(), project: projectId, id: row.token_id },
1113
+ )
1114
+ if (!result.changes) throw new HttpError(404, 'unknown_agent', 'This agent was already revoked.')
1115
+ actor.audit('token_revoked', row.token_id)
1116
+ return { ok: true, ...afterRevoke(actor, projectId, row.id) }
1117
+ }
1118
+ // What follows a token's revocation, from here or the Tokens page: the
1119
+ // comments it held and the ones that waited for it go to any agent
1120
+ // (releaseAgent), the project loses it as default, and the audit log says
1121
+ // so. Returns { comments, held, wasDefault }.
1122
+ function afterRevoke(actor, projectId, agentId) {
1123
+ forget()
1124
+ const row = need(projectId, agentId)
1125
+ const released = releaseAgent(projectId, row, { audit: actor.audit, reason: 'revoked' })
1126
+ actor.audit('agent_revoked', row.id, {
1127
+ project: projectId,
1128
+ name: row.name,
1129
+ released: released.comments,
1130
+ held: released.held,
1131
+ wasDefault: released.wasDefault,
1132
+ })
1133
+ return released
1134
+ }
1135
+
1136
+ return {
1137
+ ensure,
1138
+ create,
1139
+ get,
1140
+ forToken,
1141
+ idForToken,
1142
+ live,
1143
+ defaultAgent,
1144
+ stateOf,
1145
+ linked,
1146
+ capsOf,
1147
+ hello,
1148
+ helloPolicy,
1149
+ machinePolicy,
1150
+ approvalRules,
1151
+ editMode,
1152
+ answerCheck,
1153
+ editsView,
1154
+ chatCheck,
1155
+ linkView,
1156
+ seen,
1157
+ inAudience,
1158
+ audienceOf,
1159
+ sendCheck,
1160
+ trusted,
1161
+ addressOf,
1162
+ address,
1163
+ release,
1164
+ claimCheck,
1165
+ holds,
1166
+ workCheck,
1167
+ replyVisible,
1168
+ releaseGone,
1169
+ startRun,
1170
+ closeRuns,
1171
+ boardView,
1172
+ boardList,
1173
+ consoleView,
1174
+ consoleList,
1175
+ setIdentity,
1176
+ setDefault,
1177
+ setAudience,
1178
+ setApprovalRule,
1179
+ revoke,
1180
+ afterRevoke,
1181
+ forget,
1182
+ }
1183
+ }
1184
+
1185
+ const pick = (person) => ({ handle: person?.handle || null, displayName: person?.displayName || null })
1186
+ // The later of some ISO times (null when there is none).
1187
+ const latestOf = (...times) => times.filter(Boolean).sort().at(-1) || null
1188
+ // A machine label as `shapewall login` sent it: one short line.
1189
+ function cleanMachine(value) {
1190
+ const text =
1191
+ typeof value === 'string'
1192
+ ? value
1193
+ .replace(/[^\w .-]/g, '')
1194
+ .replace(/\s+/g, ' ')
1195
+ .trim()
1196
+ .slice(0, 40)
1197
+ : ''
1198
+ return text || null
1199
+ }