@parcha/agentrun-serve 0.1.0-beta.29 → 0.1.0-beta.31
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 +238 -0
- package/README.md +739 -116
- package/dist/adapters.d.ts +35 -6
- package/dist/adapters.js +152 -26
- package/dist/agents.d.ts +18 -7
- package/dist/agents.js +19 -10
- package/dist/app.js +101 -26
- package/dist/background.d.ts +29 -0
- package/dist/background.js +397 -0
- package/dist/box-egress-vm.d.ts +125 -0
- package/dist/box-egress-vm.js +350 -0
- package/dist/box-egress.d.ts +99 -0
- package/dist/box-egress.js +259 -0
- package/dist/box-image.d.ts +1 -1
- package/dist/box-image.js +9 -7
- package/dist/box-relay-vm.d.ts +84 -0
- package/dist/box-relay-vm.js +410 -0
- package/dist/box-relay.d.ts +8 -5
- package/dist/box-relay.js +14 -9
- package/dist/boxes.d.ts +28 -5
- package/dist/boxes.js +44 -18
- package/dist/browser-cost.d.ts +41 -0
- package/dist/browser-cost.js +158 -0
- package/dist/cap.d.ts +130 -21
- package/dist/cap.js +339 -67
- package/dist/cli.js +30 -4
- package/dist/coding-tools.d.ts +7 -3
- package/dist/coding-tools.js +16 -10
- package/dist/console/THIRD-PARTY-NOTICES.txt +580 -0
- package/dist/console/assets/index-CnJBf7Lc.js +486 -0
- package/dist/console/assets/index-DUHbWcIP.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/content-filter.d.ts +7 -0
- package/dist/content-filter.js +23 -0
- package/dist/decision-rows.d.ts +11 -3
- package/dist/decision-rows.js +18 -11
- package/dist/decisions.d.ts +3 -3
- package/dist/decisions.js +4 -3
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +5 -2
- package/dist/files.d.ts +9 -1
- package/dist/files.js +10 -2
- package/dist/grade.d.ts +11 -11
- package/dist/grade.js +43 -55
- package/dist/graph-served.d.ts +23 -0
- package/dist/graph-served.js +75 -0
- package/dist/graph-view.d.ts +7 -5
- package/dist/graph-view.js +10 -3
- package/dist/harness-app.d.ts +4 -2
- package/dist/harness-app.js +110 -19
- 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 +4 -1
- package/dist/harness.js +5 -2
- package/dist/host-check.d.ts +12 -0
- package/dist/host-check.js +34 -0
- package/dist/host-tools.d.ts +12 -2
- package/dist/host-tools.js +26 -12
- package/dist/host.js +6 -2
- package/dist/hosted-search.js +5 -1
- package/dist/import.d.ts +2 -2
- package/dist/import.js +4 -3
- package/dist/key-check.d.ts +3 -2
- package/dist/key-check.js +7 -3
- package/dist/key-refusal.js +8 -4
- package/dist/key-words.d.ts +37 -0
- package/dist/key-words.js +40 -0
- package/dist/learn/check.d.ts +10 -1
- package/dist/learn/check.js +19 -1
- package/dist/learn/grade.d.ts +6 -2
- package/dist/learn/grade.js +28 -14
- package/dist/learn/index.d.ts +3 -3
- package/dist/learn/index.js +3 -3
- package/dist/learn/notes.js +2 -1
- package/dist/learn/reflect.d.ts +2 -2
- package/dist/learn/reflect.js +53 -5
- package/dist/learn/secrets.js +28 -8
- package/dist/learn/skills.d.ts +19 -4
- package/dist/learn/skills.js +95 -6
- package/dist/learned-workflow.d.ts +59 -0
- package/dist/learned-workflow.js +191 -0
- package/dist/learning-routes.d.ts +30 -1
- package/dist/learning-routes.js +173 -19
- package/dist/learning-run.d.ts +8 -6
- package/dist/learning-run.js +70 -27
- package/dist/learning-words.d.ts +12 -5
- package/dist/learning-words.js +34 -13
- package/dist/learning.d.ts +52 -3
- package/dist/learning.js +204 -4
- package/dist/mcp-gateway.d.ts +96 -0
- package/dist/mcp-gateway.js +408 -0
- package/dist/mcp-meta.d.ts +17 -0
- package/dist/mcp-meta.js +38 -0
- package/dist/mcp-servers.d.ts +33 -9
- package/dist/mcp-servers.js +58 -10
- package/dist/mcp.js +5 -5
- package/dist/model.d.ts +13 -11
- package/dist/model.js +11 -10
- package/dist/openapi/agentrun-v2.openapi.json +1 -0
- package/dist/openapi.js +407 -54
- package/dist/page.d.ts +2 -0
- package/dist/page.js +3 -0
- package/dist/paid-calls.d.ts +5 -1
- package/dist/paid-calls.js +1 -1
- package/dist/pause.d.ts +2 -0
- package/dist/place.d.ts +29 -5
- package/dist/place.js +51 -11
- package/dist/print.d.ts +7 -0
- package/dist/print.js +13 -0
- package/dist/propose.d.ts +2 -0
- package/dist/propose.js +38 -8
- package/dist/request-start.d.ts +12 -4
- package/dist/request-start.js +139 -15
- package/dist/run-box.d.ts +56 -4
- package/dist/run-box.js +183 -23
- package/dist/runnable.d.ts +13 -3
- package/dist/runnable.js +63 -6
- package/dist/runs.d.ts +266 -37
- package/dist/runs.js +884 -90
- package/dist/secrets.d.ts +27 -0
- package/dist/secrets.js +38 -2
- package/dist/server.d.ts +141 -36
- package/dist/server.js +562 -118
- package/dist/sign-ins.d.ts +99 -0
- package/dist/sign-ins.js +288 -0
- package/dist/skills.d.ts +16 -4
- package/dist/skills.js +35 -7
- package/dist/stats.d.ts +7 -2
- package/dist/stats.js +28 -7
- package/dist/tool-gate.d.ts +281 -0
- package/dist/tool-gate.js +585 -0
- package/dist/tool-keys.d.ts +48 -11
- package/dist/tool-keys.js +46 -8
- package/dist/tool-plane.d.ts +116 -27
- package/dist/tool-plane.js +232 -50
- package/dist/tools.d.ts +69 -14
- package/dist/tools.js +148 -26
- 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 +3 -2
- package/dist/turn-end.js +3 -2
- package/dist/usage-lines.d.ts +26 -0
- package/dist/usage-lines.js +28 -0
- package/dist/validate.d.ts +2 -0
- package/dist/validate.js +11 -2
- package/dist/web-fetch.js +3 -3
- package/dist/webhooks.d.ts +11 -4
- package/dist/webhooks.js +17 -1
- package/launcher/agentrun-serve +1 -1
- package/package.json +16 -14
- package/dist/console/assets/index-BN7oVcO4.js +0 -445
- package/dist/console/assets/index-By-jkqki.css +0 -1
|
@@ -0,0 +1,397 @@
|
|
|
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); under bash: ask, bash_output, bash_list and bash_signal run unasked
|
|
22
|
+
* (tool-gate.ts SHELL_WATCHERS), since an id reaches only this run's own processes (idOf, noSuch). */
|
|
23
|
+
export const SHELL_TOOLS = ["bash", ...BACKGROUND_TOOLS];
|
|
24
|
+
const MIB = BACKGROUND_LOG_BYTES / (1024 * 1024);
|
|
25
|
+
/** Each signal's number, for an exit code past 128. */
|
|
26
|
+
const SIGNAL_NAMES = { 1: "HUP", 2: "INT", 3: "QUIT", 6: "ABRT", 9: "KILL", 13: "PIPE", 14: "ALRM", 15: "TERM" };
|
|
27
|
+
/**
|
|
28
|
+
* The runner, started under its own session by a start: `$1` the log's directory, `$2` the box-only directory, `$3` the
|
|
29
|
+
* log's cap, `$4` work/, `$5` the command, `$6` 1 to run it on a terminal: `script -qfec`, which gives it a pty, copies
|
|
30
|
+
* what the fifo brings to the pty and what the pty shows to the log, and exits with the command's code. It holds the fifo's write end open (a `sleep`), runs the command under a
|
|
31
|
+
* session of its own (so a signal to the command's group never reaches the runner) with the fifo as stdin, and keeps
|
|
32
|
+
* the first `$3` bytes of its output, written to the log as they come (head, unbuffered by stdbuf where the box has it;
|
|
33
|
+
* else the last few KiB may wait in head's buffer until the process ends). Once the output's last writer is gone, it
|
|
34
|
+
* writes the exit code.
|
|
35
|
+
*/
|
|
36
|
+
const RUNNER = [
|
|
37
|
+
'L=$1; C=$2; cap=$3; echo $$ > "$C/runner"',
|
|
38
|
+
// A display copy in work/ (put): from inside the log's directory, entered with cd -P and checked to be
|
|
39
|
+
// work/background/<id> itself by its real path, written to a new file there (mktemp: an exclusive create, so never a
|
|
40
|
+
// planted link) and renamed over its name on that same filesystem, the name taken as a file even where a link to a
|
|
41
|
+
// directory stands there (mv -T; else that link is removed first), so a link planted at the name, or at the
|
|
42
|
+
// directory, is never followed. A check that fails skips the copy; the temporary file (hidden, a dot name) is removed
|
|
43
|
+
// on every path; no call reads a copy back.
|
|
44
|
+
`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; }`,
|
|
45
|
+
// The log is opened once, here, where start has just made it a regular file, then checked as opened: the file the
|
|
46
|
+
// open reached must be work/background/<id>/output.log itself (by its real path, so through no link) and a regular
|
|
47
|
+
// file, else nothing is kept. What later stands at its name is never written through.
|
|
48
|
+
'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',
|
|
49
|
+
'[ -n "$rw" ] && [ "$(readlink /proc/self/fd/4 2>/dev/null)" = "$rw/background/\${L##*/}/output.log" ] && [ -f /proc/self/fd/4 ] || exec 4>/dev/null',
|
|
50
|
+
// The first $cap bytes, written as they come: head holds its output in a buffer unless stdbuf unbuffers it.
|
|
51
|
+
'if stdbuf -o0 true 2>/dev/null; then keep() { stdbuf -o0 head -c "$cap" >&4; }; else keep() { head -c "$cap" >&4; }; fi',
|
|
52
|
+
'sleep 2147483647 > "$C/in" & h=$!; echo "$h" > "$C/hold"',
|
|
53
|
+
// The command's group goes in C, beside the fifo (pgid), the only copy any call trusts; one byte past the cap marks
|
|
54
|
+
// the log capped.
|
|
55
|
+
`{ setsid -w sh -c 'echo $$ > "$1/.pgid" && mv -f "$1/.pgid" "$1/pgid"; cd "$2" || exit 126; b=$(command -v bash 2>/dev/null) || b=; if [ "$4" = 1 ]; then SHELL=\${b:-/bin/sh}; AGENTRUN_BG_CMD=$3; AGENTRUN_BG_SID=$1/tsid; export SHELL AGENTRUN_BG_CMD AGENTRUN_BG_SID; exec script -qfec "echo \\$\\$ > \\"\\$AGENTRUN_BG_SID\\"; c=\\$AGENTRUN_BG_CMD; unset AGENTRUN_BG_CMD AGENTRUN_BG_SID; exec \\"\\$SHELL\\" -c \\"\\$c\\"" /dev/null; fi; [ -n "$b" ] && exec bash -c "$3"; exec sh -c "$3"' agentrun-background "$C" "$4" "$5" "$6" < "$C/in" 2>&1; echo $? > "$C/code"; } | { keep; [ -n "$(head -c 1 | od -An -c)" ] && { : > "$C/capped"; put capped ""; }; cat > /dev/null; }`,
|
|
56
|
+
// A child the command left running (a server started with &, its output sent elsewhere) keeps the process going: the
|
|
57
|
+
// group is waited for, and on a terminal the terminal's session (tsid, script's command's own pid), whose processes
|
|
58
|
+
// outlive script; so it stays running, signalled, counted and ended at the run's end until no live process of either
|
|
59
|
+
// is left.
|
|
60
|
+
`g=$(cat "$C/pgid" 2>/dev/null); live() { [ -n "$g" ] || return 1; s=$(cat "$C/tsid" 2>/dev/null); if [ -r /proc/self/stat ]; then cat /proc/[0-9]*/stat 2>/dev/null | awk -v g="$g" -v s="$s" '{ sub(/^[0-9]+ \\(.*\\) /, ""); if ($1 != "Z" && ($3 == g || (s != "" && $4 == s))) n++ } END { exit n > 0 ? 0 : 1 }'; else kill -0 "-$g" 2>/dev/null; fi; }; while live; do sleep 0.5; done`,
|
|
61
|
+
'kill "$h" 2>/dev/null; code=$(cat "$C/code" 2>/dev/null); [ -n "$code" ] || code=255',
|
|
62
|
+
'printf \'%s\\n\' "$code" > "$C/.exit" && mv -f "$C/.exit" "$C/exit"; put exit "$code"; rm -f "$C/in"',
|
|
63
|
+
].join("\n");
|
|
64
|
+
/**
|
|
65
|
+
* Every call's script: `$1` work/, `$2` the operation, the rest its arguments. Each answers on stdout in lines a parse
|
|
66
|
+
* below reads. A state is `running`, `exited <code>` or `lost`. What a call trusts (the group, the exit code, the start
|
|
67
|
+
* time, the command, the run's-end mark) is read from the box-only directory `c` alone, which the run's file tools
|
|
68
|
+
* cannot write; of work/background/<id>/ only output.log is read, and only as a regular file reached through no link.
|
|
69
|
+
*/
|
|
70
|
+
const SCRIPT = [
|
|
71
|
+
'w=$1; op=$2; shift 2; d=$w/background; c=${TMPDIR:-/tmp}/.agentrun-background; rw=$(cd "$w" 2>/dev/null && pwd -P)',
|
|
72
|
+
`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; }`,
|
|
73
|
+
'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; }',
|
|
74
|
+
// The ids this box started (c), and with them, for the list alone, those of work/ (a box before this one's).
|
|
75
|
+
'cids() { for p in "$c"/*; do i=${p##*/}; case $i in ""|*[!0-9]*) continue;; esac; [ -d "$p" ] && echo "$i"; done; }',
|
|
76
|
+
'ids() { { cids; [ -L "$d" ] || for p in "$d"/*; do i=${p##*/}; case $i in ""|*[!0-9]*) continue;; esac; echo "$i"; done; } | sort -un; }',
|
|
77
|
+
'running() { for i in $(cids); do [ -f "$c/$i/exit" ] && continue; [ "$(state "$i")" = running ] && echo "$i"; done; }',
|
|
78
|
+
// $1's log, opened first and then checked as opened (fd 3): the file the open reached is work/background/<id>/output.log
|
|
79
|
+
// itself, by its real path (so through no link), and a regular file. Every read after is of that open file
|
|
80
|
+
// (/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;
|
|
81
|
+
// 2: it is not to be read (a link, not a regular file, or a box with no /proc to check it by).
|
|
82
|
+
'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; }; }',
|
|
83
|
+
'size() { if openlog "$1"; then echo $(($(wc -c < /proc/self/fd/3))); exec 3<&-; else echo 0; fi; }',
|
|
84
|
+
// A display copy in work/ (the runner's put, by id): from inside work/background/<id>, entered with cd -P and checked
|
|
85
|
+
// by its real path, an exclusive new file there renamed over its name on the same filesystem; a failed check skips it.
|
|
86
|
+
`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; }`,
|
|
87
|
+
'known() { [ -d "$c/$1" ] || { [ ! -L "$d" ] && [ -d "$d/$1" ]; }; }',
|
|
88
|
+
// A tty process's command runs in the pty's own session (tsid: script's command, its leader), whose processes may
|
|
89
|
+
// outlive script: the groups of that session (sgs), and its terminal's foreground group (fgs, the tpgid its processes
|
|
90
|
+
// read): an interactive shell's running job is a group of its own, which Ctrl-C reaches and the shell's own does not.
|
|
91
|
+
`sgs() { cat /proc/[0-9]*/stat 2>/dev/null | awk -v s="$1" '{ sub(/^[0-9]+ \\(.*\\) /, ""); if ($1 != "Z" && $4 == s) print $3 }' | sort -u; }`,
|
|
92
|
+
`fgs() { cat /proc/[0-9]*/stat 2>/dev/null | awk -v s="$1" '{ sub(/^[0-9]+ \\(.*\\) /, ""); if ($1 != "Z" && $4 == s && $6 > 0) print $6 }' | sort -u; }`,
|
|
93
|
+
// Signal $2 to process $1's group (its box-only copy, never work/'s); on a tty process (its box-only mark), to its
|
|
94
|
+
// terminal's processes instead, as a terminal delivers it: INT to the foreground group alone (Ctrl-C), TERM and KILL to
|
|
95
|
+
// every group of the terminal's session (script would turn INT into TERM, and a script signalled itself exits 0):
|
|
96
|
+
// script exits with the code its command ended with, and what its command left on the terminal is reached after
|
|
97
|
+
// script is gone. Before script has its command, script itself. Each group is signalled once, and a send that finds
|
|
98
|
+
// its group already gone is no failure: only a missing group is.
|
|
99
|
+
'hit() { g=$(cat "$c/$1/pgid" 2>/dev/null); [ -n "$g" ] || return 1; t=; if [ -f "$c/$1/tty" ]; then s=$(cat "$c/$1/tsid" 2>/dev/null); if [ -n "$s" ]; then if [ "$2" = INT ]; then t=$(fgs "$s"); fi; [ -n "$t" ] || t=$(sgs "$s"); fi; fi; if [ -z "$t" ]; then kill -"$2" -"$g" 2>/dev/null; return 0; fi; for p in $t; do kill -"$2" -"$p" 2>/dev/null; done; return 0; }',
|
|
100
|
+
'case $op in',
|
|
101
|
+
'start)',
|
|
102
|
+
' if [ "$5" = 1 ] && ! command -v script >/dev/null 2>&1; then echo noscript; exit 0; fi',
|
|
103
|
+
' mkdir -p "$c" || exit 1; [ -L "$d" ] && { echo linkdir; exit 0; }; mkdir -p "$d" || exit 1',
|
|
104
|
+
' 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',
|
|
105
|
+
' trap \'rmdir "$c/.lock" 2>/dev/null\' EXIT',
|
|
106
|
+
' n=$(running | wc -l); if [ "$n" -ge "$2" ]; then echo "full $n"; exit 0; fi',
|
|
107
|
+
' i=1; while [ -e "$d/$i" ] || [ -L "$d/$i" ] || [ -e "$c/$i" ]; do i=$((i+1)); done',
|
|
108
|
+
' mkdir "$d/$i" && mkdir "$c/$i" || exit 1',
|
|
109
|
+
' printf \'%s\' "$1" > "$c/$i/command"; date -u +%Y-%m-%dT%H:%M:%SZ > "$c/$i/started"; : > "$d/$i/output.log"',
|
|
110
|
+
' put "$i" command "$1"; put "$i" started "$(cat "$c/$i/started")" n',
|
|
111
|
+
' mkfifo "$c/$i/in" || exit 1; if [ "$5" = 1 ]; then : > "$c/$i/tty"; put "$i" tty ""; fi',
|
|
112
|
+
' setsid -f nohup sh -c "$4" agentrun-background "$d/$i" "$c/$i" "$3" "$w" "$1" "$5" </dev/null >/dev/null 2>"$c/$i/err" || exit 1',
|
|
113
|
+
' k=0; while [ ! -s "$c/$i/pgid" ] && [ ! -f "$c/$i/exit" ] && [ $k -lt 200 ]; do sleep 0.05; k=$((k+1)); done',
|
|
114
|
+
' [ -s "$c/$i/pgid" ] || [ -f "$c/$i/exit" ] || { cat "$c/$i/err" >&2; echo "process $i did not start" >&2; exit 1; }',
|
|
115
|
+
' put "$i" pid "$(cat "$c/$i/pgid" 2>/dev/null)" n; echo "started $i $(cat "$c/$i/pgid" 2>/dev/null)";;',
|
|
116
|
+
'output)',
|
|
117
|
+
' known "$1" || { echo none; exit 0; }',
|
|
118
|
+
' st=$(state "$1"); echo "state $st"',
|
|
119
|
+
' openlog "$1"; r=$?; [ $r = 2 ] && { echo notlog; exit 0; }; n=0; [ $r = 0 ] && n=$(($(wc -c < /proc/self/fd/3))); echo "size $n"',
|
|
120
|
+
' [ -f "$c/$1/capped" ] && echo capped; [ -f "$c/$1/ended" ] && echo ended; echo --',
|
|
121
|
+
' m=$((n - $2)); [ $m -gt "$3" ] && m=$3',
|
|
122
|
+
' if [ $m -gt 0 ] && [ $r = 0 ]; then tail -c +$(($2 + 1)) /proc/self/fd/3 | head -c $m | base64; fi;;',
|
|
123
|
+
'input)',
|
|
124
|
+
' known "$1" || { echo none; exit 0; }',
|
|
125
|
+
' st=$(state "$1"); [ "$st" = running ] || { echo "state $st"; exit 0; }',
|
|
126
|
+
' [ -f "$c/$1/closed" ] && { echo closed; exit 0; }',
|
|
127
|
+
' if [ -n "$2" ]; then exec 3<>"$c/$1/in" || exit 1; printf \'%s\' "$2" >&3 || exit 1; exec 3>&-; fi',
|
|
128
|
+
' if [ "$3" = 1 ]; then : > "$c/$1/closed"; kill "$(cat "$c/$1/hold" 2>/dev/null)" 2>/dev/null; fi',
|
|
129
|
+
' echo sent;;',
|
|
130
|
+
'signal)',
|
|
131
|
+
' known "$1" || { echo none; exit 0; }',
|
|
132
|
+
' st=$(state "$1"); [ "$st" = running ] || { echo "was $st"; exit 0; }',
|
|
133
|
+
' hit "$1" "$2" || { echo "was $st"; exit 0; }',
|
|
134
|
+
' k=0; while [ ! -f "$c/$1/exit" ] && [ $k -lt 40 ]; do sleep 0.05; k=$((k+1)); done',
|
|
135
|
+
' echo "state $(state "$1")";;',
|
|
136
|
+
'list)',
|
|
137
|
+
// Every running one, then the newest $1 others, chosen before any of their details is read: the list costs the same
|
|
138
|
+
// however many ended before.
|
|
139
|
+
' 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',
|
|
140
|
+
' echo "total $t"',
|
|
141
|
+
` for i in $picked; do printf '%s\\t%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)" "$([ -f "$c/$i/tty" ] && echo tty)"; head -c 200 "$c/$i/command" 2>/dev/null | base64 | tr -d '\\n'; echo; done;;`,
|
|
142
|
+
'end)',
|
|
143
|
+
' n=0; for i in $(running); do : > "$c/$i/ended"; put "$i" ended ""; hit "$i" TERM; n=$((n+1)); done',
|
|
144
|
+
' k=0; while [ $k -lt 60 ] && [ -n "$(running)" ]; do sleep 0.05; k=$((k+1)); done',
|
|
145
|
+
' for i in $(running); do hit "$i" KILL; done',
|
|
146
|
+
' k=0; while [ $k -lt 40 ] && [ -n "$(running)" ]; do sleep 0.05; k=$((k+1)); done',
|
|
147
|
+
' for i in $(running); do r=$(cat "$c/$i/runner" 2>/dev/null); [ -n "$r" ] && kill -KILL -"$r" 2>/dev/null; done',
|
|
148
|
+
' echo "ended $n";;',
|
|
149
|
+
'esac',
|
|
150
|
+
].join("\n");
|
|
151
|
+
/** One operation in the box, on the run's environment: its stdout. A call the box cannot run, or that fails, throws. */
|
|
152
|
+
async function inBox(given, op, args, context, timeout = 30) {
|
|
153
|
+
if (!given)
|
|
154
|
+
throw new Error("this call has no box to run in");
|
|
155
|
+
const env = given;
|
|
156
|
+
let out = "";
|
|
157
|
+
let said = "";
|
|
158
|
+
const work = typeof env.cwd === "string" && env.cwd ? env.cwd : BOX_WORK;
|
|
159
|
+
const ran = await env.exec(["sh", "-c", SCRIPT, "agentrun-background", work, op, ...args], {
|
|
160
|
+
timeout,
|
|
161
|
+
onOutput: (text, _context, info) => {
|
|
162
|
+
if (info.stream === "stdout")
|
|
163
|
+
out += text;
|
|
164
|
+
else if (said.length < 2_000)
|
|
165
|
+
said += text;
|
|
166
|
+
},
|
|
167
|
+
}, context);
|
|
168
|
+
if (!ran.ok)
|
|
169
|
+
throw new Error(`the run's box did not answer: ${ran.error.message}`);
|
|
170
|
+
if (ran.value.exitCode !== 0)
|
|
171
|
+
throw new Error(`the run's box answered with exit code ${ran.value.exitCode}${said.trim() ? `: ${said.trim().slice(0, 500)}` : ""}`);
|
|
172
|
+
return out;
|
|
173
|
+
}
|
|
174
|
+
/** A process's id as a call gives it: digits only, so no call names a path. */
|
|
175
|
+
function idOf(value) {
|
|
176
|
+
const id = typeof value === "number" && Number.isSafeInteger(value) ? String(value) : typeof value === "string" ? value.trim() : "";
|
|
177
|
+
if (!/^[1-9][0-9]{0,8}$/.test(id))
|
|
178
|
+
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)`);
|
|
179
|
+
return id;
|
|
180
|
+
}
|
|
181
|
+
/** A state as the script says it. */
|
|
182
|
+
function stateOf(said) {
|
|
183
|
+
if (said === "running")
|
|
184
|
+
return { state: "running" };
|
|
185
|
+
const exited = /^exited (\d+)$/.exec(said);
|
|
186
|
+
if (!exited)
|
|
187
|
+
return { state: "lost" };
|
|
188
|
+
const code = Number(exited[1]);
|
|
189
|
+
const signal = code > 128 ? SIGNAL_NAMES[code - 128] : undefined;
|
|
190
|
+
return { state: "exited", exit_code: code, ...(signal ? { signal } : {}) };
|
|
191
|
+
}
|
|
192
|
+
/** A state in words: `running`, `exited with code 0`, `ended by signal TERM (exit code 143)`, or lost. */
|
|
193
|
+
function stateWords(state, ended = false) {
|
|
194
|
+
const atEnd = ended ? ", at the run's end" : "";
|
|
195
|
+
if (state.state === "running")
|
|
196
|
+
return "is running";
|
|
197
|
+
if (state.state === "lost")
|
|
198
|
+
return "is gone: its box was replaced before it ended, so its exit code is not known";
|
|
199
|
+
return state.signal ? `ended by signal ${state.signal} (exit code ${state.exit_code})${atEnd}` : `exited with code ${state.exit_code}${atEnd}`;
|
|
200
|
+
}
|
|
201
|
+
const noSuch = (id) => new Error(`there is no background process ${id} in this run: bash_list shows them`);
|
|
202
|
+
/** The end of `bytes` that ends inside a UTF-8 character, left for the next page: how many bytes to keep (none, when the
|
|
203
|
+
* page holds only part of one character). */
|
|
204
|
+
function wholeChars(bytes) {
|
|
205
|
+
for (let back = 1; back <= Math.min(3, bytes.length); back++) {
|
|
206
|
+
const byte = bytes[bytes.length - back];
|
|
207
|
+
if ((byte & 0xc0) === 0x80)
|
|
208
|
+
continue;
|
|
209
|
+
const length = byte >= 0xf0 ? 4 : byte >= 0xe0 ? 3 : byte >= 0xc0 ? 2 : 1;
|
|
210
|
+
return length > back ? bytes.length - back : bytes.length;
|
|
211
|
+
}
|
|
212
|
+
return bytes.length;
|
|
213
|
+
}
|
|
214
|
+
const decode = (base64) => new Uint8Array(Buffer.from(base64.replace(/\s+/g, ""), "base64"));
|
|
215
|
+
const intArg = (value, name, min, max, fallback) => {
|
|
216
|
+
if (value === undefined || value === null)
|
|
217
|
+
return fallback;
|
|
218
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max)
|
|
219
|
+
throw new Error(`${name} is a whole number from ${min.toLocaleString("en-US")} to ${max.toLocaleString("en-US")}`);
|
|
220
|
+
return value;
|
|
221
|
+
};
|
|
222
|
+
const ID_SCHEMA = { type: "string", pattern: "^[1-9][0-9]*$", description: "The process's id, as bash_background answered it (\"1\")." };
|
|
223
|
+
const schema = (properties, required) => ({ type: "object", additionalProperties: false, properties, required });
|
|
224
|
+
const bashBackground = defineTool({
|
|
225
|
+
name: "bash_background",
|
|
226
|
+
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; tty: true gives it a terminal instead. At most ${BACKGROUND_MAX} run at once in a run's box. Read its output with bash_output, list them with bash_list.`,
|
|
227
|
+
parameters: schema({
|
|
228
|
+
command: { type: "string", minLength: 1, description: "The command, as you would give bash." },
|
|
229
|
+
tty: { type: "boolean", description: "Run it on a terminal (a pty, through script in the box), for a program that needs one: a prompt, a REPL, a progress display. Its log then holds what the terminal shows (your input echoed, lines ending in \\r\\n); bash_input types into the terminal, and bash_signal INT is Ctrl-C to its foreground job." },
|
|
230
|
+
}, ["command"]),
|
|
231
|
+
execute: async (args, api, context) => {
|
|
232
|
+
const command = String(args.command ?? "");
|
|
233
|
+
const tty = args.tty === true;
|
|
234
|
+
if (!command.trim())
|
|
235
|
+
throw new Error("command is the shell command to start");
|
|
236
|
+
const said = (await inBox(api.env, "start", [command, String(BACKGROUND_MAX), String(BACKGROUND_LOG_BYTES), RUNNER, tty ? "1" : "0"], context)).trim();
|
|
237
|
+
if (said === "noscript")
|
|
238
|
+
throw new Error("this box has no `script` program (util-linux), so tty: true cannot run here: start the command without tty");
|
|
239
|
+
if (said === "linkdir")
|
|
240
|
+
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");
|
|
241
|
+
const full = /^full (\d+)/.exec(said);
|
|
242
|
+
if (full)
|
|
243
|
+
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.`);
|
|
244
|
+
const started = /^started (\d+) ?(\d*)/.exec(said);
|
|
245
|
+
if (!started)
|
|
246
|
+
throw new Error(`the run's box did not start the process: ${said.slice(0, 300) || "it said nothing"}`);
|
|
247
|
+
const [, id, group] = started;
|
|
248
|
+
const log = `${BACKGROUND_DIR}/${id}/output.log`;
|
|
249
|
+
return forModel(`Started background process ${id}${group ? ` (process group ${group})` : ""}${tty ? " on a terminal" : ""}. 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) } : {}), ...(tty ? { tty } : {}) } });
|
|
250
|
+
},
|
|
251
|
+
});
|
|
252
|
+
const bashOutput = defineTool({
|
|
253
|
+
name: "bash_output",
|
|
254
|
+
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.`,
|
|
255
|
+
parameters: schema({
|
|
256
|
+
id: ID_SCHEMA,
|
|
257
|
+
offset: { type: "integer", minimum: 0, description: "The byte to read from; 0, the start, when absent." },
|
|
258
|
+
max_bytes: { type: "integer", minimum: 1, maximum: BACKGROUND_PAGE_BYTES, description: `The most bytes to read; ${BACKGROUND_PAGE_BYTES.toLocaleString("en-US")} when absent.` },
|
|
259
|
+
}, ["id"]),
|
|
260
|
+
replay: "safe",
|
|
261
|
+
execute: async (args, api, context) => {
|
|
262
|
+
const given = args;
|
|
263
|
+
const id = idOf(given.id);
|
|
264
|
+
const offset = intArg(given.offset, "offset", 0, BACKGROUND_LOG_BYTES, 0);
|
|
265
|
+
const max = intArg(given.max_bytes, "max_bytes", 1, BACKGROUND_PAGE_BYTES, BACKGROUND_PAGE_BYTES);
|
|
266
|
+
const said = await inBox(api.env, "output", [id, String(offset), String(max)], context);
|
|
267
|
+
if (said.trim() === "none")
|
|
268
|
+
throw noSuch(id);
|
|
269
|
+
if (said.split("\n").includes("notlog"))
|
|
270
|
+
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)`);
|
|
271
|
+
const at = said.indexOf("\n--\n");
|
|
272
|
+
const head = (at < 0 ? said : said.slice(0, at)).split("\n");
|
|
273
|
+
const fact = (key) => head.find((line) => line === key || line.startsWith(`${key} `))?.slice(key.length + 1);
|
|
274
|
+
const state = stateOf(fact("state") ?? "");
|
|
275
|
+
const size = Number(fact("size") ?? 0);
|
|
276
|
+
const capped = head.includes("capped");
|
|
277
|
+
const ended = head.includes("ended");
|
|
278
|
+
const read = at < 0 ? new Uint8Array() : decode(said.slice(at + 4));
|
|
279
|
+
// A character the page would split is left for the next one, unless the process has ended and nothing follows.
|
|
280
|
+
const keep = state.state === "running" || offset + read.length < size ? wholeChars(read) : read.length;
|
|
281
|
+
// A page too small for the one character it starts with reads nothing, and says what to ask instead.
|
|
282
|
+
if (keep === 0 && read.length > 0)
|
|
283
|
+
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`);
|
|
284
|
+
const bytes = read.subarray(0, keep);
|
|
285
|
+
const next = offset + bytes.length;
|
|
286
|
+
const more = next < size;
|
|
287
|
+
const where = offset >= size && bytes.length === 0
|
|
288
|
+
? `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" : ""}.`
|
|
289
|
+
: `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"}.`;
|
|
290
|
+
const cap = capped ? ` Its log reached the ${MIB} MiB cap, so later output was dropped.` : "";
|
|
291
|
+
const text = new TextDecoder().decode(bytes);
|
|
292
|
+
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 } : {}) } });
|
|
293
|
+
},
|
|
294
|
+
});
|
|
295
|
+
const bashInput = defineTool({
|
|
296
|
+
name: "bash_input",
|
|
297
|
+
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.`,
|
|
298
|
+
parameters: schema({
|
|
299
|
+
id: ID_SCHEMA,
|
|
300
|
+
text: { type: "string", description: "The bytes to write, as UTF-8; empty with close: true closes stdin alone." },
|
|
301
|
+
close: { type: "boolean", description: "Close the process's stdin after the text." },
|
|
302
|
+
}, ["id", "text"]),
|
|
303
|
+
execute: async (args, api, context) => {
|
|
304
|
+
const given = args;
|
|
305
|
+
const id = idOf(given.id);
|
|
306
|
+
const text = typeof given.text === "string" ? given.text : "";
|
|
307
|
+
if (Buffer.byteLength(text) > BACKGROUND_INPUT_BYTES)
|
|
308
|
+
throw new Error(`text is at most ${BACKGROUND_INPUT_BYTES / 1024} KiB a call; send it in parts`);
|
|
309
|
+
if (text.includes("\0"))
|
|
310
|
+
throw new Error("text holds a NUL byte, which no shell argument carries");
|
|
311
|
+
const close = given.close === true;
|
|
312
|
+
if (!text && !close)
|
|
313
|
+
throw new Error("text is what to write: give some, or close: true to close stdin");
|
|
314
|
+
const said = (await inBox(api.env, "input", [id, text, close ? "1" : "0"], context, 15).catch((error) => {
|
|
315
|
+
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)`);
|
|
316
|
+
})).trim();
|
|
317
|
+
if (said === "none")
|
|
318
|
+
throw noSuch(id);
|
|
319
|
+
if (said === "closed")
|
|
320
|
+
throw new Error(`background process ${id}'s stdin is closed: an earlier bash_input closed it`);
|
|
321
|
+
if (said.startsWith("state "))
|
|
322
|
+
throw new Error(`background process ${id} ${stateWords(stateOf(said.slice(6)))}, so it takes no input`);
|
|
323
|
+
const bytes = Buffer.byteLength(text);
|
|
324
|
+
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 } : {}) } });
|
|
325
|
+
},
|
|
326
|
+
});
|
|
327
|
+
const bashSignal = defineTool({
|
|
328
|
+
name: "bash_signal",
|
|
329
|
+
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.",
|
|
330
|
+
parameters: schema({ id: ID_SCHEMA, signal: { type: "string", enum: [...BACKGROUND_SIGNALS], description: "TERM, INT or KILL." } }, ["id", "signal"]),
|
|
331
|
+
execute: async (args, api, context) => {
|
|
332
|
+
const given = args;
|
|
333
|
+
const id = idOf(given.id);
|
|
334
|
+
const signal = typeof given.signal === "string" ? given.signal.trim().toUpperCase().replace(/^SIG/, "") : "";
|
|
335
|
+
if (!BACKGROUND_SIGNALS.includes(signal))
|
|
336
|
+
throw new Error(`signal is one of ${BACKGROUND_SIGNALS.join(", ")}`);
|
|
337
|
+
const said = (await inBox(api.env, "signal", [id, signal], context, 15)).trim();
|
|
338
|
+
if (said === "none")
|
|
339
|
+
throw noSuch(id);
|
|
340
|
+
if (said.startsWith("was "))
|
|
341
|
+
throw new Error(`background process ${id} ${stateWords(stateOf(said.slice(4)))}, so no signal was sent`);
|
|
342
|
+
const state = stateOf(said.replace(/^state /, ""));
|
|
343
|
+
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 } });
|
|
344
|
+
},
|
|
345
|
+
});
|
|
346
|
+
const bashList = defineTool({
|
|
347
|
+
name: "bash_list",
|
|
348
|
+
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).`,
|
|
349
|
+
parameters: schema({}, []),
|
|
350
|
+
replay: "safe",
|
|
351
|
+
execute: async (_args, api, context) => {
|
|
352
|
+
const said = await inBox(api.env, "list", [String(BACKGROUND_LIST_MAX)], context);
|
|
353
|
+
const [first = "", ...rows] = said.split("\n");
|
|
354
|
+
const total = Number(/^total (\d+)$/.exec(first)?.[1] ?? 0);
|
|
355
|
+
const all = rows.filter(Boolean).map((line) => {
|
|
356
|
+
const [id = "", state = "", size = "0", started = "", ended = "", tty = "", command = ""] = line.split("\t");
|
|
357
|
+
return { id, ...stateOf(state), size: Number(size) || 0, ...(started ? { started } : {}), ...(ended ? { ended_at_run_end: true } : {}), ...(tty ? { tty: true } : {}), command: new TextDecoder().decode(decode(command)) };
|
|
358
|
+
}).sort((a, b) => Number(b.id) - Number(a.id));
|
|
359
|
+
const shown = [...all.filter((p) => p.state === "running"), ...all.filter((p) => p.state !== "running")].slice(0, BACKGROUND_LIST_MAX);
|
|
360
|
+
if (!shown.length)
|
|
361
|
+
return forModel("No background processes in this run's box: bash_background starts one.", { details: { processes: [] } });
|
|
362
|
+
const running = all.filter((p) => p.state === "running").length;
|
|
363
|
+
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))}${p.tty ? " (tty)" : ""}`);
|
|
364
|
+
const left = total - shown.length;
|
|
365
|
+
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 } });
|
|
366
|
+
},
|
|
367
|
+
});
|
|
368
|
+
/** The background tools, each run on the environment its call gives (the box's, coding-tools.ts). */
|
|
369
|
+
export const backgroundTools = () => [bashBackground, bashOutput, bashInput, bashSignal, bashList];
|
|
370
|
+
/** The run's end: every background process still running in run `runId`'s box (found by `label`) is sent TERM, then
|
|
371
|
+
* 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
|
|
372
|
+
* the box is pulled and destroyed. How many it ended; a run with no box ends none. */
|
|
373
|
+
export async function endBackground(boxes, label, context) {
|
|
374
|
+
const { finish } = await import("@parcha/pi-transport");
|
|
375
|
+
const listed = await boxes.list(label, context);
|
|
376
|
+
if (!listed.ok)
|
|
377
|
+
throw listed.error;
|
|
378
|
+
let ended = 0;
|
|
379
|
+
for (const ref of listed.value) {
|
|
380
|
+
const attached = await boxes.attach(ref.id, context);
|
|
381
|
+
if (!attached.ok)
|
|
382
|
+
throw attached.error;
|
|
383
|
+
if (!attached.value)
|
|
384
|
+
continue;
|
|
385
|
+
const started = await attached.value.exec(["sh", "-c", SCRIPT, "agentrun-background", BOX_WORK, "end"], { timeoutMs: 20_000 }, context);
|
|
386
|
+
if (!started.ok)
|
|
387
|
+
throw started.error;
|
|
388
|
+
const done = await finish(started.value);
|
|
389
|
+
if (!done.ok)
|
|
390
|
+
throw done.error;
|
|
391
|
+
const said = new TextDecoder().decode(done.value.stdout).trim();
|
|
392
|
+
if (done.value.exitCode !== 0)
|
|
393
|
+
throw new Error(`ending the box's background processes failed (exit code ${done.value.exitCode}): ${done.value.stderr.trim().slice(0, 300)}`);
|
|
394
|
+
ended += Number(/^ended (\d+)/.exec(said)?.[1] ?? 0);
|
|
395
|
+
}
|
|
396
|
+
return ended;
|
|
397
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { type BoxEgress } from "./box-egress.js";
|
|
2
|
+
/** What `docker info` is asked on a Mac: the daemon's OS type, its kernel, the name it gives its OS, and its host name. */
|
|
3
|
+
export declare const VM_INFO_FORMAT = "{{.OSType}}|{{.KernelVersion}}|{{.OperatingSystem}}|{{.Name}}";
|
|
4
|
+
/** The VM runtimes a box's network goes on for, on a Mac. */
|
|
5
|
+
export declare const VM_RUNTIMES: readonly ["Docker Desktop", "OrbStack", "colima"];
|
|
6
|
+
export type VmRuntime = (typeof VM_RUNTIMES)[number];
|
|
7
|
+
/** Where this Docker runs, by `docker info`'s answer to VM_INFO_FORMAT (`answer`), on a server with `platform` and
|
|
8
|
+
* `kernel` (os.release()): a VM runtime this server knows, or why not. Pure. A runtime counts only when docker info
|
|
9
|
+
* names it (OperatingSystem `Docker Desktop` or `OrbStack`, or a colima host Name) AND its kernel is not this
|
|
10
|
+
* machine's: a VM in between. Anything else is a reason, never a guess. */
|
|
11
|
+
export declare function vmDockerOf(answer: string, here: {
|
|
12
|
+
platform: string;
|
|
13
|
+
kernel: string;
|
|
14
|
+
}): {
|
|
15
|
+
runtime: VmRuntime;
|
|
16
|
+
} | {
|
|
17
|
+
reason: string;
|
|
18
|
+
};
|
|
19
|
+
/** `docker`, with `args`, in the server's environment through the cut a run's takes, nothing on its stdin, within
|
|
20
|
+
* `timeoutMs`: its exit code (or `timeout`, or the spawn's error code) and its output. */
|
|
21
|
+
export type DockerCall = (args: readonly string[], timeoutMs: number, signal?: AbortSignal) => Promise<{
|
|
22
|
+
code: number | string;
|
|
23
|
+
stdout: string;
|
|
24
|
+
stderr: string;
|
|
25
|
+
}>;
|
|
26
|
+
export declare const dockerCall: (env: NodeJS.ProcessEnv) => DockerCall;
|
|
27
|
+
/** Where this Mac's Docker runs (vmDockerOf), asked of `docker info` within its bound; a daemon the docker CLI does not
|
|
28
|
+
* reach by a local unix socket (DOCKER_HOST, or a context, elsewhere) is not this Mac's VM, and gets no network. */
|
|
29
|
+
export declare function vmDocker(env: NodeJS.ProcessEnv, options?: {
|
|
30
|
+
platform?: string;
|
|
31
|
+
kernel?: string;
|
|
32
|
+
timeoutMs?: number;
|
|
33
|
+
docker?: DockerCall;
|
|
34
|
+
}): Promise<{
|
|
35
|
+
runtime: VmRuntime;
|
|
36
|
+
} | {
|
|
37
|
+
reason: string;
|
|
38
|
+
}>;
|
|
39
|
+
/** The proxy container's image: `node:22-bookworm-slim` (the kernel needs Node 22.19 or later), pinned to the multi-arch
|
|
40
|
+
* index digest Docker Hub served for that tag on 2026-11-05 (Node 22.23.4), as BOX_BASE is pinned (box-image.ts), so every Mac runs the
|
|
41
|
+
* same Node. To move it, read the tag's index digest again the way BOX_BASE says, and put it here. */
|
|
42
|
+
export declare const EGRESS_IMAGE = "node:22-bookworm-slim@sha256:4b150b48b4116e2a22f2c39cc27025fbf4f153e2078fd3b14d159fdb5c7279da";
|
|
43
|
+
/** The label the proxy container and its volume carry: the server's key (egressKeyOf). */
|
|
44
|
+
export declare const EGRESS_LABEL = "agentrun.egress";
|
|
45
|
+
/** Where the volume is in the proxy container, and its code. */
|
|
46
|
+
export declare const EGRESS_VOLUME_MOUNT = "/egress";
|
|
47
|
+
export declare const EGRESS_CODE_MOUNT = "/code";
|
|
48
|
+
/** What the entry logs once its socket listens. */
|
|
49
|
+
export declare const EGRESS_READY = "egress ready";
|
|
50
|
+
/** How long the start waits for EGRESS_READY once the container runs. */
|
|
51
|
+
export declare const EGRESS_READY_MS = 10000;
|
|
52
|
+
/** How often the server looks for its proxy container, to start it again when it is gone. */
|
|
53
|
+
export declare const EGRESS_WATCH_MS = 5000;
|
|
54
|
+
/** How long the start's pull of EGRESS_IMAGE may take. */
|
|
55
|
+
export declare const EGRESS_PULL_MS: number;
|
|
56
|
+
/** Connections open at once through the server's one proxy, every run's together. */
|
|
57
|
+
export declare const VM_MAX_TUNNELS = 256;
|
|
58
|
+
/** This server's key: its data root's hash, so two servers on one daemon get two proxies and two volumes. */
|
|
59
|
+
export declare const egressKeyOf: (data: string) => string;
|
|
60
|
+
/** The proxy container's name, and its volume's, for a key. */
|
|
61
|
+
export declare const egressNameOf: (key: string) => string;
|
|
62
|
+
/** The entry the proxy container runs (`node /code/main.js <socket>`): it refuses to start with no list, for a proxy with
|
|
63
|
+
* none would reach every public host, and logs EGRESS_READY once its socket listens. Its decisions go to its log. */
|
|
64
|
+
export declare const MAIN: string;
|
|
65
|
+
/** The kernel's two proxy files, as built: they import only `node:` modules and each other. */
|
|
66
|
+
export declare const PROXY_FILES: readonly ["egress-proxy.js", "egress-table.js"];
|
|
67
|
+
/** The code the proxy container binds read-only: PROXY_FILES from the kernel this server runs, and MAIN, written into
|
|
68
|
+
* `<data>/egress/<12 hex of their hash>/` once (a directory per version, so a running container's code never changes
|
|
69
|
+
* under it). Its path, real (Docker binds it by that). */
|
|
70
|
+
export declare function egressCode(data: string): Promise<string>;
|
|
71
|
+
/** `docker volume create` of the server's volume: tmpfs, so no stale socket outlives the VM, and owned by the server's
|
|
72
|
+
* uid:gid with mode 0700, as the proxy's socket (0600) and the box (both run as that uid) need. */
|
|
73
|
+
export declare const egressVolumeArgs: (key: string, uid: number, gid: number) => string[];
|
|
74
|
+
/** `docker run` of the proxy container. Docker's default network, the only container with one; no published port, no
|
|
75
|
+
* Docker socket, no variable but the list; a read-only root, no capability, no privilege to gain, the server's uid:gid;
|
|
76
|
+
* bounded memory, processes and log. Pinned by a golden test. */
|
|
77
|
+
export declare const egressRunArgs: (options: {
|
|
78
|
+
key: string;
|
|
79
|
+
uid: number;
|
|
80
|
+
gid: number;
|
|
81
|
+
code: string;
|
|
82
|
+
allow: readonly string[];
|
|
83
|
+
}) => string[];
|
|
84
|
+
/** The proxy container's state: `ready` once it listens; `preparing` while it is pulled, started or started again;
|
|
85
|
+
* `unavailable` when it could not start, with why. */
|
|
86
|
+
export type EgressState = {
|
|
87
|
+
state: "ready";
|
|
88
|
+
} | {
|
|
89
|
+
state: "preparing" | "unavailable";
|
|
90
|
+
reason: string;
|
|
91
|
+
};
|
|
92
|
+
/** `volume`: the volume a run's box mounts, once it is made; absent when it could not be. */
|
|
93
|
+
export type EgressContainer = {
|
|
94
|
+
readonly volume?: string;
|
|
95
|
+
state(): EgressState;
|
|
96
|
+
close(): Promise<void>;
|
|
97
|
+
};
|
|
98
|
+
/**
|
|
99
|
+
* The server's proxy container (see the head of this file): made ready now when Docker has its image (within
|
|
100
|
+
* EGRESS_READY_MS), else pulled and started in the background; then watched every `watchMs`, and started again when it
|
|
101
|
+
* is gone or stopped. `onChange` is told each new state. `close` stops the watch and removes the container; its volume
|
|
102
|
+
* stays, for boxes still mounting it and the next start.
|
|
103
|
+
*/
|
|
104
|
+
export declare function startEgressContainer(options: {
|
|
105
|
+
env: NodeJS.ProcessEnv;
|
|
106
|
+
data: string;
|
|
107
|
+
allow: readonly string[];
|
|
108
|
+
uid: number;
|
|
109
|
+
gid: number;
|
|
110
|
+
onChange?: (state: EgressState) => void;
|
|
111
|
+
docker?: DockerCall;
|
|
112
|
+
watchMs?: number;
|
|
113
|
+
readyMs?: number;
|
|
114
|
+
pullMs?: number;
|
|
115
|
+
}): Promise<EgressContainer>;
|
|
116
|
+
/** What the server hands a run's process on a Mac with the proxy container: its volume's name, which the run's Docker
|
|
117
|
+
* boxes mount read-only at EGRESS_MOUNT. Unset on Linux, where the run's process starts its own proxy (box-egress.ts). */
|
|
118
|
+
export declare const RUN_BOX_VOLUME_ENV = "AGENTRUN_RUN_BOX_VOLUME";
|
|
119
|
+
/** The run's process's reading of RUN_BOX_VOLUME_ENV: the volume, or undefined when it is unset or not a name this
|
|
120
|
+
* server makes. */
|
|
121
|
+
export declare function runBoxVolumeOf(env: NodeJS.ProcessEnv): string | undefined;
|
|
122
|
+
/** A run's box's egress on a Mac: the server's proxy container, its socket in the volume the Docker provider mounts on
|
|
123
|
+
* every box (run-box.ts), so nothing for the run's process to start or bind. The volume outlives each proxy, so a box
|
|
124
|
+
* made before one started again reaches the new one. */
|
|
125
|
+
export declare const vmEgress: BoxEgress;
|