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,1009 @@
1
+ // Chat with a connected agent, on the board API of a signed-in member
2
+ // (/w/:ws/p/:pid/api/agent/...). The routes copy the local board's shapes
3
+ // (src/agent/routes.js), so the same chat panel talks to both. The server
4
+ // runs no agent: it stores the person's message, hands the turn to the
5
+ // agent's machine over its link (src/hosted/agent-link.js), and relays what
6
+ // comes back to everyone who has the thread open.
7
+ //
8
+ // GET agent/status
9
+ // GET agent/boards/:bid/threads[?q=]
10
+ // GET agent/boards/:bid/threads/:thread
11
+ // POST agent/boards/:bid/threads/:thread/messages (answers with SSE)
12
+ // GET agent/boards/:bid/threads/:thread/events?after=<seq> (SSE)
13
+ // POST agent/boards/:bid/threads/:thread/stop
14
+ // POST agent/boards/:bid/threads/:thread/profile { profileId }
15
+ // PATCH agent/boards/:bid/threads/:thread { title?, archived? }
16
+ // DELETE agent/boards/:bid/threads/:thread
17
+ // POST agent/boards/:bid/threads/:thread/permissions/:id { optionId, hash }
18
+ // GET agent/boards/:bid/permissions the cards that wait for this person
19
+ //
20
+ // "Fix with <agent>" is POST .../threads/comment-<n>/messages { fix: true }:
21
+ // the server takes the comment in the agent's name (the vouch, the claim and
22
+ // the budget are the token API's own, unchanged) and opens the turn itself.
23
+ // Only for an agent whose own machine takes edits from the board; the fix is
24
+ // made on a new branch there, and every edit is a card someone answers here.
25
+ //
26
+ // Two differences from a local board: a turn outlives the request that
27
+ // started it (closing the tab does not stop the agent; Stop does), and
28
+ // `events` lets a second viewer, or a reloaded tab, join a running turn.
29
+ //
30
+ // Who may do what, checked on every route:
31
+ // - members and up only. Never a viewer, a share link guest or a public
32
+ // visitor: this router is mounted on the members' board API alone.
33
+ // - reading: "board" and "comment-<n>" threads, every member; a "chat-..."
34
+ // only the person who started it (anyone else gets 404).
35
+ // - sending: a member the project's agent policy trusts, who is in the
36
+ // audience of the thread's agent (src/hosted/agents.js chatCheck), while
37
+ // that agent's link is open. Nobody talks to an offline agent.
38
+ // - choosing a thread's agent: someone who may use the agent they choose.
39
+ // - Stop: whoever sent the message, the person who connected the agent,
40
+ // and admins.
41
+ // - answering a card: the role the agent's answer setting names (admin by
42
+ // default), in the agent's audience and trusted by the project, and the
43
+ // person who connected it alone when its machine says "owner"
44
+ // (src/hosted/agents.js answerCheck). Allow needs a fresh passkey check.
45
+ // The answer must carry the hash of the card as it was shown, before the
46
+ // card expires (2 minutes), once.
47
+
48
+ import express from 'express'
49
+ import { listJourneys } from '../journeys.js'
50
+ import { MENTION_HANDLE_RE } from '../mentions.js'
51
+ import { commentText } from '../comment-fields.js'
52
+ import { validateFiles } from '../agent/composer.js'
53
+ import { QUERY_MAX, THREAD_RE, CHAT_RE, threadKind } from '../agent/thread-history.js'
54
+ import { agentPolicy, dispatchHash } from './agent-policy.js'
55
+ import { LINK_LIMITS } from './agent-link.js'
56
+ import { LINK_TURNS_MAX } from './agents.js'
57
+ import { CARD_HASH_RE, CARD_ID_RE, cardSubjectHash } from '../agent/card-hash.js'
58
+ import { permissionView } from './chat-permissions.js'
59
+ import { CHAT_LIMITS } from './chat-store.js'
60
+ import { checkStorageQuota } from './comment-files.js'
61
+ import { transaction } from './db.js'
62
+ import { HttpError, fail } from './http.js'
63
+ import { roleAtLeast } from './permissions.js'
64
+ import { LIMITS } from './ratelimit.js'
65
+
66
+ const MENTIONS_MAX = 8
67
+ // One viewer's stream of a turn: how much may wait for a slow reader, and
68
+ // how long a blocked socket is waited for.
69
+ export const FOLLOW = { queueBytes: 4 * 1024 * 1024, stuckMs: 30_000 }
70
+ export const READ_ONLY_NOTE =
71
+ 'This agent reads the project and answers. It does not change files or run commands from the board; send a comment to an agent that runs "shapewall watch --exec" for a fix.'
72
+ // From which agent statuses a comment may be fixed (again).
73
+ const FIXABLE_FROM = [null, 'done', 'needs-human', 'branch-ready']
74
+
75
+ const cut = (value, max) => {
76
+ const text = String(value ?? '')
77
+ .replace(/\s+/g, ' ')
78
+ .trim()
79
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text
80
+ }
81
+
82
+ export function mountChatRoutes(
83
+ boardApi,
84
+ {
85
+ db,
86
+ handle,
87
+ auditOf,
88
+ agentsFor,
89
+ chatFor,
90
+ hub,
91
+ links,
92
+ chat,
93
+ boardContext,
94
+ rateLimiter,
95
+ quotas = null,
96
+ workspaceQuota = undefined,
97
+ policyFor = null,
98
+ freshOrThrow = () => {},
99
+ now = () => new Date(),
100
+ },
101
+ ) {
102
+ const router = express.Router({ mergeParams: true })
103
+ const said = (req) => (action, target, detail) => auditOf(req, action, target, detail)
104
+ const viewerOf = (req, boardId = null) => ({ userId: req.user.id, role: req.role, boardId })
105
+ const quotaOf = (req) => workspaceQuota ?? quotas?.of(req.t.workspaceId).storageBytes ?? Infinity
106
+
107
+ router.use((req, res, next) =>
108
+ roleAtLeast(req.role, 'member') ? next() : fail(res, 403, 'read_only', 'Viewers cannot use agents. Ask an admin for the member role.'),
109
+ )
110
+
111
+ // ---- Which agents ----
112
+
113
+ // The project's agents that chat, as this person may use them.
114
+ function chatAgents(req, boardId) {
115
+ const agents = agentsFor(req.t)
116
+ const list = transaction(db, () => agents.boardList(req.project.id, viewerOf(req, boardId), { boardId, audit: said(req) }))
117
+ return { agents: list.agents.filter((agent) => agent.link?.connected && agent.link.chats), defaultAgentId: list.defaultAgentId }
118
+ }
119
+ // The agent a new thread talks to: the project's default when it chats
120
+ // and this person may use it, else the first one they may use, else the
121
+ // first that chats at all (the composer then says why not).
122
+ const defaultOf = ({ agents, defaultAgentId }) =>
123
+ agents.find((agent) => agent.id === defaultAgentId && agent.chat.ok) ||
124
+ agents.find((agent) => agent.chat.ok) ||
125
+ agents.find((agent) => agent.id === defaultAgentId) ||
126
+ agents[0] ||
127
+ null
128
+ // An agent in the picker's vocabulary (client/src/chat/profiles.js).
129
+ const profileOf = (agent) => ({
130
+ id: agent.id,
131
+ label: agent.name,
132
+ icon: agent.icon,
133
+ tint: agent.tint,
134
+ logo: agent.logo,
135
+ configured: agent.chat.ok,
136
+ state: agent.chat.ok ? (agent.state === 'busy' ? 'starting' : 'ready') : 'unavailable',
137
+ // What stands under its name: where it runs, or why this person cannot use it.
138
+ line: agent.chat.ok
139
+ ? `${agent.state === 'busy' ? 'Answering' : 'Online'}${agent.machine ? ` · ${agent.machine}` : ''}`
140
+ : agent.chat.reason,
141
+ })
142
+ // What the chat panel reads about the agent of a thread.
143
+ const agentInfo = (agent) => ({
144
+ configured: Boolean(agent),
145
+ hosted: true,
146
+ backend: 'hosted',
147
+ label: agent?.name || null,
148
+ icon: agent?.icon || null,
149
+ tint: agent?.tint || null,
150
+ logo: agent?.logo || null,
151
+ machine: agent?.machine || null,
152
+ state: !agent ? 'unavailable' : agent.chat.ok ? 'ready' : 'unavailable',
153
+ local: false,
154
+ host: null,
155
+ sendsKey: false,
156
+ // Images are not sent to a connected agent yet.
157
+ vision: false,
158
+ // Nothing on a hosted board changes the agent's machine directly: a fix
159
+ // is made on a branch there, each edit allowed on a card.
160
+ ownerWrites: false,
161
+ fixWithAgent: false,
162
+ chatNeedsOwner: false,
163
+ readOnly: !agent || agent.edits?.mode === 'none',
164
+ // Edits from the board: the mode, whether this person may press Fix and
165
+ // answer its cards, and why not (src/hosted/agents.js editsView).
166
+ edits: agent?.edits || {
167
+ mode: 'none',
168
+ text: 'Reads and answers',
169
+ commands: 0,
170
+ answer: { ok: false, reason: null },
171
+ fix: { ok: false, reason: null },
172
+ },
173
+ // Whether this person may send it a message now, and why not.
174
+ composer: agent
175
+ ? { ok: agent.chat.ok, code: agent.chat.code, reason: agent.chat.reason }
176
+ : { ok: false, code: 'no_agent', reason: null },
177
+ problem: null,
178
+ })
179
+ const profilesOf = (found) => {
180
+ const fallback = defaultOf(found)
181
+ return [...(fallback ? [{ id: 'default', sameAs: fallback.id, label: fallback.name }] : []), ...found.agents.map(profileOf)]
182
+ }
183
+
184
+ router.get(
185
+ '/status',
186
+ handle((req, res) => {
187
+ const found = chatAgents(req, null)
188
+ res.json({ ...agentInfo(defaultOf(found)), profiles: profilesOf(found) })
189
+ }),
190
+ )
191
+
192
+ // ---- Threads ----
193
+
194
+ // The board, the thread id and (when it has one) its row. A chat that is
195
+ // someone else's does not exist for this person.
196
+ function open(req) {
197
+ const ctx = boardContext(req.t, req.project, req.params.bid)
198
+ const threadId = String(req.params.thread || '')
199
+ if (!THREAD_RE.test(threadId)) throw new HttpError(404, 'unknown_thread', 'No such chat.')
200
+ const store = chatFor(req.t)
201
+ const row = store.thread(req.project.id, ctx.board.id, threadId)
202
+ if (!store.visible(row, threadId, req.user.id)) throw new HttpError(404, 'unknown_thread', 'No such chat.')
203
+ // A comment's thread needs its comment.
204
+ if (threadKind(threadId) === 'comment') ctx.comments.get(Number(threadId.slice(8)))
205
+ return { ctx, threadId, store, row }
206
+ }
207
+ // The live turn of a thread. One the database still calls open but that
208
+ // is gone from memory was cut off by a restart: it ends here.
209
+ function runningOf(req, { ctx, threadId, store }) {
210
+ const live = hub.ofThread(req.t.workspaceId, req.project.id, ctx.board.id, threadId)
211
+ if (live) return live
212
+ const stale = store.openTurn(req.project.id, ctx.board.id, threadId)
213
+ if (stale) chat.interrupt(req.t, stale)
214
+ return null
215
+ }
216
+ // The agent a thread talks to: the one it was given, and no other. A
217
+ // thread nobody chose an agent for gets the default. A thread whose agent
218
+ // is offline, revoked or no longer chats stays that agent's: it is never
219
+ // handed to another one without a person choosing it (`gone`).
220
+ function agentOfThread(found, row) {
221
+ if (!row?.agent_id) return { agent: defaultOf(found), gone: false }
222
+ const agent = found.agents.find((item) => item.id === row.agent_id) || null
223
+ return { agent, gone: !agent }
224
+ }
225
+ const GONE = {
226
+ ok: false,
227
+ code: 'agent_gone',
228
+ reason: "This chat's agent is no longer connected to this project. Choose another agent for this chat.",
229
+ }
230
+
231
+ router.get(
232
+ '/boards/:bid/threads',
233
+ handle((req, res) => {
234
+ const ctx = boardContext(req.t, req.project, req.params.bid)
235
+ const query = typeof req.query.q === 'string' ? req.query.q.slice(0, QUERY_MAX) : ''
236
+ res.json({ threads: chatFor(req.t).list(req.project.id, ctx.board.id, { userId: req.user.id, query }) })
237
+ }),
238
+ )
239
+
240
+ router.get(
241
+ '/boards/:bid/threads/:thread',
242
+ handle((req, res) => {
243
+ const at = open(req)
244
+ const { ctx, threadId, store, row } = at
245
+ const live = runningOf(req, at)
246
+ const found = chatAgents(req, ctx.board.id)
247
+ const { agent, gone } = agentOfThread(found, row)
248
+ res.json({
249
+ id: threadId,
250
+ // Each answer's cards, with their diffs only for the people that agent works for.
251
+ messages: (() => {
252
+ const sees = new Map()
253
+ return store.messages(req.project.id, ctx.board.id, threadId).map((message) => {
254
+ const id = message.agent?.id || null
255
+ if (!sees.has(id)) sees.set(id, seesDiffs(req, ctx.board.id, id))
256
+ return messageFor(message, sees.get(id))
257
+ })
258
+ })(),
259
+ kind: threadKind(threadId),
260
+ title: row?.title || null,
261
+ archived: row?.archived === 1,
262
+ shared: threadKind(threadId) !== 'chat',
263
+ versions: {},
264
+ // The thread's own agent; "default" while nobody chose one.
265
+ profileId: row?.agent_id && found.agents.some((item) => item.id === row.agent_id) ? row.agent_id : 'default',
266
+ profiles: profilesOf(found),
267
+ // A thread whose agent is gone says so; it does not show another agent's name.
268
+ agent: gone ? { ...agentInfo(null), configured: true, label: 'Agent', composer: GONE } : agentInfo(agent),
269
+ running: Boolean(live),
270
+ // A turn to join (GET .../events): its id and who may stop it.
271
+ turn: live
272
+ ? {
273
+ id: live.id,
274
+ mine: live.startedBy === req.user.id,
275
+ canStop: mayStop(req, live),
276
+ }
277
+ : null,
278
+ ratings: {},
279
+ })
280
+ }),
281
+ )
282
+
283
+ // ---- Sending ----
284
+
285
+ // The "@" mentions of a message: [{ kind, id }] -> [{ kind, id, label }],
286
+ // every one on this board. Never a share link guest's comment: its text
287
+ // would ride into the agent's prompt as a label.
288
+ function cleanMentions(ctx, raw) {
289
+ if (raw === undefined || raw === null) return []
290
+ if (!Array.isArray(raw) || raw.length > MENTIONS_MAX)
291
+ throw new HttpError(400, 'bad_mention', `Mention at most ${MENTIONS_MAX} things in a message.`)
292
+ let comments = null
293
+ let journeys = null
294
+ const seen = new Set()
295
+ const out = []
296
+ for (const item of raw) {
297
+ const kind = item?.kind
298
+ let entry = null
299
+ if (kind === 'page') {
300
+ const page = ctx.board.pages.find((value) => value.id === item.id)
301
+ if (page) entry = { kind, id: page.id, label: cut(page.title || page.id, 80) }
302
+ } else if (kind === 'comment' || kind === 'element') {
303
+ comments ||= ctx.comments.list({})
304
+ const found = comments.find((value) => value.id === Number(item.id))
305
+ if (found?.authorGuest) throw new HttpError(400, 'bad_mention', "A share link guest's comment is not sent to an agent.")
306
+ if (found && (kind === 'comment' || found.anchor)) {
307
+ const text = kind === 'element' ? found.anchor?.text || found.anchor?.selector || 'element' : commentText(found)
308
+ entry = { kind, id: found.id, label: cut(`#${found.id} ${text}`, 80) }
309
+ }
310
+ } else if (kind === 'journey') {
311
+ journeys ||= listJourneys(ctx.config, ctx.board)
312
+ const journey = journeys.find((value) => value.id === item.id)
313
+ if (journey) entry = { kind, id: journey.id, label: cut(journey.name || journey.id, 80) }
314
+ } else if (kind === 'person') {
315
+ const handleName = String(item.id || '').toLowerCase()
316
+ if (MENTION_HANDLE_RE.test(handleName)) entry = { kind, id: handleName, label: `@${handleName}` }
317
+ } else throw new HttpError(400, 'bad_mention', 'A mention is a page, comment, journey, element or person.')
318
+ if (!entry) throw new HttpError(400, 'bad_mention', `That ${kind} is not on this board any more. Remove it and send again.`)
319
+ const key = `${entry.kind}:${entry.id}`
320
+ if (seen.has(key)) continue
321
+ seen.add(key)
322
+ out.push(entry)
323
+ }
324
+ return out
325
+ }
326
+
327
+ // ---- Who reads what an agent asked to change ----
328
+
329
+ // The diff on a card is a piece of the project's code. It goes to the
330
+ // people the agent works for: someone in its audience whom the project
331
+ // trusts, whoever may answer its cards, and whoever asked for this turn.
332
+ // Everyone else who can open the thread reads that the agent asked to
333
+ // edit a file, which file, and how that ended. Live and stored alike.
334
+ function seesDiffs(req, boardId, agentId, startedBy = null) {
335
+ if (startedBy && startedBy === req.user.id) return true
336
+ const agents = agentsFor(req.t)
337
+ const agent = agentId ? agents.get(req.project.id, agentId) : null
338
+ if (!agent) return false
339
+ if (agents.inAudience(agent, req.user.id) && agents.trusted(req.project.id, boardId, req.user.id)) return true
340
+ return agents.answerCheck(agent, viewerOf(req, boardId)).ok
341
+ }
342
+ const withoutDiff = (card) =>
343
+ card?.kind === 'permission'
344
+ ? { ...card, diff: null, options: [], hash: undefined, answerable: false, diffHidden: Boolean(card.diff) }
345
+ : card
346
+ const messageFor = (message, sees) =>
347
+ sees || !Array.isArray(message?.cards) ? message : { ...message, cards: message.cards.map(withoutDiff) }
348
+
349
+ // One event stream to the browser, in the shape the local board sends
350
+ // (client/src/chat/stream.js): the turn's events from `after` on, then
351
+ // every new one until it ends. Closing the response only stops listening.
352
+ function follow(req, res, live, after = 0) {
353
+ res.status(200)
354
+ res.setHeader('Content-Type', 'text/event-stream')
355
+ res.setHeader('X-Accel-Buffering', 'no')
356
+ res.flushHeaders()
357
+ let unsubscribe = () => {}
358
+ let done = false
359
+ let ending = false
360
+ // What this viewer has not been sent yet. The socket's own buffer fills
361
+ // while a replay is written or a reader is slow: the rest waits here for
362
+ // `drain`, in order. Only a viewer that stays stuck is let go (too much
363
+ // waiting, or no progress for too long); it comes back with the id of
364
+ // the last event it has (`after`), and misses nothing.
365
+ const queue = []
366
+ let queued = 0
367
+ let blocked = false
368
+ let stuck = null
369
+ const finish = () => {
370
+ if (done) return
371
+ done = true
372
+ clearInterval(timer)
373
+ clearTimeout(stuck)
374
+ unsubscribe()
375
+ res.end()
376
+ }
377
+ const pump = () => {
378
+ while (queue.length && !blocked && !done) {
379
+ const text = queue.shift()
380
+ queued -= text.length
381
+ if (!res.write(text)) {
382
+ blocked = true
383
+ stuck = setTimeout(finish, FOLLOW.stuckMs)
384
+ stuck.unref()
385
+ res.once('drain', () => {
386
+ clearTimeout(stuck)
387
+ blocked = false
388
+ pump()
389
+ })
390
+ }
391
+ }
392
+ if (ending && !queue.length && !blocked) finish()
393
+ }
394
+ const send = (text) => {
395
+ if (done) return
396
+ queue.push(text)
397
+ queued += text.length
398
+ if (queued > FOLLOW.queueBytes) return finish()
399
+ pump()
400
+ }
401
+ const timer = setInterval(() => send(': keepalive\n\n'), 15_000)
402
+ timer.unref()
403
+ const sees = seesDiffs(req, live.boardId, live.agentId, live.startedBy)
404
+ const shown = (event) =>
405
+ sees
406
+ ? event.data
407
+ : event.name === 'tool'
408
+ ? withoutDiff(event.data)
409
+ : event.name === 'done' && event.data?.message
410
+ ? { ...event.data, message: messageFor(event.data.message, false) }
411
+ : event.data
412
+ const subscribed = hub.subscribe(live, after, (event) => {
413
+ if (done) return
414
+ if (event.name === 'end') {
415
+ ending = true
416
+ return pump()
417
+ }
418
+ send(`id: ${event.seq}\nevent: ${event.name}\ndata: ${JSON.stringify(shown(event))}\n\n`)
419
+ })
420
+ if (!subscribed) {
421
+ send(`event: status\ndata: ${JSON.stringify({ text: 'Too many people are watching this answer. Reload in a moment.' })}\n\n`)
422
+ ending = true
423
+ return pump()
424
+ }
425
+ unsubscribe = subscribed
426
+ // The turn may have ended while its events were replayed.
427
+ if (!hub.get(live.id)) {
428
+ ending = true
429
+ pump()
430
+ }
431
+ res.once('close', finish)
432
+ }
433
+
434
+ // ---- Fix with <agent> ----
435
+
436
+ // The server takes the comment for the agent and opens the turn. Every
437
+ // rule of sending a comment to an agent holds, by the same functions: the
438
+ // vouch (a trusted member; a non-admin's run still needs an admin's
439
+ // approval), the agent's audience, the claim with its budgets, one agent
440
+ // at a time on a comment. On top: the agent's own machine must take edits.
441
+ function startFix(req, at) {
442
+ const { ctx, threadId, store } = at
443
+ const body = req.body || {}
444
+ if (threadKind(threadId) !== 'comment') throw new HttpError(400, 'fix_needs_comment', 'Fix with agent starts from a comment.')
445
+ if (!policyFor) throw new HttpError(404, 'not_found', 'Not on this server.')
446
+ const number = Number(threadId.slice(8))
447
+ const agents = agentsFor(req.t)
448
+ const found = chatAgents(req, ctx.board.id)
449
+ if (body.agentId !== undefined && typeof body.agentId !== 'string') throw new HttpError(400, 'invalid_agent', 'agentId: an agent id.')
450
+ const agent = body.agentId ? found.agents.find((item) => item.id === body.agentId) || null : agentOfThread(found, at.row).agent
451
+ if (!agent) throw new HttpError(409, 'no_agent', 'No connected agent of this project can make a fix.')
452
+ if (agent.edits.mode === 'none') throw new HttpError(409, 'read_only_agent', agent.edits.fix.reason || READ_ONLY_NOTE)
453
+ if (!agent.edits.fix.ok)
454
+ throw new HttpError(agent.chat.code === 'agent_audience' ? 403 : 409, agent.chat.code || 'agent_unavailable', agent.edits.fix.reason)
455
+ if (runningOf(req, at)) throw new HttpError(409, 'agent_running', 'Wait for the answer in this chat, or stop it.')
456
+ const maxTurns = agent.link.maxTurns || LINK_TURNS_MAX
457
+ if (hub.ofAgent(req.t.workspaceId, agent.id).length >= maxTurns + LINK_LIMITS.queued)
458
+ throw new HttpError(429, 'agent_busy', `${agent.name} is busy. Try again in a moment.`)
459
+ const sends = rateLimiter.hit('chatSend', req.user.id, LIMITS.chatSend)
460
+ if (!sends.ok) throw new HttpError(429, 'rate_limited', 'That is a lot of requests. Wait a moment and try again.')
461
+ const row = agents.get(req.project.id, agent.id)
462
+ const expect = typeof body.dispatchHash === 'string' ? body.dispatchHash : undefined
463
+ const author = { name: req.user.display_name, handle: req.user.handle }
464
+ // A run that still needs an admin's approval (the project's agent policy
465
+ // asks for one for a non-admin's comment). Either the person pressing Fix
466
+ // may give it: then Fix gives it, with their passkey, and starts. Or they
467
+ // may not: then the comment is really sent for approval (the vouch stays,
468
+ // addressed to this agent, and admins see "Approve agent run" on it), and
469
+ // the answer says so. Never a message about an approval nobody can find.
470
+ const pending = transaction(db, () => {
471
+ const policy = policyFor(req.t)
472
+ const comment = ctx.comments.get(number)
473
+ if (comment.status !== 'open' || ['queued', 'working'].includes(comment.agent_status)) return false
474
+ if (policy.state(req.project.id, ctx.board.id, comment).dispatchable) return false
475
+ const admin = roleAtLeast(req.role, 'admin')
476
+ policy.vouch(req.project.id, ctx.board.id, comment, req.user.id, { role: req.role, approve: false, expect })
477
+ let now2 = ctx.comments.get(number)
478
+ if (!policy.state(req.project.id, ctx.board.id, now2).dispatchable && admin) {
479
+ // An admin's Fix is also their approval of the run: the same passkey check as "Approve agent run".
480
+ freshOrThrow(req)
481
+ policy.vouch(req.project.id, ctx.board.id, now2, req.user.id, { role: req.role, approve: true, expect })
482
+ now2 = ctx.comments.get(number)
483
+ }
484
+ const approvedNow = policy.state(req.project.id, ctx.board.id, now2).dispatchable
485
+ agents.address(req.project.id, ctx.board.id, now2, { userId: req.user.id, role: req.role }, agent.id)
486
+ said(req)('comment_vouched', `${ctx.board.id}#${number}`, {
487
+ project: req.project.id,
488
+ approve: approvedNow && admin,
489
+ agent: agent.id,
490
+ fix: true,
491
+ })
492
+ return !approvedNow
493
+ })
494
+ if (pending) {
495
+ chat.notify(req.t.workspaceId, req.project.id, ctx.board.id, threadId)
496
+ throw new HttpError(
497
+ 409,
498
+ 'run_needs_approval',
499
+ `Sent for approval. An admin has to approve this agent run first (Approve agent run, on the comment). Press Fix with ${agent.name} again after that.`,
500
+ )
501
+ }
502
+ const made = transaction(db, () => {
503
+ const policy = policyFor(req.t)
504
+ const comment = ctx.comments.get(number)
505
+ if (comment.status !== 'open') throw new HttpError(409, 'comment_busy', 'This comment is resolved. Reopen it to fix it.')
506
+ if (['queued', 'working'].includes(comment.agent_status))
507
+ throw new HttpError(409, 'comment_busy', 'This comment is already with an agent.')
508
+ if (!policy.state(req.project.id, ctx.board.id, comment).dispatchable)
509
+ throw new HttpError(409, 'run_needs_approval', 'An admin has to approve this agent run first (Approve agent run, on the comment).')
510
+ if (!agents.trusted(req.project.id, ctx.board.id, req.user.id))
511
+ throw new HttpError(403, 'untrusted_member', 'Only a trusted member may send work to an agent.')
512
+ // For the text this person saw.
513
+ if (expect !== undefined && expect !== dispatchHash(comment))
514
+ throw new HttpError(409, 'comment_changed', 'This comment changed since you opened it. Read it again, then send it.')
515
+ agents.address(req.project.id, ctx.board.id, comment, { userId: req.user.id, role: req.role }, agent.id)
516
+ const fresh = agentsFor(req.t)
517
+ const check = fresh.claimCheck(fresh.get(req.project.id, agent.id), req.project.id, comment)
518
+ if (!check.ok) throw new HttpError(403, check.code, check.message)
519
+ // The claim, in the agent's name: the same budgets as a claim it makes itself.
520
+ const claimId = policy.claim(req.project.id, ctx.board.id, comment, row.token_id, row.id)
521
+ const taken = ctx.comments.setAgentStatus(number, 'queued', { onlyFrom: FIXABLE_FROM }, now())
522
+ if (!taken.changed) throw new HttpError(409, 'comment_busy', 'This comment is already with an agent.')
523
+ const { created } = store.ensure(req.project.id, ctx.board.id, threadId, { userId: req.user.id, agentId: agent.id })
524
+ store.setAgent(req.project.id, ctx.board.id, threadId, agent.id)
525
+ if (created)
526
+ said(req)('chat_thread_created', `${ctx.board.id}/${threadId}`, { project: req.project.id, agent: agent.id, agentName: agent.name })
527
+ const message = store.append(req.project.id, ctx.board.id, threadId, {
528
+ role: 'user',
529
+ userId: req.user.id,
530
+ body: { text: `Fix comment #${number} with ${agent.name}.`, sent: { comment: number }, fix: true, author },
531
+ })
532
+ const turn = store.createTurn({
533
+ projectId: req.project.id,
534
+ boardId: ctx.board.id,
535
+ threadId,
536
+ agentId: agent.id,
537
+ kind: 'fix',
538
+ userId: req.user.id,
539
+ userMessageId: message.id,
540
+ commentNumber: number,
541
+ claimId,
542
+ })
543
+ said(req)('agent_turn_started', turn.id, {
544
+ project: req.project.id,
545
+ agent: agent.id,
546
+ agentName: agent.name,
547
+ board: ctx.board.id,
548
+ thread: threadId,
549
+ kind: 'fix',
550
+ })
551
+ return { message, turn }
552
+ })
553
+ const live = hub.open({
554
+ id: made.turn.id,
555
+ workspaceId: req.t.workspaceId,
556
+ projectId: req.project.id,
557
+ boardId: ctx.board.id,
558
+ threadId,
559
+ agentId: agent.id,
560
+ kind: 'fix',
561
+ startedBy: req.user.id,
562
+ seed: [
563
+ { name: 'user', data: { message: made.message } },
564
+ { name: 'status', data: { text: `Waiting for ${agent.name}` } },
565
+ ],
566
+ })
567
+ if (!links.send(req.t.workspaceId, agent.id, 'work', { turn: made.turn.id }))
568
+ chat.interrupt(req.t, made.turn, {
569
+ message: `${row.name} went offline before it could start. Try again when it is back.`,
570
+ agentName: row.name,
571
+ })
572
+ chat.notify(req.t.workspaceId, req.project.id, ctx.board.id, threadId)
573
+ return live
574
+ }
575
+
576
+ // "Push this fix", asked again: a fix whose edits went without asking is
577
+ // held on the agent's machine until someone has looked at its whole diff.
578
+ // This only asks the machine to show that card again (it has the fix; the
579
+ // server has no repository). Whoever may ask for a fix may ask; the card
580
+ // is then answered by someone who may answer cards, as any other.
581
+ function startPush(req, at) {
582
+ const { ctx, threadId, store } = at
583
+ if (threadKind(threadId) !== 'comment') throw new HttpError(400, 'fix_needs_comment', 'A fix belongs to a comment.')
584
+ const number = Number(threadId.slice(8))
585
+ const found = chatAgents(req, ctx.board.id)
586
+ const { agent, gone } = agentOfThread(found, at.row)
587
+ if (gone || !agent) throw new HttpError(409, 'no_agent', "This comment's agent is not connected.")
588
+ if (agent.edits.mode === 'none' || !agent.edits.fix.ok)
589
+ throw new HttpError(409, agent.chat.code || 'read_only_agent', agent.edits.fix.reason || READ_ONLY_NOTE)
590
+ if (runningOf(req, at)) throw new HttpError(409, 'agent_running', 'Wait for the answer in this chat, or stop it.')
591
+ const maxTurns = agent.link.maxTurns || LINK_TURNS_MAX
592
+ if (hub.ofAgent(req.t.workspaceId, agent.id).length >= maxTurns + LINK_LIMITS.queued)
593
+ throw new HttpError(429, 'agent_busy', `${agent.name} is busy. Try again in a moment.`)
594
+ const sends = rateLimiter.hit('chatSend', req.user.id, LIMITS.chatSend)
595
+ if (!sends.ok) throw new HttpError(429, 'rate_limited', 'That is a lot of requests. Wait a moment and try again.')
596
+ const author = { name: req.user.display_name, handle: req.user.handle }
597
+ const made = transaction(db, () => {
598
+ const message = store.append(req.project.id, ctx.board.id, threadId, {
599
+ role: 'user',
600
+ userId: req.user.id,
601
+ body: { text: `Push the fix of comment #${number}.`, sent: { comment: number }, push: true, author },
602
+ })
603
+ const turn = store.createTurn({
604
+ projectId: req.project.id,
605
+ boardId: ctx.board.id,
606
+ threadId,
607
+ agentId: agent.id,
608
+ kind: 'push',
609
+ userId: req.user.id,
610
+ userMessageId: message.id,
611
+ commentNumber: number,
612
+ })
613
+ said(req)('agent_turn_started', turn.id, {
614
+ project: req.project.id,
615
+ agent: agent.id,
616
+ agentName: agent.name,
617
+ board: ctx.board.id,
618
+ thread: threadId,
619
+ kind: 'push',
620
+ })
621
+ return { message, turn }
622
+ })
623
+ const live = hub.open({
624
+ id: made.turn.id,
625
+ workspaceId: req.t.workspaceId,
626
+ projectId: req.project.id,
627
+ boardId: ctx.board.id,
628
+ threadId,
629
+ agentId: agent.id,
630
+ kind: 'push',
631
+ startedBy: req.user.id,
632
+ seed: [
633
+ { name: 'user', data: { message: made.message } },
634
+ { name: 'status', data: { text: `Waiting for ${agent.name}` } },
635
+ ],
636
+ })
637
+ if (!links.send(req.t.workspaceId, agent.id, 'work', { turn: made.turn.id }))
638
+ chat.interrupt(req.t, made.turn, { message: `${agent.name} went offline. Try again when it is back.`, agentName: agent.name })
639
+ chat.notify(req.t.workspaceId, req.project.id, ctx.board.id, threadId)
640
+ return live
641
+ }
642
+
643
+ router.post('/boards/:bid/threads/:thread/messages', express.json({ limit: '512kb' }), (req, res) => {
644
+ let live
645
+ try {
646
+ const at = open(req)
647
+ const { ctx, threadId, store } = at
648
+ const body = req.body || {}
649
+ if (body.fix || body.push) {
650
+ live = body.fix ? startFix(req, at) : startPush(req, at)
651
+ return follow(req, res, live, 0)
652
+ }
653
+ if (body.editOf || body.regenerate)
654
+ throw new HttpError(
655
+ 400,
656
+ 'not_supported',
657
+ 'Editing a sent message and asking again are not on hosted boards yet. Send a new message.',
658
+ )
659
+ if (Array.isArray(body.attachments) && body.attachments.length)
660
+ throw new HttpError(
661
+ 400,
662
+ 'no_images',
663
+ 'Images are not sent to a connected agent yet. Describe what you see, or mention the page with @.',
664
+ )
665
+ const text = typeof body.text === 'string' ? body.text.replace(/\r\n/g, '\n').trim() : ''
666
+ if (text.length > CHAT_LIMITS.text) throw new HttpError(400, 'text_too_long', `A message is at most ${CHAT_LIMITS.text} characters.`)
667
+ const mentions = cleanMentions(ctx, body.mentions)
668
+ let files
669
+ try {
670
+ files = validateFiles(body.files)
671
+ } catch (error) {
672
+ throw new HttpError(error.status || 400, error.code || 'bad_file', error.message)
673
+ }
674
+ if (!text && !mentions.length && !files.length) throw new HttpError(400, 'empty_message', 'Write a message first.')
675
+
676
+ // Which agent, and whether this person may use it now.
677
+ const agents = agentsFor(req.t)
678
+ const found = chatAgents(req, ctx.board.id)
679
+ const { agent, gone } = agentOfThread(found, at.row)
680
+ if (gone) throw new HttpError(409, GONE.code, GONE.reason)
681
+ if (!agent) throw new HttpError(409, 'no_agent', 'No agent that chats is connected to this project.')
682
+ if (!agent.chat.ok)
683
+ throw new HttpError(agent.chat.code === 'agent_audience' ? 403 : 409, agent.chat.code || 'agent_unavailable', agent.chat.reason)
684
+ const row = agents.get(req.project.id, agent.id)
685
+
686
+ // One answer at a time in a thread; an agent takes only so many.
687
+ if (runningOf(req, at)) throw new HttpError(409, 'agent_running', 'Wait for the answer in this chat, or stop it.')
688
+ const maxTurns = agent.link.maxTurns || LINK_TURNS_MAX
689
+ if (hub.ofAgent(req.t.workspaceId, agent.id).length >= maxTurns + LINK_LIMITS.queued)
690
+ throw new HttpError(429, 'agent_busy', `${agent.name} is busy with other chats. Try again in a moment.`)
691
+ const sends = rateLimiter.hit('chatSend', req.user.id, LIMITS.chatSend)
692
+ if (!sends.ok) {
693
+ res.setHeader('Retry-After', String(sends.retryAfter))
694
+ throw new HttpError(429, 'rate_limited', 'That is a lot of messages. Wait a moment and try again.')
695
+ }
696
+ const policy = agentPolicy(req.t, req.project.id, ctx.board.id)
697
+ if (store.turnsToday(req.project.id) >= policy.dailyTurns)
698
+ throw new HttpError(429, 'turn_budget', "This project has used today's agent turns (the agent policy sets the number).")
699
+
700
+ const author = { name: req.user.display_name, handle: req.user.handle }
701
+ const stored = { text, ...(mentions.length ? { mentions } : {}), ...(files.length ? { files } : {}), author }
702
+ const made = transaction(db, () => {
703
+ checkStorageQuota(req.t, Buffer.byteLength(JSON.stringify(stored)), quotaOf(req))
704
+ const { row: thread, created } = store.ensure(req.project.id, ctx.board.id, threadId, { userId: req.user.id, agentId: agent.id })
705
+ if (!thread.agent_id || thread.agent_id !== agent.id) store.setAgent(req.project.id, ctx.board.id, threadId, agent.id)
706
+ if (created)
707
+ said(req)('chat_thread_created', `${ctx.board.id}/${CHAT_RE.test(threadId) ? 'chat' : threadId}`, {
708
+ project: req.project.id,
709
+ agent: agent.id,
710
+ agentName: agent.name,
711
+ })
712
+ const message = store.append(req.project.id, ctx.board.id, threadId, { role: 'user', userId: req.user.id, body: stored })
713
+ const turn = store.createTurn({
714
+ projectId: req.project.id,
715
+ boardId: ctx.board.id,
716
+ threadId,
717
+ agentId: agent.id,
718
+ userId: req.user.id,
719
+ userMessageId: message.id,
720
+ commentNumber: threadKind(threadId) === 'comment' ? Number(threadId.slice(8)) : null,
721
+ })
722
+ // Who asked which agent, where. Never what.
723
+ said(req)('agent_turn_started', turn.id, {
724
+ project: req.project.id,
725
+ agent: agent.id,
726
+ agentName: agent.name,
727
+ board: ctx.board.id,
728
+ thread: CHAT_RE.test(threadId) ? 'chat' : threadId,
729
+ kind: 'chat',
730
+ })
731
+ return { message, turn }
732
+ })
733
+ live = hub.open({
734
+ id: made.turn.id,
735
+ workspaceId: req.t.workspaceId,
736
+ projectId: req.project.id,
737
+ boardId: ctx.board.id,
738
+ threadId,
739
+ agentId: agent.id,
740
+ startedBy: req.user.id,
741
+ seed: [
742
+ { name: 'user', data: { message: made.message } },
743
+ { name: 'status', data: { text: `Waiting for ${agent.name}` } },
744
+ ],
745
+ })
746
+ // Its machine went away between the check and now: say so at once.
747
+ if (!links.send(req.t.workspaceId, agent.id, 'work', { turn: made.turn.id }))
748
+ chat.interrupt(req.t, made.turn, {
749
+ message: `${row.name} went offline before it could answer. Ask again when it is back.`,
750
+ agentName: row.name,
751
+ })
752
+ chat.notify(req.t.workspaceId, req.project.id, ctx.board.id, threadId)
753
+ } catch (error) {
754
+ if (error?.statusCode && error?.code) return fail(res, error.statusCode, error.code, error.message)
755
+ return fail(res, 500, 'server_error', 'Something went wrong on the server.')
756
+ }
757
+ follow(req, res, live, 0)
758
+ })
759
+
760
+ // A running turn, for a second viewer or a reloaded tab: what happened so
761
+ // far (from `after`), then what happens. 204 when nothing is running.
762
+ router.get('/boards/:bid/threads/:thread/events', (req, res) => {
763
+ let live
764
+ try {
765
+ live = runningOf(req, open(req))
766
+ } catch (error) {
767
+ if (error?.statusCode && error?.code) return fail(res, error.statusCode, error.code, error.message)
768
+ return fail(res, 500, 'server_error', 'Something went wrong on the server.')
769
+ }
770
+ if (!live) return res.status(204).end()
771
+ // Where this viewer is: the id of the last event it has (never 0 again after a dropped stream).
772
+ const after = Number(req.query.after ?? req.headers['last-event-id'])
773
+ follow(req, res, live, Number.isSafeInteger(after) && after > 0 ? after : 0)
774
+ })
775
+
776
+ // ---- Stop ----
777
+
778
+ function mayStop(req, live) {
779
+ if (live.startedBy && live.startedBy === req.user.id) return true
780
+ if (roleAtLeast(req.role, 'admin')) return true
781
+ const agent = agentsFor(req.t).get(req.project.id, live.agentId)
782
+ return Boolean(agent?.created_by) && agent.created_by === req.user.id
783
+ }
784
+ router.post(
785
+ '/boards/:bid/threads/:thread/stop',
786
+ handle((req, res) => {
787
+ const at = open(req)
788
+ const live = runningOf(req, at)
789
+ if (!live) return res.json({ ok: true, running: false })
790
+ if (!mayStop(req, live))
791
+ throw new HttpError(403, 'forbidden', 'Only the person who asked, the person who connected the agent, or an admin stops an answer.')
792
+ const row = at.store.turn(live.id)
793
+ const agent = agentsFor(req.t).get(req.project.id, live.agentId)
794
+ if (!live.cancel) {
795
+ live.cancel = true
796
+ said(req)('agent_turn_stopped', live.id, {
797
+ project: req.project.id,
798
+ agent: live.agentId,
799
+ agentName: agent?.name || null,
800
+ board: at.ctx.board.id,
801
+ thread: CHAT_RE.test(at.threadId) ? 'chat' : at.threadId,
802
+ })
803
+ live.cancelAt = Date.now()
804
+ hub.push(live, 'status', { text: 'Stopping' })
805
+ // Stop cancels what waits for an answer: no card of a stopped turn is answered.
806
+ if (row) transaction(db, () => chat.cancelCards(req.t, row, live))
807
+ // With no machine to hear it, the turn ends here. A machine that
808
+ // does not let go in time is not waited for either (the sweep in
809
+ // agent-link.js ends it as stopped).
810
+ if (!links.send(req.t.workspaceId, live.agentId, 'cancel', { turn: live.id }) && row)
811
+ chat.interrupt(req.t, row, { state: 'stopped', agentName: agent?.name || null })
812
+ }
813
+ res.json({ ok: true, running: Boolean(hub.get(live.id)), turn: row?.id || live.id })
814
+ }),
815
+ )
816
+
817
+ // ---- A thread's agent, name and removal ----
818
+
819
+ router.post(
820
+ '/boards/:bid/threads/:thread/profile',
821
+ handle((req, res) => {
822
+ const at = open(req)
823
+ const { ctx, threadId, store } = at
824
+ const wanted = req.body?.profileId
825
+ if (typeof wanted !== 'string') throw new HttpError(400, 'invalid_agent', 'profileId: an agent of this project.')
826
+ if (runningOf(req, at)) throw new HttpError(409, 'agent_running', 'Wait for the answer or stop it to switch.')
827
+ const found = chatAgents(req, ctx.board.id)
828
+ const agent = wanted === 'default' ? defaultOf(found) : found.agents.find((item) => item.id === wanted)
829
+ if (!agent) throw new HttpError(404, 'unknown_agent', 'No such agent that chats in this project.')
830
+ // Only an agent this person may use: nobody points a shared thread at
831
+ // an agent they could not ask themselves.
832
+ if (!agent.chat.ok && agent.chat.code !== 'agent_offline')
833
+ throw new HttpError(403, agent.chat.code || 'agent_audience', agent.chat.reason)
834
+ transaction(db, () => {
835
+ const { row: before, created } = store.ensure(req.project.id, ctx.board.id, threadId, { userId: req.user.id, agentId: agent.id })
836
+ const from = before.agent_id && before.agent_id !== agent.id ? before.agent_id : null
837
+ store.setAgent(req.project.id, ctx.board.id, threadId, agent.id)
838
+ // A chat with messages changes hands in the open: a line in the
839
+ // thread says who switched it, from which agent to which. (It
840
+ // belongs to no agent, so it is never sent to one.)
841
+ if (from && store.messages(req.project.id, ctx.board.id, threadId).length) {
842
+ const old = agentsFor(req.t).get(req.project.id, from)
843
+ store.append(req.project.id, ctx.board.id, threadId, {
844
+ role: 'assistant',
845
+ body: {
846
+ text: '',
847
+ status: 'done',
848
+ switched: { from: old?.name || null, to: agent.name, by: req.user.display_name },
849
+ cards: [
850
+ {
851
+ id: 'note-switch',
852
+ kind: 'note',
853
+ name: 'note',
854
+ label: `${req.user.display_name} switched this chat ${old?.name ? `from ${old.name} ` : ''}to ${agent.name}. ${agent.name} gets the messages of people it takes work from, and none of ${old?.name || 'the other agent'}'s answers.`,
855
+ },
856
+ ],
857
+ agent: { id: agent.id, name: agent.name },
858
+ },
859
+ })
860
+ said(req)('chat_thread_agent_changed', `${ctx.board.id}/${CHAT_RE.test(threadId) ? 'chat' : threadId}`, {
861
+ project: req.project.id,
862
+ from,
863
+ to: agent.id,
864
+ })
865
+ }
866
+ if (created)
867
+ said(req)('chat_thread_created', `${ctx.board.id}/${CHAT_RE.test(threadId) ? 'chat' : threadId}`, {
868
+ project: req.project.id,
869
+ agent: agent.id,
870
+ agentName: agent.name,
871
+ })
872
+ })
873
+ res.json({ ok: true, profileId: agent.id })
874
+ }),
875
+ )
876
+
877
+ router.patch(
878
+ '/boards/:bid/threads/:thread',
879
+ handle((req, res) => {
880
+ const { ctx, threadId, store, row } = open(req)
881
+ if (!row) throw new HttpError(404, 'unknown_thread', 'No such chat.')
882
+ const { title, archived } = req.body || {}
883
+ if (title !== undefined && typeof title !== 'string') throw new HttpError(400, 'invalid_title', 'title: text.')
884
+ if (archived !== undefined && typeof archived !== 'boolean') throw new HttpError(400, 'invalid_archived', 'archived: true or false.')
885
+ const next = transaction(db, () => store.change(req.project.id, ctx.board.id, threadId, { title, archived }))
886
+ res.json({ thread: { id: threadId, title: next.title || null, archived: next.archived === 1 } })
887
+ }),
888
+ )
889
+
890
+ // Deleting: a chat by the person whose it is; a shared thread (the
891
+ // board's, a comment's) by an admin, since every member reads it.
892
+ router.delete(
893
+ '/boards/:bid/threads/:thread',
894
+ handle((req, res) => {
895
+ const at = open(req)
896
+ const { ctx, threadId, store, row } = at
897
+ if (!row) return res.json({ ok: true })
898
+ if (threadKind(threadId) !== 'chat' && !roleAtLeast(req.role, 'admin'))
899
+ throw new HttpError(403, 'forbidden', 'Everyone in the workspace reads this chat, so only an admin clears it.')
900
+ if (runningOf(req, at)) throw new HttpError(409, 'agent_running', 'Stop the answer first.')
901
+ transaction(db, () => {
902
+ store.remove(req.project.id, ctx.board.id, threadId)
903
+ said(req)('chat_thread_deleted', `${ctx.board.id}/${CHAT_RE.test(threadId) ? 'chat' : threadId}`, { project: req.project.id })
904
+ })
905
+ res.json({ ok: true })
906
+ }),
907
+ )
908
+
909
+ // ---- Permission cards ----
910
+
911
+ // A person answers a card: { optionId: "allow" | "deny" (or null), hash }.
912
+ // Every check is made here, on the server's own record of the card, in the
913
+ // transaction that writes the answer: the card is this thread's running
914
+ // turn's, it still waits and has not expired, the hash is the one of the
915
+ // card as it was shown, and this person may answer this agent's cards.
916
+ // Allow needs a passkey check in the last minutes; Deny does not (it only
917
+ // ever stops something). Then the machine hears it, and checks again.
918
+ router.post(
919
+ '/boards/:bid/threads/:thread/permissions/:permission',
920
+ handle((req, res) => {
921
+ const at = open(req)
922
+ const live = runningOf(req, at)
923
+ const id = String(req.params.permission || '')
924
+ const optionId = req.body?.optionId ?? null
925
+ if (![null, 'allow', 'deny'].includes(optionId)) throw new HttpError(400, 'invalid_answer', 'optionId: "allow" or "deny".')
926
+ const allow = optionId === 'allow'
927
+ const hash = req.body?.hash
928
+ if (!CARD_ID_RE.test(id) || !live) throw new HttpError(409, 'no_permission', 'This request is no longer waiting for an answer.')
929
+ const perms = chat.permsFor(req.t)
930
+ const agents = agentsFor(req.t)
931
+ const row = at.store.turn(live.id)
932
+ const outcome = transaction(db, () => {
933
+ const card = perms.get(live.id, id)
934
+ // Another turn's card, another agent's, a made-up id: all the same.
935
+ if (!card || card.board_id !== at.ctx.board.id || card.thread_id !== at.threadId || card.agent_id !== live.agentId)
936
+ throw new HttpError(409, 'no_permission', 'This request is no longer waiting for an answer.')
937
+ const agent = agents.get(req.project.id, card.agent_id)
938
+ const check = agent ? agents.answerCheck(agent, viewerOf(req, at.ctx.board.id)) : { ok: false, reason: null }
939
+ if (!check.ok) throw new HttpError(403, 'forbidden', check.reason || "You may not answer this agent's requests.")
940
+ if (live.cancel || card.state !== 'pending' || card.expires_at <= now().toISOString())
941
+ throw new HttpError(409, 'no_permission', 'This request is no longer waiting for an answer.')
942
+ if (typeof hash !== 'string' || !CARD_HASH_RE.test(hash) || hash !== card.card_hash)
943
+ throw new HttpError(409, 'permission_changed', 'This is not the request you were shown. Reload and read it again.')
944
+ if (allow) freshOrThrow(req)
945
+ if (!perms.answer(live.id, id, { state: allow ? 'approved' : 'denied', userId: req.user.id }))
946
+ throw new HttpError(409, 'no_permission', 'This request is no longer waiting for an answer.')
947
+ const shown = perms.cardOf(card)
948
+ said(req)(allow ? 'agent_permission_approved' : 'agent_permission_denied', live.id, {
949
+ project: req.project.id,
950
+ agent: card.agent_id,
951
+ agentName: agent.name,
952
+ board: card.board_id,
953
+ thread: card.thread_id,
954
+ card: card.id,
955
+ kind: card.kind,
956
+ cardHash: card.card_hash,
957
+ // The file; a command only as its hash. Never the diff.
958
+ ...(card.kind === 'edit'
959
+ ? { path: shown.detail }
960
+ : card.kind === 'push'
961
+ ? { branch: shown.detail }
962
+ : { commandHash: cardSubjectHash(shown) }),
963
+ })
964
+ return { card: perms.get(live.id, id), owner: check.owner }
965
+ })
966
+ // Everyone watching sees it at once; then the machine hears it.
967
+ hub.push(live, 'tool', permissionView(outcome.card, { name: chat.nameOf(req.t) }))
968
+ links.send(req.t.workspaceId, live.agentId, 'answer', {
969
+ turn: live.id,
970
+ card: id,
971
+ decision: allow ? 'allow' : 'deny',
972
+ hash: outcome.card.card_hash,
973
+ by: { owner: outcome.owner === true },
974
+ })
975
+ if (row) chat.notify(req.t.workspaceId, req.project.id, at.ctx.board.id, at.threadId)
976
+ res.json({ ok: true, state: allow ? 'approved' : 'denied' })
977
+ }),
978
+ )
979
+
980
+ // The cards of this board that wait for this person (for the strip above
981
+ // the board, so an admin sees them with the panel closed). Never a card
982
+ // of someone's private chat, and never one this person may not answer.
983
+ router.get(
984
+ '/boards/:bid/permissions',
985
+ handle((req, res) => {
986
+ const ctx = boardContext(req.t, req.project, req.params.bid)
987
+ const agents = agentsFor(req.t)
988
+ const name = chat.nameOf(req.t)
989
+ const waiting = chat
990
+ .permsFor(req.t)
991
+ .pendingOfBoard(req.project.id, ctx.board.id)
992
+ .filter((card) => hub.get(card.turn_id) && !CHAT_RE.test(card.thread_id))
993
+ .filter((card) => {
994
+ const agent = agents.get(req.project.id, card.agent_id)
995
+ return Boolean(agent) && agents.answerCheck(agent, viewerOf(req, ctx.board.id)).ok
996
+ })
997
+ .map((card) => ({
998
+ ...permissionView(card, { name }),
999
+ thread: card.thread_id,
1000
+ agent: { id: card.agent_id, name: agents.get(req.project.id, card.agent_id)?.name || 'Agent' },
1001
+ }))
1002
+ res.json({ permissions: waiting })
1003
+ }),
1004
+ )
1005
+ router.use((req, res) => fail(res, 404, 'not_found', 'Not on a hosted board.'))
1006
+
1007
+ boardApi.use('/agent', router)
1008
+ return { chatAgents, defaultOf, agentInfo }
1009
+ }