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
@@ -0,0 +1,256 @@
1
+ // What a connected agent's machine may send the server about a chat turn
2
+ // (src/hosted/agent-link.js), cleaned and bounded before anything is shown
3
+ // or stored. The machine is not trusted to keep to the shapes: a stolen
4
+ // agent token can post here too. Everything is copied field by field into
5
+ // new objects with known keys, string lengths and counts capped, so the
6
+ // board renders only what its own components expect. Pure: no database, no
7
+ // request.
8
+
9
+ export const FRAME_LIMITS = {
10
+ // One POST of events.
11
+ batchBytes: 256 * 1024,
12
+ batchEvents: 100,
13
+ // One card (a tool step, the plan, a note).
14
+ cardBytes: 64 * 1024,
15
+ cards: 200,
16
+ text: 100_000,
17
+ reasoning: 20_000,
18
+ // One streamed piece of text.
19
+ chunk: 20_000,
20
+ // The whole job the machine fetches for a turn.
21
+ jobBytes: 2 * 1024 * 1024,
22
+ }
23
+
24
+ const str = (value, max) => (typeof value === 'string' ? value.slice(0, max) : '')
25
+ const optional = (value, max) => (typeof value === 'string' && value ? value.slice(0, max) : null)
26
+ const count = (value) => (Number.isFinite(Number(value)) && Number(value) >= 0 ? Math.min(Math.round(Number(value)), 1e12) : null)
27
+
28
+ // The run summary of a fix (src/remote/agent-fix.js): the branch, whether it
29
+ // was pushed, the pull request, and the files with their line counts. Never
30
+ // a diff: the cards showed those.
31
+ const BRANCH_RE = /^[A-Za-z0-9][A-Za-z0-9_-]*(?:\/[A-Za-z0-9][A-Za-z0-9_-]*)*$/
32
+ const SHA_RE = /^[0-9a-f]{40}([0-9a-f]{24})?$/
33
+ export function cleanSummary(summary) {
34
+ if (!summary || typeof summary !== 'object' || summary.kind !== 'remote-branch') return null
35
+ const branch = summary.branch && typeof summary.branch === 'object' ? summary.branch : {}
36
+ const name = typeof branch.name === 'string' && branch.name.length <= 120 && BRANCH_RE.test(branch.name) ? branch.name : null
37
+ if (!name) return null
38
+ const lines = (value) => (Number.isSafeInteger(value) && value >= 0 ? Math.min(value, 1e7) : null)
39
+ const files = (Array.isArray(summary.files) ? summary.files : []).slice(0, 50).map((file) => ({
40
+ path: str(file?.path, 300),
41
+ status: ['added', 'modified'].includes(file?.status) ? file.status : 'modified',
42
+ added: lines(file?.added),
43
+ removed: lines(file?.removed),
44
+ diff: null,
45
+ }))
46
+ // A pull request: only a URL shaped like one (https://host/owner/repo/pull/7).
47
+ // It is a link only on github.com; on any other host it is shown as text,
48
+ // since this server cannot know which host the project's GitHub is on.
49
+ let pr = null
50
+ try {
51
+ const url = new URL(String(summary.pr?.url || ''))
52
+ if (
53
+ url.protocol === 'https:' &&
54
+ url.href.length <= 300 &&
55
+ !url.username &&
56
+ !url.password &&
57
+ !url.search &&
58
+ !url.hash &&
59
+ /^\/[\w.-]+\/[\w.-]+\/pull\/\d+$/.test(url.pathname)
60
+ )
61
+ pr = {
62
+ url: url.href,
63
+ number: Number(url.pathname.split('/').at(-1)),
64
+ link: url.hostname === 'github.com',
65
+ }
66
+ } catch {
67
+ pr = null
68
+ }
69
+ return {
70
+ kind: 'remote-branch',
71
+ files,
72
+ added: files.reduce((sum, file) => sum + (file.added || 0), 0),
73
+ removed: files.reduce((sum, file) => sum + (file.removed || 0), 0),
74
+ more: lines(summary.more) || 0,
75
+ branch: {
76
+ name,
77
+ commit: SHA_RE.test(String(branch.commit || '')) ? branch.commit : null,
78
+ baseName:
79
+ typeof branch.baseName === 'string' && branch.baseName.length <= 120 && /^[\w./-]+$/.test(branch.baseName) ? branch.baseName : null,
80
+ pushed: branch.pushed === true,
81
+ // Committed on the agent's machine and held there: an edit in it went
82
+ // without asking, so it is pushed only after "Push this fix".
83
+ held: branch.pushed !== true && branch.held === true,
84
+ remote: branch.pushed === true && typeof branch.remote === 'string' && /^[\w.-]{1,60}$/.test(branch.remote) ? branch.remote : null,
85
+ },
86
+ pr: branch.pushed === true ? pr : null,
87
+ }
88
+ }
89
+
90
+ const TOOL_STATES = ['running', 'done', 'error']
91
+ const PERMISSION_STATES = ['denied', 'expired', 'cancelled']
92
+
93
+ // A card of the answer: a tool step, the plan, a note, or a request the
94
+ // machine refused. A permission card is never taken as pending or approved
95
+ // on the machine's word here: one that was asked on the board comes from the
96
+ // server's own record of it (src/hosted/chat-permissions.js, put in its
97
+ // place by the caller), and anything else the machine calls pending or
98
+ // approved is shown as denied.
99
+ export function cleanCard(card) {
100
+ if (!card || typeof card !== 'object' || Array.isArray(card)) return null
101
+ const id = str(card.id, 120)
102
+ if (!id) return null
103
+ const kind = ['tool', 'plan', 'note', 'permission'].includes(card.kind) ? card.kind : 'tool'
104
+ const base = { id, kind, name: str(card.name, 80) || kind, label: str(card.label, 200) || 'Step' }
105
+ // Where the card sits in the answer's text (src/agent/reply-text.js).
106
+ if (Number.isSafeInteger(card.at) && card.at >= 0 && card.at <= FRAME_LIMITS.text) base.at = card.at
107
+ if (kind === 'plan') {
108
+ return {
109
+ ...base,
110
+ entries: (Array.isArray(card.entries) ? card.entries : []).slice(0, 30).map((entry) => ({
111
+ content: str(entry?.content, 200),
112
+ status: ['pending', 'in_progress', 'completed'].includes(entry?.status) ? entry.status : 'pending',
113
+ })),
114
+ }
115
+ }
116
+ if (kind === 'note') return base
117
+ if (kind === 'permission') {
118
+ return {
119
+ ...base,
120
+ detail: optional(card.detail, 5000),
121
+ diff: null,
122
+ state: PERMISSION_STATES.includes(card.state) ? card.state : 'denied',
123
+ options: [],
124
+ chosen: null,
125
+ answeredBy: null,
126
+ expiresAt: null,
127
+ // Nobody answers this card from the board.
128
+ answerable: false,
129
+ }
130
+ }
131
+ return { ...base, state: TOOL_STATES.includes(card.state) ? card.state : 'running', detail: optional(card.detail, 300) }
132
+ }
133
+
134
+ export function cleanUsage(usage) {
135
+ if (!usage || typeof usage !== 'object') return null
136
+ const out = {}
137
+ for (const key of ['input', 'output', 'total', 'cached', 'contextUsed', 'contextSize']) {
138
+ const value = count(usage[key])
139
+ if (value !== null) out[key] = value
140
+ }
141
+ // A cost only when the agent itself reported one (never worked out here).
142
+ const cost = count(usage.costMicros)
143
+ if (cost !== null) out.costMicros = cost
144
+ return Object.keys(out).length ? out : null
145
+ }
146
+
147
+ export function cleanOptions(options) {
148
+ return (Array.isArray(options) ? options : []).slice(0, 4).map((item) => ({
149
+ category: str(item?.category, 40),
150
+ name: str(item?.name, 60),
151
+ value: str(item?.value, 80),
152
+ ...(typeof item?.description === 'string' && item.description ? { description: item.description.slice(0, 160) } : {}),
153
+ }))
154
+ }
155
+
156
+ // One live event of a turn, as the board's stream carries it:
157
+ // [name, data], or null for anything else (dropped).
158
+ export function cleanEvent(event) {
159
+ if (!event || typeof event !== 'object') return null
160
+ const data = event.data && typeof event.data === 'object' ? event.data : {}
161
+ switch (event.name) {
162
+ case 'status':
163
+ return ['status', { text: str(data.text, 200) }]
164
+ case 'text':
165
+ case 'reasoning':
166
+ return typeof data.text === 'string' && data.text ? [event.name, { text: data.text.slice(0, FRAME_LIMITS.chunk) }] : null
167
+ case 'tool': {
168
+ const card = cleanCard(data)
169
+ if (!card || Buffer.byteLength(JSON.stringify(card)) > FRAME_LIMITS.cardBytes) return null
170
+ return ['tool', card]
171
+ }
172
+ case 'usage': {
173
+ const usage = cleanUsage(data)
174
+ return usage ? ['usage', usage] : null
175
+ }
176
+ case 'options':
177
+ return ['options', { options: cleanOptions(data.options) }]
178
+ default:
179
+ return null
180
+ }
181
+ }
182
+
183
+ const ERROR_CODES = /^[a-z][a-z0-9_]{0,39}$/
184
+
185
+ // The answer the machine finished with, as it is stored and shown.
186
+ export function cleanReply(message) {
187
+ const input = message && typeof message === 'object' && !Array.isArray(message) ? message : {}
188
+ const status = ['done', 'stopped', 'error'].includes(input.status) ? input.status : 'done'
189
+ const cards = []
190
+ for (const item of (Array.isArray(input.cards) ? input.cards : []).slice(0, FRAME_LIMITS.cards)) {
191
+ const card = cleanCard(item)
192
+ if (!card || Buffer.byteLength(JSON.stringify(card)) > FRAME_LIMITS.cardBytes) continue
193
+ // A finished answer has no step still running.
194
+ if (card.kind === 'tool' && card.state === 'running') card.state = status === 'done' ? 'done' : 'error'
195
+ cards.push(card)
196
+ }
197
+ const reply = {
198
+ text: str(input.text, FRAME_LIMITS.text),
199
+ cards,
200
+ status,
201
+ }
202
+ const summary = cleanSummary(input.summary)
203
+ if (summary && status === 'done' && !input.error) reply.summary = summary
204
+ const reasoning = str(input.reasoning, FRAME_LIMITS.reasoning)
205
+ if (reasoning) reply.reasoning = reasoning
206
+ const model = optional(input.model, 120)
207
+ if (model) reply.model = model
208
+ if (input.error && typeof input.error === 'object') {
209
+ reply.error = {
210
+ code: ERROR_CODES.test(String(input.error.code || '')) ? input.error.code : 'agent_error',
211
+ message: str(input.error.message, 500) || 'The agent could not answer.',
212
+ ...(optional(input.error.label, 60) ? { label: optional(input.error.label, 60) } : {}),
213
+ ...(optional(input.error.login, 80) ? { login: optional(input.error.login, 80) } : {}),
214
+ }
215
+ if (status === 'done') reply.status = 'error'
216
+ }
217
+ const usage = cleanUsage(input.usage)
218
+ if (usage) reply.usage = usage
219
+ const options = cleanOptions(input.options)
220
+ if (options.length) reply.options = options
221
+ const suggestions = (Array.isArray(input.suggestions) ? input.suggestions : [])
222
+ .filter((item) => typeof item === 'string' && item.trim())
223
+ .slice(0, 3)
224
+ .map((item) => item.trim().slice(0, 80))
225
+ if (suggestions.length && reply.status === 'done') reply.suggestions = suggestions
226
+ const duration = count(input.durationMs)
227
+ if (duration !== null) reply.durationMs = Math.min(duration, 24 * 60 * 60 * 1000)
228
+ if (['stored', 'length'].includes(input.limit)) reply.limit = input.limit
229
+ // Board references the answer's steps read: ids only, checked by the board.
230
+ const refs = input.refs && typeof input.refs === 'object' ? input.refs : null
231
+ if (refs) {
232
+ const comments = (Array.isArray(refs.comments) ? refs.comments : []).filter((id) => Number.isSafeInteger(id) && id > 0).slice(0, 20)
233
+ const pages = (Array.isArray(refs.pages) ? refs.pages : [])
234
+ .filter((id) => typeof id === 'string' && /^[a-z0-9][a-z0-9-]{0,63}$/.test(id))
235
+ .slice(0, 20)
236
+ if (comments.length || pages.length) reply.refs = { comments, pages }
237
+ }
238
+ return reply
239
+ }
240
+
241
+ // What the usage record keeps of an answer (src/hosted/chat-store.js
242
+ // endRun): how it ended and the numbers the agent reported. Never text.
243
+ export function usageOf(reply) {
244
+ const find = (category) => reply.options?.find((item) => item.category === category)?.value || null
245
+ return {
246
+ // A fix that left a branch is "fix_ready".
247
+ outcome: reply.status === 'done' ? (reply.summary ? 'fix_ready' : 'answered') : reply.status === 'stopped' ? 'stopped' : 'failed',
248
+ model: find('model') || reply.model || null,
249
+ effort: find('thought_level'),
250
+ inputTokens: reply.usage?.input ?? null,
251
+ outputTokens: reply.usage?.output ?? null,
252
+ cachedTokens: reply.usage?.cached ?? null,
253
+ costMicros: reply.usage?.costMicros ?? null,
254
+ steps: reply.cards.filter((card) => card.kind === 'tool').length,
255
+ }
256
+ }
@@ -0,0 +1,204 @@
1
+ // The job a connected agent's machine fetches for one chat turn (GET
2
+ // /api/v1/agent/turns/:id, src/hosted/agent-link.js): the conversation and
3
+ // the board around it, as structured data. The server quotes nothing: the
4
+ // machine wraps every piece as untrusted data itself (src/remote/agent-job.js),
5
+ // so a compromised server cannot hand it "instructions" that skip the
6
+ // quoting.
7
+ //
8
+ // What never enters a job:
9
+ // - a share link guest's comment or reply (untrusted text from outside)
10
+ // - a comment by someone outside the agent's audience, or one the token
11
+ // API would hide from this agent's token (not sent to an agent, or
12
+ // sent to another one), unless the person asking wrote it themself:
13
+ // the open comments, the thread's own comment, and what a mention
14
+ // stands for all go through the same check (`commentVisible`), and a
15
+ // mention of a comment the agent may not read keeps only its number
16
+ // - a chat message by someone outside the agent's audience: a person the
17
+ // agent does not take work from cannot steer it by writing in a shared
18
+ // thread before someone it does take work from asks a question
19
+ // - another agent's answers
20
+ // - file URLs, tokens, account ids
21
+ //
22
+ // Pure given its inputs: the caller passes the board context and the stores.
23
+
24
+ import { captureFiles } from '../store.js'
25
+ import { listJourneys } from '../journeys.js'
26
+ import { commentText } from '../comment-fields.js'
27
+ import { commentMentions } from '../mentions.js'
28
+
29
+ export const JOB_LIMITS = { history: 40, comments: 60, text: 8000, person: 10 }
30
+
31
+ const cut = (value, max) => {
32
+ const text = String(value ?? '')
33
+ .replace(/\s+/g, ' ')
34
+ .trim()
35
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text
36
+ }
37
+
38
+ const pageOf = (page) => ({
39
+ id: page.id,
40
+ title: page.title,
41
+ path: page.path,
42
+ group: page.group,
43
+ ...(page.note ? { note: page.note } : {}),
44
+ viewports: page.viewports,
45
+ })
46
+
47
+ // A comment as a list entry: who, where, what. Never a guest's.
48
+ const commentEntry = (comment) => ({
49
+ id: comment.id,
50
+ author: comment.author || null,
51
+ pageId: comment.pageId,
52
+ viewport: comment.viewport,
53
+ status: comment.status,
54
+ agentStatus: comment.agentStatus || null,
55
+ anchor: comment.anchor ? { selector: comment.anchor.selector || null, text: comment.anchor.text || null } : null,
56
+ body: cut(commentText(comment), 1200),
57
+ replies: (comment.replies || []).length,
58
+ createdAt: comment.createdAt,
59
+ })
60
+
61
+ // What a mention stands for, looked up now (the board may have changed
62
+ // since the message was written). null: the thing is gone, the label stays.
63
+ function mentionData(ctx, comments, mention) {
64
+ const board = ctx.board
65
+ if (mention.kind === 'page') {
66
+ const page = board.pages.find((item) => item.id === mention.id)
67
+ return page ? { page: { id: page.id, title: page.title, path: page.path, note: page.note || undefined } } : null
68
+ }
69
+ if (mention.kind === 'comment' || mention.kind === 'element') {
70
+ const comment = comments.find((item) => item.id === Number(mention.id))
71
+ if (!comment || comment.authorGuest) return null
72
+ const page = board.pages.find((item) => item.id === comment.pageId)
73
+ if (mention.kind === 'comment')
74
+ return { comment: commentEntry(comment), page: page ? { id: page.id, title: page.title, path: page.path } : null }
75
+ return {
76
+ element: { selector: comment.anchor?.selector || null, text: comment.anchor?.text || null },
77
+ page: page ? { id: page.id, title: page.title, path: page.path } : { id: comment.pageId },
78
+ viewport: comment.viewport,
79
+ comment: { id: comment.id, body: cut(commentText(comment), 600), status: comment.status },
80
+ }
81
+ }
82
+ if (mention.kind === 'journey') {
83
+ const journey = listJourneys(ctx.config, board).find((item) => item.id === mention.id)
84
+ if (!journey) return null
85
+ const titles = new Map(board.pages.map((page) => [page.id, page.title]))
86
+ return {
87
+ journey: {
88
+ id: journey.id,
89
+ name: journey.name,
90
+ description: journey.description || undefined,
91
+ pages: (journey.pages || []).map((id) => ({ id, title: titles.get(id) || id })),
92
+ },
93
+ }
94
+ }
95
+ if (mention.kind === 'person') {
96
+ const handle = String(mention.id)
97
+ const theirs = comments.filter(
98
+ (comment) =>
99
+ comment.status === 'open' &&
100
+ !comment.authorGuest &&
101
+ (String(comment.authorHandle || '').toLowerCase() === handle || commentMentions(comment).includes(handle)),
102
+ )
103
+ return {
104
+ person: `@${handle}`,
105
+ openComments: theirs.slice(0, JOB_LIMITS.person).map((comment) => ({
106
+ id: comment.id,
107
+ page: comment.pageId,
108
+ author: comment.author || null,
109
+ body: cut(commentText(comment), 300),
110
+ })),
111
+ more: Math.max(0, theirs.length - JOB_LIMITS.person) || undefined,
112
+ }
113
+ }
114
+ return null
115
+ }
116
+
117
+ // `rows`: the thread's stored messages (chat-store rows, oldest first).
118
+ // `inAudience(userId)`: whether the agent takes work from that person.
119
+ // `commentItem(number)`: the thread's comment as this agent's token may
120
+ // read it (replies filtered to its audience), or null.
121
+ // `commentVisible(comment)`: whether this agent may read that comment.
122
+ // `approvals`: the approval rule in effect per kind of request, for a fix.
123
+ export function buildJob({ ctx, turn, agent, rows, inAudience, asker, commentItem, commentVisible, approvals = null }) {
124
+ const board = ctx.board
125
+ const all = ctx.comments.list({})
126
+ const comments = all.filter((comment) => !comment.authorGuest && commentVisible(comment))
127
+ const readable = new Set(comments.map((comment) => comment.id))
128
+ const parse = (row) => {
129
+ try {
130
+ return JSON.parse(row.body)
131
+ } catch {
132
+ return {}
133
+ }
134
+ }
135
+ const kept = rows
136
+ .filter((row) => (row.role === 'user' ? inAudience(row.author_user_id) : row.agent_id === agent.id))
137
+ .slice(-JOB_LIMITS.history)
138
+ // The newest few person messages carry their mentions and files in full;
139
+ // older ones a line each, as on a local board.
140
+ const full = new Set(
141
+ kept
142
+ .filter((row) => row.role === 'user')
143
+ .slice(-2)
144
+ .map((row) => row.id),
145
+ )
146
+ const messages = kept.map((row) => {
147
+ const body = parse(row)
148
+ if (row.role === 'assistant') return { role: 'assistant', text: String(body.text || '').slice(0, 100_000) }
149
+ return {
150
+ role: 'user',
151
+ text: String(body.text || '').slice(0, JOB_LIMITS.text),
152
+ author: body.author?.name || null,
153
+ mentions: (Array.isArray(body.mentions) ? body.mentions : []).slice(0, 8).map((mention) => ({
154
+ kind: mention.kind,
155
+ id: mention.id,
156
+ // The label of a comment is its text: only for a comment the agent may read.
157
+ label:
158
+ ['comment', 'element'].includes(mention.kind) && !readable.has(Number(mention.id))
159
+ ? `#${Number(mention.id) || ''}`
160
+ : cut(mention.label || mention.id, 80),
161
+ ...(full.has(row.id) ? { data: mentionData(ctx, comments, mention) } : {}),
162
+ })),
163
+ files: (Array.isArray(body.files) ? body.files : []).slice(0, 3).map((file) => ({
164
+ name: String(file.name || 'file.txt').slice(0, 120),
165
+ mediaType: String(file.mediaType || 'text/plain').slice(0, 40),
166
+ ...(full.has(row.id) && typeof file.text === 'string' ? { text: file.text.slice(0, 100_000) } : {}),
167
+ })),
168
+ }
169
+ })
170
+ const commentNumber = /^comment-(\d+)$/.exec(turn.thread_id)?.[1]
171
+ const comment = commentNumber && readable.has(Number(commentNumber)) ? commentItem(Number(commentNumber)) : null
172
+ const open = comments.filter((item) => item.status === 'open' && item.id !== Number(commentNumber || 0)).sort((a, b) => b.id - a.id)
173
+ return {
174
+ turn: { id: turn.id, kind: turn.kind, board: board.id, thread: turn.thread_id, comment: commentNumber ? Number(commentNumber) : null },
175
+ agent: { id: agent.id, name: agent.name },
176
+ // Who asked. `owner`: the person who connected this agent.
177
+ asker,
178
+ ...(turn.kind === 'fix'
179
+ ? {
180
+ approvals: {
181
+ edits: approvals?.edits === 'auto' ? 'auto' : 'ask',
182
+ commands: approvals?.commands === 'auto' ? 'auto' : 'ask',
183
+ // The person who connected the agent set the rule themself.
184
+ byOwner: approvals?.byOwner === true,
185
+ },
186
+ }
187
+ : {}),
188
+ messages,
189
+ context: {
190
+ board: { id: board.id, title: board.title, url: board.publicUrl || board.baseUrl || null, pages: board.pages.map(pageOf) },
191
+ // Which pages have a capture, by viewport (names only).
192
+ captures: Object.fromEntries(
193
+ Object.entries(captureFiles(ctx.config, board)).map(([pageId, views]) => [
194
+ pageId,
195
+ Object.fromEntries(Object.keys(views).map((v) => [v, true])),
196
+ ]),
197
+ ),
198
+ counts: ctx.comments.counts(),
199
+ comment,
200
+ comments: open.slice(0, JOB_LIMITS.comments).map(commentEntry),
201
+ commentsLeft: Math.max(0, open.length - JOB_LIMITS.comments),
202
+ },
203
+ }
204
+ }
@@ -0,0 +1,191 @@
1
+ // The permission cards of connected agents on a hosted board (migration
2
+ // 14): what an agent asked to do during a fix (edit a file, run a command),
3
+ // and what became of it. A row is written when the card arrives from the
4
+ // agent's machine, and is the server's own record from then on: who may
5
+ // answer is decided against it, an answer is compared with its hash, and
6
+ // what the board shows of a card comes from it, not from what the machine
7
+ // says later.
8
+ //
9
+ // pending waits for a person, until `expires_at` (2 minutes)
10
+ // approved a person allowed it (answered_by, answered_at)
11
+ // denied a person denied it, or the machine did
12
+ // expired nobody answered in time
13
+ // cancelled the turn was stopped or ended first
14
+ // auto the machine allowed it without asking (its own policy and the
15
+ // agent's approval rule both said so)
16
+ //
17
+ // A card is answered once. Every query goes through the tenant handle `t`.
18
+
19
+ export const PERMISSION_STATES = ['pending', 'approved', 'denied', 'expired', 'cancelled', 'auto']
20
+ export const PERMISSION_LIMITS = {
21
+ // Cards one turn may ask, answered or not: a fix does not ask forever.
22
+ perTurn: 60,
23
+ // Cards of one turn that wait at the same time.
24
+ pendingPerTurn: 5,
25
+ }
26
+
27
+ const parse = (text) => {
28
+ try {
29
+ const value = JSON.parse(text)
30
+ return value && typeof value === 'object' ? value : {}
31
+ } catch {
32
+ return {}
33
+ }
34
+ }
35
+
36
+ export function createPermissionStore(t, { now = () => new Date() } = {}) {
37
+ const iso = () => now().toISOString()
38
+ const get = (turnId, id) =>
39
+ t.get('SELECT * FROM chat_permissions WHERE workspace_id = :ws AND turn_id = :turn AND id = :id', {
40
+ turn: String(turnId || ''),
41
+ id: String(id || ''),
42
+ }) || null
43
+ const ofTurn = (turnId) =>
44
+ t.all('SELECT * FROM chat_permissions WHERE workspace_id = :ws AND turn_id = :turn ORDER BY created_at, rowid', { turn: turnId })
45
+ // A new card of a turn. `card`: its content as hashed (card-hash.js
46
+ // cardContent). Returns the row, or null when the turn already has a card
47
+ // with that id or has asked too much.
48
+ function add(turn, { card, hash, state = 'pending', expiresAt }) {
49
+ const all = ofTurn(turn.id)
50
+ if (all.length >= PERMISSION_LIMITS.perTurn) return null
51
+ if (state === 'pending' && all.filter((row) => row.state === 'pending').length >= PERMISSION_LIMITS.pendingPerTurn) return null
52
+ const result = t.run(
53
+ `INSERT INTO chat_permissions (workspace_id, project_id, id, turn_id, agent_id, board_id, thread_id, kind, card, card_hash, state,
54
+ created_at, expires_at)
55
+ VALUES (:ws, :project, :id, :turn, :agent, :board, :thread, :kind, :card, :hash, :state, :at, :expires)
56
+ ON CONFLICT(workspace_id, turn_id, id) DO NOTHING`,
57
+ {
58
+ project: turn.project_id,
59
+ id: card.id,
60
+ turn: turn.id,
61
+ agent: turn.agent_id,
62
+ board: turn.board_id,
63
+ thread: turn.thread_id,
64
+ kind: card.name,
65
+ card: JSON.stringify(card),
66
+ hash,
67
+ state,
68
+ at: iso(),
69
+ expires: expiresAt,
70
+ },
71
+ )
72
+ return Number(result.changes) ? get(turn.id, card.id) : null
73
+ }
74
+ // A person's answer: only a card that still waits and has not expired, once.
75
+ function answer(turnId, id, { state, userId }) {
76
+ const at = iso()
77
+ const result = t.run(
78
+ `UPDATE chat_permissions SET state = :state, answered_by = :user, answered_at = :at
79
+ WHERE workspace_id = :ws AND turn_id = :turn AND id = :id AND state = 'pending' AND expires_at > :at`,
80
+ { turn: turnId, id, state, user: userId, at },
81
+ )
82
+ return Number(result.changes) > 0
83
+ }
84
+ // What the machine said became of a card nobody answered here: denied,
85
+ // expired or cancelled. Never approved: only a person's answer does that.
86
+ function settle(turnId, id, state) {
87
+ if (!['denied', 'expired', 'cancelled'].includes(state)) return false
88
+ const result = t.run(
89
+ "UPDATE chat_permissions SET state = :state, answered_at = :at WHERE workspace_id = :ws AND turn_id = :turn AND id = :id AND state = 'pending'",
90
+ { turn: turnId, id, state, at: iso() },
91
+ )
92
+ return Number(result.changes) > 0
93
+ }
94
+ // The machine did not take a person's "allow" (it came too late there, or
95
+ // failed its own check): the card is what the machine says it is, and
96
+ // nobody is named as having allowed it.
97
+ function overrule(turnId, id, state) {
98
+ if (!['denied', 'expired', 'cancelled'].includes(state)) return false
99
+ const result = t.run(
100
+ "UPDATE chat_permissions SET state = :state, answered_by = NULL WHERE workspace_id = :ws AND turn_id = :turn AND id = :id AND state = 'approved'",
101
+ { turn: turnId, id, state },
102
+ )
103
+ return Number(result.changes) > 0
104
+ }
105
+ // Cards past their time: expired. Returns the rows that just expired.
106
+ function expire(turnId) {
107
+ const at = iso()
108
+ const due = ofTurn(turnId).filter((row) => row.state === 'pending' && row.expires_at <= at)
109
+ for (const row of due) settle(turnId, row.id, 'expired')
110
+ return due.map((row) => get(turnId, row.id))
111
+ }
112
+ // The turn is over (finished, stopped, interrupted, its agent revoked):
113
+ // whatever still waited is cancelled. Returns those rows.
114
+ function cancelTurn(turnId) {
115
+ const waiting = ofTurn(turnId).filter((row) => row.state === 'pending')
116
+ for (const row of waiting) settle(turnId, row.id, 'cancelled')
117
+ return waiting.map((row) => get(turnId, row.id))
118
+ }
119
+ // The cards of a board that wait for someone, newest first.
120
+ const pendingOfBoard = (projectId, boardId) =>
121
+ t.all(
122
+ `SELECT * FROM chat_permissions WHERE workspace_id = :ws AND project_id = :project AND board_id = :board AND state = 'pending'
123
+ AND expires_at > :at ORDER BY created_at DESC LIMIT 50`,
124
+ { project: projectId, board: boardId, at: iso() },
125
+ )
126
+ const counts = (turnId) => {
127
+ const all = ofTurn(turnId)
128
+ return {
129
+ asked: all.length,
130
+ allowed: all.filter((row) => ['approved', 'auto'].includes(row.state)).length,
131
+ denied: all.filter((row) => ['denied', 'expired', 'cancelled'].includes(row.state)).length,
132
+ }
133
+ }
134
+ const removeThread = (projectId, boardId, threadId) =>
135
+ t.run('DELETE FROM chat_permissions WHERE workspace_id = :ws AND project_id = :project AND board_id = :board AND thread_id = :thread', {
136
+ project: projectId,
137
+ board: boardId,
138
+ thread: threadId,
139
+ })
140
+ const bytes = () => t.get('SELECT COALESCE(SUM(length(card)), 0) AS n FROM chat_permissions WHERE workspace_id = :ws').n
141
+ return {
142
+ get,
143
+ ofTurn,
144
+ add,
145
+ answer,
146
+ settle,
147
+ overrule,
148
+ expire,
149
+ cancelTurn,
150
+ pendingOfBoard,
151
+ counts,
152
+ removeThread,
153
+ bytes,
154
+ cardOf: (row) => parse(row.card),
155
+ }
156
+ }
157
+
158
+ // A stored card as the board shows it. `name(userId)`: a person's display name.
159
+ // A waiting card carries its hash (an answer must send it back) and the two
160
+ // answers there are; a settled one says how it ended and, when a person
161
+ // answered, who.
162
+ export function permissionView(row, { name = () => null } = {}) {
163
+ const card = parse(row.card)
164
+ const pending = row.state === 'pending'
165
+ const state = row.state === 'auto' ? 'approved' : row.state
166
+ return {
167
+ id: row.id,
168
+ kind: 'permission',
169
+ name: card.name,
170
+ label: card.label,
171
+ detail: card.detail,
172
+ diff: card.diff || null,
173
+ state,
174
+ options: pending
175
+ ? [
176
+ { optionId: 'allow', name: 'Allow', kind: 'allow_once' },
177
+ { optionId: 'deny', name: 'Deny', kind: 'reject_once' },
178
+ ]
179
+ : [],
180
+ chosen: row.state === 'auto' ? 'Allowed automatically' : null,
181
+ answeredBy: null,
182
+ // Who answered, by name (the board says "Allowed by ...").
183
+ answeredName: row.answered_by ? name(row.answered_by) : null,
184
+ auto: row.state === 'auto',
185
+ // By this server's clock (the machine counts the same length of time on its own).
186
+ expiresAt: pending ? row.expires_at : null,
187
+ ...(pending ? { hash: row.card_hash } : {}),
188
+ answerable: pending,
189
+ hosted: true,
190
+ }
191
+ }