shapewall 0.3.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/CHANGELOG.md +357 -0
  2. package/NOTICE +7 -0
  3. package/README.md +50 -4
  4. package/THIRD_PARTY.md +39 -0
  5. package/dist/agent/package-lock.json +2 -2
  6. package/dist/client/assets/BoardChat-DdwBcb2N.js +27 -0
  7. package/dist/client/assets/BuzzDialog-DpUcnU6S.js +1 -0
  8. package/dist/client/assets/ChecksPanel-CngYV4yz.js +1 -0
  9. package/dist/client/assets/History-CD0saQA5.js +1 -0
  10. package/dist/client/assets/LocalSettings-MZy2baig.js +1 -0
  11. package/dist/client/assets/{Management-DmTh1-tA.js → Management-CSvZ-SHO.js} +1 -1
  12. package/dist/client/assets/QuickConnect-foLh2QUm.js +1 -0
  13. package/dist/client/assets/ShareDialog-DPWDftoL.js +2 -0
  14. package/dist/client/assets/app-update-dialog-CtiXpTRD.js +1 -0
  15. package/dist/client/assets/{circle-x-3UxAvczM.js → circle-x-CteRBtXC.js} +1 -1
  16. package/dist/client/assets/index-Cxz1UVcV.css +2 -0
  17. package/dist/client/assets/index-uUZVBYUS.js +37 -0
  18. package/dist/client/assets/play-BjRNIGSf.js +1 -0
  19. package/dist/client/assets/{refresh-cw-BRHNyCnY.js → refresh-cw-r_tZiFfB.js} +1 -1
  20. package/dist/client/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  21. package/dist/client/assets/{runtime-Bft6x_6E.js → runtime-Bvq10IhH.js} +1 -1
  22. package/dist/client/assets/ui-zQpn-PdL.js +41 -0
  23. package/dist/client/build-info.json +1 -1
  24. package/dist/client/index.html +4 -3
  25. package/dist/client/sw.js +2 -2
  26. package/dist/console/assets/{LocalAccountsApp-IvHd9zWN.js → LocalAccountsApp-DIdy1KnN.js} +1 -1
  27. package/dist/console/assets/{LocalConsole-DOyLou56.js → LocalConsole-DfcQztF-.js} +1 -1
  28. package/dist/console/assets/{app-update-dialog-Da46CJpv.js → app-update-dialog-ttl9lF5A.js} +1 -1
  29. package/dist/console/assets/console-OqAjD0kV.js +55 -0
  30. package/dist/console/assets/console-kvjrAArQ.css +2 -0
  31. package/dist/console/build-info.json +1 -1
  32. package/dist/console/console.html +2 -2
  33. package/docs/agent-hardening.md +192 -0
  34. package/docs/agent-recipes.md +23 -0
  35. package/docs/agent-workflow.md +5 -0
  36. package/docs/agents.md +74 -6
  37. package/docs/config.md +1 -1
  38. package/docs/deployment.md +2 -0
  39. package/docs/design-system.md +20 -15
  40. package/docs/hosted.md +815 -3
  41. package/docs/where-to-run.md +123 -0
  42. package/package.json +2 -1
  43. package/src/agent/agent-logos.js +81 -0
  44. package/src/agent/backends/acp.js +528 -25
  45. package/src/agent/branch-mode.js +17 -3
  46. package/src/agent/card-hash.js +65 -0
  47. package/src/agent/config.js +27 -2
  48. package/src/agent/context.js +41 -0
  49. package/src/agent/exec-paths.js +105 -0
  50. package/src/agent/icon-store.js +100 -0
  51. package/src/agent/identity.js +77 -0
  52. package/src/agent/owner-mcp.js +19 -3
  53. package/src/agent/routes.js +82 -22
  54. package/src/agent/run.js +14 -2
  55. package/src/agent/settings-routes.js +233 -14
  56. package/src/agent/starter/cli.js +6 -1
  57. package/src/agent/test-timing.js +14 -0
  58. package/src/agent/tools.js +4 -2
  59. package/src/agent/turn-changes.js +70 -8
  60. package/src/agent/user-settings.js +51 -3
  61. package/src/capture/element-map.js +61 -4
  62. package/src/cli/args.js +13 -0
  63. package/src/cli/commands.js +20 -5
  64. package/src/cli/help.js +36 -1
  65. package/src/hosted/admin.js +7 -0
  66. package/src/hosted/agent-approvals.js +28 -3
  67. package/src/hosted/agent-link.js +1032 -0
  68. package/src/hosted/agent-policy.js +10 -3
  69. package/src/hosted/agent-presence.js +81 -0
  70. package/src/hosted/agent-routes.js +135 -0
  71. package/src/hosted/agents.js +1199 -0
  72. package/src/hosted/app.js +94 -4
  73. package/src/hosted/board-routes.js +134 -3
  74. package/src/hosted/chat-frames.js +256 -0
  75. package/src/hosted/chat-job.js +204 -0
  76. package/src/hosted/chat-permissions.js +191 -0
  77. package/src/hosted/chat-routes.js +1009 -0
  78. package/src/hosted/chat-store.js +460 -0
  79. package/src/hosted/comment-files.js +8 -1
  80. package/src/hosted/comments.js +1 -1
  81. package/src/hosted/console-routes.js +58 -1
  82. package/src/hosted/db.js +165 -0
  83. package/src/hosted/device-routes.js +64 -8
  84. package/src/hosted/device.js +35 -4
  85. package/src/hosted/events.js +8 -6
  86. package/src/hosted/membership.js +9 -1
  87. package/src/hosted/pages.js +2 -0
  88. package/src/hosted/permissions.js +38 -0
  89. package/src/hosted/presence.js +18 -1
  90. package/src/hosted/projects.js +60 -2
  91. package/src/hosted/ratelimit.js +8 -0
  92. package/src/hosted/tenancy.js +18 -0
  93. package/src/hosted/token-api.js +118 -15
  94. package/src/hosted/token-events.js +7 -2
  95. package/src/hosted/tokens.js +24 -7
  96. package/src/hosted/turn-hub.js +152 -0
  97. package/src/mcp.js +10 -2
  98. package/src/remote/agent-connect.js +433 -0
  99. package/src/remote/agent-fix.js +611 -0
  100. package/src/remote/agent-job.js +216 -0
  101. package/src/remote/agent-link.js +904 -0
  102. package/src/remote/agent-policy-file.js +242 -0
  103. package/src/remote/credentials.js +35 -1
  104. package/src/remote/login.js +12 -2
  105. package/src/store.js +5 -0
  106. package/dist/client/assets/BoardChat-BeRp6007.js +0 -27
  107. package/dist/client/assets/BuzzDialog-CrYy48hh.js +0 -1
  108. package/dist/client/assets/ChecksPanel-CB820mhj.js +0 -1
  109. package/dist/client/assets/History-Ba909bGJ.js +0 -1
  110. package/dist/client/assets/LocalSettings-ChMi9Zir.js +0 -1
  111. package/dist/client/assets/QuickConnect-CrVweWZB.js +0 -1
  112. package/dist/client/assets/ShareDialog-DO2HhY6g.js +0 -2
  113. package/dist/client/assets/app-update-dialog-C09ODdUQ.js +0 -1
  114. package/dist/client/assets/index-BIjfZKnp.js +0 -37
  115. package/dist/client/assets/index-CXtuJi1K.css +0 -2
  116. package/dist/client/assets/shield-check-DMpniYP6.js +0 -1
  117. package/dist/client/assets/ui-mhL9gsne.js +0 -41
  118. package/dist/console/assets/console-CIBv7cXU.js +0 -55
  119. package/dist/console/assets/console-Fp4k9iyx.css +0 -2
