@parcha/agentrun-serve 0.0.0-stage → 0.1.0-beta.30
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 +748 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +2190 -2
- package/dist/adapters.d.ts +234 -0
- package/dist/adapters.js +585 -0
- package/dist/agents.d.ts +130 -0
- package/dist/agents.js +308 -0
- package/dist/app.d.ts +7 -0
- package/dist/app.js +384 -0
- package/dist/background.d.ts +28 -0
- package/dist/background.js +376 -0
- package/dist/bound-files.d.ts +4 -0
- package/dist/bound-files.js +164 -0
- package/dist/box/record.d.ts +6 -0
- package/dist/box/record.js +41 -0
- package/dist/box/sweep.d.ts +53 -0
- package/dist/box/sweep.js +193 -0
- package/dist/box-egress.d.ts +98 -0
- package/dist/box-egress.js +259 -0
- package/dist/box-image.d.ts +98 -0
- package/dist/box-image.js +285 -0
- package/dist/box-relay-vm.d.ts +80 -0
- package/dist/box-relay-vm.js +389 -0
- package/dist/box-relay.d.ts +45 -0
- package/dist/box-relay.js +227 -0
- package/dist/boxes.d.ts +72 -0
- package/dist/boxes.js +189 -0
- package/dist/browser-cost.d.ts +41 -0
- package/dist/browser-cost.js +158 -0
- package/dist/cap.d.ts +332 -0
- package/dist/cap.js +992 -0
- package/dist/catalog.d.ts +20 -0
- package/dist/catalog.js +53 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +167 -0
- package/dist/coding-tools.d.ts +35 -0
- package/dist/coding-tools.js +87 -0
- package/dist/console/THIRD-PARTY-NOTICES.txt +1721 -0
- package/dist/console/assets/index-34jfpIbQ.js +481 -0
- package/dist/console/assets/index-DUHbWcIP.css +1 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
- package/dist/console/index.html +15 -0
- package/dist/content-filter.d.ts +7 -0
- package/dist/content-filter.js +23 -0
- package/dist/daytona-api.d.ts +21 -0
- package/dist/daytona-api.js +101 -0
- package/dist/decision-rows.d.ts +19 -0
- package/dist/decision-rows.js +123 -0
- package/dist/decisions.d.ts +94 -0
- package/dist/decisions.js +184 -0
- package/dist/effort-guidance.d.ts +5 -0
- package/dist/effort-guidance.js +14 -0
- package/dist/environment.d.ts +5 -0
- package/dist/environment.js +11 -0
- package/dist/errors.d.ts +74 -0
- package/dist/errors.js +69 -0
- package/dist/exa-keyless.d.ts +35 -0
- package/dist/exa-keyless.js +202 -0
- package/dist/fetch-page.d.ts +114 -0
- package/dist/fetch-page.js +182 -0
- package/dist/files.d.ts +65 -0
- package/dist/files.js +158 -0
- package/dist/grade.d.ts +93 -0
- package/dist/grade.js +328 -0
- package/dist/graph-served.d.ts +23 -0
- package/dist/graph-served.js +75 -0
- package/dist/graph-view.d.ts +102 -0
- package/dist/graph-view.js +219 -0
- package/dist/harness-app.d.ts +40 -0
- package/dist/harness-app.js +708 -0
- package/dist/harness-opencode/adapter.d.ts +45 -0
- package/dist/harness-opencode/adapter.js +272 -0
- package/dist/harness-opencode/binary.d.ts +18 -0
- package/dist/harness-opencode/binary.js +87 -0
- package/dist/harness-opencode/config.d.ts +24 -0
- package/dist/harness-opencode/config.js +61 -0
- package/dist/harness-opencode/harness.d.ts +77 -0
- package/dist/harness-opencode/harness.js +620 -0
- package/dist/harness-opencode/host/mcp.d.ts +40 -0
- package/dist/harness-opencode/host/mcp.js +208 -0
- package/dist/harness-opencode/host/policy.d.ts +71 -0
- package/dist/harness-opencode/host/policy.js +419 -0
- package/dist/harness-opencode/host/server.d.ts +55 -0
- package/dist/harness-opencode/host/server.js +165 -0
- package/dist/harness-opencode/index.d.ts +9 -0
- package/dist/harness-opencode/index.js +6 -0
- package/dist/harness-opencode/verify.d.ts +32 -0
- package/dist/harness-opencode/verify.js +75 -0
- package/dist/harness-opencode/versions.d.ts +33 -0
- package/dist/harness-opencode/versions.js +64 -0
- package/dist/harness.d.ts +56 -0
- package/dist/harness.js +77 -0
- package/dist/home-path.d.ts +27 -0
- package/dist/home-path.js +78 -0
- package/dist/host-tools.d.ts +30 -0
- package/dist/host-tools.js +154 -0
- package/dist/host.d.ts +39 -0
- package/dist/host.js +85 -0
- package/dist/hosted-search.d.ts +27 -0
- package/dist/hosted-search.js +133 -0
- package/dist/import-sources.d.ts +104 -0
- package/dist/import-sources.js +629 -0
- package/dist/import-summary.d.ts +25 -0
- package/dist/import-summary.js +75 -0
- package/dist/import-worker.d.ts +26 -0
- package/dist/import-worker.js +41 -0
- package/dist/import.d.ts +145 -0
- package/dist/import.js +1222 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +6 -0
- package/dist/key-check.d.ts +37 -0
- package/dist/key-check.js +112 -0
- package/dist/key-refusal.d.ts +51 -0
- package/dist/key-refusal.js +191 -0
- package/dist/learn/check.d.ts +108 -0
- package/dist/learn/check.js +277 -0
- package/dist/learn/grade.d.ts +80 -0
- package/dist/learn/grade.js +445 -0
- package/dist/learn/index.d.ts +7 -0
- package/dist/learn/index.js +11 -0
- package/dist/learn/invisible.d.ts +5 -0
- package/dist/learn/invisible.js +42 -0
- package/dist/learn/notes.d.ts +59 -0
- package/dist/learn/notes.js +147 -0
- package/dist/learn/reflect.d.ts +49 -0
- package/dist/learn/reflect.js +213 -0
- package/dist/learn/secrets.d.ts +18 -0
- package/dist/learn/secrets.js +131 -0
- package/dist/learn/skills.d.ts +97 -0
- package/dist/learn/skills.js +271 -0
- package/dist/learned-workflow.d.ts +59 -0
- package/dist/learned-workflow.js +191 -0
- package/dist/learning-routes.d.ts +196 -0
- package/dist/learning-routes.js +609 -0
- package/dist/learning-run.d.ts +306 -0
- package/dist/learning-run.js +819 -0
- package/dist/learning-words.d.ts +76 -0
- package/dist/learning-words.js +174 -0
- package/dist/learning.d.ts +418 -0
- package/dist/learning.js +946 -0
- package/dist/llm.d.ts +40 -0
- package/dist/llm.js +37 -0
- package/dist/llms.txt +37 -0
- package/dist/mcp-servers.d.ts +118 -0
- package/dist/mcp-servers.js +450 -0
- package/dist/mcp.d.ts +51 -0
- package/dist/mcp.js +392 -0
- package/dist/model.d.ts +186 -0
- package/dist/model.js +485 -0
- package/dist/monid.d.ts +74 -0
- package/dist/monid.js +277 -0
- package/dist/openapi/agentrun-v2.openapi.json +4806 -0
- package/dist/openapi.d.ts +10 -0
- package/dist/openapi.js +1727 -0
- package/dist/owner.d.ts +55 -0
- package/dist/owner.js +222 -0
- package/dist/packs.d.ts +71 -0
- package/dist/packs.js +180 -0
- package/dist/page.d.ts +32 -0
- package/dist/page.js +133 -0
- package/dist/paid-calls.d.ts +50 -0
- package/dist/paid-calls.js +110 -0
- package/dist/pause.d.ts +70 -0
- package/dist/pause.js +97 -0
- package/dist/pdf-pages.d.ts +44 -0
- package/dist/pdf-pages.js +147 -0
- package/dist/place.d.ts +69 -0
- package/dist/place.js +137 -0
- package/dist/print.d.ts +20 -0
- package/dist/print.js +29 -0
- package/dist/propose.d.ts +40 -0
- package/dist/propose.js +112 -0
- package/dist/quiet-sqlite-warning.d.ts +1 -0
- package/dist/quiet-sqlite-warning.js +14 -0
- package/dist/request-start.d.ts +22 -0
- package/dist/request-start.js +350 -0
- package/dist/result.d.ts +3 -0
- package/dist/result.js +5 -0
- package/dist/rows.d.ts +46 -0
- package/dist/rows.js +121 -0
- package/dist/run-box.d.ts +186 -0
- package/dist/run-box.js +590 -0
- package/dist/run-manifest.d.ts +27 -0
- package/dist/run-manifest.js +60 -0
- package/dist/runnable.d.ts +83 -0
- package/dist/runnable.js +170 -0
- package/dist/runs.d.ts +1062 -0
- package/dist/runs.js +3020 -0
- package/dist/secret-cut.d.ts +27 -0
- package/dist/secret-cut.js +109 -0
- package/dist/secrets.d.ts +62 -0
- package/dist/secrets.js +158 -0
- package/dist/server-lock.d.ts +44 -0
- package/dist/server-lock.js +140 -0
- package/dist/server.d.ts +722 -0
- package/dist/server.js +2118 -0
- package/dist/sessions.d.ts +4 -0
- package/dist/sessions.js +105 -0
- package/dist/sign-ins.d.ts +99 -0
- package/dist/sign-ins.js +288 -0
- package/dist/skills.d.ts +43 -0
- package/dist/skills.js +96 -0
- package/dist/stats.d.ts +106 -0
- package/dist/stats.js +103 -0
- package/dist/tool-gate.d.ts +266 -0
- package/dist/tool-gate.js +554 -0
- package/dist/tool-keys.d.ts +187 -0
- package/dist/tool-keys.js +315 -0
- package/dist/tool-plane.d.ts +228 -0
- package/dist/tool-plane.js +400 -0
- package/dist/tools.d.ts +202 -0
- package/dist/tools.js +372 -0
- package/dist/trigger-secrets.d.ts +32 -0
- package/dist/trigger-secrets.js +143 -0
- package/dist/triggers.d.ts +439 -0
- package/dist/triggers.js +863 -0
- package/dist/turn-end.d.ts +24 -0
- package/dist/turn-end.js +15 -0
- package/dist/turns.d.ts +34 -0
- package/dist/turns.js +202 -0
- package/dist/uploads.d.ts +104 -0
- package/dist/uploads.js +474 -0
- package/dist/usage-lines.d.ts +26 -0
- package/dist/usage-lines.js +28 -0
- package/dist/usage.d.ts +29 -0
- package/dist/usage.js +58 -0
- package/dist/validate.d.ts +57 -0
- package/dist/validate.js +184 -0
- package/dist/web-fetch.d.ts +64 -0
- package/dist/web-fetch.js +262 -0
- package/dist/web-search.d.ts +54 -0
- package/dist/web-search.js +136 -0
- package/dist/webhooks.d.ts +189 -0
- package/dist/webhooks.js +503 -0
- package/dist/workspace-paths.d.ts +33 -0
- package/dist/workspace-paths.js +104 -0
- package/dist/workspace.d.ts +88 -0
- package/dist/workspace.js +369 -0
- package/launcher/agentrun-serve +109 -0
- package/package.json +100 -4
- package/skills/agentrun-serve/SKILL.md +128 -0
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
import { defineTool } from "@earendil-works/pi-durable";
|
|
2
|
+
import { BOX_WORK } from "./place.js";
|
|
3
|
+
import { forModel } from "./result.js";
|
|
4
|
+
/** The most background processes that run at once in one run's box. */
|
|
5
|
+
export const BACKGROUND_MAX = 8;
|
|
6
|
+
/** The most bytes of output one background process's log keeps: later output is dropped, and the process runs on. */
|
|
7
|
+
export const BACKGROUND_LOG_BYTES = 16 * 1024 * 1024;
|
|
8
|
+
/** The most bytes of output one `bash_output` call answers, and its default. */
|
|
9
|
+
export const BACKGROUND_PAGE_BYTES = 48 * 1024;
|
|
10
|
+
/** The most bytes one `bash_input` call writes. */
|
|
11
|
+
export const BACKGROUND_INPUT_BYTES = 64 * 1024;
|
|
12
|
+
/** The most processes `bash_list` names: every running one, then the newest that ended. */
|
|
13
|
+
export const BACKGROUND_LIST_MAX = 40;
|
|
14
|
+
/** Where a background process's log and state live, under the run's work/. */
|
|
15
|
+
export const BACKGROUND_DIR = "background";
|
|
16
|
+
/** The signals `bash_signal` sends. */
|
|
17
|
+
export const BACKGROUND_SIGNALS = ["TERM", "INT", "KILL"];
|
|
18
|
+
/** The tools, by name. */
|
|
19
|
+
export const BACKGROUND_TOOLS = ["bash_background", "bash_output", "bash_input", "bash_signal", "bash_list"];
|
|
20
|
+
/** The tools that run a command in the box, never on this server: bash, and the background tools. The tool gate holds
|
|
21
|
+
* each to bash's setting (tool-gate.ts SHELL_FAMILY). */
|
|
22
|
+
export const SHELL_TOOLS = ["bash", ...BACKGROUND_TOOLS];
|
|
23
|
+
const MIB = BACKGROUND_LOG_BYTES / (1024 * 1024);
|
|
24
|
+
/** Each signal's number, for an exit code past 128. */
|
|
25
|
+
const SIGNAL_NAMES = { 1: "HUP", 2: "INT", 3: "QUIT", 6: "ABRT", 9: "KILL", 13: "PIPE", 14: "ALRM", 15: "TERM" };
|
|
26
|
+
/**
|
|
27
|
+
* The runner, started under its own session by a start: `$1` the log's directory, `$2` the box-only directory, `$3` the
|
|
28
|
+
* log's cap, `$4` work/, `$5` the command. It holds the fifo's write end open (a `sleep`), runs the command under a
|
|
29
|
+
* session of its own (so a signal to the command's group never reaches the runner) with the fifo as stdin, and keeps
|
|
30
|
+
* the first `$3` bytes of its output, written to the log as they come (head, unbuffered by stdbuf where the box has it;
|
|
31
|
+
* else the last few KiB may wait in head's buffer until the process ends). Once the output's last writer is gone, it
|
|
32
|
+
* writes the exit code.
|
|
33
|
+
*/
|
|
34
|
+
const RUNNER = [
|
|
35
|
+
'L=$1; C=$2; cap=$3; echo $$ > "$C/runner"',
|
|
36
|
+
// A display copy in work/ (put): from inside the log's directory, entered with cd -P and checked to be
|
|
37
|
+
// work/background/<id> itself by its real path, written to a new file there (mktemp: an exclusive create, so never a
|
|
38
|
+
// planted link) and renamed over its name on that same filesystem, the name taken as a file even where a link to a
|
|
39
|
+
// directory stands there (mv -T; else that link is removed first), so a link planted at the name, or at the
|
|
40
|
+
// directory, is never followed. A check that fails skips the copy; the temporary file (hidden, a dot name) is removed
|
|
41
|
+
// on every path; no call reads a copy back.
|
|
42
|
+
`put() { [ -n "$rw" ] || return 0; ( cd -P "$L" 2>/dev/null && [ "$(pwd -P)" = "$rw/background/\${L##*/}" ] || exit 0; t=$(mktemp ./.put.XXXXXX) || exit 0; printf '%s\\n' "$2" > "$t" && { mv -fT "$t" "./$1" 2>/dev/null || { [ -L "./$1" ] && rm -f "./$1"; mv -f "$t" "./$1"; }; } || rm -f "$t" ) 2>/dev/null; return 0; }`,
|
|
43
|
+
// The log is opened once, here, where start has just made it a regular file, then checked as opened: the file the
|
|
44
|
+
// open reached must be work/background/<id>/output.log itself (by its real path, so through no link) and a regular
|
|
45
|
+
// file, else nothing is kept. What later stands at its name is never written through.
|
|
46
|
+
'rw=$(cd "$4" 2>/dev/null && pwd -P); [ -f "$L/output.log" ] && [ ! -L "$L/output.log" ] && exec 4>>"$L/output.log" || exec 4>/dev/null',
|
|
47
|
+
'[ -n "$rw" ] && [ "$(readlink /proc/self/fd/4 2>/dev/null)" = "$rw/background/\${L##*/}/output.log" ] && [ -f /proc/self/fd/4 ] || exec 4>/dev/null',
|
|
48
|
+
// The first $cap bytes, written as they come: head holds its output in a buffer unless stdbuf unbuffers it.
|
|
49
|
+
'if stdbuf -o0 true 2>/dev/null; then keep() { stdbuf -o0 head -c "$cap" >&4; }; else keep() { head -c "$cap" >&4; }; fi',
|
|
50
|
+
'sleep 2147483647 > "$C/in" & h=$!; echo "$h" > "$C/hold"',
|
|
51
|
+
// The command's group goes in C, beside the fifo (pgid), the only copy any call trusts; one byte past the cap marks
|
|
52
|
+
// the log capped.
|
|
53
|
+
`{ setsid -w sh -c 'echo $$ > "$1/.pgid" && mv -f "$1/.pgid" "$1/pgid"; cd "$2" || exit 126; if command -v bash >/dev/null 2>&1; then exec bash -c "$3"; fi; exec sh -c "$3"' agentrun-background "$C" "$4" "$5" < "$C/in" 2>&1; echo $? > "$C/code"; } | { keep; [ -n "$(head -c 1 | od -An -c)" ] && { : > "$C/capped"; put capped ""; }; cat > /dev/null; }`,
|
|
54
|
+
// A child the command left running (a server started with &, its output sent elsewhere) keeps the process going: the
|
|
55
|
+
// group is waited for, so it stays running, signalled, counted and ended at the run's end until no live process of
|
|
56
|
+
// the group is left.
|
|
57
|
+
`g=$(cat "$C/pgid" 2>/dev/null); live() { [ -n "$g" ] || return 1; if [ -r /proc/self/stat ]; then cat /proc/[0-9]*/stat 2>/dev/null | awk -v g="$g" '{ sub(/^[0-9]+ \\(.*\\) /, ""); if ($1 != "Z" && $3 == g) n++ } END { exit n > 0 ? 0 : 1 }'; else kill -0 "-$g" 2>/dev/null; fi; }; while live; do sleep 0.5; done`,
|
|
58
|
+
'kill "$h" 2>/dev/null; code=$(cat "$C/code" 2>/dev/null); [ -n "$code" ] || code=255',
|
|
59
|
+
'printf \'%s\\n\' "$code" > "$C/.exit" && mv -f "$C/.exit" "$C/exit"; put exit "$code"; rm -f "$C/in"',
|
|
60
|
+
].join("\n");
|
|
61
|
+
/**
|
|
62
|
+
* Every call's script: `$1` work/, `$2` the operation, the rest its arguments. Each answers on stdout in lines a parse
|
|
63
|
+
* below reads. A state is `running`, `exited <code>` or `lost`. What a call trusts (the group, the exit code, the start
|
|
64
|
+
* time, the command, the run's-end mark) is read from the box-only directory `c` alone, which the run's file tools
|
|
65
|
+
* cannot write; of work/background/<id>/ only output.log is read, and only as a regular file reached through no link.
|
|
66
|
+
*/
|
|
67
|
+
const SCRIPT = [
|
|
68
|
+
'w=$1; op=$2; shift 2; d=$w/background; c=${TMPDIR:-/tmp}/.agentrun-background; rw=$(cd "$w" 2>/dev/null && pwd -P)',
|
|
69
|
+
`alive() { [ -n "$1" ] || return 1; if [ -r /proc/self/stat ]; then s=$(sed 's/^.*) //' "/proc/$1/stat" 2>/dev/null | cut -d' ' -f1); [ -n "$s" ] && [ "$s" != Z ] && [ "$s" != X ]; else kill -0 "$1" 2>/dev/null; fi; }`,
|
|
70
|
+
'state() { if [ -f "$c/$1/exit" ]; then echo "exited $(cat "$c/$1/exit")"; elif alive "$(cat "$c/$1/runner" 2>/dev/null)"; then echo running; else echo lost; fi; }',
|
|
71
|
+
// The ids this box started (c), and with them, for the list alone, those of work/ (a box before this one's).
|
|
72
|
+
'cids() { for p in "$c"/*; do i=${p##*/}; case $i in ""|*[!0-9]*) continue;; esac; [ -d "$p" ] && echo "$i"; done; }',
|
|
73
|
+
'ids() { { cids; [ -L "$d" ] || for p in "$d"/*; do i=${p##*/}; case $i in ""|*[!0-9]*) continue;; esac; echo "$i"; done; } | sort -un; }',
|
|
74
|
+
'running() { for i in $(cids); do [ -f "$c/$i/exit" ] && continue; [ "$(state "$i")" = running ] && echo "$i"; done; }',
|
|
75
|
+
// $1's log, opened first and then checked as opened (fd 3): the file the open reached is work/background/<id>/output.log
|
|
76
|
+
// itself, by its real path (so through no link), and a regular file. Every read after is of that open file
|
|
77
|
+
// (/proc/self/fd/3), so a link swapped in at its name after the check is never read. 0: open; 1: there is no log;
|
|
78
|
+
// 2: it is not to be read (a link, not a regular file, or a box with no /proc to check it by).
|
|
79
|
+
'openlog() { exec 3<&-; f="$d/$1/output.log"; [ -e "$f" ] || [ -L "$f" ] || return 1; [ -f "$f" ] && [ ! -L "$f" ] && [ -n "$rw" ] || return 2; exec 3< "$f" 2>/dev/null || return 2; [ "$(readlink /proc/self/fd/3 2>/dev/null)" = "$rw/background/$1/output.log" ] && [ -f /proc/self/fd/3 ] || { exec 3<&-; return 2; }; }',
|
|
80
|
+
'size() { if openlog "$1"; then echo $(($(wc -c < /proc/self/fd/3))); exec 3<&-; else echo 0; fi; }',
|
|
81
|
+
// A display copy in work/ (the runner's put, by id): from inside work/background/<id>, entered with cd -P and checked
|
|
82
|
+
// by its real path, an exclusive new file there renamed over its name on the same filesystem; a failed check skips it.
|
|
83
|
+
`put() { [ -n "$rw" ] || return 0; ( cd -P "$d/$1" 2>/dev/null && [ "$(pwd -P)" = "$rw/background/$1" ] || exit 0; t=$(mktemp ./.put.XXXXXX) || exit 0; if [ "$4" = n ]; then printf '%s\\n' "$3"; else printf '%s' "$3"; fi > "$t" && { mv -fT "$t" "./$2" 2>/dev/null || { [ -L "./$2" ] && rm -f "./$2"; mv -f "$t" "./$2"; }; } || rm -f "$t" ) 2>/dev/null; return 0; }`,
|
|
84
|
+
'known() { [ -d "$c/$1" ] || { [ ! -L "$d" ] && [ -d "$d/$1" ]; }; }',
|
|
85
|
+
'case $op in',
|
|
86
|
+
'start)',
|
|
87
|
+
' mkdir -p "$c" || exit 1; [ -L "$d" ] && { echo linkdir; exit 0; }; mkdir -p "$d" || exit 1',
|
|
88
|
+
' k=0; until mkdir "$c/.lock" 2>/dev/null; do k=$((k+1)); if [ $k -ge 100 ]; then rmdir "$c/.lock" 2>/dev/null; k=0; fi; sleep 0.05; done',
|
|
89
|
+
' trap \'rmdir "$c/.lock" 2>/dev/null\' EXIT',
|
|
90
|
+
' n=$(running | wc -l); if [ "$n" -ge "$2" ]; then echo "full $n"; exit 0; fi',
|
|
91
|
+
' i=1; while [ -e "$d/$i" ] || [ -L "$d/$i" ] || [ -e "$c/$i" ]; do i=$((i+1)); done',
|
|
92
|
+
' mkdir "$d/$i" && mkdir "$c/$i" || exit 1',
|
|
93
|
+
' printf \'%s\' "$1" > "$c/$i/command"; date -u +%Y-%m-%dT%H:%M:%SZ > "$c/$i/started"; : > "$d/$i/output.log"',
|
|
94
|
+
' put "$i" command "$1"; put "$i" started "$(cat "$c/$i/started")" n',
|
|
95
|
+
' mkfifo "$c/$i/in" || exit 1',
|
|
96
|
+
' setsid -f nohup sh -c "$4" agentrun-background "$d/$i" "$c/$i" "$3" "$w" "$1" </dev/null >/dev/null 2>"$c/$i/err" || exit 1',
|
|
97
|
+
' k=0; while [ ! -s "$c/$i/pgid" ] && [ ! -f "$c/$i/exit" ] && [ $k -lt 200 ]; do sleep 0.05; k=$((k+1)); done',
|
|
98
|
+
' [ -s "$c/$i/pgid" ] || [ -f "$c/$i/exit" ] || { cat "$c/$i/err" >&2; echo "process $i did not start" >&2; exit 1; }',
|
|
99
|
+
' put "$i" pid "$(cat "$c/$i/pgid" 2>/dev/null)" n; echo "started $i $(cat "$c/$i/pgid" 2>/dev/null)";;',
|
|
100
|
+
'output)',
|
|
101
|
+
' known "$1" || { echo none; exit 0; }',
|
|
102
|
+
' st=$(state "$1"); echo "state $st"',
|
|
103
|
+
' openlog "$1"; r=$?; [ $r = 2 ] && { echo notlog; exit 0; }; n=0; [ $r = 0 ] && n=$(($(wc -c < /proc/self/fd/3))); echo "size $n"',
|
|
104
|
+
' [ -f "$c/$1/capped" ] && echo capped; [ -f "$c/$1/ended" ] && echo ended; echo --',
|
|
105
|
+
' m=$((n - $2)); [ $m -gt "$3" ] && m=$3',
|
|
106
|
+
' if [ $m -gt 0 ] && [ $r = 0 ]; then tail -c +$(($2 + 1)) /proc/self/fd/3 | head -c $m | base64; fi;;',
|
|
107
|
+
'input)',
|
|
108
|
+
' known "$1" || { echo none; exit 0; }',
|
|
109
|
+
' st=$(state "$1"); [ "$st" = running ] || { echo "state $st"; exit 0; }',
|
|
110
|
+
' [ -f "$c/$1/closed" ] && { echo closed; exit 0; }',
|
|
111
|
+
' if [ -n "$2" ]; then exec 3<>"$c/$1/in" || exit 1; printf \'%s\' "$2" >&3 || exit 1; exec 3>&-; fi',
|
|
112
|
+
' if [ "$3" = 1 ]; then : > "$c/$1/closed"; kill "$(cat "$c/$1/hold" 2>/dev/null)" 2>/dev/null; fi',
|
|
113
|
+
' echo sent;;',
|
|
114
|
+
'signal)',
|
|
115
|
+
' known "$1" || { echo none; exit 0; }',
|
|
116
|
+
' st=$(state "$1"); [ "$st" = running ] || { echo "was $st"; exit 0; }',
|
|
117
|
+
' g=$(cat "$c/$1/pgid" 2>/dev/null); [ -n "$g" ] || { echo "was $st"; exit 0; }',
|
|
118
|
+
' kill -"$2" -"$g" 2>/dev/null',
|
|
119
|
+
' k=0; while [ ! -f "$c/$1/exit" ] && [ $k -lt 40 ]; do sleep 0.05; k=$((k+1)); done',
|
|
120
|
+
' echo "state $(state "$1")";;',
|
|
121
|
+
'list)',
|
|
122
|
+
// Every running one, then the newest $1 others, chosen before any of their details is read: the list costs the same
|
|
123
|
+
// however many ended before.
|
|
124
|
+
' t=0; o=0; picked=""; for i in $(ids | sort -rn); do t=$((t+1)); if [ -f "$c/$i/exit" ] || [ "$(state "$i")" != running ]; then [ $o -lt "$1" ] || continue; o=$((o+1)); fi; picked="$picked $i"; done',
|
|
125
|
+
' echo "total $t"',
|
|
126
|
+
` for i in $picked; do printf '%s\\t%s\\t%s\\t%s\\t%s\\t' "$i" "$(state "$i")" "$(size "$i")" "$(cat "$c/$i/started" 2>/dev/null)" "$([ -f "$c/$i/ended" ] && echo ended)"; head -c 200 "$c/$i/command" 2>/dev/null | base64 | tr -d '\\n'; echo; done;;`,
|
|
127
|
+
'end)',
|
|
128
|
+
' n=0; for i in $(running); do : > "$c/$i/ended"; put "$i" ended ""; g=$(cat "$c/$i/pgid" 2>/dev/null); [ -n "$g" ] && kill -TERM -"$g" 2>/dev/null; n=$((n+1)); done',
|
|
129
|
+
' k=0; while [ $k -lt 60 ] && [ -n "$(running)" ]; do sleep 0.05; k=$((k+1)); done',
|
|
130
|
+
' for i in $(running); do g=$(cat "$c/$i/pgid" 2>/dev/null); [ -n "$g" ] && kill -KILL -"$g" 2>/dev/null; done',
|
|
131
|
+
' k=0; while [ $k -lt 40 ] && [ -n "$(running)" ]; do sleep 0.05; k=$((k+1)); done',
|
|
132
|
+
' for i in $(running); do r=$(cat "$c/$i/runner" 2>/dev/null); [ -n "$r" ] && kill -KILL -"$r" 2>/dev/null; done',
|
|
133
|
+
' echo "ended $n";;',
|
|
134
|
+
'esac',
|
|
135
|
+
].join("\n");
|
|
136
|
+
/** One operation in the box, on the run's environment: its stdout. A call the box cannot run, or that fails, throws. */
|
|
137
|
+
async function inBox(given, op, args, context, timeout = 30) {
|
|
138
|
+
if (!given)
|
|
139
|
+
throw new Error("this call has no box to run in");
|
|
140
|
+
const env = given;
|
|
141
|
+
let out = "";
|
|
142
|
+
let said = "";
|
|
143
|
+
const work = typeof env.cwd === "string" && env.cwd ? env.cwd : BOX_WORK;
|
|
144
|
+
const ran = await env.exec(["sh", "-c", SCRIPT, "agentrun-background", work, op, ...args], {
|
|
145
|
+
timeout,
|
|
146
|
+
onOutput: (text, _context, info) => {
|
|
147
|
+
if (info.stream === "stdout")
|
|
148
|
+
out += text;
|
|
149
|
+
else if (said.length < 2_000)
|
|
150
|
+
said += text;
|
|
151
|
+
},
|
|
152
|
+
}, context);
|
|
153
|
+
if (!ran.ok)
|
|
154
|
+
throw new Error(`the run's box did not answer: ${ran.error.message}`);
|
|
155
|
+
if (ran.value.exitCode !== 0)
|
|
156
|
+
throw new Error(`the run's box answered with exit code ${ran.value.exitCode}${said.trim() ? `: ${said.trim().slice(0, 500)}` : ""}`);
|
|
157
|
+
return out;
|
|
158
|
+
}
|
|
159
|
+
/** A process's id as a call gives it: digits only, so no call names a path. */
|
|
160
|
+
function idOf(value) {
|
|
161
|
+
const id = typeof value === "number" && Number.isSafeInteger(value) ? String(value) : typeof value === "string" ? value.trim() : "";
|
|
162
|
+
if (!/^[1-9][0-9]{0,8}$/.test(id))
|
|
163
|
+
throw new Error(`${JSON.stringify(value)} is no background process id: an id is the number bash_background answered, such as "1" (bash_list shows them)`);
|
|
164
|
+
return id;
|
|
165
|
+
}
|
|
166
|
+
/** A state as the script says it. */
|
|
167
|
+
function stateOf(said) {
|
|
168
|
+
if (said === "running")
|
|
169
|
+
return { state: "running" };
|
|
170
|
+
const exited = /^exited (\d+)$/.exec(said);
|
|
171
|
+
if (!exited)
|
|
172
|
+
return { state: "lost" };
|
|
173
|
+
const code = Number(exited[1]);
|
|
174
|
+
const signal = code > 128 ? SIGNAL_NAMES[code - 128] : undefined;
|
|
175
|
+
return { state: "exited", exit_code: code, ...(signal ? { signal } : {}) };
|
|
176
|
+
}
|
|
177
|
+
/** A state in words: `running`, `exited with code 0`, `ended by signal TERM (exit code 143)`, or lost. */
|
|
178
|
+
function stateWords(state, ended = false) {
|
|
179
|
+
const atEnd = ended ? ", at the run's end" : "";
|
|
180
|
+
if (state.state === "running")
|
|
181
|
+
return "is running";
|
|
182
|
+
if (state.state === "lost")
|
|
183
|
+
return "is gone: its box was replaced before it ended, so its exit code is not known";
|
|
184
|
+
return state.signal ? `ended by signal ${state.signal} (exit code ${state.exit_code})${atEnd}` : `exited with code ${state.exit_code}${atEnd}`;
|
|
185
|
+
}
|
|
186
|
+
const noSuch = (id) => new Error(`there is no background process ${id} in this run: bash_list shows them`);
|
|
187
|
+
/** The end of `bytes` that ends inside a UTF-8 character, left for the next page: how many bytes to keep (none, when the
|
|
188
|
+
* page holds only part of one character). */
|
|
189
|
+
function wholeChars(bytes) {
|
|
190
|
+
for (let back = 1; back <= Math.min(3, bytes.length); back++) {
|
|
191
|
+
const byte = bytes[bytes.length - back];
|
|
192
|
+
if ((byte & 0xc0) === 0x80)
|
|
193
|
+
continue;
|
|
194
|
+
const length = byte >= 0xf0 ? 4 : byte >= 0xe0 ? 3 : byte >= 0xc0 ? 2 : 1;
|
|
195
|
+
return length > back ? bytes.length - back : bytes.length;
|
|
196
|
+
}
|
|
197
|
+
return bytes.length;
|
|
198
|
+
}
|
|
199
|
+
const decode = (base64) => new Uint8Array(Buffer.from(base64.replace(/\s+/g, ""), "base64"));
|
|
200
|
+
const intArg = (value, name, min, max, fallback) => {
|
|
201
|
+
if (value === undefined || value === null)
|
|
202
|
+
return fallback;
|
|
203
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max)
|
|
204
|
+
throw new Error(`${name} is a whole number from ${min.toLocaleString("en-US")} to ${max.toLocaleString("en-US")}`);
|
|
205
|
+
return value;
|
|
206
|
+
};
|
|
207
|
+
const ID_SCHEMA = { type: "string", pattern: "^[1-9][0-9]*$", description: "The process's id, as bash_background answered it (\"1\")." };
|
|
208
|
+
const schema = (properties, required) => ({ type: "object", additionalProperties: false, properties, required });
|
|
209
|
+
const bashBackground = defineTool({
|
|
210
|
+
name: "bash_background",
|
|
211
|
+
description: `Start a shell command in the background in the run's box, from its work/, and answer at once with its id. Each call is a fresh shell (bash, else sh). The command runs until it and every child it left in its process group (a server started with &) have exited, bash_signal ends it, or the run ends, which ends it. Its stdout and stderr go together to work/background/<id>/output.log, which the run's files keep: the first ${MIB} MiB of them, later output dropped while it runs on. Its stdin is a pipe that bash_input writes. At most ${BACKGROUND_MAX} run at once in a run's box. Read its output with bash_output, list them with bash_list.`,
|
|
212
|
+
parameters: schema({ command: { type: "string", minLength: 1, description: "The command, as you would give bash." } }, ["command"]),
|
|
213
|
+
execute: async (args, api, context) => {
|
|
214
|
+
const command = String(args.command ?? "");
|
|
215
|
+
if (!command.trim())
|
|
216
|
+
throw new Error("command is the shell command to start");
|
|
217
|
+
const said = (await inBox(api.env, "start", [command, String(BACKGROUND_MAX), String(BACKGROUND_LOG_BYTES), RUNNER], context)).trim();
|
|
218
|
+
if (said === "linkdir")
|
|
219
|
+
throw new Error("work/background is a link, so no background process starts: remove it, and its logs go in a directory of their own again");
|
|
220
|
+
const full = /^full (\d+)/.exec(said);
|
|
221
|
+
if (full)
|
|
222
|
+
throw new Error(`${full[1]} background processes already run in this run's box, the most at once (${BACKGROUND_MAX}): end one with bash_signal (bash_list shows them), or wait for one to exit, then start this again.`);
|
|
223
|
+
const started = /^started (\d+) ?(\d*)/.exec(said);
|
|
224
|
+
if (!started)
|
|
225
|
+
throw new Error(`the run's box did not start the process: ${said.slice(0, 300) || "it said nothing"}`);
|
|
226
|
+
const [, id, group] = started;
|
|
227
|
+
const log = `${BACKGROUND_DIR}/${id}/output.log`;
|
|
228
|
+
return forModel(`Started background process ${id}${group ? ` (process group ${group})` : ""}. Its output goes to ${log} in work/: read it with bash_output {"id": "${id}"}, write its stdin with bash_input, end it with bash_signal.`, { details: { id, log, ...(group ? { pid: Number(group) } : {}) } });
|
|
229
|
+
},
|
|
230
|
+
});
|
|
231
|
+
const bashOutput = defineTool({
|
|
232
|
+
name: "bash_output",
|
|
233
|
+
description: `Read a background process's output (stdout and stderr together) from a byte offset: at most max_bytes (default and most ${BACKGROUND_PAGE_BYTES / 1024} KiB), with whether it still runs, its exit code once it has ended, the log's size, and the offset to read from next. Start at 0; pass the next offset to read on, also to see what a running process wrote since.`,
|
|
234
|
+
parameters: schema({
|
|
235
|
+
id: ID_SCHEMA,
|
|
236
|
+
offset: { type: "integer", minimum: 0, description: "The byte to read from; 0, the start, when absent." },
|
|
237
|
+
max_bytes: { type: "integer", minimum: 1, maximum: BACKGROUND_PAGE_BYTES, description: `The most bytes to read; ${BACKGROUND_PAGE_BYTES.toLocaleString("en-US")} when absent.` },
|
|
238
|
+
}, ["id"]),
|
|
239
|
+
replay: "safe",
|
|
240
|
+
execute: async (args, api, context) => {
|
|
241
|
+
const given = args;
|
|
242
|
+
const id = idOf(given.id);
|
|
243
|
+
const offset = intArg(given.offset, "offset", 0, BACKGROUND_LOG_BYTES, 0);
|
|
244
|
+
const max = intArg(given.max_bytes, "max_bytes", 1, BACKGROUND_PAGE_BYTES, BACKGROUND_PAGE_BYTES);
|
|
245
|
+
const said = await inBox(api.env, "output", [id, String(offset), String(max)], context);
|
|
246
|
+
if (said.trim() === "none")
|
|
247
|
+
throw noSuch(id);
|
|
248
|
+
if (said.split("\n").includes("notlog"))
|
|
249
|
+
throw new Error(`background process ${id}'s log is not read: ${BACKGROUND_DIR}/${id}/output.log (or a directory on its way) is a link or not a regular file, so it could name another file (or this box has no /proc to check it by)`);
|
|
250
|
+
const at = said.indexOf("\n--\n");
|
|
251
|
+
const head = (at < 0 ? said : said.slice(0, at)).split("\n");
|
|
252
|
+
const fact = (key) => head.find((line) => line === key || line.startsWith(`${key} `))?.slice(key.length + 1);
|
|
253
|
+
const state = stateOf(fact("state") ?? "");
|
|
254
|
+
const size = Number(fact("size") ?? 0);
|
|
255
|
+
const capped = head.includes("capped");
|
|
256
|
+
const ended = head.includes("ended");
|
|
257
|
+
const read = at < 0 ? new Uint8Array() : decode(said.slice(at + 4));
|
|
258
|
+
// A character the page would split is left for the next one, unless the process has ended and nothing follows.
|
|
259
|
+
const keep = state.state === "running" || offset + read.length < size ? wholeChars(read) : read.length;
|
|
260
|
+
// A page too small for the one character it starts with reads nothing, and says what to ask instead.
|
|
261
|
+
if (keep === 0 && read.length > 0)
|
|
262
|
+
throw new Error(`the character at byte ${offset} of background process ${id}'s output is longer than max_bytes ${max}: ask again with max_bytes 4 or more`);
|
|
263
|
+
const bytes = read.subarray(0, keep);
|
|
264
|
+
const next = offset + bytes.length;
|
|
265
|
+
const more = next < size;
|
|
266
|
+
const where = offset >= size && bytes.length === 0
|
|
267
|
+
? `No output past byte ${offset.toLocaleString("en-US")} (the log has ${size.toLocaleString("en-US")} bytes)${state.state === "running" ? "; call again later with the same offset for what comes next" : ""}.`
|
|
268
|
+
: `Output bytes ${offset.toLocaleString("en-US")} to ${next.toLocaleString("en-US")} of ${size.toLocaleString("en-US")}${more ? `; call again with offset ${next} for the next part` : state.state === "running" ? `, all of it so far; call again with offset ${next} for what comes next` : ", the end"}.`;
|
|
269
|
+
const cap = capped ? ` Its log reached the ${MIB} MiB cap, so later output was dropped.` : "";
|
|
270
|
+
const text = new TextDecoder().decode(bytes);
|
|
271
|
+
return forModel(`Background process ${id} ${stateWords(state, ended)}. ${where}${cap}${text ? `\n\n${text}` : ""}`, { details: { id, ...state, offset, next_offset: next, size, ...(capped ? { capped } : {}), ...(ended ? { ended_at_run_end: true } : {}) } });
|
|
272
|
+
},
|
|
273
|
+
});
|
|
274
|
+
const bashInput = defineTool({
|
|
275
|
+
name: "bash_input",
|
|
276
|
+
description: `Write text to a running background process's stdin, as given (end a line with \\n), at most ${BACKGROUND_INPUT_BYTES / 1024} KiB a call. close: true closes its stdin after the text, so the process reads the end of its input. To interrupt it, send bash_signal INT; a control character written here is only a byte.`,
|
|
277
|
+
parameters: schema({
|
|
278
|
+
id: ID_SCHEMA,
|
|
279
|
+
text: { type: "string", description: "The bytes to write, as UTF-8; empty with close: true closes stdin alone." },
|
|
280
|
+
close: { type: "boolean", description: "Close the process's stdin after the text." },
|
|
281
|
+
}, ["id", "text"]),
|
|
282
|
+
execute: async (args, api, context) => {
|
|
283
|
+
const given = args;
|
|
284
|
+
const id = idOf(given.id);
|
|
285
|
+
const text = typeof given.text === "string" ? given.text : "";
|
|
286
|
+
if (Buffer.byteLength(text) > BACKGROUND_INPUT_BYTES)
|
|
287
|
+
throw new Error(`text is at most ${BACKGROUND_INPUT_BYTES / 1024} KiB a call; send it in parts`);
|
|
288
|
+
if (text.includes("\0"))
|
|
289
|
+
throw new Error("text holds a NUL byte, which no shell argument carries");
|
|
290
|
+
const close = given.close === true;
|
|
291
|
+
if (!text && !close)
|
|
292
|
+
throw new Error("text is what to write: give some, or close: true to close stdin");
|
|
293
|
+
const said = (await inBox(api.env, "input", [id, text, close ? "1" : "0"], context, 15).catch((error) => {
|
|
294
|
+
throw new Error(`process ${id} did not take its input: ${error.message} (a process that does not read its stdin fills its pipe at 64 KiB)`);
|
|
295
|
+
})).trim();
|
|
296
|
+
if (said === "none")
|
|
297
|
+
throw noSuch(id);
|
|
298
|
+
if (said === "closed")
|
|
299
|
+
throw new Error(`background process ${id}'s stdin is closed: an earlier bash_input closed it`);
|
|
300
|
+
if (said.startsWith("state "))
|
|
301
|
+
throw new Error(`background process ${id} ${stateWords(stateOf(said.slice(6)))}, so it takes no input`);
|
|
302
|
+
const bytes = Buffer.byteLength(text);
|
|
303
|
+
return forModel(`Wrote ${bytes.toLocaleString("en-US")} bytes to background process ${id}'s stdin${close ? ", then closed it" : ""}. Read what it answers with bash_output.`, { details: { id, bytes, ...(close ? { closed: true } : {}) } });
|
|
304
|
+
},
|
|
305
|
+
});
|
|
306
|
+
const bashSignal = defineTool({
|
|
307
|
+
name: "bash_signal",
|
|
308
|
+
description: "Send a signal to a background process's process group: TERM asks it to stop, INT is Ctrl-C, KILL ends it at once. Answers its state after up to 2 s: a process that handles the signal may run on.",
|
|
309
|
+
parameters: schema({ id: ID_SCHEMA, signal: { type: "string", enum: [...BACKGROUND_SIGNALS], description: "TERM, INT or KILL." } }, ["id", "signal"]),
|
|
310
|
+
execute: async (args, api, context) => {
|
|
311
|
+
const given = args;
|
|
312
|
+
const id = idOf(given.id);
|
|
313
|
+
const signal = typeof given.signal === "string" ? given.signal.trim().toUpperCase().replace(/^SIG/, "") : "";
|
|
314
|
+
if (!BACKGROUND_SIGNALS.includes(signal))
|
|
315
|
+
throw new Error(`signal is one of ${BACKGROUND_SIGNALS.join(", ")}`);
|
|
316
|
+
const said = (await inBox(api.env, "signal", [id, signal], context, 15)).trim();
|
|
317
|
+
if (said === "none")
|
|
318
|
+
throw noSuch(id);
|
|
319
|
+
if (said.startsWith("was "))
|
|
320
|
+
throw new Error(`background process ${id} ${stateWords(stateOf(said.slice(4)))}, so no signal was sent`);
|
|
321
|
+
const state = stateOf(said.replace(/^state /, ""));
|
|
322
|
+
return forModel(`Sent ${signal} to background process ${id}: it ${stateWords(state)}.${state.state === "running" ? " Send KILL to end it at once." : ""}`, { details: { id, signal, ...state } });
|
|
323
|
+
},
|
|
324
|
+
});
|
|
325
|
+
const bashList = defineTool({
|
|
326
|
+
name: "bash_list",
|
|
327
|
+
description: `List this run's background processes: each one's id, whether it runs or how it ended, its output's size and its command's start, every running one first, then the newest that ended (${BACKGROUND_LIST_MAX} at most).`,
|
|
328
|
+
parameters: schema({}, []),
|
|
329
|
+
replay: "safe",
|
|
330
|
+
execute: async (_args, api, context) => {
|
|
331
|
+
const said = await inBox(api.env, "list", [String(BACKGROUND_LIST_MAX)], context);
|
|
332
|
+
const [first = "", ...rows] = said.split("\n");
|
|
333
|
+
const total = Number(/^total (\d+)$/.exec(first)?.[1] ?? 0);
|
|
334
|
+
const all = rows.filter(Boolean).map((line) => {
|
|
335
|
+
const [id = "", state = "", size = "0", started = "", ended = "", command = ""] = line.split("\t");
|
|
336
|
+
return { id, ...stateOf(state), size: Number(size) || 0, ...(started ? { started } : {}), ...(ended ? { ended_at_run_end: true } : {}), command: new TextDecoder().decode(decode(command)) };
|
|
337
|
+
}).sort((a, b) => Number(b.id) - Number(a.id));
|
|
338
|
+
const shown = [...all.filter((p) => p.state === "running"), ...all.filter((p) => p.state !== "running")].slice(0, BACKGROUND_LIST_MAX);
|
|
339
|
+
if (!shown.length)
|
|
340
|
+
return forModel("No background processes in this run's box: bash_background starts one.", { details: { processes: [] } });
|
|
341
|
+
const running = all.filter((p) => p.state === "running").length;
|
|
342
|
+
const lines = shown.map((p) => `${p.id}: ${stateWords(p, p.ended_at_run_end === true)}; ${p.size.toLocaleString("en-US")} bytes of output; started ${p.started ?? "at an unknown time"}; ${JSON.stringify(p.command.replace(/\s+/g, " ").slice(0, 120))}`);
|
|
343
|
+
const left = total - shown.length;
|
|
344
|
+
return forModel(`${running} of at most ${BACKGROUND_MAX} running.\n${lines.join("\n")}${left > 0 ? `\n(and ${left} older ones that ended)` : ""}`, { details: { running, processes: shown } });
|
|
345
|
+
},
|
|
346
|
+
});
|
|
347
|
+
/** The background tools, each run on the environment its call gives (the box's, coding-tools.ts). */
|
|
348
|
+
export const backgroundTools = () => [bashBackground, bashOutput, bashInput, bashSignal, bashList];
|
|
349
|
+
/** The run's end: every background process still running in run `runId`'s box (found by `label`) is sent TERM, then
|
|
350
|
+
* KILL after 3 s, and marked as ended at the run's end, so its runner writes its exit code and its log is whole before
|
|
351
|
+
* the box is pulled and destroyed. How many it ended; a run with no box ends none. */
|
|
352
|
+
export async function endBackground(boxes, label, context) {
|
|
353
|
+
const { finish } = await import("@parcha/pi-transport");
|
|
354
|
+
const listed = await boxes.list(label, context);
|
|
355
|
+
if (!listed.ok)
|
|
356
|
+
throw listed.error;
|
|
357
|
+
let ended = 0;
|
|
358
|
+
for (const ref of listed.value) {
|
|
359
|
+
const attached = await boxes.attach(ref.id, context);
|
|
360
|
+
if (!attached.ok)
|
|
361
|
+
throw attached.error;
|
|
362
|
+
if (!attached.value)
|
|
363
|
+
continue;
|
|
364
|
+
const started = await attached.value.exec(["sh", "-c", SCRIPT, "agentrun-background", BOX_WORK, "end"], { timeoutMs: 20_000 }, context);
|
|
365
|
+
if (!started.ok)
|
|
366
|
+
throw started.error;
|
|
367
|
+
const done = await finish(started.value);
|
|
368
|
+
if (!done.ok)
|
|
369
|
+
throw done.error;
|
|
370
|
+
const said = new TextDecoder().decode(done.value.stdout).trim();
|
|
371
|
+
if (done.value.exitCode !== 0)
|
|
372
|
+
throw new Error(`ending the box's background processes failed (exit code ${done.value.exitCode}): ${done.value.stderr.trim().slice(0, 300)}`);
|
|
373
|
+
ended += Number(/^ended (\d+)/.exec(said)?.[1] ?? 0);
|
|
374
|
+
}
|
|
375
|
+
return ended;
|
|
376
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { type ExecutionEnv } from "@earendil-works/pi-durable/env";
|
|
2
|
+
/** A box run's read, write and edit environment on this machine's `hostWork` (canonical: the bind's source), naming the
|
|
3
|
+
* box's paths. Its shell runs nothing, and only the operations those tools make are offered. */
|
|
4
|
+
export declare function boundFiles(hostWork: string): ExecutionEnv;
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// The file tools of a run whose box binds its work/ from this machine (Docker here): read, write and edit run on this
|
|
2
|
+
// machine, on the bind's source, and not as commands in the box, which cost one `docker exec` or more each (half a second
|
|
3
|
+
// and up on real Docker). bash stays in the box. This holds only where the confinement walks held directory handles
|
|
4
|
+
// (workspace.ts writesHeld: Linux's /proc/self/fd): a command in the box runs beside these tools and can plant a link, a
|
|
5
|
+
// hard link or a swapped directory at any moment, and only a walk on held handles refuses a swap between the check and
|
|
6
|
+
// the use. Elsewhere (macOS, a box that binds nothing, Daytona's) all four stay in the box (coding-tools.ts).
|
|
7
|
+
//
|
|
8
|
+
// Nothing a box's command makes in work/ is followed or taken. Every path is work/ joined with its own names, and a link
|
|
9
|
+
// anywhere on the way is refused, even one pointing inside work/. Only a regular file with one hard link is read or
|
|
10
|
+
// written. A write goes through a temporary file renamed over the old one, keeping its mode (workspace.ts
|
|
11
|
+
// writeWorkFile). work/ itself must be its own canonical path: the directory the box was given (run-box.ts
|
|
12
|
+
// mountSource). The model names the box's paths (BOX_WORK), mapped one for one onto the bind's source; every path and
|
|
13
|
+
// message it gets back names the box's, never this machine's.
|
|
14
|
+
import { realpathSync } from "node:fs";
|
|
15
|
+
import { posix } from "node:path";
|
|
16
|
+
import { err, ExecutionError, FileError, ok } from "@earendil-works/pi-durable/env";
|
|
17
|
+
import { NodeExecutionEnv } from "@earendil-works/pi-durable/env/node";
|
|
18
|
+
import { PathOutsideWorkError } from "@parcha/pi-durable-disk";
|
|
19
|
+
import { BOX_WORK } from "./place.js";
|
|
20
|
+
import { openWorkFile, WorkRefused, writeWorkFile } from "./workspace.js";
|
|
21
|
+
/** What a refusal tells the model, by the path it named: what is wrong, and that bash, in the box, can still reach it. */
|
|
22
|
+
const REFUSED = {
|
|
23
|
+
link: (path) => `${path}: refused: a link is on the way to it, or it is one, and read, write and edit follow no link in this run's work/ (bash, in the box, can)`,
|
|
24
|
+
hard_link: (path) => `${path}: refused: it has another hard link, and read, write and edit take only a file with one (bash, in the box, can)`,
|
|
25
|
+
not_regular: (path) => `${path}: refused: it is not a regular file`,
|
|
26
|
+
unreadable: (path) => `${path}: refused: this server may not read it (a command in the box made it private)`,
|
|
27
|
+
over_cap: (path) => `${path}: refused: it is too large`,
|
|
28
|
+
unheld: (path) => `${path}: refused: this host reaches the run's directories by path`,
|
|
29
|
+
};
|
|
30
|
+
const NODE_CODES = { ENOENT: "not_found", EACCES: "permission_denied", EPERM: "permission_denied", ENOTDIR: "not_directory", EISDIR: "is_directory", ELOOP: "invalid" };
|
|
31
|
+
/** A box run's read, write and edit environment on this machine's `hostWork` (canonical: the bind's source), naming the
|
|
32
|
+
* box's paths. Its shell runs nothing, and only the operations those tools make are offered. */
|
|
33
|
+
export function boundFiles(hostWork) {
|
|
34
|
+
// pi's own implementation, only ever handed a checked handle's /proc/self/fd entry, which names that inode and no path.
|
|
35
|
+
const node = new NodeExecutionEnv({ cwd: hostWork });
|
|
36
|
+
/** `text` with this machine's work/ named as the box names it. */
|
|
37
|
+
const boxed = (text) => text.split(`${hostWork}/`).join(`${BOX_WORK}/`).split(hostWork).join(BOX_WORK);
|
|
38
|
+
// The confinement's typed refusal, its message naming no path: the tools name it by the path the call gave
|
|
39
|
+
// (workspace-paths.ts asGivenRefusals). It crosses from pi-durable-disk's pi-durable as a value, typed on this side.
|
|
40
|
+
const outside = (path) => new PathOutsideWorkError(path, "outside_work", "outside the workspace");
|
|
41
|
+
/** `path` as an absolute path of the box, or the refusal of one outside its work/. */
|
|
42
|
+
const absolute = (path) => {
|
|
43
|
+
const abs = posix.resolve(BOX_WORK, path);
|
|
44
|
+
return abs === BOX_WORK || abs.startsWith(`${BOX_WORK}/`) ? ok(abs) : err(outside(path));
|
|
45
|
+
};
|
|
46
|
+
const failure = (error, path) => {
|
|
47
|
+
if (error instanceof WorkRefused) {
|
|
48
|
+
if (error.reason === "missing")
|
|
49
|
+
return new FileError("not_found", `ENOENT: no such file or directory, open '${path}'`, path);
|
|
50
|
+
return new FileError("permission_denied", REFUSED[error.reason](path), path);
|
|
51
|
+
}
|
|
52
|
+
if (error instanceof FileError)
|
|
53
|
+
return new FileError(error.code, boxed(error.message), path, error);
|
|
54
|
+
const code = error?.code;
|
|
55
|
+
return new FileError((code && NODE_CODES[code]) || "unknown", boxed(error?.message ?? String(error)), path);
|
|
56
|
+
};
|
|
57
|
+
/** The work/ the box was given: refused when it is no longer its own canonical path (swapped for a link). */
|
|
58
|
+
const root = () => {
|
|
59
|
+
if (realpathSync(hostWork) !== hostWork)
|
|
60
|
+
throw new WorkRefused(".", "link");
|
|
61
|
+
};
|
|
62
|
+
/** `use` on the file at `path`, opened held: a regular file with one link, reached through no link. */
|
|
63
|
+
async function opened(path, use) {
|
|
64
|
+
const abs = absolute(path);
|
|
65
|
+
if (!abs.ok)
|
|
66
|
+
return abs;
|
|
67
|
+
const rel = posix.relative(BOX_WORK, abs.value);
|
|
68
|
+
if (rel === "")
|
|
69
|
+
return err(new FileError("is_directory", `${abs.value}: is the run's work directory, not a file`, abs.value));
|
|
70
|
+
try {
|
|
71
|
+
root();
|
|
72
|
+
const { handle, stats } = await openWorkFile(hostWork, rel);
|
|
73
|
+
try {
|
|
74
|
+
return ok(await use(handle, stats, abs.value));
|
|
75
|
+
}
|
|
76
|
+
finally {
|
|
77
|
+
await handle.close().catch(() => undefined);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
return err(failure(error, abs.value));
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/** pi's reader of a checked handle, its info naming the box's path. */
|
|
85
|
+
const reader = async (handle, abs, context) => {
|
|
86
|
+
const made = await node.openBinaryReader(`/proc/self/fd/${handle.fd}`, undefined, context);
|
|
87
|
+
if (!made.ok)
|
|
88
|
+
throw made.error;
|
|
89
|
+
const inner = made.value;
|
|
90
|
+
return {
|
|
91
|
+
info: async (at) => {
|
|
92
|
+
const info = await inner.info(at);
|
|
93
|
+
return info.ok ? ok({ ...info.value, name: posix.basename(abs), path: abs }) : err(failure(info.error, abs));
|
|
94
|
+
},
|
|
95
|
+
read: (offset, length, at) => inner.read(offset, length, at),
|
|
96
|
+
scanLines: (options, at) => inner.scanLines(options, at),
|
|
97
|
+
close: (at) => inner.close(at),
|
|
98
|
+
};
|
|
99
|
+
};
|
|
100
|
+
/** An operation read, write and edit never make: refused, so nothing else of this machine is reached through it. */
|
|
101
|
+
const unoffered = (name) => async () => err(new FileError("not_supported", `${name} is not offered here: a box run's file tools on this machine read, write and edit, and bash runs in the box`));
|
|
102
|
+
return {
|
|
103
|
+
id: `bound-work:${hostWork}`,
|
|
104
|
+
cwd: BOX_WORK,
|
|
105
|
+
absolutePath: async (path) => absolute(path),
|
|
106
|
+
joinPath: async (parts) => ok(posix.join(...parts)),
|
|
107
|
+
// The mutation queue then keys a file by its absolute path: a link is never followed here, so that is the file.
|
|
108
|
+
canonicalPath: unoffered("canonicalPath"),
|
|
109
|
+
exists: async (path) => {
|
|
110
|
+
const abs = absolute(path);
|
|
111
|
+
if (!abs.ok)
|
|
112
|
+
return abs;
|
|
113
|
+
const found = await opened(abs.value, async () => true);
|
|
114
|
+
// A file refused is there: the operation that follows says why.
|
|
115
|
+
return found.ok || found.error.code !== "not_found" ? ok(true) : ok(false);
|
|
116
|
+
},
|
|
117
|
+
fileInfo: (path) => opened(path, async (_handle, info, abs) => ({ name: posix.basename(abs), path: abs, kind: "file", size: info.size, mtimeMs: info.mtimeMs })),
|
|
118
|
+
readTextFile: (path, context) => opened(path, (handle) => handle.readFile({ encoding: "utf8", ...(context.abortSignal ? { signal: context.abortSignal } : {}) })),
|
|
119
|
+
readBinaryFile: (path, context) => opened(path, async (handle) => new Uint8Array(await handle.readFile(context.abortSignal ? { signal: context.abortSignal } : {}))),
|
|
120
|
+
openBinaryReader: (path, _options, context) => opened(path, (handle, _info, abs) => reader(handle, abs, context)),
|
|
121
|
+
openTextLineReader: (path, context) => opened(path, async (handle, _info, abs) => {
|
|
122
|
+
const made = await node.openTextLineReader(`/proc/self/fd/${handle.fd}`, context);
|
|
123
|
+
if (!made.ok)
|
|
124
|
+
throw failure(made.error, abs);
|
|
125
|
+
return made.value;
|
|
126
|
+
}),
|
|
127
|
+
readTextLines: (path, options, context) => opened(path, async (handle, _info, abs) => {
|
|
128
|
+
const read = await node.readTextLines(`/proc/self/fd/${handle.fd}`, options, context);
|
|
129
|
+
if (!read.ok)
|
|
130
|
+
throw failure(read.error, abs);
|
|
131
|
+
return read.value;
|
|
132
|
+
}),
|
|
133
|
+
writeFile: async (path, content) => {
|
|
134
|
+
const abs = absolute(path);
|
|
135
|
+
if (!abs.ok)
|
|
136
|
+
return abs;
|
|
137
|
+
const rel = posix.relative(BOX_WORK, abs.value);
|
|
138
|
+
if (rel === "")
|
|
139
|
+
return err(new FileError("is_directory", `${abs.value}: is the run's work directory, not a file`, abs.value));
|
|
140
|
+
try {
|
|
141
|
+
root();
|
|
142
|
+
// A new file as a box's command would make it (0644); one already there keeps its mode.
|
|
143
|
+
await writeWorkFile(hostWork, rel, typeof content === "string" ? Buffer.from(content) : content, 0o644, true);
|
|
144
|
+
return ok(undefined);
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
return err(failure(error, abs.value));
|
|
148
|
+
}
|
|
149
|
+
},
|
|
150
|
+
appendFile: unoffered("appendFile"),
|
|
151
|
+
truncateFile: unoffered("truncateFile"),
|
|
152
|
+
flushFile: unoffered("flushFile"),
|
|
153
|
+
renameFile: unoffered("renameFile"),
|
|
154
|
+
listDir: unoffered("listDir"),
|
|
155
|
+
openDirReader: unoffered("openDirReader"),
|
|
156
|
+
watch: unoffered("watch"),
|
|
157
|
+
createDir: unoffered("createDir"),
|
|
158
|
+
remove: unoffered("remove"),
|
|
159
|
+
createTempDir: unoffered("createTempDir"),
|
|
160
|
+
createTempFile: unoffered("createTempFile"),
|
|
161
|
+
exec: async () => err(new ExecutionError("shell_unavailable", "this environment runs no command: bash runs in the box")),
|
|
162
|
+
cleanup: async () => undefined,
|
|
163
|
+
};
|
|
164
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { BoxRecorder } from "@parcha/agentrun-kernel/host";
|
|
2
|
+
/** The run directory's box record. */
|
|
3
|
+
export declare const BOX_RECORD = "box.json";
|
|
4
|
+
/** The recorder a box start is given for the run in `runDir`: each call replaces the record. `ahead` returns only once
|
|
5
|
+
* the file and its directory are synced; `started` resolves then. */
|
|
6
|
+
export declare function boxRecorder(runDir: string): BoxRecorder;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// A run's box record, beside the run: written durably before anything runs in the box, so whatever crashes after (the
|
|
2
|
+
// run's process, the server, the machine) leaves a record a later start can find the box by. The box's first record
|
|
3
|
+
// (its id, its cgroup, its writer) is written synchronously before its spawn (`ahead`); its second (its first process's
|
|
4
|
+
// pid, start time and pid namespace) before that process is let go (`started`). The box's start names the writer, the
|
|
5
|
+
// run process: a record nothing could count is cleared only once that writer is gone, so a record without one is refused.
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { BoxError } from "@parcha/agentrun-kernel/host";
|
|
8
|
+
import { writeDurable, writeDurableSync } from "../files.js";
|
|
9
|
+
/** The run directory's box record. */
|
|
10
|
+
export const BOX_RECORD = "box.json";
|
|
11
|
+
function text(record) {
|
|
12
|
+
const writer = record.writer;
|
|
13
|
+
if (!writer || !Number.isSafeInteger(writer.pid) || typeof writer.startTime !== "string" || writer.startTime === "") {
|
|
14
|
+
throw new BoxError("box_record_failed", "box_record_failed: a box record names no writer (its run process's pid and start time), so it could never be cleared safely");
|
|
15
|
+
}
|
|
16
|
+
return `${JSON.stringify(record)}\n`;
|
|
17
|
+
}
|
|
18
|
+
/** The recorder a box start is given for the run in `runDir`: each call replaces the record. `ahead` returns only once
|
|
19
|
+
* the file and its directory are synced; `started` resolves then. */
|
|
20
|
+
export function boxRecorder(runDir) {
|
|
21
|
+
const path = join(runDir, BOX_RECORD);
|
|
22
|
+
const failed = (error) => (error instanceof BoxError ? error : new BoxError("box_record_failed", `box_record_failed: the box record could not be written whole: ${error.message}`, { cause: error }));
|
|
23
|
+
return {
|
|
24
|
+
ahead: (record) => {
|
|
25
|
+
try {
|
|
26
|
+
writeDurableSync(path, text(record));
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
throw failed(error);
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
started: async (record) => {
|
|
33
|
+
try {
|
|
34
|
+
await writeDurable(path, text(record));
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
throw failed(error);
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
}
|