shapewall 0.0.0-stage → 0.2.2

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 (304) hide show
  1. package/CHANGELOG.md +139 -0
  2. package/Dockerfile.agent +45 -0
  3. package/LICENSE +202 -0
  4. package/NOTICE +12 -0
  5. package/README.md +651 -2
  6. package/THIRD_PARTY.md +165 -0
  7. package/bin/shapewall.js +29 -0
  8. package/dist/agent/package-lock.json +8384 -0
  9. package/dist/client/assets/BoardChat-D5SFd8HE.js +28 -0
  10. package/dist/client/assets/BuzzDialog-HWXBy52W.js +1 -0
  11. package/dist/client/assets/ChecksPanel-DTdImWoD.js +1 -0
  12. package/dist/client/assets/History-CEv6b-av.js +1 -0
  13. package/dist/client/assets/LocalSettings-C4vriEVQ.js +1 -0
  14. package/dist/client/assets/Management-DCfhcEUY.js +1 -0
  15. package/dist/client/assets/QuickConnect-DQGgUsl1.js +1 -0
  16. package/dist/client/assets/ShareDialog-C_plIto0.js +2 -0
  17. package/dist/client/assets/app-update-dialog-2hPz_N9G.js +1 -0
  18. package/dist/client/assets/circle-x-BZMPi8Zf.js +1 -0
  19. package/dist/client/assets/index-ByQRKVit.css +2 -0
  20. package/dist/client/assets/index-DweQ8Qtu.js +29 -0
  21. package/dist/client/assets/refresh-cw-CRow0Nbq.js +1 -0
  22. package/dist/client/assets/runtime-Bft6x_6E.js +4 -0
  23. package/dist/client/assets/square-A8EnIYLR.js +1 -0
  24. package/dist/client/assets/tts-dist-DYlBQmwG.js +18 -0
  25. package/dist/client/assets/tts-en-g2p-BPUtBFGG.js +1 -0
  26. package/dist/client/assets/tts-ort-wasm-simd-threaded-qh98TCA_.wasm +0 -0
  27. package/dist/client/assets/tts-ort.wasm.bundle.min-rEkcs_ow.js +12 -0
  28. package/dist/client/assets/tts-rolldown-runtime-D8NudN84.js +1 -0
  29. package/dist/client/assets/tts-spacy-en-tokenizer-6SNMl--A.json +1 -0
  30. package/dist/client/assets/tts-tts.worker-Bzm6aWbv.js +1 -0
  31. package/dist/client/assets/tts-us_gold-DcjeNMH1.json +92589 -0
  32. package/dist/client/assets/tts-us_silver-C964mEB5.json +93363 -0
  33. package/dist/client/assets/ui-CLbws0rx.js +41 -0
  34. package/dist/client/build-info.json +1 -0
  35. package/dist/client/favicon.svg +7 -0
  36. package/dist/client/icons/apple-touch-icon.png +0 -0
  37. package/dist/client/icons/icon-192.png +0 -0
  38. package/dist/client/icons/icon-512.png +0 -0
  39. package/dist/client/icons/maskable-512.png +0 -0
  40. package/dist/client/index.html +25 -0
  41. package/dist/client/manifest.webmanifest +15 -0
  42. package/dist/client/sw.js +53 -0
  43. package/dist/client/theme-boot.js +27 -0
  44. package/dist/console/assets/LocalAccountsApp-BQCcmj3x.js +1 -0
  45. package/dist/console/assets/LocalConsole-Bb2FUDs7.js +1 -0
  46. package/dist/console/assets/app-update-dialog-DIeYepLZ.js +1 -0
  47. package/dist/console/assets/console-C7uJLLOn.js +51 -0
  48. package/dist/console/assets/console-R8IBY3Am.css +2 -0
  49. package/dist/console/build-info.json +1 -0
  50. package/dist/console/console.html +21 -0
  51. package/dist/console/favicon.svg +7 -0
  52. package/dist/console/icons/apple-touch-icon.png +0 -0
  53. package/dist/console/icons/icon-192.png +0 -0
  54. package/dist/console/icons/icon-512.png +0 -0
  55. package/dist/console/icons/maskable-512.png +0 -0
  56. package/dist/console/manifest.webmanifest +15 -0
  57. package/dist/console/theme-boot.js +27 -0
  58. package/docs/agent-hardening.md +342 -0
  59. package/docs/agent-recipes.md +187 -0
  60. package/docs/agent-workflow.md +320 -0
  61. package/docs/agents.md +894 -0
  62. package/docs/architecture.md +242 -0
  63. package/docs/buzz.md +140 -0
  64. package/docs/capture-warnings.md +57 -0
  65. package/docs/config.md +489 -0
  66. package/docs/deployment.md +289 -0
  67. package/docs/design-system.md +162 -0
  68. package/docs/github.md +107 -0
  69. package/docs/hosted.md +764 -0
  70. package/docs/images/board-overview.png +0 -0
  71. package/docs/images/journeys.png +0 -0
  72. package/docs/images/live-comment.png +0 -0
  73. package/docs/images/phone-comment.png +0 -0
  74. package/docs/images/phone-overview.png +0 -0
  75. package/docs/images/variant.png +0 -0
  76. package/docs/interaction-audits.md +40 -0
  77. package/docs/journeys.md +137 -0
  78. package/docs/local-accounts.md +80 -0
  79. package/docs/notifications.md +237 -0
  80. package/docs/page-checks.md +69 -0
  81. package/docs/performance.md +174 -0
  82. package/docs/starter-agent.md +325 -0
  83. package/docs/updates.md +87 -0
  84. package/examples/audits/interaction.audit.json +17 -0
  85. package/package.json +132 -4
  86. package/src/accounts/avatar.js +121 -0
  87. package/src/accounts/local.js +464 -0
  88. package/src/agent/acp/command.js +204 -0
  89. package/src/agent/acp/detect.js +75 -0
  90. package/src/agent/acp/sandbox.js +160 -0
  91. package/src/agent/agent-health.js +75 -0
  92. package/src/agent/backends/acp.js +1297 -0
  93. package/src/agent/backends/index.js +61 -0
  94. package/src/agent/backends/openai.js +308 -0
  95. package/src/agent/composer.js +221 -0
  96. package/src/agent/config.js +338 -0
  97. package/src/agent/context.js +191 -0
  98. package/src/agent/control.js +122 -0
  99. package/src/agent/errors.js +17 -0
  100. package/src/agent/feedback-loop.js +137 -0
  101. package/src/agent/manage.js +94 -0
  102. package/src/agent/next-steps.js +51 -0
  103. package/src/agent/owner-mcp.js +38 -0
  104. package/src/agent/plain-text.js +52 -0
  105. package/src/agent/ratings-core.js +213 -0
  106. package/src/agent/ratings.js +100 -0
  107. package/src/agent/reply-text.js +67 -0
  108. package/src/agent/routes.js +1065 -0
  109. package/src/agent/run.js +326 -0
  110. package/src/agent/settings-routes.js +704 -0
  111. package/src/agent/showable.js +23 -0
  112. package/src/agent/starter/approvals.js +181 -0
  113. package/src/agent/starter/build-image.js +90 -0
  114. package/src/agent/starter/cli.js +163 -0
  115. package/src/agent/starter/disk.js +53 -0
  116. package/src/agent/starter/doctor.js +180 -0
  117. package/src/agent/starter/egress-proxy.js +351 -0
  118. package/src/agent/starter/gate.js +90 -0
  119. package/src/agent/starter/loop.js +114 -0
  120. package/src/agent/starter/model-relay.js +289 -0
  121. package/src/agent/starter/pause.js +14 -0
  122. package/src/agent/starter/probe.js +272 -0
  123. package/src/agent/starter/prompt.js +41 -0
  124. package/src/agent/starter/push-guard.js +146 -0
  125. package/src/agent/starter/rpc.js +164 -0
  126. package/src/agent/starter/runtime.js +287 -0
  127. package/src/agent/starter/sandbox-main.js +121 -0
  128. package/src/agent/starter/settings.js +290 -0
  129. package/src/agent/starter/source.js +69 -0
  130. package/src/agent/starter/supervisor.js +755 -0
  131. package/src/agent/starter/sweep.js +46 -0
  132. package/src/agent/starter/tools.js +524 -0
  133. package/src/agent/starter/watch.js +84 -0
  134. package/src/agent/starter/worktree.js +409 -0
  135. package/src/agent/text-diff.js +210 -0
  136. package/src/agent/thread-history.js +223 -0
  137. package/src/agent/threads.js +399 -0
  138. package/src/agent/tools.js +200 -0
  139. package/src/agent/turn-changes.js +424 -0
  140. package/src/agent/undo-state.js +26 -0
  141. package/src/agent/user-settings.js +308 -0
  142. package/src/auth/record.js +375 -0
  143. package/src/broken-links.js +164 -0
  144. package/src/buzz/client.js +75 -0
  145. package/src/buzz/config.js +151 -0
  146. package/src/buzz/environment.js +13 -0
  147. package/src/buzz/gateway.js +192 -0
  148. package/src/buzz/routes.js +61 -0
  149. package/src/buzz/signer-child.js +205 -0
  150. package/src/buzz/store.js +89 -0
  151. package/src/buzz/transport.js +60 -0
  152. package/src/buzz/verify.js +140 -0
  153. package/src/capture/actions.js +159 -0
  154. package/src/capture/capture.js +776 -0
  155. package/src/capture/dom-names.js +189 -0
  156. package/src/capture/element-map.js +509 -0
  157. package/src/capture/live.js +827 -0
  158. package/src/capture/media-scheme.js +317 -0
  159. package/src/capture/network-summary.js +86 -0
  160. package/src/capture/pacing.js +34 -0
  161. package/src/capture/requests.js +167 -0
  162. package/src/capture/sanitize.js +752 -0
  163. package/src/checks/accessibility.js +134 -0
  164. package/src/checks/budgets.js +58 -0
  165. package/src/checks/cli.js +55 -0
  166. package/src/checks/comparison.js +113 -0
  167. package/src/checks/environments.js +32 -0
  168. package/src/checks/flow-config.js +82 -0
  169. package/src/checks/flow-origin.js +53 -0
  170. package/src/checks/flows.js +398 -0
  171. package/src/checks/lighthouse-auth.js +145 -0
  172. package/src/checks/lighthouse-findings.js +130 -0
  173. package/src/checks/lighthouse.js +395 -0
  174. package/src/checks/robots.js +85 -0
  175. package/src/checks/routes.js +52 -0
  176. package/src/checks/run-control.js +259 -0
  177. package/src/checks/runner.js +724 -0
  178. package/src/checks/schema.js +133 -0
  179. package/src/checks/seo-analysis.js +443 -0
  180. package/src/checks/seo-probe.js +190 -0
  181. package/src/checks/seo-snapshot.js +99 -0
  182. package/src/checks/store.js +214 -0
  183. package/src/checks/transport.js +47 -0
  184. package/src/cli/args.js +319 -0
  185. package/src/cli/capture.js +79 -0
  186. package/src/cli/commands.js +92 -0
  187. package/src/cli/comments.js +84 -0
  188. package/src/cli/help.js +243 -0
  189. package/src/cli/init.js +214 -0
  190. package/src/cli/misc.js +64 -0
  191. package/src/cli/notify.js +87 -0
  192. package/src/cli/open.js +22 -0
  193. package/src/cli/serve.js +274 -0
  194. package/src/cli/variant.js +82 -0
  195. package/src/cli/watch.js +70 -0
  196. package/src/cli.js +130 -0
  197. package/src/comment-fields.js +76 -0
  198. package/src/comments-cli.js +208 -0
  199. package/src/config-reload.js +100 -0
  200. package/src/config.js +1061 -0
  201. package/src/devices-cli.js +21 -0
  202. package/src/diff.js +95 -0
  203. package/src/discover.js +284 -0
  204. package/src/doctor.js +295 -0
  205. package/src/event-log.js +268 -0
  206. package/src/events-cli.js +102 -0
  207. package/src/events.js +113 -0
  208. package/src/export.js +119 -0
  209. package/src/feedback.js +246 -0
  210. package/src/github.js +551 -0
  211. package/src/hosted/LICENSE.md +105 -0
  212. package/src/hosted/access-cli.js +78 -0
  213. package/src/hosted/admin.js +682 -0
  214. package/src/hosted/agent-approvals.js +163 -0
  215. package/src/hosted/agent-policy.js +189 -0
  216. package/src/hosted/app.js +510 -0
  217. package/src/hosted/auth-routes.js +540 -0
  218. package/src/hosted/auth.js +536 -0
  219. package/src/hosted/backup.js +483 -0
  220. package/src/hosted/board-context.js +35 -0
  221. package/src/hosted/board-routes.js +486 -0
  222. package/src/hosted/board-view.js +94 -0
  223. package/src/hosted/clean-worker.js +24 -0
  224. package/src/hosted/cleaner.js +89 -0
  225. package/src/hosted/comments.js +355 -0
  226. package/src/hosted/console-routes.js +401 -0
  227. package/src/hosted/cookies.js +18 -0
  228. package/src/hosted/crypto.js +80 -0
  229. package/src/hosted/db.js +496 -0
  230. package/src/hosted/device-routes.js +175 -0
  231. package/src/hosted/device.js +233 -0
  232. package/src/hosted/events.js +63 -0
  233. package/src/hosted/guards.js +172 -0
  234. package/src/hosted/guest-view.js +65 -0
  235. package/src/hosted/http.js +39 -0
  236. package/src/hosted/import.js +300 -0
  237. package/src/hosted/mail.js +73 -0
  238. package/src/hosted/mcp-http.js +71 -0
  239. package/src/hosted/membership.js +114 -0
  240. package/src/hosted/operator.js +478 -0
  241. package/src/hosted/ops-cli.js +345 -0
  242. package/src/hosted/pages.js +146 -0
  243. package/src/hosted/permissions.js +113 -0
  244. package/src/hosted/presence.js +372 -0
  245. package/src/hosted/projects.js +124 -0
  246. package/src/hosted/public.js +109 -0
  247. package/src/hosted/push.js +622 -0
  248. package/src/hosted/quotas.js +115 -0
  249. package/src/hosted/ratelimit.js +96 -0
  250. package/src/hosted/rebind.js +316 -0
  251. package/src/hosted/retention.js +128 -0
  252. package/src/hosted/server.js +260 -0
  253. package/src/hosted/setup-link.js +64 -0
  254. package/src/hosted/setup.js +323 -0
  255. package/src/hosted/shares.js +444 -0
  256. package/src/hosted/tailscale.js +204 -0
  257. package/src/hosted/tenancy.js +301 -0
  258. package/src/hosted/token-api.js +455 -0
  259. package/src/hosted/token-events.js +60 -0
  260. package/src/hosted/tokens.js +57 -0
  261. package/src/hosted/turnstile.js +49 -0
  262. package/src/hosted/usercontent.js +154 -0
  263. package/src/hosted/zip.js +155 -0
  264. package/src/invocation.js +58 -0
  265. package/src/journey-paths.js +282 -0
  266. package/src/journeys.js +189 -0
  267. package/src/links.js +106 -0
  268. package/src/local-projects.js +182 -0
  269. package/src/lock.js +193 -0
  270. package/src/mcp.js +417 -0
  271. package/src/mentions.js +151 -0
  272. package/src/net.js +15 -0
  273. package/src/notify/config.js +275 -0
  274. package/src/notify/index.js +301 -0
  275. package/src/notify/lease.js +73 -0
  276. package/src/notify/messages.js +212 -0
  277. package/src/notify/run.js +174 -0
  278. package/src/pixeldiff.js +49 -0
  279. package/src/png.js +143 -0
  280. package/src/reactions.js +111 -0
  281. package/src/remote/cli.js +133 -0
  282. package/src/remote/credentials.js +62 -0
  283. package/src/remote/ids.js +12 -0
  284. package/src/remote/login.js +155 -0
  285. package/src/remote/remote-mcp.js +237 -0
  286. package/src/remote/remote-watch.js +291 -0
  287. package/src/remote/remote.js +313 -0
  288. package/src/remote/share-state.js +78 -0
  289. package/src/remote/share.js +369 -0
  290. package/src/remote/terminal.js +13 -0
  291. package/src/serve-state.js +64 -0
  292. package/src/server/app.js +824 -0
  293. package/src/server/devices.js +186 -0
  294. package/src/server/local-console.js +28 -0
  295. package/src/server/local-user.js +59 -0
  296. package/src/server/pairing-routes.js +159 -0
  297. package/src/server/share-routes.js +89 -0
  298. package/src/server/tailscale.js +97 -0
  299. package/src/sitemap.js +431 -0
  300. package/src/store.js +983 -0
  301. package/src/tokens.js +11 -0
  302. package/src/update/routes.js +245 -0
  303. package/src/watch.js +403 -0
  304. package/src/which.js +58 -0