package/src/hosted/app.js CHANGED
@@ -31,7 +31,7 @@ import { listTokens, mountAdmin } from './admin.js'
31
31
  import { createDeviceLogins } from './device.js'
32
32
  import { cleanEmail } from './mail.js'
33
33
  import { mountShareAdmin, mountSharePublic } from './shares.js'
34
- import { createCommentStore } from './comments.js'
34
+ import { REPLY_AUTHOR, createCommentStore } from './comments.js'
35
35
  import { createUsercontent } from './usercontent.js'
36
36
  import { mountRebind, prepareOrigins, previousHostGate } from './rebind.js'
37
37
  import { mountPublicAdmin } from './public.js'
@@ -60,6 +60,12 @@ import { mountDeviceApi } from './device-routes.js'
60
60
  import { createBoardContext } from './board-context.js'
61
61
  import { mountBoardRoutes } from './board-routes.js'
62
62
  import { mountTokenApi } from './token-api.js'
63
+ import { createAgentPresence } from './agent-presence.js'
64
+ import { COMMENT_ROUTING, createAgentStore } from './agents.js'
65
+ import { mountAgentRoutes } from './agent-routes.js'
66
+ import { createAgentLinks, createChatService } from './agent-link.js'
67
+ import { createChatStore } from './chat-store.js'
68
+ import { createTurnHub } from './turn-hub.js'
63
69
  import { mountPages } from './pages.js'
