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,46 @@
|
|
|
1
|
+
// What a run that died (killed, power cut) leaves behind: its containers,
|
|
2
|
+
// its network and its checkout folder. `agent run` and `agent watch` sweep
|
|
3
|
+
// them at the start. Only things whose owner process is gone are removed:
|
|
4
|
+
// another `shapewall agent` running now keeps its own.
|
|
5
|
+
|
|
6
|
+
import { OWNER_LABEL, RUN_LABEL } from './runtime.js'
|
|
7
|
+
import { processAlive, sweepWorkRoot } from './worktree.js'
|
|
8
|
+
|
|
9
|
+
const NAME_RE = /^shapewall-(agent|egress)-\d{14}-[a-f0-9]{6}$/
|
|
10
|
+
|
|
11
|
+
async function ownerOf(runtime, kind, name) {
|
|
12
|
+
const args =
|
|
13
|
+
kind === 'network'
|
|
14
|
+
? ['network', 'inspect', '--format', `{{index .Labels "${OWNER_LABEL}"}}`, name]
|
|
15
|
+
: ['inspect', '--format', `{{index .Config.Labels "${OWNER_LABEL}"}}`, name]
|
|
16
|
+
const found = await runtime.exec(args)
|
|
17
|
+
if (found.code !== 0) return null
|
|
18
|
+
const pid = Number(found.stdout.trim())
|
|
19
|
+
return Number.isInteger(pid) && pid > 0 ? pid : null
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// -> { containers: [...], networks: [...], folders: [...] } (what was removed)
|
|
23
|
+
export async function sweepLeftovers({ runtime, root = null, isAlive = processAlive, log = () => {} }) {
|
|
24
|
+
const removed = { containers: [], networks: [], folders: [] }
|
|
25
|
+
if (runtime) {
|
|
26
|
+
const listed = await runtime.exec(['ps', '-a', '--filter', `label=${RUN_LABEL}`, '--format', '{{.Names}}'])
|
|
27
|
+
for (const name of listed.code === 0 ? listed.stdout.split('\n').map((line) => line.trim()) : []) {
|
|
28
|
+
if (!NAME_RE.test(name)) continue
|
|
29
|
+
const pid = await ownerOf(runtime, 'container', name)
|
|
30
|
+
// No owner label: made before owners were recorded, so it is a leftover too.
|
|
31
|
+
if (pid !== null && isAlive(pid)) continue
|
|
32
|
+
if ((await runtime.exec(['rm', '-f', name])).code === 0) removed.containers.push(name)
|
|
33
|
+
}
|
|
34
|
+
const networks = await runtime.exec(['network', 'ls', '--filter', `label=${RUN_LABEL}`, '--format', '{{.Name}}'])
|
|
35
|
+
for (const name of networks.code === 0 ? networks.stdout.split('\n').map((line) => line.trim()) : []) {
|
|
36
|
+
if (!NAME_RE.test(name)) continue
|
|
37
|
+
const pid = await ownerOf(runtime, 'network', name)
|
|
38
|
+
if (pid !== null && isAlive(pid)) continue
|
|
39
|
+
if ((await runtime.exec(['network', 'rm', name])).code === 0) removed.networks.push(name)
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
if (root) removed.folders = sweepWorkRoot(root, { isAlive })
|
|
43
|
+
const total = removed.containers.length + removed.networks.length + removed.folders.length
|
|
44
|
+
if (total) log(`removed what earlier runs left: ${[...removed.containers, ...removed.networks, ...removed.folders].join(', ')}`)
|
|
45
|
+
return removed
|
|
46
|
+
}
|
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
// The starter agent's tools, run inside the container. A fixed set: read,
|
|
2
|
+
// search and edit files in the worktree, run the configured test command,
|
|
3
|
+
// `shapewall capture`, reply on the comment, set its status, and (only with
|
|
4
|
+
// the person's approval of each command, on the board) run a shell command.
|
|
5
|
+
//
|
|
6
|
+
// Every path goes through the ACP bridge's sandbox (src/agent/acp/sandbox.js):
|
|
7
|
+
// resolved after symlinks, refused outside the worktree, and writes refused
|
|
8
|
+
// in .git. Reads of .git are refused too (in a worktree it only points at
|
|
9
|
+
// the host's repository). The container is the outer wall; this is the
|
|
10
|
+
// inner one, so a tool call that names a file outside is refused, not tried.
|
|
11
|
+
|
|
12
|
+
import fs from 'node:fs'
|
|
13
|
+
import path from 'node:path'
|
|
14
|
+
import { spawn } from 'node:child_process'
|
|
15
|
+
import { fileURLToPath } from 'node:url'
|
|
16
|
+
import { createSandbox, inside } from '../acp/sandbox.js'
|
|
17
|
+
|
|
18
|
+
export const TOOL_OUTPUT_MAX = 16000
|
|
19
|
+
const READ_CHARS_MAX = 100000
|
|
20
|
+
const LIST_MAX = 400
|
|
21
|
+
const SEARCH_MATCHES_MAX = 100
|
|
22
|
+
const SEARCH_FILE_BYTES_MAX = 1024 * 1024
|
|
23
|
+
const SEARCH_FILES_MAX = 20000
|
|
24
|
+
const COMMAND_OUTPUT_MAX = 64 * 1024
|
|
25
|
+
const COMMAND_MS_MAX = 10 * 60 * 1000
|
|
26
|
+
const SKIP_DIRS = new Set(['.git', 'node_modules', '.shapewall', 'shapewall-export'])
|
|
27
|
+
// Files that decide what a test command runs: manifests, lockfiles, test and
|
|
28
|
+
// build configs, and the files the command names.
|
|
29
|
+
const TEST_INPUT_RE =
|
|
30
|
+
/(^|\/)(package\.json|package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|pnpm-workspace\.yaml|\.npmrc|\.yarnrc(\.yml)?|\.nvmrc|\.mocharc(\.[a-z]+)?|\.babelrc(\.[a-z]+)?|babel\.config\.[a-z]+|(jest|vitest|vite|playwright|karma|ava|cypress|webpack|rollup|esbuild|nyc|c8)\.config\.[a-z.]+|\.c8rc(\.json)?|\.nycrc(\.[a-z]+)?|tsconfig(\.[a-z.]+)?\.json|\.taprc|pytest\.ini|conftest\.py|setup\.cfg|setup\.py|tox\.ini|noxfile\.py|pyproject\.toml|makefile|justfile|\.env(\..*)?)$/i
|
|
31
|
+
export function testInput(file, testCommand = []) {
|
|
32
|
+
if (TEST_INPUT_RE.test(file)) return true
|
|
33
|
+
return testCommand.some((part) => {
|
|
34
|
+
if (!/[/\\]|\.(c|m)?[jt]s$|\.(py|sh|rb|pl)$/.test(part) || path.isAbsolute(part)) return false
|
|
35
|
+
return path.posix.normalize(part.replace(/\\/g, '/')).replace(/^\.\//, '') === file
|
|
36
|
+
})
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export const REPLY_MAX = 2000
|
|
40
|
+
export const REPLIES_MAX = 3
|
|
41
|
+
export const SHELL_COMMAND_MAX = 2000
|
|
42
|
+
const SHAPEWALL_BIN = fileURLToPath(new URL('../../../bin/shapewall.js', import.meta.url))
|
|
43
|
+
|
|
44
|
+
export class ToolError extends Error {}
|
|
45
|
+
|
|
46
|
+
// What every capture call answers when the site is not reachable from the
|
|
47
|
+
// sandbox (the host decided so before the run, or the capture could not connect).
|
|
48
|
+
export const CAPTURE_UNAVAILABLE = 'capture is unavailable in the sandbox; skip it'
|
|
49
|
+
// Capture output that means the browser could not reach the site at all.
|
|
50
|
+
const UNREACHABLE_RE =
|
|
51
|
+
/net::ERR_(CONNECTION_REFUSED|CONNECTION_RESET|CONNECTION_CLOSED|CONNECTION_FAILED|CONNECTION_TIMED_OUT|NAME_NOT_RESOLVED|NAME_RESOLUTION_FAILED|ADDRESS_UNREACHABLE|INTERNET_DISCONNECTED|NETWORK_ACCESS_DENIED|PROXY_CONNECTION_FAILED|TUNNEL_CONNECTION_FAILED|TIMED_OUT)|\b(ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ENETUNREACH|EHOSTUNREACH)\b/
|
|
52
|
+
export const captureUnreachable = (output) => UNREACHABLE_RE.test(String(output || ''))
|
|
53
|
+
// The worktree is mounted here in the container; models often write it into paths.
|
|
54
|
+
const MOUNT = '/work'
|
|
55
|
+
|
|
56
|
+
const truncate = (text, max = TOOL_OUTPUT_MAX) =>
|
|
57
|
+
text.length > max ? `${text.slice(0, max)}\n[... ${text.length - max} more characters cut]` : text
|
|
58
|
+
|
|
59
|
+
const tail = (text, max = 8000) => (text.length > max ? `[... ${text.length - max} characters cut]\n${text.slice(-max)}` : text)
|
|
60
|
+
|
|
61
|
+
// The environment of commands the agent runs: the container's own fixed
|
|
62
|
+
// variables (home, caches, proxy), never anything from the host.
|
|
63
|
+
export function commandEnv(env = process.env) {
|
|
64
|
+
const keep = [
|
|
65
|
+
'PATH',
|
|
66
|
+
'HOME',
|
|
67
|
+
'TMPDIR',
|
|
68
|
+
'CI',
|
|
69
|
+
'HTTPS_PROXY',
|
|
70
|
+
'HTTP_PROXY',
|
|
71
|
+
'https_proxy',
|
|
72
|
+
'http_proxy',
|
|
73
|
+
'NO_PROXY',
|
|
74
|
+
'no_proxy',
|
|
75
|
+
'NODE_USE_ENV_PROXY',
|
|
76
|
+
'npm_config_cache',
|
|
77
|
+
'npm_config_update_notifier',
|
|
78
|
+
'PLAYWRIGHT_BROWSERS_PATH',
|
|
79
|
+
'SHAPEWALL_SANDBOX',
|
|
80
|
+
]
|
|
81
|
+
const out = { LANG: 'C.UTF-8', FORCE_COLOR: '0', NO_COLOR: '1' }
|
|
82
|
+
for (const name of keep) if (typeof env[name] === 'string') out[name] = env[name]
|
|
83
|
+
return out
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Runs argv without a shell; resolves { code, signal, output, timedOut }.
|
|
87
|
+
export function runProgram(argv, { cwd, timeoutMs, env = commandEnv(), signal = null }) {
|
|
88
|
+
return new Promise((resolve) => {
|
|
89
|
+
let output = ''
|
|
90
|
+
let child
|
|
91
|
+
try {
|
|
92
|
+
child = spawn(argv[0], argv.slice(1), { cwd, env, stdio: ['ignore', 'pipe', 'pipe'], shell: false, detached: true })
|
|
93
|
+
} catch (error) {
|
|
94
|
+
resolve({ code: null, signal: null, output: `could not start: ${error.message}`, timedOut: false })
|
|
95
|
+
return
|
|
96
|
+
}
|
|
97
|
+
const collect = (chunk) => {
|
|
98
|
+
output += chunk
|
|
99
|
+
if (output.length > COMMAND_OUTPUT_MAX * 2) output = output.slice(-COMMAND_OUTPUT_MAX)
|
|
100
|
+
}
|
|
101
|
+
child.stdout.on('data', collect)
|
|
102
|
+
child.stderr.on('data', collect)
|
|
103
|
+
let timedOut = false
|
|
104
|
+
const kill = () => {
|
|
105
|
+
try {
|
|
106
|
+
process.kill(-child.pid, 'SIGKILL')
|
|
107
|
+
} catch {
|
|
108
|
+
child.kill('SIGKILL')
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
const timer = setTimeout(() => {
|
|
112
|
+
timedOut = true
|
|
113
|
+
kill()
|
|
114
|
+
}, timeoutMs)
|
|
115
|
+
const onAbort = () => kill()
|
|
116
|
+
signal?.addEventListener('abort', onAbort, { once: true })
|
|
117
|
+
child.once('error', (error) => {
|
|
118
|
+
clearTimeout(timer)
|
|
119
|
+
signal?.removeEventListener('abort', onAbort)
|
|
120
|
+
resolve({ code: null, signal: null, output: `could not start: ${error.code || error.message}`, timedOut })
|
|
121
|
+
})
|
|
122
|
+
child.once('close', (code, exitSignal) => {
|
|
123
|
+
clearTimeout(timer)
|
|
124
|
+
signal?.removeEventListener('abort', onAbort)
|
|
125
|
+
resolve({ code, signal: exitSignal, output: output.slice(-COMMAND_OUTPUT_MAX), timedOut })
|
|
126
|
+
})
|
|
127
|
+
})
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function commandResult(label, result) {
|
|
131
|
+
const how = result.timedOut
|
|
132
|
+
? 'was stopped (time limit)'
|
|
133
|
+
: result.code === 0
|
|
134
|
+
? 'passed (exit 0)'
|
|
135
|
+
: `failed (${result.code === null ? `signal ${result.signal || 'unknown'}` : `exit ${result.code}`})`
|
|
136
|
+
return { text: `${label} ${how}.\n${tail(result.output)}`, detail: `${label} ${how}`, ok: result.code === 0 }
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const stringArg = (args, name, { optional = false, max = 4096 } = {}) => {
|
|
140
|
+
const value = args?.[name]
|
|
141
|
+
if (value === undefined || value === null) {
|
|
142
|
+
if (optional) return null
|
|
143
|
+
throw new ToolError(`${name} is required`)
|
|
144
|
+
}
|
|
145
|
+
if (typeof value !== 'string') throw new ToolError(`${name} must be a string`)
|
|
146
|
+
if (value.length > max) throw new ToolError(`${name} is longer than ${max} characters`)
|
|
147
|
+
return value
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// createTools({ root, rpc, testCommand, capture, shell, remainingMs, signal })
|
|
151
|
+
// -> { specs, run(call) -> { ok, text, label, detail }, state }
|
|
152
|
+
export function createTools({
|
|
153
|
+
root,
|
|
154
|
+
rpc,
|
|
155
|
+
testCommand = null,
|
|
156
|
+
capture = false,
|
|
157
|
+
projectDir = '.',
|
|
158
|
+
shell = false,
|
|
159
|
+
remainingMs = () => COMMAND_MS_MAX,
|
|
160
|
+
signal = null,
|
|
161
|
+
}) {
|
|
162
|
+
const sandbox = createSandbox({ root })
|
|
163
|
+
const state = { replies: 0, status: null, statusNote: null, changed: new Set(), shellRan: false, captureUnavailable: false }
|
|
164
|
+
|
|
165
|
+
// A path from the model, relative to the worktree. Small models often
|
|
166
|
+
// write the mount point into it: "/work/src/x", and (when the repo has no
|
|
167
|
+
// top-level "work") "work/src/x", both mean "src/x". Mapped onto the tool
|
|
168
|
+
// root, not onto /work itself, so it means the same wherever the root is.
|
|
169
|
+
const hasWorkEntry = () => {
|
|
170
|
+
try {
|
|
171
|
+
fs.lstatSync(path.join(sandbox.root, 'work'))
|
|
172
|
+
return true
|
|
173
|
+
} catch {
|
|
174
|
+
return false
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
const mapPath = (raw) => {
|
|
178
|
+
const posix = raw.replace(/\\/g, '/')
|
|
179
|
+
if (path.isAbsolute(raw)) {
|
|
180
|
+
const absolute = path.resolve(raw)
|
|
181
|
+
if (inside(sandbox.root, absolute)) return absolute
|
|
182
|
+
if (posix === MOUNT || posix.startsWith(`${MOUNT}/`)) return path.resolve(sandbox.root, `.${posix.slice(MOUNT.length)}`)
|
|
183
|
+
return absolute
|
|
184
|
+
}
|
|
185
|
+
if ((posix === 'work' || posix.startsWith('work/')) && !hasWorkEntry()) return path.resolve(sandbox.root, `.${posix.slice(4)}`)
|
|
186
|
+
return path.resolve(sandbox.root, raw)
|
|
187
|
+
}
|
|
188
|
+
const shown = (absolute) => (path.relative(sandbox.root, absolute) || '.').split(path.sep).join('/')
|
|
189
|
+
// mustExist: a plain "not found" that says how paths work, not an error code.
|
|
190
|
+
const resolvePath = (value, { write = false, mustExist = false } = {}) => {
|
|
191
|
+
const raw = stringArg({ value }, 'value', { max: 1000 })
|
|
192
|
+
if (raw.includes('\0')) throw new ToolError('bad path')
|
|
193
|
+
const absolute = mapPath(raw)
|
|
194
|
+
let real
|
|
195
|
+
try {
|
|
196
|
+
real = sandbox.resolve(absolute, { write })
|
|
197
|
+
} catch (error) {
|
|
198
|
+
throw new ToolError(`refused: ${error.message.replace(sandbox.root, 'the worktree')}`)
|
|
199
|
+
}
|
|
200
|
+
if (!write && inside(path.join(sandbox.root, '.git'), real)) throw new ToolError('refused: .git is not readable here')
|
|
201
|
+
if (mustExist && !fs.existsSync(real)) throw new ToolError(`path not found: ${shown(absolute)}; paths are relative to the repo root`)
|
|
202
|
+
return real
|
|
203
|
+
}
|
|
204
|
+
const rel = (real) => path.relative(sandbox.root, real) || '.'
|
|
205
|
+
|
|
206
|
+
const walk = function* (dir, depth) {
|
|
207
|
+
let entries = []
|
|
208
|
+
try {
|
|
209
|
+
entries = fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))
|
|
210
|
+
} catch {
|
|
211
|
+
return
|
|
212
|
+
}
|
|
213
|
+
for (const entry of entries) {
|
|
214
|
+
const file = path.join(dir, entry.name)
|
|
215
|
+
if (entry.isDirectory()) {
|
|
216
|
+
if (SKIP_DIRS.has(entry.name)) continue
|
|
217
|
+
yield { file, dir: true }
|
|
218
|
+
if (depth > 0) yield* walk(file, depth - 1)
|
|
219
|
+
} else if (entry.isFile()) yield { file, dir: false }
|
|
220
|
+
// Symlinks are listed, never followed.
|
|
221
|
+
else if (entry.isSymbolicLink()) yield { file, dir: false, link: true }
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const TOOLS = [
|
|
226
|
+
{
|
|
227
|
+
name: 'list_files',
|
|
228
|
+
label: 'List files',
|
|
229
|
+
description: 'List files and folders under a folder of the project (default the root), two levels deep. Skips .git and node_modules.',
|
|
230
|
+
parameters: {
|
|
231
|
+
type: 'object',
|
|
232
|
+
properties: { path: { type: 'string', description: 'Folder, relative to the project root.' } },
|
|
233
|
+
additionalProperties: false,
|
|
234
|
+
},
|
|
235
|
+
run(args) {
|
|
236
|
+
const dir = resolvePath(args?.path ?? '.', { mustExist: true })
|
|
237
|
+
if (!fs.statSync(dir).isDirectory()) throw new ToolError(`${rel(dir)} is not a folder`)
|
|
238
|
+
const lines = []
|
|
239
|
+
for (const item of walk(dir, 1)) {
|
|
240
|
+
lines.push(`${rel(item.file)}${item.dir ? '/' : item.link ? ' (link)' : ''}`)
|
|
241
|
+
if (lines.length >= LIST_MAX) {
|
|
242
|
+
lines.push(`[... more than ${LIST_MAX} entries]`)
|
|
243
|
+
break
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return { text: lines.join('\n') || '(empty)', detail: `${rel(dir)}: ${lines.length} entries` }
|
|
247
|
+
},
|
|
248
|
+
},
|
|
249
|
+
{
|
|
250
|
+
name: 'read_file',
|
|
251
|
+
label: 'Read a file',
|
|
252
|
+
description: 'Read a text file of the project. Optional startLine (1-based) and lineCount for a part of a long file.',
|
|
253
|
+
parameters: {
|
|
254
|
+
type: 'object',
|
|
255
|
+
properties: { path: { type: 'string' }, startLine: { type: 'integer' }, lineCount: { type: 'integer' } },
|
|
256
|
+
required: ['path'],
|
|
257
|
+
additionalProperties: false,
|
|
258
|
+
},
|
|
259
|
+
run(args) {
|
|
260
|
+
const file = resolvePath(stringArg(args, 'path', { max: 1000 }), { mustExist: true })
|
|
261
|
+
let content
|
|
262
|
+
try {
|
|
263
|
+
content = sandbox.read({ path: file, line: args.startLine ?? null, limit: args.lineCount ?? null })
|
|
264
|
+
} catch (error) {
|
|
265
|
+
throw new ToolError(error.message.replace(sandbox.root, 'the worktree'))
|
|
266
|
+
}
|
|
267
|
+
return { text: truncate(content, READ_CHARS_MAX), detail: rel(file) }
|
|
268
|
+
},
|
|
269
|
+
},
|
|
270
|
+
{
|
|
271
|
+
name: 'search',
|
|
272
|
+
label: 'Search the code',
|
|
273
|
+
description: 'Find lines containing a text (or a regular expression with regex: true) in the project files. At most 100 matches.',
|
|
274
|
+
parameters: {
|
|
275
|
+
type: 'object',
|
|
276
|
+
properties: {
|
|
277
|
+
query: { type: 'string' },
|
|
278
|
+
path: { type: 'string', description: 'Folder to search (default the root).' },
|
|
279
|
+
regex: { type: 'boolean' },
|
|
280
|
+
},
|
|
281
|
+
required: ['query'],
|
|
282
|
+
additionalProperties: false,
|
|
283
|
+
},
|
|
284
|
+
run(args) {
|
|
285
|
+
const query = stringArg(args, 'query', { max: 500 })
|
|
286
|
+
if (!query) throw new ToolError('query is empty')
|
|
287
|
+
let test
|
|
288
|
+
if (args.regex) {
|
|
289
|
+
let re
|
|
290
|
+
try {
|
|
291
|
+
re = new RegExp(query)
|
|
292
|
+
} catch (error) {
|
|
293
|
+
throw new ToolError(`bad regular expression: ${error.message}`)
|
|
294
|
+
}
|
|
295
|
+
test = (line) => re.test(line)
|
|
296
|
+
} else test = (line) => line.includes(query)
|
|
297
|
+
const dir = resolvePath(args.path ?? '.', { mustExist: true })
|
|
298
|
+
const matches = []
|
|
299
|
+
let files = 0
|
|
300
|
+
for (const item of walk(dir, 30)) {
|
|
301
|
+
if (item.dir || item.link) continue
|
|
302
|
+
if (++files > SEARCH_FILES_MAX) break
|
|
303
|
+
let buffer
|
|
304
|
+
try {
|
|
305
|
+
if (fs.statSync(item.file).size > SEARCH_FILE_BYTES_MAX) continue
|
|
306
|
+
buffer = fs.readFileSync(item.file)
|
|
307
|
+
} catch {
|
|
308
|
+
continue
|
|
309
|
+
}
|
|
310
|
+
if (buffer.includes(0)) continue
|
|
311
|
+
const lines = buffer.toString('utf8').split('\n')
|
|
312
|
+
for (let index = 0; index < lines.length && matches.length < SEARCH_MATCHES_MAX; index += 1) {
|
|
313
|
+
if (test(lines[index])) matches.push(`${rel(item.file)}:${index + 1}: ${lines[index].slice(0, 300)}`)
|
|
314
|
+
}
|
|
315
|
+
if (matches.length >= SEARCH_MATCHES_MAX) break
|
|
316
|
+
}
|
|
317
|
+
return { text: matches.join('\n') || 'No matches.', detail: `${matches.length} match${matches.length === 1 ? '' : 'es'}` }
|
|
318
|
+
},
|
|
319
|
+
},
|
|
320
|
+
{
|
|
321
|
+
name: 'write_file',
|
|
322
|
+
label: 'Write a file',
|
|
323
|
+
description: 'Create or replace a text file of the project with the given content.',
|
|
324
|
+
parameters: {
|
|
325
|
+
type: 'object',
|
|
326
|
+
properties: { path: { type: 'string' }, content: { type: 'string' } },
|
|
327
|
+
required: ['path', 'content'],
|
|
328
|
+
additionalProperties: false,
|
|
329
|
+
},
|
|
330
|
+
run(args) {
|
|
331
|
+
const target = resolvePath(stringArg(args, 'path', { max: 1000 }), { write: true })
|
|
332
|
+
const content = stringArg(args, 'content', { max: 4 * 1024 * 1024 })
|
|
333
|
+
try {
|
|
334
|
+
sandbox.write({ path: target, content })
|
|
335
|
+
} catch (error) {
|
|
336
|
+
throw new ToolError(`refused: ${error.message.replace(sandbox.root, 'the worktree')}`)
|
|
337
|
+
}
|
|
338
|
+
state.changed.add(rel(target))
|
|
339
|
+
return { text: `Wrote ${rel(target)} (${Buffer.byteLength(content)} bytes).`, detail: rel(target) }
|
|
340
|
+
},
|
|
341
|
+
},
|
|
342
|
+
{
|
|
343
|
+
name: 'edit_file',
|
|
344
|
+
label: 'Edit a file',
|
|
345
|
+
description: 'Replace one exact piece of text in a file. oldText must appear exactly once; include enough context to make it unique.',
|
|
346
|
+
parameters: {
|
|
347
|
+
type: 'object',
|
|
348
|
+
properties: { path: { type: 'string' }, oldText: { type: 'string' }, newText: { type: 'string' } },
|
|
349
|
+
required: ['path', 'oldText', 'newText'],
|
|
350
|
+
additionalProperties: false,
|
|
351
|
+
},
|
|
352
|
+
run(args) {
|
|
353
|
+
const target = resolvePath(stringArg(args, 'path', { max: 1000 }), { write: true, mustExist: true })
|
|
354
|
+
const oldText = stringArg(args, 'oldText', { max: 200000 })
|
|
355
|
+
const newText = stringArg(args, 'newText', { max: 1024 * 1024 })
|
|
356
|
+
if (!oldText) throw new ToolError('oldText is empty')
|
|
357
|
+
let content
|
|
358
|
+
try {
|
|
359
|
+
content = sandbox.read({ path: target })
|
|
360
|
+
} catch (error) {
|
|
361
|
+
throw new ToolError(error.message.replace(sandbox.root, 'the worktree'))
|
|
362
|
+
}
|
|
363
|
+
const first = content.indexOf(oldText)
|
|
364
|
+
if (first < 0) throw new ToolError('oldText was not found in the file')
|
|
365
|
+
if (content.indexOf(oldText, first + 1) >= 0) throw new ToolError('oldText appears more than once; include more context')
|
|
366
|
+
try {
|
|
367
|
+
sandbox.write({ path: target, content: content.slice(0, first) + newText + content.slice(first + oldText.length) })
|
|
368
|
+
} catch (error) {
|
|
369
|
+
throw new ToolError(`refused: ${error.message.replace(sandbox.root, 'the worktree')}`)
|
|
370
|
+
}
|
|
371
|
+
state.changed.add(rel(target))
|
|
372
|
+
return { text: `Edited ${rel(target)}.`, detail: rel(target) }
|
|
373
|
+
},
|
|
374
|
+
},
|
|
375
|
+
testCommand && {
|
|
376
|
+
name: 'run_tests',
|
|
377
|
+
label: 'Run the tests',
|
|
378
|
+
description: `Run the project's test command (${testCommand.join(' ')}) and get the result with the end of its output.`,
|
|
379
|
+
parameters: { type: 'object', properties: {}, additionalProperties: false },
|
|
380
|
+
async run() {
|
|
381
|
+
// The test command runs code from the project, so changing what it
|
|
382
|
+
// runs is changing what runs: then a person approves it first.
|
|
383
|
+
const inputs = [...state.changed].filter((file) => testInput(file, testCommand))
|
|
384
|
+
if (inputs.length || state.shellRan) {
|
|
385
|
+
const why = inputs.length
|
|
386
|
+
? `The agent changed ${inputs.slice(0, 4).join(', ')}${inputs.length > 4 ? ', ...' : ''}, which decide${inputs.length === 1 ? 's' : ''} what the test command runs.`
|
|
387
|
+
: 'An approved command ran earlier in this run and may have changed what the test command runs.'
|
|
388
|
+
if (!shell)
|
|
389
|
+
return {
|
|
390
|
+
text: `Not run: ${why} That needs a person's approval, which this run does not have.`,
|
|
391
|
+
detail: 'needs approval',
|
|
392
|
+
ok: false,
|
|
393
|
+
}
|
|
394
|
+
const answer = await rpc.call('approve', { command: testCommand.join(' '), reason: why })
|
|
395
|
+
if (!answer?.approved)
|
|
396
|
+
return { text: `Not run: ${answer?.error || 'the person did not approve it'}.`, detail: 'not approved', ok: false }
|
|
397
|
+
}
|
|
398
|
+
const result = await runProgram(testCommand, { cwd: sandbox.root, timeoutMs: Math.min(COMMAND_MS_MAX, remainingMs()), signal })
|
|
399
|
+
return commandResult('The tests', result)
|
|
400
|
+
},
|
|
401
|
+
},
|
|
402
|
+
capture && {
|
|
403
|
+
name: 'capture',
|
|
404
|
+
label: 'Capture a page',
|
|
405
|
+
description:
|
|
406
|
+
'Run "shapewall capture" for one page of the board in the worktree, to see the change rendered. Works only when the site it captures is reachable from the sandbox.',
|
|
407
|
+
parameters: { type: 'object', properties: { pageId: { type: 'string' } }, required: ['pageId'], additionalProperties: false },
|
|
408
|
+
async run(args) {
|
|
409
|
+
if (state.captureUnavailable) return { text: CAPTURE_UNAVAILABLE, detail: CAPTURE_UNAVAILABLE, ok: false }
|
|
410
|
+
const pageId = stringArg(args, 'pageId', { max: 64 })
|
|
411
|
+
if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(pageId)) throw new ToolError('pageId is a page id such as "home"')
|
|
412
|
+
const cwd = path.resolve(sandbox.root, projectDir)
|
|
413
|
+
if (!inside(sandbox.root, cwd) || !fs.existsSync(path.join(cwd, 'shapewall.config.json'))) {
|
|
414
|
+
throw new ToolError('the project has no shapewall.config.json')
|
|
415
|
+
}
|
|
416
|
+
const result = await runProgram([process.execPath, SHAPEWALL_BIN, 'capture', '--only', pageId], {
|
|
417
|
+
cwd,
|
|
418
|
+
timeoutMs: Math.min(5 * 60 * 1000, remainingMs()),
|
|
419
|
+
signal,
|
|
420
|
+
})
|
|
421
|
+
// The site did not answer from in here: say so plainly, once for the
|
|
422
|
+
// run, so the model stops trying instead of reading browser errors.
|
|
423
|
+
if (result.code !== 0 && captureUnreachable(result.output)) {
|
|
424
|
+
state.captureUnavailable = true
|
|
425
|
+
return { text: CAPTURE_UNAVAILABLE, detail: CAPTURE_UNAVAILABLE, ok: false }
|
|
426
|
+
}
|
|
427
|
+
return commandResult(`Capturing ${pageId}`, result)
|
|
428
|
+
},
|
|
429
|
+
},
|
|
430
|
+
{
|
|
431
|
+
name: 'reply',
|
|
432
|
+
label: 'Reply on the comment',
|
|
433
|
+
description: `Post a reply on the comment (up to ${REPLY_MAX} characters, at most ${REPLIES_MAX} per run), for a question or progress. Your final answer is posted anyway.`,
|
|
434
|
+
parameters: { type: 'object', properties: { body: { type: 'string' } }, required: ['body'], additionalProperties: false },
|
|
435
|
+
async run(args) {
|
|
436
|
+
const body = stringArg(args, 'body', { max: REPLY_MAX }).trim()
|
|
437
|
+
if (!body) throw new ToolError('body is empty')
|
|
438
|
+
if (state.replies >= REPLIES_MAX) throw new ToolError(`at most ${REPLIES_MAX} replies per run`)
|
|
439
|
+
const answer = await rpc.call('reply', { body })
|
|
440
|
+
if (!answer?.ok) throw new ToolError(answer?.error || 'the reply was not posted')
|
|
441
|
+
state.replies += 1
|
|
442
|
+
return { text: 'Reply posted.', detail: body.slice(0, 80) }
|
|
443
|
+
},
|
|
444
|
+
},
|
|
445
|
+
{
|
|
446
|
+
name: 'set_status',
|
|
447
|
+
label: 'Set the status',
|
|
448
|
+
description:
|
|
449
|
+
'Say how the work ended: done (the change is made), or needs-human (a person must decide or help). Applied when the run ends.',
|
|
450
|
+
parameters: {
|
|
451
|
+
type: 'object',
|
|
452
|
+
properties: { status: { type: 'string', enum: ['done', 'needs-human'] }, note: { type: 'string' } },
|
|
453
|
+
required: ['status'],
|
|
454
|
+
additionalProperties: false,
|
|
455
|
+
},
|
|
456
|
+
run(args) {
|
|
457
|
+
if (!['done', 'needs-human'].includes(args?.status)) throw new ToolError('status is done or needs-human')
|
|
458
|
+
state.status = args.status
|
|
459
|
+
state.statusNote = stringArg(args, 'note', { optional: true, max: 1000 })
|
|
460
|
+
return { text: `Status will be ${args.status}.`, detail: args.status }
|
|
461
|
+
},
|
|
462
|
+
},
|
|
463
|
+
shell && {
|
|
464
|
+
name: 'run_shell',
|
|
465
|
+
label: 'Run a command',
|
|
466
|
+
description:
|
|
467
|
+
'Run one shell command in the project folder, inside the sandbox. A person must approve each command on the board first, so use it only when no other tool does the job, and say why.',
|
|
468
|
+
parameters: {
|
|
469
|
+
type: 'object',
|
|
470
|
+
properties: { command: { type: 'string' }, reason: { type: 'string' } },
|
|
471
|
+
required: ['command', 'reason'],
|
|
472
|
+
additionalProperties: false,
|
|
473
|
+
},
|
|
474
|
+
async run(args) {
|
|
475
|
+
const command = stringArg(args, 'command', { max: SHELL_COMMAND_MAX })
|
|
476
|
+
const reason = stringArg(args, 'reason', { max: 500 })
|
|
477
|
+
if (!command.trim()) throw new ToolError('command is empty')
|
|
478
|
+
const answer = await rpc.call('approve', { command, reason })
|
|
479
|
+
if (!answer?.approved)
|
|
480
|
+
return { text: `Not run: ${answer?.error || 'the person did not approve it'}.`, detail: 'not approved', ok: false }
|
|
481
|
+
state.shellRan = true
|
|
482
|
+
const result = await runProgram(['/bin/sh', '-c', command], {
|
|
483
|
+
cwd: sandbox.root,
|
|
484
|
+
timeoutMs: Math.min(COMMAND_MS_MAX, remainingMs()),
|
|
485
|
+
signal,
|
|
486
|
+
})
|
|
487
|
+
return commandResult('The command', result)
|
|
488
|
+
},
|
|
489
|
+
},
|
|
490
|
+
].filter(Boolean)
|
|
491
|
+
|
|
492
|
+
return {
|
|
493
|
+
state,
|
|
494
|
+
names: TOOLS.map((tool) => tool.name),
|
|
495
|
+
specs: TOOLS.map(({ name, description, parameters }) => ({ name, description, parameters })),
|
|
496
|
+
async run(call) {
|
|
497
|
+
const tool = TOOLS.find((item) => item.name === call.name)
|
|
498
|
+
// Not offered (the site is not reachable from the sandbox), and called anyway.
|
|
499
|
+
if (!tool && call.name === 'capture')
|
|
500
|
+
return { ok: false, label: 'Capture a page', text: CAPTURE_UNAVAILABLE, detail: CAPTURE_UNAVAILABLE }
|
|
501
|
+
if (!tool)
|
|
502
|
+
return {
|
|
503
|
+
ok: false,
|
|
504
|
+
label: String(call.name || 'tool').slice(0, 60),
|
|
505
|
+
text: `There is no tool "${String(call.name).slice(0, 60)}".`,
|
|
506
|
+
detail: 'unknown tool',
|
|
507
|
+
}
|
|
508
|
+
if (call.args?._invalid !== undefined)
|
|
509
|
+
return { ok: false, label: tool.label, text: 'The arguments were not valid JSON.', detail: 'bad arguments' }
|
|
510
|
+
try {
|
|
511
|
+
const result = await tool.run(call.args || {})
|
|
512
|
+
return {
|
|
513
|
+
ok: result.ok !== false,
|
|
514
|
+
label: tool.label,
|
|
515
|
+
text: truncate(result.text),
|
|
516
|
+
detail: result.detail ? String(result.detail).slice(0, 200) : null,
|
|
517
|
+
}
|
|
518
|
+
} catch (error) {
|
|
519
|
+
const message = error instanceof ToolError ? error.message : `the tool failed (${error.code || error.message})`
|
|
520
|
+
return { ok: false, label: tool.label, text: message, detail: message.slice(0, 200) }
|
|
521
|
+
}
|
|
522
|
+
},
|
|
523
|
+
}
|
|
524
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// `shapewall agent watch`: runs the starter agent on each comment the
|
|
2
|
+
// trigger gate lets through, one at a time, until Ctrl+C (or, with `once`,
|
|
3
|
+
// until the comments open now are done).
|
|
4
|
+
//
|
|
5
|
+
// A comment is looked at while it is open with no agent status. One the gate
|
|
6
|
+
// holds back (an untrusted author nobody tagged yet) is looked at again on
|
|
7
|
+
// every scan, so a trusted member's "@agent" reply starts it later; a
|
|
8
|
+
// guest's comment is skipped for good.
|
|
9
|
+
|
|
10
|
+
import fs from 'node:fs'
|
|
11
|
+
import path from 'node:path'
|
|
12
|
+
import { acquireLock, readLock, releaseLock } from '../../lock.js'
|
|
13
|
+
import { boardDir } from '../../store.js'
|
|
14
|
+
import { gateComment } from './gate.js'
|
|
15
|
+
import { pause } from './pause.js'
|
|
16
|
+
import { runStarter } from './supervisor.js'
|
|
17
|
+
|
|
18
|
+
export async function watchStarter({
|
|
19
|
+
source,
|
|
20
|
+
settings,
|
|
21
|
+
once = false,
|
|
22
|
+
pollMs = 3000,
|
|
23
|
+
signal = null,
|
|
24
|
+
log = () => {},
|
|
25
|
+
run = runStarter,
|
|
26
|
+
...runOptions
|
|
27
|
+
}) {
|
|
28
|
+
let lockFile = null
|
|
29
|
+
if (source.config) {
|
|
30
|
+
lockFile = path.join(boardDir(source.config, source.board.id), 'starter-watch.lock')
|
|
31
|
+
fs.mkdirSync(path.dirname(lockFile), { recursive: true })
|
|
32
|
+
if (!acquireLock(lockFile)) {
|
|
33
|
+
const holder = readLock(lockFile)
|
|
34
|
+
throw new Error(
|
|
35
|
+
`Another "shapewall agent watch" is running for board "${source.board.id}"${holder?.pid ? ` (pid ${holder.pid})` : ''}.`,
|
|
36
|
+
)
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const said = new Map()
|
|
40
|
+
const results = []
|
|
41
|
+
const trusted = settings.trustedFor(source.board.id)
|
|
42
|
+
if (!trusted.size)
|
|
43
|
+
log(`No member may dispatch work on board "${source.board.id}": set starterAgent.trusted in the config or pass --trusted.`)
|
|
44
|
+
try {
|
|
45
|
+
if (!once) log(`Starter agent watching board "${source.board.id}" (every ${Math.round(pollMs / 1000)}s). Ctrl+C stops.`)
|
|
46
|
+
for (;;) {
|
|
47
|
+
if (signal?.aborted) break
|
|
48
|
+
let ran = false
|
|
49
|
+
let comments = []
|
|
50
|
+
try {
|
|
51
|
+
comments = (await source.list()).filter((item) => item.agentStatus === null).sort((a, b) => a.id - b.id)
|
|
52
|
+
} catch (error) {
|
|
53
|
+
log(`agent watch: ${error.message}`)
|
|
54
|
+
}
|
|
55
|
+
for (const comment of comments) {
|
|
56
|
+
if (signal?.aborted) break
|
|
57
|
+
const gate = gateComment(comment, { trusted, hosted: source.hosted })
|
|
58
|
+
if (!gate.dispatch) {
|
|
59
|
+
if (said.get(comment.id) !== gate.reason) {
|
|
60
|
+
said.set(comment.id, gate.reason)
|
|
61
|
+
log(`#${comment.id} skipped: ${gate.reason}`)
|
|
62
|
+
}
|
|
63
|
+
continue
|
|
64
|
+
}
|
|
65
|
+
said.delete(comment.id)
|
|
66
|
+
try {
|
|
67
|
+
results.push(await run({ source, settings, commentId: comment.id, signal, log, ...runOptions }))
|
|
68
|
+
ran = true
|
|
69
|
+
} catch (error) {
|
|
70
|
+
// Taken by someone else meanwhile, or the gate said no on a fresh read.
|
|
71
|
+
log(`#${comment.id}: ${error.message}`)
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
if (once) {
|
|
75
|
+
if (!ran) break
|
|
76
|
+
continue
|
|
77
|
+
}
|
|
78
|
+
await pause(pollMs, signal)
|
|
79
|
+
}
|
|
80
|
+
} finally {
|
|
81
|
+
if (lockFile) releaseLock(lockFile)
|
|
82
|
+
}
|
|
83
|
+
return results
|
|
84
|
+
}
|