@@ -0,0 +1,137 @@
1
+ // Local owner feedback loop. Never infer page ids or commands from model prose.
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import { addReply, currentVersion, getComment, setAgentStatus } from '../store.js'
5
+ import { isSetupError } from './errors.js'
6
+
7
+ const SKIP = new Set(['.git', 'node_modules', 'dist', 'build', '.next', '.cache', 'coverage', '.output', '.shapewall'])
8
+ const FILES_MAX = 30000
9
+
10
+ // Metadata only: no source text or secrets enter the model or the chat log.
11
+ // Symlinks are not followed. A bounded scan also covers terminal/native edits.
12
+ export function projectSnapshot(config) {
13
+ const entries = new Map()
14
+ let visited = 0
15
+ const walk = (dir) => {
16
+ if (path.resolve(dir) === path.resolve(config.outputDir)) return
17
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
18
+ if (++visited > FILES_MAX) return
19
+ if (entry.isSymbolicLink() || SKIP.has(entry.name)) continue
20
+ const file = path.join(dir, entry.name)
21
+ try {
22
+ if (entry.isDirectory()) walk(file)
23
+ else if (entry.isFile()) {
24
+ const stat = fs.statSync(file, { bigint: true })
25
+ entries.set(path.relative(config.dir, file), `${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`)
26
+ }
27
+ } catch {
28
+ /* a file may disappear while the agent works */
29
+ }
30
+ }
31
+ }
32
+ try {
33
+ walk(config.dir)
34
+ } catch {
35
+ /* caller still has explicit edit events */
36
+ }
37
+ return { entries, incomplete: visited > FILES_MAX }
38
+ }
39
+
40
+ export function projectChanged(before, after) {
41
+ return (
42
+ before.incomplete ||
43
+ after.incomplete ||
44
+ before.entries.size !== after.entries.size ||
45
+ [...before.entries].some(([file, stamp]) => after.entries.get(file) !== stamp)
46
+ )
47
+ }
48
+
49
+ export async function recaptureComment({ config, board, id, pageIds = [], capture = null, log = () => {} }) {
50
+ const comment = getComment(config, board.id, id)
51
+ if (String(comment.pageId).startsWith('variant:')) throw new Error('Recapture variants from the terminal before marking this fix done.')
52
+ const ids = [...new Set([comment.pageId, ...pageIds])]
53
+ if (ids.some((pageId) => !board.pages.some((page) => page.id === pageId))) throw new Error('Unknown page to recapture.')
54
+ const before = currentVersion(config, board.id, comment.pageId, comment.viewport)
55
+ const run = capture || (await import('../capture/capture.js')).runCapture
56
+ const result = await run({ config, boardId: board.id, only: ids, log })
57
+ if (!result.ok || result.failed) throw new Error('The recapture failed. Check the dev server and capture the page again.')
58
+ const version = currentVersion(config, board.id, comment.pageId, comment.viewport)
59
+ if (!version || version === before) throw new Error('The recapture did not produce a page version.')
60
+ await addReply(config, board.id, id, {
61
+ author: 'shapewall',
62
+ body: comment.captureVersion
63
+ ? `Recaptured ${ids.join(', ')}. Before and after are ready below this comment. Review the change, then resolve or reply “not yet”.`
64
+ : `Recaptured ${ids.join(', ')}. This comment has no original capture for comparison. Review the updated page, then resolve or reply “not yet”.`,
65
+ })
66
+ return result
67
+ }
68
+
69
+ // Why a fix run stopped, in one plain sentence: the agent's last error (its
70
+ // first sentence, never a stack), or that the answer was stopped.
71
+ export function stopReason(reply, signal) {
72
+ const message = String(reply?.error?.message || '')
73
+ .split('\n')
74
+ .map((line) => line.trim())
75
+ .find(Boolean)
76
+ if (message) {
77
+ const sentence = (/^.*?[.!?](?=\s|$)/.exec(message)?.[0] || message).slice(0, 200).trim()
78
+ return /[.!?]$/.test(sentence) ? sentence : `${sentence}.`
79
+ }
80
+ if (signal?.aborted || reply?.status === 'stopped') return 'The answer was stopped before it finished.'
81
+ return 'The agent did not finish its answer.'
82
+ }
83
+
84
+ // `previousStatus`: the comment's agent status before this run claimed it.
85
+ export async function finishFix({
86
+ config,
87
+ board,
88
+ id,
89
+ reply,
90
+ changed,
91
+ capture,
92
+ pageIds = [],
93
+ signal,
94
+ previousStatus = null,
95
+ log = () => {},
96
+ }) {
97
+ let comment
98
+ try {
99
+ comment = getComment(config, board.id, id)
100
+ } catch {
101
+ return
102
+ }
103
+ // The agent never got to work (not logged in, not set up, did not start):
104
+ // nothing to review on the comment, which goes back to how it was. The
105
+ // chat shows the error and how to fix it.
106
+ if (!changed && !signal?.aborted && reply.status === 'error' && isSetupError(reply.error)) {
107
+ await setAgentStatus(config, board.id, id, previousStatus, { onlyFrom: ['queued', 'working'], actor: 'shapewall' })
108
+ return
109
+ }
110
+ if (signal?.aborted || reply.status !== 'done' || !changed) {
111
+ if (comment.status === 'open') {
112
+ await addReply(config, board.id, id, {
113
+ author: 'shapewall',
114
+ body:
115
+ reply.status !== 'done' || signal?.aborted
116
+ ? `The agent stopped before the fix could be verified. ${stopReason(reply, signal)} Review its answer and try again.`
117
+ : 'No project file changes were detected. Review the agent’s answer before continuing.',
118
+ })
119
+ await setAgentStatus(config, board.id, id, 'needs-human', { actor: 'shapewall' })
120
+ }
121
+ return
122
+ }
123
+ try {
124
+ await recaptureComment({ config, board, id, capture, pageIds, log })
125
+ if (signal?.aborted) {
126
+ await setAgentStatus(config, board.id, id, 'needs-human', { actor: 'shapewall' })
127
+ } else if (getComment(config, board.id, id).status === 'open' && getComment(config, board.id, id).agentStatus !== 'needs-human') {
128
+ await setAgentStatus(config, board.id, id, 'done', { actor: 'shapewall' })
129
+ }
130
+ } catch (error) {
131
+ await addReply(config, board.id, id, {
132
+ author: 'shapewall',
133
+ body: `The agent changed files, but verification needs a person: ${error.message}`,
134
+ })
135
+ await setAgentStatus(config, board.id, id, 'needs-human', { actor: 'shapewall' })
136
+ }
137
+ }
@@ -0,0 +1,94 @@
1
+ // A temporary host-only settings surface. It has no board routes, account
2
+ // exceptions, notification worker, serve-state file or project registration.
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import { randomBytes } from 'node:crypto'
6
+ import { fileURLToPath } from 'node:url'
7
+ import express from 'express'
8
+ import { agentRouter } from './routes.js'
9
+ import { localRequest, newSettingsToken } from './settings-routes.js'
10
+
11
+ const CLIENT = fileURLToPath(new URL('../../dist/client/', import.meta.url))
12
+ const CSP =
13
+ "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'; object-src 'none'"
14
+
15
+ export function createAgentManagement({ config, env = process.env, token = newSettingsToken(), clientDir = CLIENT, agentLimits = {} }) {
16
+ const app = express()
17
+ app.disable('x-powered-by')
18
+ app.set('trust proxy', false)
19
+ const agents = agentRouter({ config, env, settingsToken: token, limits: agentLimits })
20
+ const links = new Map()
21
+ const fail = (res, status) =>
22
+ res.status(status).json({
23
+ error: { code: status === 404 ? 'not_found' : 'host_only', message: 'Use the private agent settings link on this computer.' },
24
+ })
25
+ let closing = false
26
+ app.use((req, res, next) => {
27
+ if (closing) return fail(res, 503)
28
+ res.setHeader('Cache-Control', 'no-store')
29
+ res.setHeader('Content-Security-Policy', CSP)
30
+ res.setHeader('X-Content-Type-Options', 'nosniff')
31
+ res.setHeader('Referrer-Policy', 'no-referrer')
32
+ if (!localRequest(req)) return fail(res, 403)
33
+ next()
34
+ })
35
+ app.get('/open/:nonce', (req, res) => {
36
+ const expires = links.get(req.params.nonce)
37
+ links.delete(req.params.nonce)
38
+ if (!expires || expires < Date.now()) return fail(res, 404)
39
+ res.redirect(303, `/#settings-token=${token}`)
40
+ })
41
+ app.use('/api', (req, res, next) => (/^\/agent\/settings(?:\/|$)/.test(req.path) ? next() : fail(res, 404)))
42
+ app.use('/api/agent', agents)
43
+ app.use('/api', (req, res) => fail(res, 404))
44
+ app.use('/assets', express.static(path.join(clientDir, 'assets'), { index: false, dotfiles: 'deny' }))
45
+ // Sent relative to a root: an absolute path is refused when any folder in
46
+ // it starts with a dot, which is where installs live (~/.local, .pnpm).
47
+ for (const name of ['theme-boot.js', 'favicon.svg']) app.get(`/${name}`, (req, res) => res.sendFile(name, { root: clientDir }))
48
+ app.get('/', (req, res) => {
49
+ const html = fs
50
+ .readFileSync(path.join(clientDir, 'index.html'), 'utf8')
51
+ .replace('<head>', '<head><meta name="shapewall-agent-settings" content="true">')
52
+ .replace(/<link\b[^>]*rel="(?:manifest|apple-touch-icon)"[^>]*>/g, '')
53
+ res.type('html').send(html)
54
+ })
55
+ app.use((req, res) => fail(res, 404))
56
+ app.locals.openLink = () => {
57
+ const nonce = randomBytes(24).toString('base64url')
58
+ links.clear()
59
+ links.set(nonce, Date.now() + 60000)
60
+ return `/open/${nonce}`
61
+ }
62
+ let stopped
63
+ app.locals.close = () => {
64
+ closing = true
65
+ links.clear()
66
+ stopped ||= agents.close()
67
+ return stopped
68
+ }
69
+ return { app, token }
70
+ }
71
+
72
+ export async function startAgentManagement({ config, env = process.env, port = 0, out = () => {} }) {
73
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('Settings port must be 0 to 65535.')
74
+ const { app, token } = createAgentManagement({ config, env })
75
+ const server = app.listen(port, '127.0.0.1')
76
+ await new Promise((resolve, reject) => {
77
+ server.once('listening', resolve)
78
+ server.once('error', reject)
79
+ })
80
+ const url = `http://127.0.0.1:${server.address().port}`
81
+ out(`Private agent settings (this computer only; keep it to yourself): ${url}/#settings-token=${token}`)
82
+ out('This temporary server has no board, capture or chat routes. Stop it with Ctrl-C when finished.')
83
+ server.once('close', () => app.locals.close())
84
+ return {
85
+ app,
86
+ server,
87
+ url,
88
+ close: async () => {
89
+ const stopped = app.locals.close()
90
+ server.closeAllConnections()
91
+ await Promise.all([stopped, new Promise((resolve) => server.close(resolve))])
92
+ },
93
+ }
94
+ }
@@ -0,0 +1,51 @@
1
+ // Suggested next steps: the agent is asked (context.js NEXT_STEPS_PROMPT) to
2
+ // end an answer with up to three short follow-ups in a <next-steps> block.
3
+ // The server takes the block out of the stored answer (run.js) and keeps the
4
+ // items as `suggestions`; the panel shows them as chips. Pure functions with
5
+ // no imports, shared with the board client (a streaming answer hides the
6
+ // block while it is still being written).
7
+
8
+ export const NEXT_STEPS_MAX = 3
9
+ export const NEXT_STEP_CHARS_MAX = 90
10
+ const BLOCK_RE = /<next-steps>([\s\S]*?)(?:<\/next-steps>|$)/gi
11
+ // The start of a block still arriving: "<", "<next", "<next-st", ...
12
+ const PARTIAL_RE = /<(?:n(?:e(?:x(?:t(?:-(?:s(?:t(?:e(?:p(?:s)?)?)?)?)?)?)?)?)?)?$/i
13
+
14
+ // One suggestion line: no list markers or quotes, one line, no markup.
15
+ function cleanStep(line) {
16
+ const value = String(line || '')
17
+ .replace(/^\s*(?:[-*•]|\d{1,2}[.)])\s+/, '')
18
+ .replace(/^["“'`]+|["”'`]+$/g, '')
19
+ .replace(/\s+/g, ' ')
20
+ .trim()
21
+ if (value.length < 2 || value.length > NEXT_STEP_CHARS_MAX) return null
22
+ // Markup or a link is not a follow-up the person would type.
23
+ if (/[<>]|https?:\/\//i.test(value)) return null
24
+ return value
25
+ }
26
+
27
+ // { text, steps }: the answer without any <next-steps> block, and the
28
+ // suggestions of the last block (at most NEXT_STEPS_MAX, no repeats).
29
+ export function splitNextSteps(text) {
30
+ const source = String(text ?? '')
31
+ let last = null
32
+ for (const match of source.matchAll(BLOCK_RE)) last = match[1]
33
+ const stripped = source.replace(BLOCK_RE, '').replace(/\s+$/, '')
34
+ if (last === null) return { text: stripped, steps: [] }
35
+ const seen = new Set()
36
+ const steps = []
37
+ for (const line of last.split(/\r?\n/)) {
38
+ const step = cleanStep(line)
39
+ if (!step || seen.has(step.toLowerCase())) continue
40
+ seen.add(step.toLowerCase())
41
+ steps.push(step)
42
+ if (steps.length >= NEXT_STEPS_MAX) break
43
+ }
44
+ return { text: stripped, steps }
45
+ }
46
+
47
+ // Text that is still streaming, without a block (complete or not) and
48
+ // without the start of one at the very end.
49
+ export function hideNextSteps(text) {
50
+ return splitNextSteps(text).text.replace(PARTIAL_RE, '')
51
+ }
@@ -0,0 +1,38 @@
1
+ // The ACP session receives this stdio server only for a trusted owner request.
2
+ // No GitHub actions, alternate boards, paths or credentials are accepted.
3
+ import { fileURLToPath } from 'node:url'
4
+ import { loadConfig } from '../config.js'
5
+ import { createMcpServer } from '../mcp.js'
6
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
7
+
8
+ export function ownerMcpServers(config, boardId, { allowCapture = true } = {}) {
9
+ if (!config.file) return []
10
+ return [
11
+ {
12
+ name: 'shapewall',
13
+ command: process.execPath,
14
+ args: [fileURLToPath(import.meta.url), config.file, boardId, allowCapture ? 'capture' : 'no-capture'],
15
+ env: [],
16
+ },
17
+ ]
18
+ }
19
+
20
+ if (process.argv[1] === fileURLToPath(import.meta.url)) {
21
+ const config = loadConfig(process.argv[2])
22
+ const server = createMcpServer({
23
+ config,
24
+ boardId: process.argv[3],
25
+ allowCapture: process.argv[4] === 'capture',
26
+ toolNames: [
27
+ 'list_pages',
28
+ 'list_journeys',
29
+ 'list_comments',
30
+ 'get_comment',
31
+ 'reply_to_comment',
32
+ 'set_comment_status',
33
+ 'resolve_comment',
34
+ 'recapture_pages',
35
+ ],
36
+ })
37
+ await server.connect(new StdioServerTransport())
38
+ }
@@ -0,0 +1,52 @@
1
+ // An agent's answer as text a person reads: reference tokens ([[comment:16]],
2
+ // [[page:home]], client/src/chat/refs.js) become words, and for one-line
3
+ // previews (search snippets, the Console's feedback list) the Markdown marks
4
+ // go too. Shared by the server (search snippets) and the board (Copy, Copy as
5
+ // Markdown, Download .md, previews). Pure, no DOM.
6
+
7
+ const TOKEN_ANY = /\[\[([a-z]+):([^\]\n]{1,120})\]\]/g
8
+
9
+ // The default words for a token when the board's own name for it is not at
10
+ // hand: "comment #16", "home page", "checks for pricing", or the id.
11
+ export function tokenWords(kind, id) {
12
+ const value = String(id || '').trim()
13
+ if (kind === 'comment') return /^#?\d{1,9}$/.test(value) ? `comment #${value.replace(/^#/, '')}` : `comment ${value}`
14
+ if (kind === 'page') return `${value} page`
15
+ if (kind === 'journey') return `${value} journey`
16
+ if (kind === 'check') return `checks for ${value}`
17
+ return value
18
+ }
19
+
20
+ // Every token as words. `label(kind, id)` may give a better name (the page's
21
+ // title, from the board); null falls back to tokenWords. Other Markdown stays.
22
+ export function tokensToText(text, label = null) {
23
+ return String(text || '').replace(TOKEN_ANY, (_, kind, id) => (label && label(kind, id)) || tokenWords(kind, id))
24
+ }
25
+
26
+ // Markdown to plain text for a preview: tokens as words, then no emphasis,
27
+ // code marks, headings, quotes, list bullets, link targets or table pipes.
28
+ // Keeps the words; good enough for a snippet, not a renderer.
29
+ export function markdownToPlain(text, label = null) {
30
+ return (
31
+ tokensToText(text, label)
32
+ // Half a token cut off at a snippet's edge.
33
+ .replace(/^[^[\]]{0,120}\]\]/, '')
34
+ .replace(/\[\[[^\]]{0,120}$/, '')
35
+ .replace(/```[^\n]*\n?/g, '')
36
+ .replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1')
37
+ .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
38
+ .replace(/`([^`]*)`/g, '$1')
39
+ .replace(/`/g, '')
40
+ .replace(/(\*\*|__)(.+?)\1/g, '$2')
41
+ .replace(/(^|[\s(])[*_]([^*_\s][^*_]*?)[*_](?=[\s).,;:!?]|$)/g, '$1$2')
42
+ .replace(/\*\*|__/g, '')
43
+ .replace(/~~(.+?)~~/g, '$1')
44
+ .replace(/^[ \t]{0,3}#{1,6}[ \t]+/gm, '')
45
+ .replace(/^[ \t]{0,3}>[ \t]?/gm, '')
46
+ .replace(/^[ \t]*(?:[-*+]|\d+[.)])[ \t]+/gm, '')
47
+ .replace(/^[ \t]*\|?(?:\s*:?-{3,}:?\s*\|)+\s*:?-*:?\s*$/gm, '')
48
+ .replace(/[ \t]*\|[ \t]*/g, ' ')
49
+ .replace(/[ \t]+/g, ' ')
50
+ .trim()
51
+ )
52
+ }
@@ -0,0 +1,213 @@
1
+ // Answer feedback rules, pure and with no Node imports, so the server
2
+ // (ratings.js) and the demo's in-browser backend (client/src/demo) share one
3
+ // set: what a rating holds, which answer it can be on, the owner's summary,
4
+ // and what goes back to the model.
5
+
6
+ import { AgentError } from './errors.js'
7
+
8
+ export const RATINGS = ['up', 'down']
9
+ // Quick reasons on a thumbs down. Ids are stored; the labels are the panel's.
10
+ export const REASONS = ['wrong', 'ignored', 'slow', 'unsafe', 'other']
11
+ export const REASON_LABELS = {
12
+ wrong: 'Wrong',
13
+ ignored: "Didn't do what I asked",
14
+ slow: 'Too slow',
15
+ unsafe: 'Unsafe change',
16
+ other: 'Other',
17
+ }
18
+ export const NOTE_MAX = 1000
19
+ export const EXCERPT_MAX = 400
20
+ const RATER_MAX = 120
21
+ const MESSAGE_ID_RE = /^[a-z]+_[a-z0-9]{3,40}$/
22
+
23
+ const clean = (value, max) =>
24
+ String(value ?? '')
25
+ .replace(/\r\n/g, '\n')
26
+ // eslint-disable-next-line no-control-regex
27
+ .replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, '')
28
+ .trim()
29
+ .slice(0, max)
30
+
31
+ export const excerpt = (value, max = EXCERPT_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
+ // { rating, reasons, note } from the panel. Reasons only go with a thumbs down.
39
+ export function validateRating(input) {
40
+ const rating = input?.rating
41
+ if (!RATINGS.includes(rating)) throw new AgentError('bad_rating', 'A rating is "up" or "down".', 400)
42
+ const raw = input?.reasons ?? []
43
+ if (!Array.isArray(raw) || raw.length > REASONS.length || raw.some((item) => !REASONS.includes(item)))
44
+ throw new AgentError('bad_reason', `Reasons are some of: ${REASONS.join(', ')}.`, 400)
45
+ if (input?.note !== undefined && input.note !== null && typeof input.note !== 'string')
46
+ throw new AgentError('bad_note', 'A note is text.', 400)
47
+ if (typeof input?.note === 'string' && input.note.trim().length > NOTE_MAX)
48
+ throw new AgentError('note_too_long', `A note is at most ${NOTE_MAX} characters.`, 400)
49
+ return { rating, reasons: rating === 'down' ? [...new Set(raw)] : [], note: clean(input?.note, NOTE_MAX) }
50
+ }
51
+
52
+ // The answer (the current one, or an earlier version Regenerate kept) and
53
+ // the question it answered. Only a finished answer can be rated.
54
+ export function findAnswer(messages, messageId) {
55
+ if (!MESSAGE_ID_RE.test(String(messageId || ''))) return null
56
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
57
+ const message = messages[index]
58
+ if (message.role !== 'assistant') continue
59
+ const answer = message.id === messageId ? message : (message.versions || []).find((item) => item.id === messageId)
60
+ if (!answer) continue
61
+ if (message.starter?.state === 'running') return null
62
+ const question = messages.slice(0, index).findLast((item) => item.role === 'user')
63
+ return { answer, question, current: message }
64
+ }
65
+ return null
66
+ }
67
+
68
+ // The stored entry for a rating. `previous`: this person's earlier rating
69
+ // of the same answer (it keeps its createdAt).
70
+ export function ratingEntry({ boardId, threadId, rater, value, found, agent, previous = null, time }) {
71
+ return {
72
+ boardId,
73
+ threadId,
74
+ messageId: found.answer.id,
75
+ rater: rater.key,
76
+ raterName: clean(rater.name, RATER_MAX),
77
+ ...value,
78
+ agent: {
79
+ profileId: agent?.profileId || 'default',
80
+ backend: agent?.backend || null,
81
+ label: agent?.label || null,
82
+ model: found.answer.model || agent?.model || null,
83
+ },
84
+ question: excerpt(found.question?.text),
85
+ answer: excerpt(found.answer.text || found.answer.error?.message),
86
+ answerStatus: found.answer.status || 'done',
87
+ createdAt: previous?.createdAt || time,
88
+ updatedAt: time,
89
+ }
90
+ }
91
+
92
+ const sameRating = (item, { threadId, messageId, rater }) =>
93
+ item.messageId === messageId && item.threadId === threadId && item.rater === rater.key
94
+
95
+ // Puts the entry in place of this person's earlier one. Returns it.
96
+ export function upsertRating(entries, key, make) {
97
+ const index = entries.findIndex((item) => sameRating(item, key))
98
+ const entry = make(index >= 0 ? entries[index] : null)
99
+ if (index >= 0) entries[index] = entry
100
+ else entries.push(entry)
101
+ return entry
102
+ }
103
+
104
+ export function dropRating(entries, key) {
105
+ const index = entries.findIndex((item) => sameRating(item, key))
106
+ if (index < 0) return false
107
+ entries.splice(index, 1)
108
+ return true
109
+ }
110
+
111
+ // This person's ratings in one thread, for the panel: { [messageId]: { rating, reasons, note } }.
112
+ export function ratingsOf(entries, threadId, rater) {
113
+ const mine = {}
114
+ for (const item of entries) {
115
+ if (item.threadId === threadId && item.rater === rater.key)
116
+ mine[item.messageId] = { rating: item.rating, reasons: item.reasons || [], note: item.note || '' }
117
+ }
118
+ return mine
119
+ }
120
+
121
+ export const agentName = (item) => item.agent?.label || item.agent?.model || item.agent?.backend || 'Agent'
122
+
123
+ // The owner's review: counts per day and per agent over `days`, and the
124
+ // newest entries filtered by rating. `entries` carry boardId and boardTitle.
125
+ export function summarizeRatings(entries, { rating = null, days = 30, limit = 200, now = Date.now() } = {}) {
126
+ const since = new Date(now - days * 86400000).toISOString()
127
+ const all = entries
128
+ .filter((item) => String(item.updatedAt) >= since)
129
+ .sort((a, b) => String(b.updatedAt).localeCompare(String(a.updatedAt)))
130
+ const byDay = new Map()
131
+ const byAgent = new Map()
132
+ const reasons = Object.fromEntries(REASONS.map((id) => [id, 0]))
133
+ for (const item of all) {
134
+ const day = String(item.updatedAt).slice(0, 10)
135
+ if (!byDay.has(day)) byDay.set(day, { day, up: 0, down: 0 })
136
+ byDay.get(day)[item.rating] += 1
137
+ const name = agentName(item)
138
+ if (!byAgent.has(name)) byAgent.set(name, { agent: name, up: 0, down: 0 })
139
+ byAgent.get(name)[item.rating] += 1
140
+ for (const reason of item.reasons || []) if (reason in reasons) reasons[reason] += 1
141
+ }
142
+ const items = all.filter((item) => !rating || item.rating === rating)
143
+ return {
144
+ days,
145
+ summary: {
146
+ total: all.length,
147
+ up: all.filter((item) => item.rating === 'up').length,
148
+ down: all.filter((item) => item.rating === 'down').length,
149
+ reasons,
150
+ byDay: [...byDay.values()].sort((a, b) => b.day.localeCompare(a.day)),
151
+ byAgent: [...byAgent.values()].sort((a, b) => b.up + b.down - (a.up + a.down)),
152
+ },
153
+ items: items.slice(0, limit).map((item) => ({ ...item, agentName: agentName(item) })),
154
+ more: Math.max(0, items.length - limit),
155
+ }
156
+ }
157
+
158
+ // The review's query string: days 1 to 365 (30), rating up or down (both).
159
+ export function reviewQuery(params) {
160
+ const days = Math.min(365, Math.max(1, Number.parseInt(params.get('days'), 10) || 30))
161
+ const rating = ['up', 'down'].includes(params.get('rating')) ? params.get('rating') : null
162
+ return { days, rating, board: params.get('board') || null }
163
+ }
164
+
165
+ export function exportDocument(entries, now = new Date()) {
166
+ return {
167
+ format: 'shapewall-agent-feedback',
168
+ version: 1,
169
+ exportedAt: now.toISOString(),
170
+ reasons: REASON_LABELS,
171
+ entries: [...entries].sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt))),
172
+ }
173
+ }
174
+
175
+ // The owner's rater keys (ratings.js raterOf): this computer, a paired
176
+ // device, the owner over Tailscale. Visitors and accounts rate as their
177
+ // private-chat key ("key:...", "user:...").
178
+ export const ownerRater = (key) => key === 'local' || key === 'identity' || String(key || '').startsWith('device:')
179
+
180
+ // Recent thumbs-down with a reason or a note, for the model's board context
181
+ // (context.js threadContext): what went wrong before. Newest first, bounded;
182
+ // quoted as untrusted data like every other board text.
183
+ //
184
+ // Only the owner's own ratings on shared threads (the board thread and
185
+ // comment threads, which everyone chatting on the board can read anyway):
186
+ // never a private chat's question, and never what a visitor or another
187
+ // account wrote, since any of it would reach every other person's turns.
188
+ // `notes`: the owner's free-text notes too, only for the owner's own turns
189
+ // (a note is visible to its rater and the owner's review alone); every
190
+ // other turn gets the reasons and the shared question.
191
+ export const CONTEXT_ITEMS_MAX = 3
192
+ export const CONTEXT_DAYS = 14
193
+ const PRIVATE_THREAD_RE = /^chat-/
194
+ export function downNotes(entries, { now = Date.now(), max = CONTEXT_ITEMS_MAX, notes = false } = {}) {
195
+ const since = new Date(now - CONTEXT_DAYS * 86400000).toISOString()
196
+ return entries
197
+ .filter(
198
+ (item) =>
199
+ item.rating === 'down' &&
200
+ ownerRater(item.rater) &&
201
+ !PRIVATE_THREAD_RE.test(String(item.threadId || '')) &&
202
+ String(item.updatedAt) >= since &&
203
+ ((notes && item.note) || item.reasons?.length),
204
+ )
205
+ .sort((a, b) => String(b.updatedAt).localeCompare(String(a.updatedAt)))
206
+ .slice(0, max)
207
+ .map((item) => ({
208
+ reasons: (item.reasons || []).map((id) => REASON_LABELS[id] || id),
209
+ note: notes && item.note ? excerpt(item.note, 300) : undefined,
210
+ question: excerpt(item.question, 160) || undefined,
211
+ at: String(item.updatedAt).slice(0, 10),
212
+ }))
213
+ }