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.
- package/CHANGELOG.md +139 -0
- package/Dockerfile.agent +45 -0
- package/LICENSE +202 -0
- package/NOTICE +12 -0
- package/README.md +651 -2
- package/THIRD_PARTY.md +165 -0
- package/bin/shapewall.js +29 -0
- package/dist/agent/package-lock.json +8384 -0
- package/dist/client/assets/BoardChat-D5SFd8HE.js +28 -0
- package/dist/client/assets/BuzzDialog-HWXBy52W.js +1 -0
- package/dist/client/assets/ChecksPanel-DTdImWoD.js +1 -0
- package/dist/client/assets/History-CEv6b-av.js +1 -0
- package/dist/client/assets/LocalSettings-C4vriEVQ.js +1 -0
- package/dist/client/assets/Management-DCfhcEUY.js +1 -0
- package/dist/client/assets/QuickConnect-DQGgUsl1.js +1 -0
- package/dist/client/assets/ShareDialog-C_plIto0.js +2 -0
- package/dist/client/assets/app-update-dialog-2hPz_N9G.js +1 -0
- package/dist/client/assets/circle-x-BZMPi8Zf.js +1 -0
- package/dist/client/assets/index-ByQRKVit.css +2 -0
- package/dist/client/assets/index-DweQ8Qtu.js +29 -0
- package/dist/client/assets/refresh-cw-CRow0Nbq.js +1 -0
- package/dist/client/assets/runtime-Bft6x_6E.js +4 -0
- package/dist/client/assets/square-A8EnIYLR.js +1 -0
- package/dist/client/assets/tts-dist-DYlBQmwG.js +18 -0
- package/dist/client/assets/tts-en-g2p-BPUtBFGG.js +1 -0
- package/dist/client/assets/tts-ort-wasm-simd-threaded-qh98TCA_.wasm +0 -0
- package/dist/client/assets/tts-ort.wasm.bundle.min-rEkcs_ow.js +12 -0
- package/dist/client/assets/tts-rolldown-runtime-D8NudN84.js +1 -0
- package/dist/client/assets/tts-spacy-en-tokenizer-6SNMl--A.json +1 -0
- package/dist/client/assets/tts-tts.worker-Bzm6aWbv.js +1 -0
- package/dist/client/assets/tts-us_gold-DcjeNMH1.json +92589 -0
- package/dist/client/assets/tts-us_silver-C964mEB5.json +93363 -0
- package/dist/client/assets/ui-CLbws0rx.js +41 -0
- package/dist/client/build-info.json +1 -0
- package/dist/client/favicon.svg +7 -0
- package/dist/client/icons/apple-touch-icon.png +0 -0
- package/dist/client/icons/icon-192.png +0 -0
- package/dist/client/icons/icon-512.png +0 -0
- package/dist/client/icons/maskable-512.png +0 -0
- package/dist/client/index.html +25 -0
- package/dist/client/manifest.webmanifest +15 -0
- package/dist/client/sw.js +53 -0
- package/dist/client/theme-boot.js +27 -0
- package/dist/console/assets/LocalAccountsApp-BQCcmj3x.js +1 -0
- package/dist/console/assets/LocalConsole-Bb2FUDs7.js +1 -0
- package/dist/console/assets/app-update-dialog-DIeYepLZ.js +1 -0
- package/dist/console/assets/console-C7uJLLOn.js +51 -0
- package/dist/console/assets/console-R8IBY3Am.css +2 -0
- package/dist/console/build-info.json +1 -0
- package/dist/console/console.html +21 -0
- package/dist/console/favicon.svg +7 -0
- package/dist/console/icons/apple-touch-icon.png +0 -0
- package/dist/console/icons/icon-192.png +0 -0
- package/dist/console/icons/icon-512.png +0 -0
- package/dist/console/icons/maskable-512.png +0 -0
- package/dist/console/manifest.webmanifest +15 -0
- package/dist/console/theme-boot.js +27 -0
- package/docs/agent-hardening.md +342 -0
- package/docs/agent-recipes.md +187 -0
- package/docs/agent-workflow.md +320 -0
- package/docs/agents.md +894 -0
- package/docs/architecture.md +242 -0
- package/docs/buzz.md +140 -0
- package/docs/capture-warnings.md +57 -0
- package/docs/config.md +489 -0
- package/docs/deployment.md +289 -0
- package/docs/design-system.md +162 -0
- package/docs/github.md +107 -0
- package/docs/hosted.md +764 -0
- package/docs/images/board-overview.png +0 -0
- package/docs/images/journeys.png +0 -0
- package/docs/images/live-comment.png +0 -0
- package/docs/images/phone-comment.png +0 -0
- package/docs/images/phone-overview.png +0 -0
- package/docs/images/variant.png +0 -0
- package/docs/interaction-audits.md +40 -0
- package/docs/journeys.md +137 -0
- package/docs/local-accounts.md +80 -0
- package/docs/notifications.md +237 -0
- package/docs/page-checks.md +69 -0
- package/docs/performance.md +174 -0
- package/docs/starter-agent.md +325 -0
- package/docs/updates.md +87 -0
- package/examples/audits/interaction.audit.json +17 -0
- package/package.json +132 -4
- package/src/accounts/avatar.js +121 -0
- package/src/accounts/local.js +464 -0
- package/src/agent/acp/command.js +204 -0
- package/src/agent/acp/detect.js +75 -0
- package/src/agent/acp/sandbox.js +160 -0
- package/src/agent/agent-health.js +75 -0
- package/src/agent/backends/acp.js +1297 -0
- package/src/agent/backends/index.js +61 -0
- package/src/agent/backends/openai.js +308 -0
- package/src/agent/composer.js +221 -0
- package/src/agent/config.js +338 -0
- package/src/agent/context.js +191 -0
- package/src/agent/control.js +122 -0
- package/src/agent/errors.js +17 -0
- package/src/agent/feedback-loop.js +137 -0
- package/src/agent/manage.js +94 -0
- package/src/agent/next-steps.js +51 -0
- package/src/agent/owner-mcp.js +38 -0
- package/src/agent/plain-text.js +52 -0
- package/src/agent/ratings-core.js +213 -0
- package/src/agent/ratings.js +100 -0
- package/src/agent/reply-text.js +67 -0
- package/src/agent/routes.js +1065 -0
- package/src/agent/run.js +326 -0
- package/src/agent/settings-routes.js +704 -0
- package/src/agent/showable.js +23 -0
- package/src/agent/starter/approvals.js +181 -0
- package/src/agent/starter/build-image.js +90 -0
- package/src/agent/starter/cli.js +163 -0
- package/src/agent/starter/disk.js +53 -0
- package/src/agent/starter/doctor.js +180 -0
- package/src/agent/starter/egress-proxy.js +351 -0
- package/src/agent/starter/gate.js +90 -0
- package/src/agent/starter/loop.js +114 -0
- package/src/agent/starter/model-relay.js +289 -0
- package/src/agent/starter/pause.js +14 -0
- package/src/agent/starter/probe.js +272 -0
- package/src/agent/starter/prompt.js +41 -0
- package/src/agent/starter/push-guard.js +146 -0
- package/src/agent/starter/rpc.js +164 -0
- package/src/agent/starter/runtime.js +287 -0
- package/src/agent/starter/sandbox-main.js +121 -0
- package/src/agent/starter/settings.js +290 -0
- package/src/agent/starter/source.js +69 -0
- package/src/agent/starter/supervisor.js +755 -0
- package/src/agent/starter/sweep.js +46 -0
- package/src/agent/starter/tools.js +524 -0
- package/src/agent/starter/watch.js +84 -0
- package/src/agent/starter/worktree.js +409 -0
- package/src/agent/text-diff.js +210 -0
- package/src/agent/thread-history.js +223 -0
- package/src/agent/threads.js +399 -0
- package/src/agent/tools.js +200 -0
- package/src/agent/turn-changes.js +424 -0
- package/src/agent/undo-state.js +26 -0
- package/src/agent/user-settings.js +308 -0
- package/src/auth/record.js +375 -0
- package/src/broken-links.js +164 -0
- package/src/buzz/client.js +75 -0
- package/src/buzz/config.js +151 -0
- package/src/buzz/environment.js +13 -0
- package/src/buzz/gateway.js +192 -0
- package/src/buzz/routes.js +61 -0
- package/src/buzz/signer-child.js +205 -0
- package/src/buzz/store.js +89 -0
- package/src/buzz/transport.js +60 -0
- package/src/buzz/verify.js +140 -0
- package/src/capture/actions.js +159 -0
- package/src/capture/capture.js +776 -0
- package/src/capture/dom-names.js +189 -0
- package/src/capture/element-map.js +509 -0
- package/src/capture/live.js +827 -0
- package/src/capture/media-scheme.js +317 -0
- package/src/capture/network-summary.js +86 -0
- package/src/capture/pacing.js +34 -0
- package/src/capture/requests.js +167 -0
- package/src/capture/sanitize.js +752 -0
- package/src/checks/accessibility.js +134 -0
- package/src/checks/budgets.js +58 -0
- package/src/checks/cli.js +55 -0
- package/src/checks/comparison.js +113 -0
- package/src/checks/environments.js +32 -0
- package/src/checks/flow-config.js +82 -0
- package/src/checks/flow-origin.js +53 -0
- package/src/checks/flows.js +398 -0
- package/src/checks/lighthouse-auth.js +145 -0
- package/src/checks/lighthouse-findings.js +130 -0
- package/src/checks/lighthouse.js +395 -0
- package/src/checks/robots.js +85 -0
- package/src/checks/routes.js +52 -0
- package/src/checks/run-control.js +259 -0
- package/src/checks/runner.js +724 -0
- package/src/checks/schema.js +133 -0
- package/src/checks/seo-analysis.js +443 -0
- package/src/checks/seo-probe.js +190 -0
- package/src/checks/seo-snapshot.js +99 -0
- package/src/checks/store.js +214 -0
- package/src/checks/transport.js +47 -0
- package/src/cli/args.js +319 -0
- package/src/cli/capture.js +79 -0
- package/src/cli/commands.js +92 -0
- package/src/cli/comments.js +84 -0
- package/src/cli/help.js +243 -0
- package/src/cli/init.js +214 -0
- package/src/cli/misc.js +64 -0
- package/src/cli/notify.js +87 -0
- package/src/cli/open.js +22 -0
- package/src/cli/serve.js +274 -0
- package/src/cli/variant.js +82 -0
- package/src/cli/watch.js +70 -0
- package/src/cli.js +130 -0
- package/src/comment-fields.js +76 -0
- package/src/comments-cli.js +208 -0
- package/src/config-reload.js +100 -0
- package/src/config.js +1061 -0
- package/src/devices-cli.js +21 -0
- package/src/diff.js +95 -0
- package/src/discover.js +284 -0
- package/src/doctor.js +295 -0
- package/src/event-log.js +268 -0
- package/src/events-cli.js +102 -0
- package/src/events.js +113 -0
- package/src/export.js +119 -0
- package/src/feedback.js +246 -0
- package/src/github.js +551 -0
- package/src/hosted/LICENSE.md +105 -0
- package/src/hosted/access-cli.js +78 -0
- package/src/hosted/admin.js +682 -0
- package/src/hosted/agent-approvals.js +163 -0
- package/src/hosted/agent-policy.js +189 -0
- package/src/hosted/app.js +510 -0
- package/src/hosted/auth-routes.js +540 -0
- package/src/hosted/auth.js +536 -0
- package/src/hosted/backup.js +483 -0
- package/src/hosted/board-context.js +35 -0
- package/src/hosted/board-routes.js +486 -0
- package/src/hosted/board-view.js +94 -0
- package/src/hosted/clean-worker.js +24 -0
- package/src/hosted/cleaner.js +89 -0
- package/src/hosted/comments.js +355 -0
- package/src/hosted/console-routes.js +401 -0
- package/src/hosted/cookies.js +18 -0
- package/src/hosted/crypto.js +80 -0
- package/src/hosted/db.js +496 -0
- package/src/hosted/device-routes.js +175 -0
- package/src/hosted/device.js +233 -0
- package/src/hosted/events.js +63 -0
- package/src/hosted/guards.js +172 -0
- package/src/hosted/guest-view.js +65 -0
- package/src/hosted/http.js +39 -0
- package/src/hosted/import.js +300 -0
- package/src/hosted/mail.js +73 -0
- package/src/hosted/mcp-http.js +71 -0
- package/src/hosted/membership.js +114 -0
- package/src/hosted/operator.js +478 -0
- package/src/hosted/ops-cli.js +345 -0
- package/src/hosted/pages.js +146 -0
- package/src/hosted/permissions.js +113 -0
- package/src/hosted/presence.js +372 -0
- package/src/hosted/projects.js +124 -0
- package/src/hosted/public.js +109 -0
- package/src/hosted/push.js +622 -0
- package/src/hosted/quotas.js +115 -0
- package/src/hosted/ratelimit.js +96 -0
- package/src/hosted/rebind.js +316 -0
- package/src/hosted/retention.js +128 -0
- package/src/hosted/server.js +260 -0
- package/src/hosted/setup-link.js +64 -0
- package/src/hosted/setup.js +323 -0
- package/src/hosted/shares.js +444 -0
- package/src/hosted/tailscale.js +204 -0
- package/src/hosted/tenancy.js +301 -0
- package/src/hosted/token-api.js +455 -0
- package/src/hosted/token-events.js +60 -0
- package/src/hosted/tokens.js +57 -0
- package/src/hosted/turnstile.js +49 -0
- package/src/hosted/usercontent.js +154 -0
- package/src/hosted/zip.js +155 -0
- package/src/invocation.js +58 -0
- package/src/journey-paths.js +282 -0
- package/src/journeys.js +189 -0
- package/src/links.js +106 -0
- package/src/local-projects.js +182 -0
- package/src/lock.js +193 -0
- package/src/mcp.js +417 -0
- package/src/mentions.js +151 -0
- package/src/net.js +15 -0
- package/src/notify/config.js +275 -0
- package/src/notify/index.js +301 -0
- package/src/notify/lease.js +73 -0
- package/src/notify/messages.js +212 -0
- package/src/notify/run.js +174 -0
- package/src/pixeldiff.js +49 -0
- package/src/png.js +143 -0
- package/src/reactions.js +111 -0
- package/src/remote/cli.js +133 -0
- package/src/remote/credentials.js +62 -0
- package/src/remote/ids.js +12 -0
- package/src/remote/login.js +155 -0
- package/src/remote/remote-mcp.js +237 -0
- package/src/remote/remote-watch.js +291 -0
- package/src/remote/remote.js +313 -0
- package/src/remote/share-state.js +78 -0
- package/src/remote/share.js +369 -0
- package/src/remote/terminal.js +13 -0
- package/src/serve-state.js +64 -0
- package/src/server/app.js +824 -0
- package/src/server/devices.js +186 -0
- package/src/server/local-console.js +28 -0
- package/src/server/local-user.js +59 -0
- package/src/server/pairing-routes.js +159 -0
- package/src/server/share-routes.js +89 -0
- package/src/server/tailscale.js +97 -0
- package/src/sitemap.js +431 -0
- package/src/store.js +983 -0
- package/src/tokens.js +11 -0
- package/src/update/routes.js +245 -0
- package/src/watch.js +403 -0
- package/src/which.js +58 -0
|
@@ -0,0 +1,1065 @@
|
|
|
1
|
+
// /api/agent/*: the chat panel's API. JSON in, server-sent events out.
|
|
2
|
+
//
|
|
3
|
+
// GET /api/agent/status what chat is connected to (no secrets)
|
|
4
|
+
// GET /api/agent/boards/:id/threads the viewer's chat history (?q= searches it)
|
|
5
|
+
// GET /api/agent/boards/:id/threads/:thread one thread
|
|
6
|
+
// POST /api/agent/boards/:id/threads/:thread/messages send a message (editOf: rerun from an edit; regenerate: a new answer); SSE back
|
|
7
|
+
// POST /api/agent/boards/:id/threads/:thread/stop stop the answer being written
|
|
8
|
+
// PATCH /api/agent/boards/:id/threads/:thread rename or archive { title?, archived? }
|
|
9
|
+
// POST /api/agent/boards/:id/threads/:thread/versions/:v bring back an earlier version (before an edit)
|
|
10
|
+
// DELETE /api/agent/boards/:id/threads/:thread clear the thread (a chat: delete it)
|
|
11
|
+
// POST .../threads/:thread/messages/:message/rating rate an answer (thumbs up/down); DELETE takes it back
|
|
12
|
+
// GET /api/agent/feedback, .../feedback/export the owner's review of answer ratings (src/agent/ratings.js)
|
|
13
|
+
// POST /api/agent/boards/:id/threads/:thread/messages/:message/undo
|
|
14
|
+
// undo what an agent turn changed (owner only, turn-changes.js)
|
|
15
|
+
// GET /api/agent/boards/:id/files/:file an attached image
|
|
16
|
+
// GET /api/agent/settings, POST .../settings, .../test Settings > Agent (src/agent/settings-routes.js)
|
|
17
|
+
//
|
|
18
|
+
// :thread is "board", "comment-<id>" or "chat-<16 letters and digits>" (New
|
|
19
|
+
// chat). The app mounts this router only when chat is on (never on a
|
|
20
|
+
// read-only board).
|
|
21
|
+
//
|
|
22
|
+
// Privacy (threads.js visibleTo): a chat-* thread belongs to the viewer who
|
|
23
|
+
// sent its first message, and anyone else gets 404 for it and never sees it in
|
|
24
|
+
// the list. The viewer (viewerOf below) is the signed-in local account, else
|
|
25
|
+
// the owner (this machine, a paired device, the owner over Tailscale), else a
|
|
26
|
+
// random key in an HttpOnly cookie for this browser (a visitor of a board
|
|
27
|
+
// shared with --chat). The board thread and comment threads stay shared, as
|
|
28
|
+
// they were before chat history.
|
|
29
|
+
//
|
|
30
|
+
// Every message spends the server owner's key, so sending is limited: a token
|
|
31
|
+
// bucket per board, a cap on answers being written at once across all
|
|
32
|
+
// boards, and a byte quota per board for stored threads and images.
|
|
33
|
+
|
|
34
|
+
import { createHash, randomBytes } from 'node:crypto'
|
|
35
|
+
import express from 'express'
|
|
36
|
+
import { addReply, getComment, listComments, setAgentStatus } from '../store.js'
|
|
37
|
+
import { createBackend } from './backends/index.js'
|
|
38
|
+
import { authFiles } from '../config.js'
|
|
39
|
+
import { agentSettings, publicAgentInfo } from './config.js'
|
|
40
|
+
import { AgentError } from './errors.js'
|
|
41
|
+
import { createAgentHealth } from './agent-health.js'
|
|
42
|
+
import { beginAgentOperation } from './control.js'
|
|
43
|
+
import { validateFiles, validateMentions } from './composer.js'
|
|
44
|
+
import { profileForDefault, userAgentEntry } from './user-settings.js'
|
|
45
|
+
import { finishFix, projectChanged, projectSnapshot } from './feedback-loop.js'
|
|
46
|
+
import { ownerMcpServers } from './owner-mcp.js'
|
|
47
|
+
import { RUN_MS_MAX, commentIdOf, runTurn } from './run.js'
|
|
48
|
+
import { beginTurnChanges, finishTurnChanges, undoFiles, undoStarterBranch } from './turn-changes.js'
|
|
49
|
+
import { latestChange, withUndoAvailability } from './undo-state.js'
|
|
50
|
+
import { exportRatings, findAnswer, myRatings, raterOf, removeRating, reviewRatings, setRating } from './ratings.js'
|
|
51
|
+
import { localRequest, sameOriginWrite, settingsRoutes, settingsTokenOk } from './settings-routes.js'
|
|
52
|
+
import { APPROVAL_ID_RE, answerApproval } from './starter/approvals.js'
|
|
53
|
+
import {
|
|
54
|
+
CHAT_RE,
|
|
55
|
+
MEDIA_TYPES,
|
|
56
|
+
QUERY_MAX,
|
|
57
|
+
THREAD_RE,
|
|
58
|
+
appendAssistantMessage,
|
|
59
|
+
appendUserMessage,
|
|
60
|
+
attachmentPath,
|
|
61
|
+
changeMessage,
|
|
62
|
+
changeThreadInfo,
|
|
63
|
+
chatBytes,
|
|
64
|
+
clearThread,
|
|
65
|
+
listThreads,
|
|
66
|
+
readThread,
|
|
67
|
+
replaceAnswer,
|
|
68
|
+
restoreVersion,
|
|
69
|
+
setThreadProfile,
|
|
70
|
+
threadKind,
|
|
71
|
+
titleOf,
|
|
72
|
+
validateUserMessage,
|
|
73
|
+
versionsOf,
|
|
74
|
+
visibleTo,
|
|
75
|
+
} from './threads.js'
|
|
76
|
+
|
|
77
|
+
// Four 5 MB images in base64, and the text. Only POST .../messages reads a
|
|
78
|
+
// body this big, and only once the message is allowed to run.
|
|
79
|
+
export const BODY_LIMIT = '28mb'
|
|
80
|
+
const SMALL_BODY_LIMIT = '4kb'
|
|
81
|
+
|
|
82
|
+
export const DEFAULT_LIMITS = {
|
|
83
|
+
// Answers being written at once, across all boards.
|
|
84
|
+
runsMax: 4,
|
|
85
|
+
// Messages per board: a bucket of `burst` that refills `perMinute` a minute.
|
|
86
|
+
burst: 10,
|
|
87
|
+
perMinute: 20,
|
|
88
|
+
// Stored chat (threads and images) per board.
|
|
89
|
+
chatBytesMax: 200 * 1024 * 1024,
|
|
90
|
+
// A comment line on an open stream, so proxies keep it open while the model thinks.
|
|
91
|
+
keepaliveMs: 15000,
|
|
92
|
+
// Rating changes per board (thumbs up/down, taken back): a bucket of
|
|
93
|
+
// `ratingBurst` that refills `ratingPerMinute` a minute, so nobody can
|
|
94
|
+
// flood the ratings file and push the owner's older entries out.
|
|
95
|
+
ratingBurst: 30,
|
|
96
|
+
ratingPerMinute: 60,
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function fail(res, status, code, message) {
|
|
100
|
+
res.status(status).json({ error: { code, message } })
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// The browser key of a viewer without an account or owner access.
|
|
104
|
+
export const CHAT_KEY_COOKIE = 'sw_chat_key'
|
|
105
|
+
const CHAT_KEY_RE = /^[a-f0-9]{32}$/
|
|
106
|
+
const VERSION_RE = /^ver_[a-z0-9]{6,20}$/
|
|
107
|
+
|
|
108
|
+
function cookieValue(req, name) {
|
|
109
|
+
for (const part of String(req.headers.cookie || '').split(';')) {
|
|
110
|
+
const [key, ...rest] = part.trim().split('=')
|
|
111
|
+
if (key === name) return rest.join('=')
|
|
112
|
+
}
|
|
113
|
+
return null
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Who is asking, as the key a private chat stores as its owner (never sent
|
|
117
|
+
// to the browser). `accountUser(req)`: the signed-in local account's id.
|
|
118
|
+
export function viewerOf(req, res, { accountUser = null } = {}) {
|
|
119
|
+
const user = accountUser?.(req)
|
|
120
|
+
if (user) return `user:${user}`
|
|
121
|
+
const access = req.shapewallAccess
|
|
122
|
+
if (access ? ['host', 'device', 'identity'].includes(access.kind) : localRequest(req)) return 'owner'
|
|
123
|
+
let key = cookieValue(req, CHAT_KEY_COOKIE)
|
|
124
|
+
if (!CHAT_KEY_RE.test(key || '')) {
|
|
125
|
+
key = randomBytes(16).toString('hex')
|
|
126
|
+
if (!res.headersSent)
|
|
127
|
+
res.append(
|
|
128
|
+
'Set-Cookie',
|
|
129
|
+
`${CHAT_KEY_COOKIE}=${key}; Path=/api/agent; HttpOnly; SameSite=Strict; Max-Age=31536000${req.secure ? '; Secure' : ''}`,
|
|
130
|
+
)
|
|
131
|
+
}
|
|
132
|
+
return `key:${createHash('sha256').update(key).digest('hex').slice(0, 32)}`
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// A token bucket: take() is true while there is a token.
|
|
136
|
+
export function tokenBucket({ burst, perMinute, now = () => Date.now() }) {
|
|
137
|
+
let tokens = burst
|
|
138
|
+
let at = now()
|
|
139
|
+
return {
|
|
140
|
+
take() {
|
|
141
|
+
const time = now()
|
|
142
|
+
tokens = Math.min(burst, tokens + ((time - at) / 60000) * perMinute)
|
|
143
|
+
at = time
|
|
144
|
+
if (tokens < 1) return false
|
|
145
|
+
tokens -= 1
|
|
146
|
+
return true
|
|
147
|
+
},
|
|
148
|
+
retryAfter: () => Math.max(1, Math.ceil(((1 - tokens) / perMinute) * 60)),
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// `acp` is the ACP agent command from `shapewall serve --agent-acp` (or null:
|
|
153
|
+
// SHAPEWALL_AGENT_ACP in `env` is read too). `limits.acp` tunes the ACP
|
|
154
|
+
// bridge (src/agent/backends/acp.js ACP_DEFAULTS).
|
|
155
|
+
//
|
|
156
|
+
// `shared`: the board is reachable beyond this machine. Then an ACP agent
|
|
157
|
+
// runs only with `allowRemoteAgent` (serve --allow-remote-agent), whatever
|
|
158
|
+
// the settings say later (they are read on every request, so a save on
|
|
159
|
+
// another board of this project would otherwise switch this one over), and
|
|
160
|
+
// Settings > Agent is off.
|
|
161
|
+
export function agentRouter({
|
|
162
|
+
config,
|
|
163
|
+
env = process.env,
|
|
164
|
+
fetchImpl = globalThis.fetch,
|
|
165
|
+
log = () => {},
|
|
166
|
+
limits = {},
|
|
167
|
+
acp = null,
|
|
168
|
+
shared = false,
|
|
169
|
+
settingsToken = null,
|
|
170
|
+
allowRemoteAgent = false,
|
|
171
|
+
allowCapture = true,
|
|
172
|
+
capture = null,
|
|
173
|
+
accountUser = null,
|
|
174
|
+
}) {
|
|
175
|
+
const limit = { ...DEFAULT_LIMITS, ...limits }
|
|
176
|
+
const router = express.Router()
|
|
177
|
+
const settings = (profileId = null) => {
|
|
178
|
+
const current = agentSettings(config, env, { acp, profileId })
|
|
179
|
+
if (shared && !allowRemoteAgent && current.backend === 'acp' && current.configured) {
|
|
180
|
+
return {
|
|
181
|
+
...current,
|
|
182
|
+
configured: false,
|
|
183
|
+
problem:
|
|
184
|
+
'an ACP agent does not run on a board shared beyond this machine (anyone reaching it would act as you); start shapewall serve with --allow-remote-agent to allow it',
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return current
|
|
188
|
+
}
|
|
189
|
+
router.settings = settings
|
|
190
|
+
// A backend keeps what it learned (a model without tools, running agent
|
|
191
|
+
// processes) while the settings stay the same.
|
|
192
|
+
let cached = null
|
|
193
|
+
const backends = new Map()
|
|
194
|
+
const processPool = { epoch: 0, agents: new Set(), max: Math.min(limit.runsMax, limit.acp?.processesMax ?? limit.runsMax) }
|
|
195
|
+
// How each agent is doing (agent-health.js): from the last turn or test.
|
|
196
|
+
const health = createAgentHealth()
|
|
197
|
+
const agentStatus = (current) => health.status(current, processPool)
|
|
198
|
+
router.health = health
|
|
199
|
+
const profiles = () => {
|
|
200
|
+
const saved = userAgentEntry(config.dir, env)
|
|
201
|
+
const locked = acp || env.SHAPEWALL_AGENT_ACP
|
|
202
|
+
// The default connection runs the same command as a saved profile: the
|
|
203
|
+
// picker shows that profile once, by name (sameAs), not both.
|
|
204
|
+
const fallback = settings().defaultProfile
|
|
205
|
+
const same = !locked ? profileForDefault(saved.entry) || (fallback ? { id: fallback } : null) : null
|
|
206
|
+
return [
|
|
207
|
+
{ id: 'default', ...publicAgentInfo(settings()), ...agentStatus(settings()), ...(same ? { sameAs: same.id } : {}) },
|
|
208
|
+
...(!locked
|
|
209
|
+
? (saved.entry?.profiles || []).map((item) => ({
|
|
210
|
+
id: item.id,
|
|
211
|
+
...publicAgentInfo(settings(item.id)),
|
|
212
|
+
...agentStatus(settings(item.id)),
|
|
213
|
+
}))
|
|
214
|
+
: []),
|
|
215
|
+
]
|
|
216
|
+
}
|
|
217
|
+
const ownerWritesFor = (req) =>
|
|
218
|
+
!shared && ((localRequest(req) && settingsTokenOk(req, settingsToken)) || ['device', 'identity'].includes(req.shapewallAccess?.kind))
|
|
219
|
+
router.ownerWritesFor = ownerWritesFor
|
|
220
|
+
// An ACP agent can run commands as the person. Where this server has an
|
|
221
|
+
// owner capability (the settings token of a direct local board, a paired
|
|
222
|
+
// device), reaching the port is not enough to drive one: the owner, or the
|
|
223
|
+
// signed-in account, must be asking. Without a token (a board shared with
|
|
224
|
+
// --chat --allow-remote-agent) the documented rule stays: whoever reaches
|
|
225
|
+
// the board may chat.
|
|
226
|
+
const agentOwner = (req) => ownerWritesFor(req) || Boolean(accountUser?.(req))
|
|
227
|
+
const ownerGate = Boolean(settingsToken) && !shared
|
|
228
|
+
const chatNeedsOwner = (req, current = settings()) => ownerGate && current.backend === 'acp' && current.configured && !agentOwner(req)
|
|
229
|
+
router.chatNeedsOwner = chatNeedsOwner
|
|
230
|
+
// The same state fields /status reports, for /api/info.
|
|
231
|
+
router.agentStatus = () => agentStatus(settings())
|
|
232
|
+
const ownerNeeded = (res) =>
|
|
233
|
+
fail(
|
|
234
|
+
res,
|
|
235
|
+
403,
|
|
236
|
+
'control_needs_owner',
|
|
237
|
+
'This agent can run commands on this computer, so only its owner can use it. Open the private owner link from the terminal (or run shapewall serve --open), or use a paired device.',
|
|
238
|
+
)
|
|
239
|
+
const backendFor = (current, ownerWrites = false) => {
|
|
240
|
+
const key = JSON.stringify({ profileId: current.profileId || 'default', ownerWrites })
|
|
241
|
+
const fingerprint = JSON.stringify(current)
|
|
242
|
+
if (backends.has(key) && backends.get(key).fingerprint !== fingerprint) {
|
|
243
|
+
backends.get(key).backend?.close?.()
|
|
244
|
+
backends.delete(key)
|
|
245
|
+
}
|
|
246
|
+
if (!backends.has(key)) {
|
|
247
|
+
// usage: an endpoint is asked for token counts (the composer's usage
|
|
248
|
+
// ring); one that refuses stream_options is asked again without.
|
|
249
|
+
const backend = createBackend(
|
|
250
|
+
{ ...current, usage: current.usage ?? true },
|
|
251
|
+
{
|
|
252
|
+
env,
|
|
253
|
+
fetchImpl,
|
|
254
|
+
processPool,
|
|
255
|
+
root: config.dir,
|
|
256
|
+
protect: [config.outputDir],
|
|
257
|
+
// Files capture runs or logs in with: a write needs an approval card.
|
|
258
|
+
sensitivePaths: () => authFiles(config),
|
|
259
|
+
mcpServersFor: ownerWrites ? (thread) => ownerMcpServers(config, thread.split('/')[0], { allowCapture }) : null,
|
|
260
|
+
// One agent process per thread, no more than answers at once.
|
|
261
|
+
limits: { processesMax: limit.runsMax, ...limit.acp },
|
|
262
|
+
log,
|
|
263
|
+
},
|
|
264
|
+
)
|
|
265
|
+
backends.set(key, { key, fingerprint, backend })
|
|
266
|
+
}
|
|
267
|
+
cached = backends.get(key)
|
|
268
|
+
return cached.backend
|
|
269
|
+
}
|
|
270
|
+
// The owner backend already running for these settings, never a new one
|
|
271
|
+
// (the composer's pickers read a live session's choices).
|
|
272
|
+
const liveOwnerBackend = (current) => {
|
|
273
|
+
const entry = backends.get(JSON.stringify({ profileId: current.profileId || 'default', ownerWrites: true }))
|
|
274
|
+
return entry && entry.fingerprint === JSON.stringify(current) ? entry.backend : null
|
|
275
|
+
}
|
|
276
|
+
// Server shutdown: stop agent processes (src/server/app.js stopChildren).
|
|
277
|
+
router.close = () => {
|
|
278
|
+
processPool.epoch += 1
|
|
279
|
+
const settingsStopped = settingsApi.close()
|
|
280
|
+
const owned = [...processPool.agents]
|
|
281
|
+
for (const agent of owned) agent.kill('shutdown')
|
|
282
|
+
for (const entry of backends.values()) entry.backend?.close?.()
|
|
283
|
+
backends.clear()
|
|
284
|
+
cached = null
|
|
285
|
+
return Promise.all([settingsStopped, ...owned.map((agent) => agent.stoppingPromise)])
|
|
286
|
+
}
|
|
287
|
+
router.backend = () => cached?.backend || null
|
|
288
|
+
router.processes = () =>
|
|
289
|
+
[...processPool.agents].map((item) => ({ thread: item.thread, pid: item.pid, state: item.state, busy: Boolean(item.turn) }))
|
|
290
|
+
// The composer's model and effort pickers for a thread: an ACP session's
|
|
291
|
+
// own config options, or the model list of an endpoint (this chat's choice
|
|
292
|
+
// kept here, in memory, while the settings stay the same). Owner only.
|
|
293
|
+
const threadModels = new Map()
|
|
294
|
+
const chosenModel = (current, key) => {
|
|
295
|
+
const entry = threadModels.get(key)
|
|
296
|
+
return entry && entry.fingerprint === JSON.stringify(current) ? entry.model : null
|
|
297
|
+
}
|
|
298
|
+
const pickerOptions = async (current, key) => {
|
|
299
|
+
const backend = liveOwnerBackend(current)
|
|
300
|
+
if (backend?.sessionOptions) return backend.sessionOptions(key)
|
|
301
|
+
if (!backend?.listModels) return null
|
|
302
|
+
const ids = await backend.listModels()
|
|
303
|
+
const model = chosenModel(current, key) || current.model
|
|
304
|
+
const values = [...new Set([model, ...ids])].filter(Boolean).map((id) => ({ value: id, name: id }))
|
|
305
|
+
return values.length > 1 ? [{ id: 'model', category: 'model', name: 'Model', currentValue: model, values }] : null
|
|
306
|
+
}
|
|
307
|
+
const setPickerOption = async (current, key, configId, value) => {
|
|
308
|
+
const backend = liveOwnerBackend(current)
|
|
309
|
+
if (backend?.setSessionOption) return backend.setSessionOption(key, configId, value)
|
|
310
|
+
if (!backend?.listModels) throw new AgentError('no_session', 'The agent session ended. Send a message, then choose again.', 409)
|
|
311
|
+
if (configId !== 'model' || (value !== current.model && !(await backend.listModels()).includes(value)))
|
|
312
|
+
throw new AgentError('bad_option', 'The endpoint does not list that model.', 400)
|
|
313
|
+
if (value === current.model) threadModels.delete(key)
|
|
314
|
+
else threadModels.set(key, { model: value, fingerprint: JSON.stringify(current) })
|
|
315
|
+
return pickerOptions(current, key)
|
|
316
|
+
}
|
|
317
|
+
const runs = new Map()
|
|
318
|
+
const selecting = new Set()
|
|
319
|
+
let connectionTesting = () => false
|
|
320
|
+
// Keep controls privileged for the lifetime of an owner thread/session,
|
|
321
|
+
// including an idle ACP process. A tokenless turn cannot reset its memory.
|
|
322
|
+
const ownerThreads = new Set()
|
|
323
|
+
router.hasActiveFix = (boardId) => [...runs].some(([key, run]) => key.startsWith(`${boardId}/`) && run.fix)
|
|
324
|
+
const controlsAllowed = (req, board, threadId) => {
|
|
325
|
+
const key = `${board.id}/${threadId}`
|
|
326
|
+
if (!ownerThreads.has(key) && !runs.get(key)?.ownerWrites && !readThread(config, board.id, threadId).profileId) return true
|
|
327
|
+
return ownerWritesFor(req) && sameOriginWrite(req)
|
|
328
|
+
}
|
|
329
|
+
const controlDenied = (res) =>
|
|
330
|
+
fail(
|
|
331
|
+
res,
|
|
332
|
+
403,
|
|
333
|
+
'control_needs_owner',
|
|
334
|
+
'Only an owner device can control this agent session. Open the private link from the terminal or use a paired device.',
|
|
335
|
+
)
|
|
336
|
+
// Undo records of owner turns (turn-changes.js), in this process only:
|
|
337
|
+
// "<board>/<thread>/<message id>" -> { files, bytes }. The oldest go first.
|
|
338
|
+
const undoRecords = new Map()
|
|
339
|
+
const UNDO_RECORDS_MAX = 20
|
|
340
|
+
const UNDO_BYTES_MAX = 64 * 1024 * 1024
|
|
341
|
+
const rememberUndo = (key, record) => {
|
|
342
|
+
record.bytes = record.files.reduce((sum, item) => sum + (item.before?.length || 0), 0)
|
|
343
|
+
undoRecords.set(key, record)
|
|
344
|
+
let total = [...undoRecords.values()].reduce((sum, item) => sum + item.bytes, 0)
|
|
345
|
+
for (const [oldKey, old] of undoRecords) {
|
|
346
|
+
if (undoRecords.size <= UNDO_RECORDS_MAX && total <= UNDO_BYTES_MAX) break
|
|
347
|
+
undoRecords.delete(oldKey)
|
|
348
|
+
total -= old.bytes
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
router.undoRecords = undoRecords
|
|
352
|
+
// Turns started in this process: a turn that saw another start (or run)
|
|
353
|
+
// meanwhile cannot tell its own edits apart, so it offers no Undo.
|
|
354
|
+
let turnSerial = 0
|
|
355
|
+
let undoing = false
|
|
356
|
+
// The stored summary says whether Undo was possible; this process knows
|
|
357
|
+
// whether it still is, and only the thread's latest change offers it (undo-state.js).
|
|
358
|
+
const withUndoState = (boardId, threadId, messages, all = messages) =>
|
|
359
|
+
withUndoAvailability(
|
|
360
|
+
messages,
|
|
361
|
+
(message) =>
|
|
362
|
+
message.summary.undo.kind === 'files'
|
|
363
|
+
? undoRecords.has(`${boardId}/${threadId}/${message.id}`)
|
|
364
|
+
: message.summary.undo.available === true,
|
|
365
|
+
all,
|
|
366
|
+
)
|
|
367
|
+
const buckets = new Map()
|
|
368
|
+
const bucketFor = (boardId) => {
|
|
369
|
+
if (!buckets.has(boardId)) buckets.set(boardId, tokenBucket(limit))
|
|
370
|
+
return buckets.get(boardId)
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
const handleError = (res, error) => {
|
|
374
|
+
if (res.headersSent) return
|
|
375
|
+
const status = error.status || error.statusCode
|
|
376
|
+
if (error instanceof AgentError || (error.code && status && status < 500)) return fail(res, status, error.code, error.message)
|
|
377
|
+
log(`error: ${error.stack || error.message}`)
|
|
378
|
+
fail(res, 500, 'server_error', 'Something went wrong on the server.')
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
// Finds the board and checks the thread id (and its comment) for routes
|
|
382
|
+
// that have them; puts them on res.locals.
|
|
383
|
+
const findThread = (req, res, next) => {
|
|
384
|
+
const board = config.boards.find((item) => item.id === req.params.id)
|
|
385
|
+
if (!board) return fail(res, 404, 'unknown_board', 'No such board.')
|
|
386
|
+
const threadId = req.params.thread
|
|
387
|
+
try {
|
|
388
|
+
if (threadId !== undefined) {
|
|
389
|
+
if (!THREAD_RE.test(threadId)) return fail(res, 404, 'unknown_thread', 'No such chat thread.')
|
|
390
|
+
const commentId = commentIdOf(threadId)
|
|
391
|
+
if (commentId) getComment(config, board.id, commentId)
|
|
392
|
+
}
|
|
393
|
+
} catch (error) {
|
|
394
|
+
return handleError(res, error)
|
|
395
|
+
}
|
|
396
|
+
res.locals.board = board
|
|
397
|
+
res.locals.threadId = threadId
|
|
398
|
+
res.locals.viewer = viewerOf(req, res, { accountUser })
|
|
399
|
+
// Someone else's chat is not there at all.
|
|
400
|
+
if (threadId !== undefined && CHAT_RE.test(threadId) && !visibleTo(readThread(config, board.id, threadId), res.locals.viewer))
|
|
401
|
+
return fail(res, 404, 'unknown_thread', 'No such chat thread.')
|
|
402
|
+
next()
|
|
403
|
+
}
|
|
404
|
+
// A new agent session for a thread whose transcript changed under it (an
|
|
405
|
+
// edit, another version): the next turn sends the thread so far instead.
|
|
406
|
+
const resetSessions = (key) => {
|
|
407
|
+
for (const entry of backends.values()) entry.backend?.resetThread?.(key)
|
|
408
|
+
}
|
|
409
|
+
const handle = (handler) => async (req, res) => {
|
|
410
|
+
try {
|
|
411
|
+
await handler(req, res, res.locals.board, res.locals.threadId)
|
|
412
|
+
} catch (error) {
|
|
413
|
+
handleError(res, error)
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// ---- Sending: checked and reserved before the big body is read ----------
|
|
418
|
+
|
|
419
|
+
const admitMessage = async (req, res, next) => {
|
|
420
|
+
if (connectionTesting()) return fail(res, 409, 'test_running', 'A connection test is running. Wait for it before sending.')
|
|
421
|
+
if (undoing) return fail(res, 409, 'agent_running', 'An undo is running. Try again in a moment.')
|
|
422
|
+
const admission = new AbortController()
|
|
423
|
+
let release
|
|
424
|
+
res.once('close', () => {
|
|
425
|
+
admission.abort()
|
|
426
|
+
if (!res.locals.agentOperationRunning) release?.().catch((error) => log(`Agent activity cleanup: ${error.message}`))
|
|
427
|
+
})
|
|
428
|
+
if (req.aborted || res.destroyed) admission.abort()
|
|
429
|
+
try {
|
|
430
|
+
release = await beginAgentOperation(config, env, 'turn', { signal: admission.signal })
|
|
431
|
+
} catch {
|
|
432
|
+
if (admission.signal.aborted) return
|
|
433
|
+
return fail(res, 503, 'agent_activity_unavailable', 'Agent activity could not be checked. Inspect this installation before retrying.')
|
|
434
|
+
}
|
|
435
|
+
if (admission.signal.aborted) {
|
|
436
|
+
await release?.()
|
|
437
|
+
return
|
|
438
|
+
}
|
|
439
|
+
if (!release) return fail(res, 409, 'agent_running', 'Agent settings are changing in another window. Try again when finished.')
|
|
440
|
+
res.locals.releaseAgentOperation = release
|
|
441
|
+
const { board, threadId } = res.locals
|
|
442
|
+
const profileId = readThread(config, board.id, threadId).profileId || 'default'
|
|
443
|
+
const current = settings(profileId)
|
|
444
|
+
const ownerWrites = ownerWritesFor(req) && sameOriginWrite(req)
|
|
445
|
+
if (profileId !== 'default' && !ownerWrites) return controlDenied(res)
|
|
446
|
+
if (chatNeedsOwner(req, current) || (ownerGate && current.backend === 'acp' && current.configured && !sameOriginWrite(req)))
|
|
447
|
+
return ownerNeeded(res)
|
|
448
|
+
if (connectionTesting()) return fail(res, 409, 'test_running', 'A connection test is running. Wait for it before sending.')
|
|
449
|
+
const backend = backendFor(current, ownerWrites)
|
|
450
|
+
if (!backend) {
|
|
451
|
+
return fail(
|
|
452
|
+
res,
|
|
453
|
+
409,
|
|
454
|
+
'agent_not_configured',
|
|
455
|
+
'No agent is connected. See docs/agents.md to connect an OpenAI-compatible endpoint or an ACP agent (--agent-acp).',
|
|
456
|
+
)
|
|
457
|
+
}
|
|
458
|
+
const key = `${board.id}/${threadId}`
|
|
459
|
+
if ([...runs.values()].some((run) => run.fix)) return fail(res, 409, 'agent_running', 'A fix is already running in this project.')
|
|
460
|
+
if (runs.has(key) || selecting.has(key))
|
|
461
|
+
return fail(res, 409, 'agent_running', 'An answer or profile change is still running in this thread.')
|
|
462
|
+
if (runs.size >= limit.runsMax) {
|
|
463
|
+
res.setHeader('Retry-After', '5')
|
|
464
|
+
return fail(res, 429, 'agent_busy', 'The agent is answering other messages. Try again in a moment.')
|
|
465
|
+
}
|
|
466
|
+
const bucket = bucketFor(board.id)
|
|
467
|
+
if (!bucket.take()) {
|
|
468
|
+
res.setHeader('Retry-After', String(bucket.retryAfter()))
|
|
469
|
+
return fail(res, 429, 'rate_limited', 'Too many messages on this board. Wait a moment and send again.')
|
|
470
|
+
}
|
|
471
|
+
// The slot is held from here until the response closes, whatever happens
|
|
472
|
+
// (a body too large, a bad image, the board going away mid-answer).
|
|
473
|
+
const controller = new AbortController()
|
|
474
|
+
const run = { controller, current, backend, ownerWrites }
|
|
475
|
+
runs.set(key, run)
|
|
476
|
+
const timer = setTimeout(() => controller.abort('timeout'), backend.runMsMax || RUN_MS_MAX)
|
|
477
|
+
res.on('close', () => {
|
|
478
|
+
clearTimeout(timer)
|
|
479
|
+
clearInterval(run.keepalive)
|
|
480
|
+
// The board went away (tab closed, network): stop the model too.
|
|
481
|
+
if (!res.writableEnded) controller.abort('disconnected')
|
|
482
|
+
if (!res.locals.agentOperationRunning && runs.get(key) === run) runs.delete(key)
|
|
483
|
+
})
|
|
484
|
+
res.locals.run = run
|
|
485
|
+
next()
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
router.post(
|
|
489
|
+
'/boards/:id/threads/:thread/messages',
|
|
490
|
+
findThread,
|
|
491
|
+
admitMessage,
|
|
492
|
+
express.json({ limit: BODY_LIMIT }),
|
|
493
|
+
handle(async (req, res, board, threadId) => {
|
|
494
|
+
const { controller, current, backend, ownerWrites } = res.locals.run
|
|
495
|
+
res.locals.agentOperationRunning = true
|
|
496
|
+
try {
|
|
497
|
+
const fix = req.body?.fix === true
|
|
498
|
+
// Regenerate: the same request again, the new answer in the old one's
|
|
499
|
+
// place (threads.js replaceAnswer). Only the thread's latest answer.
|
|
500
|
+
const regenerate = req.body?.regenerate === undefined ? null : String(req.body.regenerate)
|
|
501
|
+
let previous = null
|
|
502
|
+
if (regenerate !== null) {
|
|
503
|
+
if (fix) return fail(res, 400, 'bad_regenerate', 'Regenerate and Fix with agent do not go together.')
|
|
504
|
+
const stored = readThread(config, board.id, threadId).messages
|
|
505
|
+
const last = stored.at(-1)
|
|
506
|
+
if (!last || last.id !== regenerate || last.role !== 'assistant' || last.starter || stored.at(-2)?.role !== 'user')
|
|
507
|
+
return fail(res, 409, 'cannot_regenerate', 'Only the latest answer to a message can be regenerated.')
|
|
508
|
+
if (chatBytes(config, board.id) + Buffer.byteLength(JSON.stringify(last)) > limit.chatBytesMax)
|
|
509
|
+
return fail(res, 413, 'chat_quota', 'Chat storage for this board is full. Clear a thread to free space.')
|
|
510
|
+
previous = last
|
|
511
|
+
}
|
|
512
|
+
if (fix && runs.size > 1) return fail(res, 409, 'agent_running', 'Wait for other agent turns before starting a fix.')
|
|
513
|
+
res.locals.run.fix = fix
|
|
514
|
+
const commentId = commentIdOf(threadId)
|
|
515
|
+
if (fix && (!ownerWrites || !allowCapture || !commentId || backend.id !== 'acp')) {
|
|
516
|
+
return fail(res, 403, 'fix_needs_owner', 'Fix with agent needs an owner device, captures enabled, and a connected coding agent.')
|
|
517
|
+
}
|
|
518
|
+
// Images for a model that does not take them are stored, then dropped
|
|
519
|
+
// before the request, with a note in the chat (run.js).
|
|
520
|
+
// Composer extras: @ mentions (ids, checked against this board) and text files.
|
|
521
|
+
const mentions = previous ? [] : validateMentions(config, board, req.body?.mentions)
|
|
522
|
+
const files = previous ? [] : validateFiles(req.body?.files)
|
|
523
|
+
const input = previous
|
|
524
|
+
? null
|
|
525
|
+
: { ...validateUserMessage(board, req.body, { extras: mentions.length + files.length }), mentions, files }
|
|
526
|
+
const editOf = req.body?.editOf ?? null
|
|
527
|
+
if (editOf !== null && (typeof editOf !== 'string' || editOf.length > 64 || fix || previous))
|
|
528
|
+
return fail(res, 400, 'bad_edit', 'editOf is the id of one of your messages in this thread.')
|
|
529
|
+
// An edit or a new answer rewrites the thread (and moves an owner
|
|
530
|
+
// turn's answer, with its Undo, into an earlier version): like
|
|
531
|
+
// bringing back a version, an owner session's thread needs the owner.
|
|
532
|
+
if ((editOf !== null || previous) && !controlsAllowed(req, board, threadId)) return controlDenied(res)
|
|
533
|
+
// The comment's agent status before this run, to put back when the
|
|
534
|
+
// agent never got to work (feedback-loop.js finishFix).
|
|
535
|
+
let previousStatus = null
|
|
536
|
+
if (fix) {
|
|
537
|
+
const comment = getComment(config, board.id, commentId)
|
|
538
|
+
previousStatus = comment.agentStatus ?? null
|
|
539
|
+
if (comment.status !== 'open' || ['queued', 'working'].includes(comment.agentStatus))
|
|
540
|
+
return fail(res, 409, 'comment_busy', 'This comment is resolved or already with an agent.')
|
|
541
|
+
const claimed = await setAgentStatus(config, board.id, commentId, 'queued', {
|
|
542
|
+
onlyFrom: [null, 'done', 'needs-human'],
|
|
543
|
+
actor: 'shapewall',
|
|
544
|
+
})
|
|
545
|
+
if (!claimed.changed) return fail(res, 409, 'comment_busy', 'This comment is already with an agent.')
|
|
546
|
+
}
|
|
547
|
+
const snapshot = ownerWrites && commentId && allowCapture ? projectSnapshot(config) : null
|
|
548
|
+
let userMessage
|
|
549
|
+
try {
|
|
550
|
+
userMessage = previous
|
|
551
|
+
? readThread(config, board.id, threadId).messages.at(-2)
|
|
552
|
+
: await appendUserMessage(config, board.id, threadId, input, {
|
|
553
|
+
quotaBytes: limit.chatBytesMax,
|
|
554
|
+
viewer: res.locals.viewer,
|
|
555
|
+
editOf,
|
|
556
|
+
})
|
|
557
|
+
} catch (error) {
|
|
558
|
+
if (fix) await setAgentStatus(config, board.id, commentId, 'needs-human', { onlyFrom: ['queued'], actor: 'shapewall' })
|
|
559
|
+
throw error
|
|
560
|
+
}
|
|
561
|
+
if (ownerWrites) ownerThreads.add(`${board.id}/${threadId}`)
|
|
562
|
+
if (editOf !== null) resetSessions(`${board.id}/${threadId}`)
|
|
563
|
+
if (controller.signal.aborted) {
|
|
564
|
+
if (fix) await setAgentStatus(config, board.id, commentId, 'needs-human', { onlyFrom: ['queued'], actor: 'shapewall' })
|
|
565
|
+
return
|
|
566
|
+
}
|
|
567
|
+
if (fix) {
|
|
568
|
+
const working = await setAgentStatus(config, board.id, commentId, 'working', { onlyFrom: ['queued'], actor: 'shapewall' })
|
|
569
|
+
if (!working.changed)
|
|
570
|
+
return fail(res, 409, 'comment_changed', 'The comment changed before the agent started. Review it and try again.')
|
|
571
|
+
}
|
|
572
|
+
res.writeHead(200, {
|
|
573
|
+
'Content-Type': 'text/event-stream; charset=utf-8',
|
|
574
|
+
'Cache-Control': 'no-store',
|
|
575
|
+
'X-Accel-Buffering': 'no',
|
|
576
|
+
Connection: 'keep-alive',
|
|
577
|
+
})
|
|
578
|
+
res.flushHeaders?.()
|
|
579
|
+
const emit = (event, data) => {
|
|
580
|
+
if (!res.writableEnded) res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)
|
|
581
|
+
}
|
|
582
|
+
res.locals.run.keepalive = setInterval(() => {
|
|
583
|
+
if (!res.writableEnded) res.write(': ping\n\n')
|
|
584
|
+
}, limit.keepaliveMs)
|
|
585
|
+
try {
|
|
586
|
+
emit('user', { message: userMessage })
|
|
587
|
+
let { messages } = readThread(config, board.id, threadId)
|
|
588
|
+
if (previous) {
|
|
589
|
+
messages = messages.filter((item) => item.id !== previous.id)
|
|
590
|
+
// An ACP agent keeps its own session, which saw the old answer.
|
|
591
|
+
if (backend.id === 'acp')
|
|
592
|
+
messages[messages.length - 1] = {
|
|
593
|
+
...messages.at(-1),
|
|
594
|
+
text: `[Shapewall] The person asked for a new answer to this same message. Answer it again from the start.\n\n${messages.at(-1).text || ''}`,
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
const requestedPages = new Set()
|
|
598
|
+
// An owner's turn: what it changes becomes the run summary, with Undo
|
|
599
|
+
// for an ACP agent's file edits (turn-changes.js).
|
|
600
|
+
const serial = ++turnSerial
|
|
601
|
+
const overlappedAtStart = runs.size > 1
|
|
602
|
+
const baseline = ownerWrites
|
|
603
|
+
? await beginTurnChanges(config, { comments: listComments(config, board.id), files: backend.id === 'acp' }).catch((error) => {
|
|
604
|
+
log(`run summary: ${error.message}`)
|
|
605
|
+
return null
|
|
606
|
+
})
|
|
607
|
+
: null
|
|
608
|
+
const reply = await runTurn({
|
|
609
|
+
config,
|
|
610
|
+
board,
|
|
611
|
+
threadId,
|
|
612
|
+
messages,
|
|
613
|
+
backend,
|
|
614
|
+
model: current.model,
|
|
615
|
+
// The composer's model picker (an endpoint's own list), owner turns only.
|
|
616
|
+
modelOverride: ownerWrites ? chosenModel(current, `${board.id}/${threadId}`) : null,
|
|
617
|
+
// The owner's own feedback notes go to the owner's turns only (ratings-core.js downNotes).
|
|
618
|
+
ownerTurn: res.locals.viewer === 'owner',
|
|
619
|
+
emit,
|
|
620
|
+
signal: controller.signal,
|
|
621
|
+
ownerWrites,
|
|
622
|
+
allowCapture,
|
|
623
|
+
capture,
|
|
624
|
+
requestedPages,
|
|
625
|
+
})
|
|
626
|
+
health.record(current, reply)
|
|
627
|
+
if (baseline) {
|
|
628
|
+
try {
|
|
629
|
+
const { summary, undo } = await finishTurnChanges(config, baseline, {
|
|
630
|
+
comments: listComments(config, board.id),
|
|
631
|
+
board,
|
|
632
|
+
reply,
|
|
633
|
+
pageIds: [...requestedPages],
|
|
634
|
+
commentId,
|
|
635
|
+
overlapped: overlappedAtStart || serial !== turnSerial || runs.size > 1,
|
|
636
|
+
})
|
|
637
|
+
if (summary) reply.summary = summary
|
|
638
|
+
if (undo) rememberUndo(`${board.id}/${threadId}/${reply.id}`, undo)
|
|
639
|
+
} catch (error) {
|
|
640
|
+
log(`run summary: ${error.message}`)
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
if (snapshot) {
|
|
644
|
+
const changed = projectChanged(snapshot, projectSnapshot(config))
|
|
645
|
+
if (fix || changed) {
|
|
646
|
+
emit('status', { text: changed ? 'Recapturing the changed page' : 'Checking the fix' })
|
|
647
|
+
await finishFix({
|
|
648
|
+
config,
|
|
649
|
+
board,
|
|
650
|
+
id: commentId,
|
|
651
|
+
reply,
|
|
652
|
+
changed,
|
|
653
|
+
pageIds: [...requestedPages],
|
|
654
|
+
capture,
|
|
655
|
+
signal: controller.signal,
|
|
656
|
+
previousStatus,
|
|
657
|
+
log,
|
|
658
|
+
})
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
if (previous) await replaceAnswer(config, board.id, threadId, previous.id, reply)
|
|
662
|
+
else await appendAssistantMessage(config, board.id, threadId, reply)
|
|
663
|
+
emit('done', { message: reply })
|
|
664
|
+
} finally {
|
|
665
|
+
clearInterval(res.locals.run.keepalive)
|
|
666
|
+
if (!res.writableEnded) res.end()
|
|
667
|
+
}
|
|
668
|
+
} finally {
|
|
669
|
+
try {
|
|
670
|
+
await res.locals.releaseAgentOperation()
|
|
671
|
+
} finally {
|
|
672
|
+
res.locals.agentOperationRunning = false
|
|
673
|
+
if (runs.get(`${board.id}/${threadId}`) === res.locals.run) runs.delete(`${board.id}/${threadId}`)
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
}),
|
|
677
|
+
)
|
|
678
|
+
|
|
679
|
+
// ---- Everything else: small bodies only ------------------------------------
|
|
680
|
+
|
|
681
|
+
router.use(express.json({ limit: SMALL_BODY_LIMIT }))
|
|
682
|
+
|
|
683
|
+
router.get('/status', (req, res) =>
|
|
684
|
+
res.json({
|
|
685
|
+
...publicAgentInfo(settings()),
|
|
686
|
+
...agentStatus(settings()),
|
|
687
|
+
...(profiles().length > 1 ? { profiles: profiles() } : {}),
|
|
688
|
+
ownerWrites: ownerWritesFor(req),
|
|
689
|
+
fixWithAgent: allowCapture && ownerWritesFor(req) && settings().backend === 'acp',
|
|
690
|
+
// Sending would answer 403 control_needs_owner: show the owner-link hint instead.
|
|
691
|
+
chatNeedsOwner: chatNeedsOwner(req),
|
|
692
|
+
}),
|
|
693
|
+
)
|
|
694
|
+
const settingsApi = settingsRoutes({
|
|
695
|
+
config,
|
|
696
|
+
env,
|
|
697
|
+
fetchImpl,
|
|
698
|
+
settings,
|
|
699
|
+
processPool,
|
|
700
|
+
health,
|
|
701
|
+
shared,
|
|
702
|
+
token: settingsToken,
|
|
703
|
+
busy: () => runs.size > 0 || selecting.size > 0,
|
|
704
|
+
// The chat switches over now: the next message gets the new backend, and
|
|
705
|
+
// agent processes of the old one stop.
|
|
706
|
+
reload: () => {
|
|
707
|
+
for (const entry of backends.values()) entry.backend?.close?.()
|
|
708
|
+
backends.clear()
|
|
709
|
+
return backendFor(settings())
|
|
710
|
+
},
|
|
711
|
+
})
|
|
712
|
+
connectionTesting = settingsApi.isTesting
|
|
713
|
+
router.use('/settings', settingsApi)
|
|
714
|
+
router.get(
|
|
715
|
+
'/boards/:id/threads',
|
|
716
|
+
findThread,
|
|
717
|
+
handle((req, res, board) => {
|
|
718
|
+
const query = typeof req.query.q === 'string' ? req.query.q.slice(0, QUERY_MAX) : ''
|
|
719
|
+
res.json({ threads: listThreads(config, board.id, { viewer: res.locals.viewer, query }) })
|
|
720
|
+
}),
|
|
721
|
+
)
|
|
722
|
+
router.get(
|
|
723
|
+
'/boards/:id/threads/:thread',
|
|
724
|
+
findThread,
|
|
725
|
+
handle(async (req, res, board, threadId) => {
|
|
726
|
+
const thread = readThread(config, board.id, threadId)
|
|
727
|
+
const current = settings(thread.profileId)
|
|
728
|
+
const options = ownerWritesFor(req) ? await pickerOptions(current, `${board.id}/${threadId}`) : null
|
|
729
|
+
res.json({
|
|
730
|
+
// The composer's model and effort pickers (owner only: a running ACP
|
|
731
|
+
// session's own choices, or an endpoint's model list).
|
|
732
|
+
...(options?.length ? { options } : {}),
|
|
733
|
+
id: thread.id,
|
|
734
|
+
messages: withUndoState(board.id, threadId, thread.messages),
|
|
735
|
+
kind: threadKind(threadId),
|
|
736
|
+
title: titleOf(thread),
|
|
737
|
+
archived: thread.archived === true,
|
|
738
|
+
shared: threadKind(threadId) !== 'chat',
|
|
739
|
+
versions: versionsOf(thread),
|
|
740
|
+
profileId: thread.profileId || 'default',
|
|
741
|
+
profiles: profiles(),
|
|
742
|
+
agent: {
|
|
743
|
+
...publicAgentInfo(current),
|
|
744
|
+
...agentStatus(current),
|
|
745
|
+
ownerWrites: ownerWritesFor(req),
|
|
746
|
+
fixWithAgent: allowCapture && ownerWritesFor(req) && current.backend === 'acp',
|
|
747
|
+
},
|
|
748
|
+
running: runs.has(`${board.id}/${threadId}`),
|
|
749
|
+
ratings: myRatings(config, board.id, threadId, raterOf(req.shapewallAccess, res.locals.viewer)),
|
|
750
|
+
})
|
|
751
|
+
}),
|
|
752
|
+
)
|
|
753
|
+
|
|
754
|
+
// ---- Answer feedback (ratings.js) --------------------------------------------
|
|
755
|
+
|
|
756
|
+
// Anyone who can use this thread rates the answers in it, once each: their
|
|
757
|
+
// own rating, never another person's. Writes come from this board's page.
|
|
758
|
+
const ratingBuckets = new Map()
|
|
759
|
+
const ratingBucketFor = (boardId) => {
|
|
760
|
+
if (!ratingBuckets.has(boardId)) ratingBuckets.set(boardId, tokenBucket({ burst: limit.ratingBurst, perMinute: limit.ratingPerMinute }))
|
|
761
|
+
return ratingBuckets.get(boardId)
|
|
762
|
+
}
|
|
763
|
+
const ratingRoute = (remove) =>
|
|
764
|
+
handle(async (req, res, board, threadId) => {
|
|
765
|
+
if (!sameOriginWrite(req)) return fail(res, 403, 'bad_origin', 'Rate answers from the board page.')
|
|
766
|
+
const bucket = ratingBucketFor(board.id)
|
|
767
|
+
if (!bucket.take()) {
|
|
768
|
+
res.setHeader('Retry-After', String(bucket.retryAfter()))
|
|
769
|
+
return fail(res, 429, 'rate_limited', 'Too many ratings on this board. Wait a moment and try again.')
|
|
770
|
+
}
|
|
771
|
+
const thread = readThread(config, board.id, threadId)
|
|
772
|
+
const found = findAnswer(thread.messages, req.params.message)
|
|
773
|
+
if (!found) return fail(res, 404, 'unknown_message', 'No such answer in this thread.')
|
|
774
|
+
const rater = raterOf(req.shapewallAccess, res.locals.viewer)
|
|
775
|
+
if (remove) {
|
|
776
|
+
await removeRating(config, board.id, { threadId, messageId: found.answer.id, rater })
|
|
777
|
+
return res.json({ rating: null })
|
|
778
|
+
}
|
|
779
|
+
const info = publicAgentInfo(settings(thread.profileId))
|
|
780
|
+
const entry = await setRating(config, board.id, {
|
|
781
|
+
threadId,
|
|
782
|
+
messageId: found.answer.id,
|
|
783
|
+
rater,
|
|
784
|
+
input: req.body,
|
|
785
|
+
found,
|
|
786
|
+
agent: { profileId: thread.profileId || 'default', backend: info.backend, label: info.label, model: info.model },
|
|
787
|
+
})
|
|
788
|
+
res.json({ rating: { rating: entry.rating, reasons: entry.reasons, note: entry.note } })
|
|
789
|
+
})
|
|
790
|
+
router.post('/boards/:id/threads/:thread/messages/:message/rating', findThread, ratingRoute(false))
|
|
791
|
+
router.delete('/boards/:id/threads/:thread/messages/:message/rating', findThread, ratingRoute(true))
|
|
792
|
+
|
|
793
|
+
// The owner's review (Console > Agent feedback) and its JSON export. Only an
|
|
794
|
+
// owner device: ratings quote questions and answers from every thread.
|
|
795
|
+
const reviewAllowed = (req, res, next) => {
|
|
796
|
+
if (!ownerWritesFor(req))
|
|
797
|
+
return fail(
|
|
798
|
+
res,
|
|
799
|
+
403,
|
|
800
|
+
'feedback_needs_owner',
|
|
801
|
+
'Only the owner can review agent feedback. Open the private link from the terminal or use a paired device.',
|
|
802
|
+
)
|
|
803
|
+
next()
|
|
804
|
+
}
|
|
805
|
+
router.get('/feedback', reviewAllowed, (req, res) => {
|
|
806
|
+
const days = Math.min(365, Math.max(1, Number.parseInt(req.query.days, 10) || 30))
|
|
807
|
+
const rating = ['up', 'down'].includes(req.query.rating) ? req.query.rating : null
|
|
808
|
+
const boardId = config.boards.some((board) => board.id === req.query.board) ? req.query.board : null
|
|
809
|
+
res.json({
|
|
810
|
+
...reviewRatings(config, { rating, days, boardId }),
|
|
811
|
+
boards: config.boards.map((board) => ({ id: board.id, title: board.title })),
|
|
812
|
+
})
|
|
813
|
+
})
|
|
814
|
+
router.get('/feedback/export', reviewAllowed, (req, res) => {
|
|
815
|
+
const data = exportRatings(config)
|
|
816
|
+
res.setHeader('Content-Disposition', `attachment; filename="shapewall-agent-feedback-${data.exportedAt.slice(0, 10)}.json"`)
|
|
817
|
+
res.json(data)
|
|
818
|
+
})
|
|
819
|
+
router.post(
|
|
820
|
+
'/boards/:id/threads/:thread/profile',
|
|
821
|
+
findThread,
|
|
822
|
+
handle(async (req, res, board, threadId) => {
|
|
823
|
+
if (!ownerWritesFor(req) || !sameOriginWrite(req)) return controlDenied(res)
|
|
824
|
+
if (connectionTesting()) return fail(res, 409, 'test_running', 'A connection test is running. Wait before changing its agent.')
|
|
825
|
+
const admission = new AbortController()
|
|
826
|
+
res.once('close', () => admission.abort())
|
|
827
|
+
if (req.aborted || res.destroyed) admission.abort()
|
|
828
|
+
const release = await beginAgentOperation(config, env, 'turn', { signal: admission.signal })
|
|
829
|
+
if (admission.signal.aborted) {
|
|
830
|
+
await release?.()
|
|
831
|
+
return
|
|
832
|
+
}
|
|
833
|
+
if (!release) return fail(res, 409, 'agent_running', 'Agent settings are changing in another window. Try again when finished.')
|
|
834
|
+
try {
|
|
835
|
+
const key = `${board.id}/${threadId}`
|
|
836
|
+
if (runs.has(key) || selecting.has(key)) return fail(res, 409, 'agent_running', 'Stop the answer before changing its agent.')
|
|
837
|
+
const profileId = req.body?.profileId
|
|
838
|
+
if (typeof profileId !== 'string' || !profiles().some((item) => item.id === profileId))
|
|
839
|
+
return fail(res, 400, 'unknown_profile', 'Choose a saved native agent profile.')
|
|
840
|
+
selecting.add(key)
|
|
841
|
+
try {
|
|
842
|
+
await setThreadProfile(config, board.id, threadId, profileId)
|
|
843
|
+
for (const entry of backends.values()) entry.backend?.resetThread?.(key)
|
|
844
|
+
ownerThreads.add(key)
|
|
845
|
+
res.json({ profileId, agent: publicAgentInfo(settings(profileId)) })
|
|
846
|
+
} finally {
|
|
847
|
+
selecting.delete(key)
|
|
848
|
+
}
|
|
849
|
+
} finally {
|
|
850
|
+
await release()
|
|
851
|
+
}
|
|
852
|
+
}),
|
|
853
|
+
)
|
|
854
|
+
// The composer's model or effort picker: { configId, value }, one of the
|
|
855
|
+
// choices the thread's running agent session lists. Owner only, never
|
|
856
|
+
// while an answer runs; the agent's defaults and Settings > Agent stay as
|
|
857
|
+
// they are (the choice lasts as long as the session).
|
|
858
|
+
router.post(
|
|
859
|
+
'/boards/:id/threads/:thread/options',
|
|
860
|
+
findThread,
|
|
861
|
+
handle(async (req, res, board, threadId) => {
|
|
862
|
+
if (!ownerWritesFor(req) || !sameOriginWrite(req)) return controlDenied(res)
|
|
863
|
+
const key = `${board.id}/${threadId}`
|
|
864
|
+
if (runs.has(key) || selecting.has(key)) return fail(res, 409, 'agent_running', 'Wait for the answer to finish before switching.')
|
|
865
|
+
const { configId, value } = req.body || {}
|
|
866
|
+
if (typeof configId !== 'string' || typeof value !== 'string' || configId.length > 100 || value.length > 200)
|
|
867
|
+
return fail(res, 400, 'bad_option', 'configId and value are strings.')
|
|
868
|
+
const options = await setPickerOption(settings(readThread(config, board.id, threadId).profileId), key, configId, value)
|
|
869
|
+
res.json({ options })
|
|
870
|
+
}),
|
|
871
|
+
)
|
|
872
|
+
router.delete(
|
|
873
|
+
'/boards/:id/threads/:thread',
|
|
874
|
+
findThread,
|
|
875
|
+
handle(async (req, res, board, threadId) => {
|
|
876
|
+
if (!controlsAllowed(req, board, threadId)) return controlDenied(res)
|
|
877
|
+
if (runs.has(`${board.id}/${threadId}`) || selecting.has(`${board.id}/${threadId}`))
|
|
878
|
+
return fail(res, 409, 'agent_running', 'Stop the answer first.')
|
|
879
|
+
await clearThread(config, board.id, threadId)
|
|
880
|
+
// An agent with its own memory (an ACP process per thread) forgets it
|
|
881
|
+
// too: the next message starts a fresh session.
|
|
882
|
+
for (const entry of backends.values()) entry.backend?.resetThread?.(`${board.id}/${threadId}`)
|
|
883
|
+
ownerThreads.delete(`${board.id}/${threadId}`)
|
|
884
|
+
threadModels.delete(`${board.id}/${threadId}`)
|
|
885
|
+
res.json({ ok: true })
|
|
886
|
+
}),
|
|
887
|
+
)
|
|
888
|
+
// Undo what one agent turn changed: an ACP agent's file edits (restored
|
|
889
|
+
// from this process's undo record, only while every file is still what
|
|
890
|
+
// the agent left), or the starter agent's unpushed branch (deleted). Owner
|
|
891
|
+
// device and same-origin only, never while an agent turn runs.
|
|
892
|
+
router.post(
|
|
893
|
+
'/boards/:id/threads/:thread/messages/:message/undo',
|
|
894
|
+
findThread,
|
|
895
|
+
handle(async (req, res, board, threadId) => {
|
|
896
|
+
if (!ownerWritesFor(req) || !sameOriginWrite(req)) return controlDenied(res)
|
|
897
|
+
if (runs.size || selecting.size || undoing) return fail(res, 409, 'agent_running', 'Wait for the agent to finish, then undo.')
|
|
898
|
+
const messageId = String(req.params.message)
|
|
899
|
+
const thread = readThread(config, board.id, threadId)
|
|
900
|
+
const message = thread.messages.find((item) => item.id === messageId && item.role === 'assistant')
|
|
901
|
+
const summary = message?.summary
|
|
902
|
+
if (!summary?.undo) return fail(res, 404, 'undo_unavailable', 'That answer changed nothing that can be undone.')
|
|
903
|
+
if (summary.undone) return fail(res, 409, 'undo_done', 'That change was undone already.')
|
|
904
|
+
if (latestChange(thread.messages) !== messageId)
|
|
905
|
+
return fail(res, 409, 'undo_unavailable', 'A later answer changed things after this one. Undo that one first.')
|
|
906
|
+
const key = `${board.id}/${threadId}/${messageId}`
|
|
907
|
+
undoing = true
|
|
908
|
+
try {
|
|
909
|
+
let undone
|
|
910
|
+
if (summary.undo.kind === 'files') {
|
|
911
|
+
const record = undoRecords.get(key)
|
|
912
|
+
if (!record) {
|
|
913
|
+
return fail(
|
|
914
|
+
res,
|
|
915
|
+
410,
|
|
916
|
+
'undo_unavailable',
|
|
917
|
+
'Undo is no longer available for this answer: the board server restarted, or newer answers took its place.',
|
|
918
|
+
)
|
|
919
|
+
}
|
|
920
|
+
const files = undoFiles(config, record)
|
|
921
|
+
undoRecords.delete(key)
|
|
922
|
+
undone = { kind: 'files', files: files.length }
|
|
923
|
+
} else if (summary.undo.kind === 'branch' && summary.undo.available) {
|
|
924
|
+
const commentId = commentIdOf(threadId)
|
|
925
|
+
if (!commentId) return fail(res, 404, 'undo_unavailable', 'That answer changed nothing that can be undone.')
|
|
926
|
+
const result = await undoStarterBranch(config, {
|
|
927
|
+
boardId: board.id,
|
|
928
|
+
commentId,
|
|
929
|
+
branch: summary.undo.branch,
|
|
930
|
+
commit: summary.undo.commit,
|
|
931
|
+
})
|
|
932
|
+
undone = { kind: 'branch', branch: result.branch }
|
|
933
|
+
} else {
|
|
934
|
+
return fail(
|
|
935
|
+
res,
|
|
936
|
+
409,
|
|
937
|
+
'undo_unavailable',
|
|
938
|
+
summary.undo.reason ? `Undo is not available: ${summary.undo.reason}.` : 'Undo is not available.',
|
|
939
|
+
)
|
|
940
|
+
}
|
|
941
|
+
// A comment the turn marked "Agent done" now needs a person again.
|
|
942
|
+
const commentId = commentIdOf(threadId)
|
|
943
|
+
if (commentId) {
|
|
944
|
+
try {
|
|
945
|
+
const changed = await setAgentStatus(config, board.id, commentId, 'needs-human', { onlyFrom: ['done'], actor: 'shapewall' })
|
|
946
|
+
if (changed.changed) {
|
|
947
|
+
await addReply(config, board.id, commentId, {
|
|
948
|
+
author: 'shapewall',
|
|
949
|
+
body: 'The agent’s change was undone from the chat. The page shows the earlier version again once it is recaptured.',
|
|
950
|
+
})
|
|
951
|
+
}
|
|
952
|
+
} catch (error) {
|
|
953
|
+
log(`undo: comment status: ${error.message}`)
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
const at = new Date().toISOString()
|
|
957
|
+
let stored = null
|
|
958
|
+
await changeMessage(config, board.id, threadId, messageId, (item) => {
|
|
959
|
+
item.summary = { ...item.summary, undone: { ...undone, at, by: req.shapewallAccess?.name || null } }
|
|
960
|
+
stored = item
|
|
961
|
+
})
|
|
962
|
+
res.json({ ok: true, message: withUndoState(board.id, threadId, [stored], readThread(config, board.id, threadId).messages)[0] })
|
|
963
|
+
} finally {
|
|
964
|
+
undoing = false
|
|
965
|
+
}
|
|
966
|
+
}),
|
|
967
|
+
)
|
|
968
|
+
router.patch(
|
|
969
|
+
'/boards/:id/threads/:thread',
|
|
970
|
+
findThread,
|
|
971
|
+
handle(async (req, res, board, threadId) => {
|
|
972
|
+
if (!controlsAllowed(req, board, threadId)) return controlDenied(res)
|
|
973
|
+
const { title, archived } = req.body || {}
|
|
974
|
+
if ((title !== undefined && typeof title !== 'string') || (archived !== undefined && typeof archived !== 'boolean'))
|
|
975
|
+
return fail(res, 400, 'bad_thread_info', 'Send { title: string } or { archived: true | false }.')
|
|
976
|
+
res.json(await changeThreadInfo(config, board.id, threadId, { title, archived }))
|
|
977
|
+
}),
|
|
978
|
+
)
|
|
979
|
+
router.post(
|
|
980
|
+
'/boards/:id/threads/:thread/versions/:version',
|
|
981
|
+
findThread,
|
|
982
|
+
handle(async (req, res, board, threadId) => {
|
|
983
|
+
if (!controlsAllowed(req, board, threadId)) return controlDenied(res)
|
|
984
|
+
const key = `${board.id}/${threadId}`
|
|
985
|
+
if (!VERSION_RE.test(req.params.version))
|
|
986
|
+
return fail(res, 404, 'unknown_version', 'That version is no longer kept. Reload the thread.')
|
|
987
|
+
if (runs.has(key) || selecting.has(key)) return fail(res, 409, 'agent_running', 'Stop the answer first.')
|
|
988
|
+
await restoreVersion(config, board.id, threadId, req.params.version)
|
|
989
|
+
resetSessions(key)
|
|
990
|
+
res.json({ ok: true })
|
|
991
|
+
}),
|
|
992
|
+
)
|
|
993
|
+
router.post(
|
|
994
|
+
'/boards/:id/threads/:thread/stop',
|
|
995
|
+
findThread,
|
|
996
|
+
handle((req, res, board, threadId) => {
|
|
997
|
+
if (!controlsAllowed(req, board, threadId)) return controlDenied(res)
|
|
998
|
+
const run = runs.get(`${board.id}/${threadId}`)
|
|
999
|
+
if (run) run.controller.abort('stopped')
|
|
1000
|
+
res.json({ stopped: Boolean(run) })
|
|
1001
|
+
}),
|
|
1002
|
+
)
|
|
1003
|
+
router.get(
|
|
1004
|
+
'/boards/:id/files/:file',
|
|
1005
|
+
findThread,
|
|
1006
|
+
handle((req, res, board) => {
|
|
1007
|
+
const file = attachmentPath(config, board.id, req.params.file)
|
|
1008
|
+
if (!file) return fail(res, 404, 'not_found', 'No such file.')
|
|
1009
|
+
res.setHeader('Cache-Control', 'private, max-age=604800, immutable')
|
|
1010
|
+
res.setHeader('Cross-Origin-Resource-Policy', 'same-origin')
|
|
1011
|
+
res.setHeader('Content-Security-Policy', "default-src 'none'; sandbox")
|
|
1012
|
+
res.type(MEDIA_TYPES[req.params.file.split('.').pop()]).sendFile(file, { dotfiles: 'allow' })
|
|
1013
|
+
}),
|
|
1014
|
+
)
|
|
1015
|
+
|
|
1016
|
+
// The person's answer to an agent's permission card: { optionId } picks one
|
|
1017
|
+
// of the agent's options, { optionId: null } denies.
|
|
1018
|
+
router.post(
|
|
1019
|
+
'/boards/:id/threads/:thread/permissions/:permission',
|
|
1020
|
+
findThread,
|
|
1021
|
+
handle(async (req, res, board, threadId) => {
|
|
1022
|
+
const optionId = req.body?.optionId ?? null
|
|
1023
|
+
if (optionId !== null && typeof optionId !== 'string') return fail(res, 400, 'bad_option', 'optionId is a string or null.')
|
|
1024
|
+
const permission = String(req.params.permission)
|
|
1025
|
+
let state = null
|
|
1026
|
+
if (!APPROVAL_ID_RE.test(permission)) {
|
|
1027
|
+
// A streaming answer's card lets the agent run a command or write a
|
|
1028
|
+
// file on this machine. Owner sessions need an owner device; every
|
|
1029
|
+
// answer must come from this board's own page.
|
|
1030
|
+
if (!(controlsAllowed(req, board, threadId) && sameOriginWrite(req))) return controlDenied(res)
|
|
1031
|
+
const run = runs.get(`${board.id}/${threadId}`)
|
|
1032
|
+
// An approval lets the agent run a command or write a file as the
|
|
1033
|
+
// person: with an owner capability on this server, only the owner answers.
|
|
1034
|
+
if (ownerGate && run?.backend.id === 'acp' && !agentOwner(req)) return ownerNeeded(res)
|
|
1035
|
+
state = run?.backend.answerPermission?.(`${board.id}/${threadId}`, permission, optionId, req.shapewallAccess?.name || null) ?? null
|
|
1036
|
+
} else {
|
|
1037
|
+
// A starter agent's command (written by `shapewall agent run`,
|
|
1038
|
+
// approvals.js). Only the person at this machine may answer it: the
|
|
1039
|
+
// settings token, a local and direct request from this board's page,
|
|
1040
|
+
// a board not shared.
|
|
1041
|
+
if (!(
|
|
1042
|
+
sameOriginWrite(req) &&
|
|
1043
|
+
(['device', 'identity'].includes(req.shapewallAccess?.kind) ||
|
|
1044
|
+
(!shared && settingsTokenOk(req, settingsToken) && localRequest(req)))
|
|
1045
|
+
)) {
|
|
1046
|
+
return fail(
|
|
1047
|
+
res,
|
|
1048
|
+
403,
|
|
1049
|
+
'approval_needs_owner',
|
|
1050
|
+
'Only the person running Shapewall can approve the starter agent: open the board from the link shapewall serve printed, on that machine.',
|
|
1051
|
+
)
|
|
1052
|
+
}
|
|
1053
|
+
state = await answerApproval(config, board.id, threadId, String(req.params.permission), optionId, {
|
|
1054
|
+
answeredBy: req.shapewallAccess?.name || null,
|
|
1055
|
+
})
|
|
1056
|
+
}
|
|
1057
|
+
if (state === false) return fail(res, 400, 'bad_option', 'The agent did not offer that option.')
|
|
1058
|
+
if (!state) return fail(res, 404, 'no_permission', 'That request is no longer waiting for an answer.')
|
|
1059
|
+
res.json({ state })
|
|
1060
|
+
}),
|
|
1061
|
+
)
|
|
1062
|
+
|
|
1063
|
+
router.use((req, res) => fail(res, 404, 'not_found', 'No such API route.'))
|
|
1064
|
+
return router
|
|
1065
|
+
}
|