64
70
 
65
71
  export { changeEventType, publicBoardView, TOKEN_SCOPES, INVITE_DAYS }
@@ -131,14 +137,49 @@ export function createHostedApp({
131
137
  deviceLogins ||= createDeviceLogins({ db, now })
132
138
  const ownsEvents = !eventBus
133
139
  const events = eventBus || createEventBus()
140
+ // Which agents are listening right now (in memory only).
141
+ const agentPresence = createAgentPresence({ now })
134
142
  const streams = new Set()
143
+ // Connected agents (`shapewall agent connect`): the chat turns in flight
144
+ // and the open links, in memory (src/hosted/turn-hub.js, agent-link.js).
145
+ const turnHub = createTurnHub({ now: () => now().getTime() })
146
+ const links = createAgentLinks({ hub: turnHub })
147
+ const chatFor = (t) => createChatStore(t, { now })
135
148
  const policyFor = (t) =>
136
149
  createAgentPolicy(t, { now, handleFor: (user) => q.get('SELECT handle FROM users WHERE id = :id', { id: user })?.handle || null })
150
+ const handleFor = (user) => q.get('SELECT handle FROM users WHERE id = :id', { id: user })?.handle || null
151
+ // The agents of a workspace (src/hosted/agents.js), one store per tenant
152
+ // handle: a handle lives for one request, so what the store read once in
153
+ // a request is not read again.
154
+ const agentStores = new WeakMap()
155
+ const agentsFor = (t) => {
156
+ if (!agentStores.has(t)) agentStores.set(t, createAgentStore(t, { now, presence: agentPresence, handleFor, links }))
157
+ return agentStores.get(t)
158
+ }
137
159
  const dispatchView = (t, project, board, comment) => {
138
160
  const row = createCommentStore(t, project, board).get(comment.id)
161
+ const agents = agentsFor(t)
139
162
  // dispatchHash: what "Send to agent" must send back, so a vouch covers
140
163
  // the text its sender saw (src/hosted/board-routes.js).
141
- return { ...comment, ...policyFor(t).state(project, board, row), dispatchHash: dispatchHash(row) }
164
+ return {
165
+ ...comment,
166
+ ...policyFor(t).state(project, board, row),
167
+ dispatchHash: dispatchHash(row),
168
+ // The agent the comment was sent to (null: any agent), and which agent
169
+ // wrote each agent reply, for its face on the thread. Agent ids only.
170
+ agentId: agents.addressOf(project, row),
171
+ replies: comment.replies.map((reply) => {
172
+ const agentId = agents.idForToken(project, reply[REPLY_AUTHOR]?.token)
173
+ return agentId ? { ...reply, agentId } : reply
174
+ }),
175
+ // What decides whether a token may take it (never serialized).
176
+ [COMMENT_ROUTING]: {
177
+ agent_id: row.agent_id || null,
178
+ dispatch_by: row.dispatch_by || null,
179
+ board_id: row.board_id,
180
+ number: row.number,
181
+ },
182
+ }
142
183
  }
143
184
  const q = accounts(db)
144
185
  const iso = (offset = 0) => new Date(now().getTime() + offset).toISOString()
@@ -171,6 +212,10 @@ export function createHostedApp({
171
212
  const SESSION_COOKIE = sessionCookieName(secure)
172
213
  const CEREMONY_COOKIE = secure ? '__Host-sw_ceremony' : 'sw_ceremony'
173
214
 
215
+ // What ends a chat turn from the server's side (the machine went away, a
216
+ // revoked agent, a restart).
217
+ const chat = createChatService({ db, hub: turnHub, links, events, chatFor, now })
218
+
174
219
  const app = express()
175
220
  app.disable('x-powered-by')
176
221
  app.use(publishMutations({ events, streams }))
@@ -226,7 +271,13 @@ export function createHostedApp({
226
271
  // While moving: which origin a request is for; the old one serves only the move.
227
272
  app.use(previousHostGate(sites))
228
273
 
229
- const { publicUser, createWorkspace, acceptInvite, revokeGrantsOf, ownerCount } = createMembership({ db, quotas, iso, auditOf })
274
+ const { publicUser, createWorkspace, acceptInvite, revokeGrantsOf, ownerCount } = createMembership({
275
+ db,
276
+ quotas,
277
+ iso,
278
+ auditOf,
279
+ agentsFor,
280
+ })
230
281
 
231
282
  // ---- Health ----
232
283
  app.get('/api/health', (req, res) => res.json({ ok: true }))
@@ -330,7 +381,7 @@ export function createHostedApp({
330
381
  consoleApi.use(guardWrites)
331
382
  consoleApi.use(express.json({ limit: '64kb' }))
332
383
 
333
- const createApiToken = createApiTokens({ iso, auditOf })
384
+ const createApiToken = createApiTokens({ iso, auditOf, agentsFor })
334
385
  const consoleDeps = {
335
386
  db,
336
387
  dataDir,
@@ -358,6 +409,7 @@ export function createHostedApp({
358
409
  revokeGrantsOf,
359
410
  ownerCount,
360
411
  createApiToken,
412
+ agentsFor,
361
413
  }
362
414
  mountInviteLinks(consoleApi, consoleDeps)
363
415
  // Share link preview and opening: no session, the link is the secret.
@@ -368,11 +420,13 @@ export function createHostedApp({
368
420
  consoleApi.use(needSession)
369
421
  consoleApi.use(limit('session', (req) => req.user.id))
370
422
  mountConsoleRoutes(consoleApi, consoleDeps)
423
+ mountAgentRoutes(consoleApi, consoleDeps)
371
424
  mountAdmin(consoleApi, deps)
372
425
  mountShareAdmin(consoleApi, deps)
373
426
  mountPublicAdmin(consoleApi, deps)
374
427
 
375
428
  const { approvalApi } = mountBoardRoutes(app, {
429
+ agentPresence,
376
430
  db,
377
431
  dataDir,
378
432
  iso,
@@ -390,17 +444,23 @@ export function createHostedApp({
390
444
  auditOf,
391
445
  clientIp,
392
446
  policyFor,
447
+ agentsFor,
393
448
  dispatchView,
394
449
  boardContext,
395
450
  cleaner,
396
451
  quotas,
397
452
  workspaceQuota,
398
453
  deps,
454
+ chatFor,
455
+ hub: turnHub,
456
+ links,
457
+ chat,
399
458
  })
400
459
 
401
460
  mountDeviceApi(app, consoleDeps)
402
461
 
403
462
  const { v1, tokenAuth } = mountTokenApi({
463
+ agentPresence,
404
464
  db,
405
465
  dataDir,
406
466
  iso,
@@ -418,10 +478,15 @@ export function createHostedApp({
418
478
  auditOf,
419
479
  clientIp,
420
480
  policyFor,
481
+ agentsFor,
421
482
  boardContext,
422
483
  dispatchView,
423
484
  needFresh,
424
485
  approvalApi,
486
+ chatFor,
487
+ hub: turnHub,
488
+ links,
489
+ chat,
425
490
  })
426
491
  // The token API first: it never falls through to the cookie-based console API.
427
492
  mountMcpHttp(app, { tokenAuth, origin: publicOrigin, dataDir, db })
@@ -481,6 +546,25 @@ export function createHostedApp({
481
546
  if (!guestOnly) sweep()
482
547
  const sweepTimer = !guestOnly && sweepEveryMs ? setInterval(sweep, sweepEveryMs) : null
483
548
  sweepTimer?.unref()
549
+ // No turn survives a restart: what the database still calls running ends here.
550
+ if (!guestOnly) {
551
+ try {
552
+ chat.sweepStale()
553
+ } catch (error) {
554
+ log(`turn sweep at start: ${error.message}`)
555
+ }
556
+ }
557
+ // Chat turns whose machine went away end as interrupted (unref'd too).
558
+ const turnTimer = guestOnly
559
+ ? null
560
+ : setInterval(() => {
561
+ try {
562
+ chat.sweep()
563
+ } catch (error) {
564
+ log(`turn sweep: ${error.message}`)
565
+ }
566
+ }, 5000)
567
+ turnTimer?.unref()
484
568
  const ownsPresence = !presenceHub
485
569
  const hub = presenceHub || createPresenceHub({ events })
486
570
  // A WebSocket upgrade never passes through Express, so its address is
@@ -502,6 +586,9 @@ export function createHostedApp({
502
586
  const presence = hub.listener(presenceAuthorizer({ db, dataDir, origin: publicOrigin, auth, now, guestOnly }), { clientIp: upgradeIp })
503
587
  app.locals.presence = { attach: presence.attach, close: presence.close, hub }
504
588
  app.locals.events = events
589
+ app.locals.agentPresence = agentPresence
590
+ app.locals.agentsFor = agentsFor
591
+ app.locals.chat = { hub: turnHub, links, service: chat, storeFor: chatFor }
505
592
  app.locals.sweep = sweep
506
593
  app.locals.close = async () => {
507
594
  presence.close()
@@ -509,6 +596,9 @@ export function createHostedApp({
509
596
  if (ownsEvents) events.close()
510
597
  for (const check of [...streams]) check(true)
511
598
  if (sweepTimer) clearInterval(sweepTimer)
599
+ if (turnTimer) clearInterval(turnTimer)
600
+ chat.close()
601
+ links.closeAll()
512
602
  await cleaner.close()
513
603
  }
514
604
  return app
@@ -13,6 +13,7 @@ import { avatarUrl } from '../accounts/avatar.js'
13
13
  import { checksView, readReport } from '../checks/store.js'
14
14
  import { agentPolicy } from './agent-policy.js'
15
15
  import { hostedBoardView, sendPng } from './board-context.js'
16
+ import { mountChatRoutes } from './chat-routes.js'
16
17
  import { guestView, rowToComment } from './comments.js'
17
18
  import { transaction } from './db.js'
18
19
  import { publicView } from './guest-view.js'
@@ -29,6 +30,7 @@ import { roleAtLeast, tenant } from './tenancy.js'
29
30
  export function mountBoardRoutes(
30
31
  app,
31
32
  {
33
+ agentPresence = null,
32
34
  db,
33
35
  dataDir,
34
36
  iso,
@@ -46,6 +48,7 @@ export function mountBoardRoutes(
46
48
  auditOf,
47
49
  clientIp,
48
50
  policyFor,
51
+ agentsFor,
49
52
  dispatchView,
50
53
  boardContext,
51
54
  // Cleans comment images off the event loop (src/hosted/cleaner.js).
@@ -55,6 +58,11 @@ export function mountBoardRoutes(
55
58
  workspaceQuota = undefined,
56
59
  // What readGuest needs (the shared deps of src/hosted/app.js).
57
60
  deps,
61
+ // Chat with connected agents (src/hosted/chat-routes.js): members only.
62
+ chatFor = null,
63
+ hub = null,
64
+ links = null,
65
+ chat = null,
58
66
  },
59
67
  ) {
60
68
  // ---- Usercontent: live HTML through signed URLs ----
@@ -75,7 +83,8 @@ export function mountBoardRoutes(
75
83
  // New comments and replies may carry images (base64, 4 of 5 MB): their
76
84
  // body is read after the session and role checks, with its own limit
77
85
  // (mediaBody); every other route keeps 64 kB.
78
- const MEDIA_POST_RE = /^\/boards\/[^/]+\/comments(?:\/[^/]+\/replies)?\/?$/
86
+ // A chat message to a connected agent has its own limit too (chat-routes.js).
87
+ const MEDIA_POST_RE = /^\/(?:boards\/[^/]+\/comments(?:\/[^/]+\/replies)?|agent\/boards\/[^/]+\/threads\/[^/]+\/messages)\/?$/
79
88
  const skipMedia = (parser) => (req, res, next) =>
80
89
  req.method === 'POST' && MEDIA_POST_RE.test(req.path) ? next() : parser(req, res, next)
81
90
  boardApi.use(skipMedia(express.json({ limit: '64kb' })))
@@ -109,11 +118,45 @@ export function mountBoardRoutes(
109
118
  }),
110
119
  )
111
120
 
121
+ // The project's agents as this person may see and use them, for the
122
+ // board's Agent panel and "Send to agent": names, faces, states, what each
123
+ // holds on this board, and whether this person may send it work (with the
124
+ // reason when not). Members and viewers only: this router is never
125
+ // mounted for a share link's guests or a public project's visitors. No
126
+ // token ids, prefixes or scopes, and no account ids.
127
+ boardApi.get(
128
+ '/boards/:bid/agents',
129
+ handle((req, res) => {
130
+ const ctx = boardContext(req.t, req.project, req.params.bid)
131
+ // Reading the list is also where an agent that is gone lets go of its
132
+ // work, and where a token from an older build is first seen.
133
+ const audit = (action, target, detail) => auditOf(req, action, target, detail)
134
+ res.json(
135
+ transaction(db, () =>
136
+ agentsFor(req.t).boardList(req.project.id, { userId: req.user.id, role: req.role }, { boardId: ctx.board.id, audit }),
137
+ ),
138
+ )
139
+ }),
140
+ )
141
+ const actorOf = (req) => ({
142
+ userId: req.user.id,
143
+ role: req.role,
144
+ audit: (action, target, detail) => auditOf(req, action, target, detail),
145
+ })
146
+
147
+ // Sends a comment to an agent. `agentId` names one agent of the project
148
+ // (the sender must be in its audience), null means any agent, and without
149
+ // it the project's default agent is used when the sender may use it (any
150
+ // agent otherwise). An admin's approval of a run someone else asked for
151
+ // keeps where that comment was going.
112
152
  boardApi.post(
113
153
  '/boards/:bid/comments/:cid/send-to-agent',
114
154
  handle((req, res) => {
115
155
  const ctx = boardContext(req.t, req.project, req.params.bid)
116
156
  const approve = req.body?.approve === true
157
+ const named = Object.hasOwn(req.body || {}, 'agentId')
158
+ if (named && req.body.agentId !== null && typeof req.body.agentId !== 'string')
159
+ throw new HttpError(400, 'invalid_agent', 'agentId: an agent id, or null for any agent.')
117
160
  // The vouch covers the text its sender saw: the body carries the
118
161
  // comment's dispatchHash (from the board API), compared with the row
119
162
  // in the transaction that writes the vouch. Edited meanwhile: 409
@@ -125,14 +168,75 @@ export function mountBoardRoutes(
125
168
  if (!roleAtLeast(req.role, 'admin')) throw new HttpError(403, 'forbidden', 'Only trusted admins approve runs.')
126
169
  freshOrThrow(req)
127
170
  }
171
+ const agents = agentsFor(req.t)
172
+ const going = agents.addressOf(req.project.id, current)
173
+ const wanted = named ? req.body.agentId : approve && current.dispatch_hash ? going : undefined
174
+ // Work an agent already took stays with it, and so does the approval
175
+ // it was taken under: sending it again changes nothing (not who
176
+ // vouched for it, not where it goes), and sending it elsewhere is
177
+ // refused. Without a named agent (an older board) it is "again".
178
+ if (['queued', 'working'].includes(current.agent_status)) {
179
+ if (!roleAtLeast(req.role, 'member') || !agents.trusted(req.project.id, ctx.board.id, req.user.id))
180
+ throw new HttpError(403, 'untrusted_member', 'Only a trusted member may send work to an agent.')
181
+ if (named && wanted !== going) throw new HttpError(409, 'agent_working', 'An agent is already working on this comment.')
182
+ return current
183
+ }
128
184
  policyFor(req.t).vouch(req.project.id, ctx.board.id, current, req.user.id, { role: req.role, approve, expect })
129
- auditOf(req, 'comment_vouched', `${ctx.board.id}#${current.number}`, { project: req.project.id, approve })
185
+ // After the vouch (which refuses people the agent policy does not
186
+ // trust): the audience of the agent it is sent to, checked for the
187
+ // sender, and for the admin who approves someone else's run.
188
+ const agent = agents.address(req.project.id, ctx.board.id, current, { userId: req.user.id, role: req.role }, wanted)
189
+ auditOf(req, 'comment_vouched', `${ctx.board.id}#${current.number}`, { project: req.project.id, approve, agent })
130
190
  return current
131
191
  })
132
192
  res.json({ comment: dispatchView(req.t, req.project.id, ctx.board.id, rowToComment(ctx.comments.get(row.number))) })
133
193
  }),
134
194
  )
135
195
 
196
+ // "Let any agent take it": a comment that waits for one agent (it is
197
+ // offline, say) goes to whichever agent takes it first. For the people who
198
+ // may send comments to an agent here; not once an agent has taken it.
199
+ boardApi.post(
200
+ '/boards/:bid/comments/:cid/release-agent',
201
+ handle((req, res) => {
202
+ const ctx = boardContext(req.t, req.project, req.params.bid)
203
+ const agents = agentsFor(req.t)
204
+ transaction(db, () => {
205
+ const current = ctx.comments.get(req.params.cid)
206
+ if (!roleAtLeast(req.role, 'member') || !agents.trusted(req.project.id, ctx.board.id, req.user.id))
207
+ throw new HttpError(403, 'untrusted_member', 'Only a trusted member may send work to an agent.')
208
+ if (['queued', 'working'].includes(current.agent_status))
209
+ throw new HttpError(409, 'agent_working', 'An agent is already working on this comment.')
210
+ agents.release(actorOf(req), req.project.id, ctx.board.id, current)
211
+ })
212
+ res.json({ comment: dispatchView(req.t, req.project.id, ctx.board.id, rowToComment(ctx.comments.get(req.params.cid))) })
213
+ }),
214
+ )
215
+
216
+ // Chat with the project's connected agents: on the members' API only.
217
+ // A share link's guests and a public project's visitors have no such
218
+ // routes at all (their routers below never mount them).
219
+ const chatApi =
220
+ chatFor && hub && links && chat
221
+ ? mountChatRoutes(boardApi, {
222
+ db,
223
+ handle,
224
+ auditOf,
225
+ agentsFor,
226
+ chatFor,
227
+ hub,
228
+ links,
229
+ chat,
230
+ boardContext,
231
+ rateLimiter,
232
+ quotas,
233
+ workspaceQuota,
234
+ policyFor,
235
+ freshOrThrow,
236
+ now,
237
+ })
238
+ : null
239
+
136
240
  const shareApi = express.Router({ mergeParams: true })
137
241
  shareApi.use((req, res, next) => {
138
242
  res.setHeader('Cache-Control', 'no-store')
@@ -301,6 +405,16 @@ export function mountBoardRoutes(
301
405
  app.use('/s/:sid/api', shareApi)
302
406
  app.use('/p/:pubid/api', publicApi)
303
407
 
408
+ function hostedAgentInfo(req) {
409
+ try {
410
+ const found = chatApi.chatAgents(req, null)
411
+ if (!found.agents.length) return {}
412
+ return { agent: chatApi.agentInfo(chatApi.defaultOf(found)) }
413
+ } catch {
414
+ return {}
415
+ }
416
+ }
417
+
304
418
  function boardRoutes(router) {
305
419
  router.get('/info', (req, res) =>
306
420
  res.json({
@@ -316,6 +430,10 @@ export function mountBoardRoutes(
316
430
  consoleUrl: `/w/${req.t.workspaceId}`,
317
431
  // The board header's way back to the project's page in the console.
318
432
  project: { id: req.project.id, name: req.project.name, url: `/w/${req.t.workspaceId}/projects/${req.project.id}` },
433
+ // Chat with a connected agent: for members and up, once an agent
434
+ // that chats is connected to the project (online or not). Never for
435
+ // a share link's guest or a public visitor (their /info is their own).
436
+ ...(router === boardApi && chatApi && roleAtLeast(req.role, 'member') ? hostedAgentInfo(req) : {}),
319
437
  }),
320
438
  )
321
439
 
@@ -340,6 +458,12 @@ export function mountBoardRoutes(
340
458
  ...hostedBoardView(ctx),
341
459
  agentDispatch: Boolean(trusted),
342
460
  agentApprove: Boolean(trusted && roleAtLeast(req.role, 'admin')),
461
+ // Whether an agent is listening for this project, for members
462
+ // only (never a share link guest or a public viewer): the token's
463
+ // display name and when it was last heard from.
464
+ ...(agentPresence && !req.guest && !req.publicViewer
465
+ ? { agentListening: agentPresence.of(req.t.workspaceId, req.project.id) }
466
+ : {}),
343
467
  })
344
468
  }),
345
469
  )
@@ -429,7 +553,14 @@ export function mountBoardRoutes(
429
553
  const comment = transaction(db, () => {
430
554
  checkStorageQuota(req.t, imageBytes(media), quotaOf(req))
431
555
  const made = ctx.comments.create(ctx.config, ctx.board, req.body, authorOf(req), now(), media)
432
- if (!req.guest) policyFor(req.t).autoVouch(req.project.id, ctx.board.id, ctx.comments.get(made.id), req.user.id, req.role)
556
+ if (!req.guest) {
557
+ policyFor(req.t).autoVouch(req.project.id, ctx.board.id, ctx.comments.get(made.id), req.user.id, req.role)
558
+ // Vouched for as it was written: it goes to the project's default
559
+ // agent when its author may use that agent, to any agent otherwise.
560
+ const vouched = ctx.comments.get(made.id)
561
+ if (vouched.dispatch_hash)
562
+ agentsFor(req.t).address(req.project.id, ctx.board.id, vouched, { userId: req.user.id, role: req.role }, undefined)
563
+ }
433
564
  if (req.guest) auditOf(req, 'guest_commented', `${ctx.board.id}#${made.id}`, { project: req.project.id, guest: req.guest.name })
434
565
  return made
435
566
  })