@parcha/agentrun-serve 0.0.0-bootstrap.0 → 0.1.0-beta.29
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 +560 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +1724 -0
- package/dist/adapters.d.ts +205 -0
- package/dist/adapters.js +459 -0
- package/dist/agents.d.ts +124 -0
- package/dist/agents.js +302 -0
- package/dist/app.d.ts +7 -0
- package/dist/app.js +324 -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-image.d.ts +98 -0
- package/dist/box-image.js +283 -0
- package/dist/box-relay.d.ts +42 -0
- package/dist/box-relay.js +222 -0
- package/dist/boxes.d.ts +54 -0
- package/dist/boxes.js +182 -0
- package/dist/cap.d.ts +224 -0
- package/dist/cap.js +721 -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 +31 -0
- package/dist/coding-tools.js +81 -0
- package/dist/console/THIRD-PARTY-NOTICES.txt +1141 -0
- package/dist/console/assets/index-BN7oVcO4.js +445 -0
- package/dist/console/assets/index-By-jkqki.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/daytona-api.d.ts +21 -0
- package/dist/daytona-api.js +101 -0
- package/dist/decision-rows.d.ts +11 -0
- package/dist/decision-rows.js +116 -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 +72 -0
- package/dist/errors.js +66 -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 +60 -0
- package/dist/files.js +153 -0
- package/dist/grade.d.ts +96 -0
- package/dist/grade.js +348 -0
- package/dist/graph-view.d.ts +100 -0
- package/dist/graph-view.js +212 -0
- package/dist/harness-app.d.ts +38 -0
- package/dist/harness-app.js +626 -0
- package/dist/harness.d.ts +53 -0
- package/dist/harness.js +74 -0
- package/dist/home-path.d.ts +27 -0
- package/dist/home-path.js +78 -0
- package/dist/host-tools.d.ts +20 -0
- package/dist/host-tools.js +140 -0
- package/dist/host.d.ts +39 -0
- package/dist/host.js +81 -0
- package/dist/hosted-search.d.ts +27 -0
- package/dist/hosted-search.js +129 -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 +1221 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +6 -0
- package/dist/key-check.d.ts +36 -0
- package/dist/key-check.js +108 -0
- package/dist/key-refusal.d.ts +51 -0
- package/dist/key-refusal.js +187 -0
- package/dist/learn/check.d.ts +99 -0
- package/dist/learn/check.js +259 -0
- package/dist/learn/grade.d.ts +79 -0
- package/dist/learn/grade.js +433 -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 +146 -0
- package/dist/learn/reflect.d.ts +49 -0
- package/dist/learn/reflect.js +167 -0
- package/dist/learn/secrets.d.ts +18 -0
- package/dist/learn/secrets.js +111 -0
- package/dist/learn/skills.d.ts +84 -0
- package/dist/learn/skills.js +198 -0
- package/dist/learning-routes.d.ts +196 -0
- package/dist/learning-routes.js +609 -0
- package/dist/learning-run.d.ts +304 -0
- package/dist/learning-run.js +797 -0
- package/dist/learning-words.d.ts +73 -0
- package/dist/learning-words.js +171 -0
- package/dist/learning.d.ts +377 -0
- package/dist/learning.js +801 -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 +115 -0
- package/dist/mcp-servers.js +445 -0
- package/dist/mcp.d.ts +51 -0
- package/dist/mcp.js +392 -0
- package/dist/model.d.ts +184 -0
- package/dist/model.js +484 -0
- package/dist/monid.d.ts +74 -0
- package/dist/monid.js +277 -0
- package/dist/openapi/agentrun-v2.openapi.json +4805 -0
- package/dist/openapi.d.ts +10 -0
- package/dist/openapi.js +1417 -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 +46 -0
- package/dist/paid-calls.js +110 -0
- package/dist/pause.d.ts +68 -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 +46 -0
- package/dist/place.js +105 -0
- package/dist/print.d.ts +20 -0
- package/dist/print.js +29 -0
- package/dist/propose.d.ts +38 -0
- package/dist/propose.js +82 -0
- package/dist/quiet-sqlite-warning.d.ts +1 -0
- package/dist/quiet-sqlite-warning.js +14 -0
- package/dist/request-start.d.ts +14 -0
- package/dist/request-start.js +226 -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 +134 -0
- package/dist/run-box.js +440 -0
- package/dist/run-manifest.d.ts +27 -0
- package/dist/run-manifest.js +60 -0
- package/dist/runnable.d.ts +80 -0
- package/dist/runnable.js +162 -0
- package/dist/runs.d.ts +840 -0
- package/dist/runs.js +2279 -0
- package/dist/secret-cut.d.ts +27 -0
- package/dist/secret-cut.js +109 -0
- package/dist/secrets.d.ts +50 -0
- package/dist/secrets.js +140 -0
- package/dist/server-lock.d.ts +44 -0
- package/dist/server-lock.js +140 -0
- package/dist/server.d.ts +626 -0
- package/dist/server.js +1756 -0
- package/dist/sessions.d.ts +4 -0
- package/dist/sessions.js +105 -0
- package/dist/skills.d.ts +31 -0
- package/dist/skills.js +68 -0
- package/dist/stats.d.ts +101 -0
- package/dist/stats.js +82 -0
- package/dist/tool-keys.d.ts +151 -0
- package/dist/tool-keys.js +273 -0
- package/dist/tool-plane.d.ts +143 -0
- package/dist/tool-plane.js +242 -0
- package/dist/tools.d.ts +147 -0
- package/dist/tools.js +253 -0
- package/dist/turn-end.d.ts +23 -0
- package/dist/turn-end.js +14 -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.d.ts +29 -0
- package/dist/usage.js +58 -0
- package/dist/validate.d.ts +55 -0
- package/dist/validate.js +175 -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 +182 -0
- package/dist/webhooks.js +487 -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 +96 -1
- package/skills/agentrun-serve/SKILL.md +128 -0
package/dist/server.js
ADDED
|
@@ -0,0 +1,1756 @@
|
|
|
1
|
+
// The /v2 API over the agent store in a data directory: the contract agentrun.v2/0, served on loopback with a bearer
|
|
2
|
+
// token.
|
|
3
|
+
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
4
|
+
import { chmod, lstat, mkdir, readdir, readFile, realpath, rename, stat, writeFile } from "node:fs/promises";
|
|
5
|
+
import { createServer } from "node:http";
|
|
6
|
+
import { dirname, join, resolve } from "node:path";
|
|
7
|
+
import { pipeline } from "node:stream/promises";
|
|
8
|
+
import { pathToFileURL } from "node:url";
|
|
9
|
+
import { Worker } from "node:worker_threads";
|
|
10
|
+
import { once } from "node:events";
|
|
11
|
+
import { existsSync } from "node:fs";
|
|
12
|
+
import { rm } from "node:fs/promises";
|
|
13
|
+
import { homedir } from "node:os";
|
|
14
|
+
import { agentView, Agents, etagOf, homeBusy, revisionView, storeBusy } from "./agents.js";
|
|
15
|
+
import { WORKFLOW_ADAPTERS } from "./app.js";
|
|
16
|
+
import { DECISION_ADAPTER, decisionsOf, FAUX_JEV_ENV, FAUX_OPENROUTER_ENV, FAUX_PARALLEL_ENV } from "./decisions.js";
|
|
17
|
+
import { FAUX_WEB_ENV } from "./fetch-page.js";
|
|
18
|
+
import { FAUX_MONID_ENV } from "./monid.js";
|
|
19
|
+
import { FAUX_EXA_ENV } from "./exa-keyless.js";
|
|
20
|
+
import { FAUX_BROWSER_ENV, NODE_TOOLS, toolingOf, toolsView } from "./tools.js";
|
|
21
|
+
import { ApiError, invalid, unsupported } from "./errors.js";
|
|
22
|
+
import { DATA_ENV, DOOR_TOKEN_FILE, HOME_HOST_OWNED, HOMES_DIR, homeOf, readJson, RUN_META, syncDir, TOKEN_FILE, writeDurable } from "./files.js";
|
|
23
|
+
import { checkedPath, decodedPath, homePath, hostOwnedOf, hostOwnedRefusal, ownedByIdentity } from "./home-path.js";
|
|
24
|
+
import { chooseModel, EFFORTS, FAUX_ENV, FAUX_UPSTREAM_ENV, MODEL_NODES, modelSource, THINKING_LEVELS, withoutFaux } from "./model.js";
|
|
25
|
+
import { DEFAULT_HARNESS, FAUX_HARNESS_ENV, harnessOffers } from "./harness.js";
|
|
26
|
+
import { healthOf, hostMemory, maxRunsOf, MIN_FREE_MIB, runsThatFit } from "./host.js";
|
|
27
|
+
import { IMPORT_ASKED } from "./import.js";
|
|
28
|
+
import { gradeModelOf, learningBudgetOf, learningOf } from "./learning.js";
|
|
29
|
+
import { agentLearning, learningLog, learningNotes, noteBody, readNote, runDiff, runLearning, secretsShown, sendNote, writeNote } from "./learning-routes.js";
|
|
30
|
+
import { answerLlms, MCP_PATH, mcpEndpoint } from "./mcp.js";
|
|
31
|
+
import { openapiDocument, servedOpenapi, UNSUPPORTED } from "./openapi.js";
|
|
32
|
+
import { boxesLine, noBoxReason, placesOf, resolvePlace } from "./place.js";
|
|
33
|
+
import { boxLimitsOf, FAUX_BOX_ENV, fauxBoxes } from "./run-box.js";
|
|
34
|
+
import { Owner, passwordProblem, SESSION_MS } from "./owner.js";
|
|
35
|
+
import { answerPage, byOwnerSession, isJson, ownerCookie, ownOrigin, signedIn } from "./page.js";
|
|
36
|
+
import { durationMs, logLine } from "./print.js";
|
|
37
|
+
import { Runs, STATUSES, statusOf, toolCostOf } from "./runs.js";
|
|
38
|
+
import { BOX_QUARANTINE, Quarantine } from "./box/sweep.js";
|
|
39
|
+
import { boxesLog, boxRegistry, daytonaApi, enabledBoxes } from "./boxes.js";
|
|
40
|
+
import { boxImageOf, clearImage, dockerImage, withImage } from "./box-image.js";
|
|
41
|
+
import { startBoxRelay } from "./box-relay.js";
|
|
42
|
+
import { DOCUMENTS_ENV } from "./pdf-pages.js";
|
|
43
|
+
import { metersIn } from "./cap.js";
|
|
44
|
+
import { blockersOf, CODE_NODES_ENV, issueOf } from "./runnable.js";
|
|
45
|
+
import { hostSecrets, SECRET_NAMES, secret, withSecrets } from "./secrets.js";
|
|
46
|
+
import { analyticsFilter, analyticsView, statsView } from "./stats.js";
|
|
47
|
+
import { outcomes } from "./usage.js";
|
|
48
|
+
import { keyOf, SEAL_KEY_ENV, sealKeyOf, TOOL_FIELDS, ToolKeys } from "./tool-keys.js";
|
|
49
|
+
import { MCP_AUTH_TYPES, McpServers } from "./mcp-servers.js";
|
|
50
|
+
import { WEBHOOK_EVENTS, Webhooks } from "./webhooks.js";
|
|
51
|
+
import { checkDefinitionBody, DEFAULT_INPUT_SCHEMA, ID, inputIssues, isObject, stable, unknownFields } from "./validate.js";
|
|
52
|
+
import { agentTools, settingsIssues, ToolSettings, withDefaults } from "./tool-plane.js";
|
|
53
|
+
import { MAX_FILES_PER_RUN, MAX_UPLOAD_BYTES, Uploads, UPLOADS_DIR } from "./uploads.js";
|
|
54
|
+
import { INLINE_TYPES, openWorkFile, removeWorkFile, typeOf, WALK_DEPTH, walkWork, WorkRefused, writesHeld, writeWorkFile } from "./workspace.js";
|
|
55
|
+
import { markRunning, markStopping, takeServerLockAfterStop } from "./server-lock.js";
|
|
56
|
+
export const CONTRACT = "agentrun.v2/0";
|
|
57
|
+
/** A process's flags for a worker of it: without --input-type and the code string given with -e, --eval, -p or --print. */
|
|
58
|
+
const workerArgs = (args) => args.filter((arg, i) => !arg.startsWith("--input-type") && !/^(?:-e|--eval|-p|--print)(?:=|$)/.test(arg) && !/^(?:-e|--eval|-p|--print)$/.test(args[i - 1] ?? ""));
|
|
59
|
+
export const DEFAULT_PORT = 7340;
|
|
60
|
+
const VERSION = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
61
|
+
const IDEMPOTENCY_FILE = ".idempotency.json";
|
|
62
|
+
const MAX_BODY = 1 << 20;
|
|
63
|
+
const MAX_MESSAGE = 20_000;
|
|
64
|
+
const MAX_WAIT_MS = 25_000;
|
|
65
|
+
const PAGE_ROWS = 500;
|
|
66
|
+
const IDEMPOTENCY_TTL_S = 86_400;
|
|
67
|
+
const FILE_LIST_CAP = 2_000;
|
|
68
|
+
/** What a stopping server's record allows past its runs' kill bound, the cap a start waits under: the runs' carry backs,
|
|
69
|
+
* retried while the agent store is held (about 15.5 s), their boxes' cleanup (up to a minute), and the deliveries', the
|
|
70
|
+
* listener's and the stores' stop. A start stops waiting sooner once the stopping server's process is gone. */
|
|
71
|
+
const STOP_MARGIN_MS = 120_000;
|
|
72
|
+
/** A wait, as the stop's lines give it: whole seconds, rounded up, one at least. */
|
|
73
|
+
const seconds = (ms) => `${Math.max(1, Math.ceil(ms / 1000))} s`;
|
|
74
|
+
/** Where the stop's lines go (ServeOptions.notice). Best-effort: a notice that throws never stops a close or a start. */
|
|
75
|
+
const noticeOf = (options) => (line) => {
|
|
76
|
+
try {
|
|
77
|
+
(options.notice ?? ((said) => void process.stderr.write(`agentrun-serve: ${said}\n`)))(line);
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
// The line is told, not needed: the stop and the wait go on without it.
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
/** Why a home's PUT or DELETE is 501 where `capabilities.home.writes` is false (workspace.ts writesHeld). */
|
|
84
|
+
const HOME_WRITES_OFF = "This server can't write a home's files safely here: a write needs /proc/self/fd, as on Linux, which this platform lacks. Reads and the list still work.";
|
|
85
|
+
const FILE_CSP = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox; form-action 'none'";
|
|
86
|
+
/** Each test switch a run's process reads, by the variable it reads it from: set only under `faux`, but the faux
|
|
87
|
+
* harness's, which scripts the harnesses with or without it. */
|
|
88
|
+
const FAUX_SWITCHES = [["fauxBrowser", FAUX_BROWSER_ENV], ["fauxWeb", FAUX_WEB_ENV], ["fauxJev", FAUX_JEV_ENV], ["fauxParallel", FAUX_PARALLEL_ENV], ["fauxOpenrouter", FAUX_OPENROUTER_ENV], ["fauxMonid", FAUX_MONID_ENV], ["fauxUpstream", FAUX_UPSTREAM_ENV], ["fauxExa", FAUX_EXA_ENV], ["fauxBox", FAUX_BOX_ENV]];
|
|
89
|
+
/** The test switches a run's process gets, each module path resolved: empty outside tests. */
|
|
90
|
+
function fauxEnvOf(options) {
|
|
91
|
+
const env = options.fauxHarness ? { [FAUX_HARNESS_ENV]: resolve(options.fauxHarness) } : {};
|
|
92
|
+
if (!options.faux)
|
|
93
|
+
return env;
|
|
94
|
+
env[FAUX_ENV] = resolve(options.faux);
|
|
95
|
+
for (const [option, name] of FAUX_SWITCHES)
|
|
96
|
+
if (options[option])
|
|
97
|
+
env[name] = resolve(options[option]);
|
|
98
|
+
return env;
|
|
99
|
+
}
|
|
100
|
+
const isLoopback = (host) => host === "localhost" || host === "::1" || /^127\./.test(host);
|
|
101
|
+
/** A private token in `file` (0600), made once and kept; `made` when this call made it. */
|
|
102
|
+
async function tokenIn(file) {
|
|
103
|
+
const known = await readFile(file, "utf8").then((text) => text.trim(), () => "");
|
|
104
|
+
if (known && !/\s/.test(known)) {
|
|
105
|
+
await chmod(file, 0o600);
|
|
106
|
+
return { token: known, made: false };
|
|
107
|
+
}
|
|
108
|
+
const token = `ar_local_${randomBytes(24).toString("base64url")}`;
|
|
109
|
+
await writeFile(file, `${token}\n`, { mode: 0o600, flag: "w" });
|
|
110
|
+
await chmod(file, 0o600);
|
|
111
|
+
return { token, made: true };
|
|
112
|
+
}
|
|
113
|
+
const digest = (text) => createHash("sha256").update(text).digest();
|
|
114
|
+
const SESSION_S = SESSION_MS / 1000;
|
|
115
|
+
export const ROUTES = [
|
|
116
|
+
{ method: "GET", pattern: /^\/capabilities$/, name: "getCapabilities" },
|
|
117
|
+
{ method: "GET", pattern: /^\/openapi\.json$/, name: "getOpenapi" },
|
|
118
|
+
{ method: "GET", pattern: /^\/health$/, name: "getHealth" },
|
|
119
|
+
{ method: "POST", pattern: /^\/agents$/, name: "createAgent" },
|
|
120
|
+
{ method: "GET", pattern: /^\/agents$/, name: "listAgents" },
|
|
121
|
+
{ method: "GET", pattern: /^\/agents\/([^/]+)$/, name: "getAgent" },
|
|
122
|
+
{ method: "PUT", pattern: /^\/agents\/([^/]+)\/definition$/, name: "updateDefinition" },
|
|
123
|
+
{ method: "GET", pattern: /^\/agents\/([^/]+)\/revisions$/, name: "listRevisions" },
|
|
124
|
+
{ method: "POST", pattern: /^\/agents\/([^/]+)\/current$/, name: "setCurrent" },
|
|
125
|
+
{ method: "POST", pattern: /^\/agents\/([^/]+)\/archive$/, name: "archiveAgent" },
|
|
126
|
+
{ method: "POST", pattern: /^\/agents\/([^/]+)\/unarchive$/, name: "unarchiveAgent" },
|
|
127
|
+
{ method: "POST", pattern: /^\/agents\/([^/]+)\/runs$/, name: "createRun" },
|
|
128
|
+
{ method: "GET", pattern: /^\/agents\/([^/]+)\/runs$/, name: "listRuns" },
|
|
129
|
+
{ method: "GET", pattern: /^\/agents\/([^/]+)\/home$/, name: "exportHome", capability: "home.export" },
|
|
130
|
+
{ method: "PUT", pattern: /^\/agents\/([^/]+)\/home$/, name: "importHome", capability: "home.import" },
|
|
131
|
+
{ method: "GET", pattern: /^\/agents\/([^/]+)\/home\/files$/, name: "listHomeFiles" },
|
|
132
|
+
{ method: "GET", pattern: /^\/agents\/([^/]+)\/home\/files\/(.+)$/, name: "readHomeFile" },
|
|
133
|
+
{ method: "PUT", pattern: /^\/agents\/([^/]+)\/home\/files\/(.+)$/, name: "writeHomeFile" },
|
|
134
|
+
{ method: "DELETE", pattern: /^\/agents\/([^/]+)\/home\/files\/(.+)$/, name: "deleteHomeFile" },
|
|
135
|
+
{ method: "GET", pattern: /^\/runs$/, name: "listAllRuns" },
|
|
136
|
+
{ method: "GET", pattern: /^\/runs\/([^/]+)$/, name: "getRun" },
|
|
137
|
+
{ method: "GET", pattern: /^\/runs\/([^/]+)\/timeline$/, name: "getTimeline" },
|
|
138
|
+
{ method: "POST", pattern: /^\/runs\/([^/]+)\/messages$/, name: "sendMessage" },
|
|
139
|
+
{ method: "POST", pattern: /^\/runs\/([^/]+)\/stop$/, name: "stopRun" },
|
|
140
|
+
{ method: "POST", pattern: /^\/runs\/([^/]+)\/cancel$/, name: "cancelRun" },
|
|
141
|
+
{ method: "POST", pattern: /^\/runs\/([^/]+)\/archive$/, name: "archiveRun" },
|
|
142
|
+
{ method: "POST", pattern: /^\/runs\/([^/]+)\/unarchive$/, name: "unarchiveRun" },
|
|
143
|
+
{ method: "POST", pattern: /^\/runs\/([^/]+)\/kill$/, name: "killRun", capability: "runs.kill" },
|
|
144
|
+
{ method: "GET", pattern: /^\/runs\/([^/]+)\/graph$/, name: "getRunGraph" },
|
|
145
|
+
{ method: "POST", pattern: /^\/workflows\/validate$/, name: "validateWorkflow" },
|
|
146
|
+
{ method: "POST", pattern: /^\/runs\/([^/]+)\/pause$/, name: "pauseRun" },
|
|
147
|
+
{ method: "POST", pattern: /^\/runs\/([^/]+)\/resume$/, name: "resumeRun" },
|
|
148
|
+
{ method: "GET", pattern: /^\/runs\/([^/]+)\/files$/, name: "listRunFiles" },
|
|
149
|
+
{ method: "GET", pattern: /^\/runs\/([^/]+)\/files\/(.+)$/, name: "readRunFile" },
|
|
150
|
+
{ method: "POST", pattern: /^\/files$/, name: "createFile", raw: true },
|
|
151
|
+
{ method: "GET", pattern: /^\/files$/, name: "listFiles" },
|
|
152
|
+
{ method: "GET", pattern: /^\/files\/([^/]+)$/, name: "getFile" },
|
|
153
|
+
{ method: "PUT", pattern: /^\/files\/([^/]+)$/, name: "uploadFile", raw: true },
|
|
154
|
+
{ method: "DELETE", pattern: /^\/files\/([^/]+)$/, name: "deleteFile" },
|
|
155
|
+
{ method: "POST", pattern: /^\/quotes$/, name: "createQuote", capability: "quotes" },
|
|
156
|
+
{ method: "GET", pattern: /^\/usage$/, name: "getUsage" },
|
|
157
|
+
{ method: "GET", pattern: /^\/stats$/, name: "getStats" },
|
|
158
|
+
{ method: "GET", pattern: /^\/settings\/tool-keys$/, name: "listToolKeys" },
|
|
159
|
+
{ method: "PUT", pattern: /^\/settings\/tool-keys\/([^/]+)$/, name: "saveToolKey" },
|
|
160
|
+
{ method: "DELETE", pattern: /^\/settings\/tool-keys\/([^/]+)$/, name: "deleteToolKey" },
|
|
161
|
+
{ method: "GET", pattern: /^\/settings\/mcp-servers$/, name: "listMcpServers" },
|
|
162
|
+
{ method: "POST", pattern: /^\/settings\/mcp-servers\/preview$/, name: "previewMcpServer" },
|
|
163
|
+
{ method: "GET", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "getMcpServer" },
|
|
164
|
+
{ method: "PUT", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "saveMcpServer" },
|
|
165
|
+
{ method: "DELETE", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "deleteMcpServer" },
|
|
166
|
+
{ method: "POST", pattern: /^\/settings\/mcp-servers\/([^/]+)\/refresh$/, name: "refreshMcpServer" },
|
|
167
|
+
{ method: "GET", pattern: /^\/settings\/tools$/, name: "getToolSettings" },
|
|
168
|
+
{ method: "PUT", pattern: /^\/settings\/tools$/, name: "putToolSettings" },
|
|
169
|
+
{ method: "GET", pattern: /^\/settings\/webhook$/, name: "getWebhook" },
|
|
170
|
+
{ method: "PUT", pattern: /^\/settings\/webhook$/, name: "saveWebhook" },
|
|
171
|
+
{ method: "DELETE", pattern: /^\/settings\/webhook$/, name: "deleteWebhook" },
|
|
172
|
+
{ method: "POST", pattern: /^\/settings\/webhook\/test$/, name: "testWebhook" },
|
|
173
|
+
{ method: "GET", pattern: /^\/settings\/webhook\/deliveries$/, name: "listWebhookDeliveries" },
|
|
174
|
+
{ method: "POST", pattern: /^\/settings\/webhook\/deliveries\/([^/]+)\/redeliver$/, name: "redeliverWebhook" },
|
|
175
|
+
// Answered before routing (mcp.ts), with the token only: listed here for the document.
|
|
176
|
+
{ method: "POST", pattern: /^\/mcp$/, name: "callMcp" },
|
|
177
|
+
{ method: "GET", pattern: /^\/agents\/([^/]+)\/learning$/, name: "getAgentLearning" },
|
|
178
|
+
{ method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/notes$/, name: "listLearningNotes" },
|
|
179
|
+
{ method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/log$/, name: "listLearningLog" },
|
|
180
|
+
{ method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)$/, name: "readLearningFile" },
|
|
181
|
+
{ method: "PUT", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)$/, name: "writeLearningFile" },
|
|
182
|
+
{ method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/retire$/, name: "retireLearningFile" },
|
|
183
|
+
{ method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/approve$/, name: "approveLearningFile" },
|
|
184
|
+
{ method: "GET", pattern: /^\/runs\/([^/]+)\/learning$/, name: "getRunLearning" },
|
|
185
|
+
{ method: "GET", pattern: /^\/runs\/([^/]+)\/learning\/diff$/, name: "getRunLearningDiff" },
|
|
186
|
+
];
|
|
187
|
+
/** Where agent `agentId`'s host-owned path is read on this server: its route, when ROUTES has one (the learning API, for
|
|
188
|
+
* learning/). */
|
|
189
|
+
const ownedReadAt = (agentId) => (owned) => (ROUTES.some((r) => r.method === "GET" && r.pattern.test(`/agents/${agentId}/${owned}`)) ? `/v2/agents/${agentId}/${owned}` : undefined);
|
|
190
|
+
/** Whether the request to `path` (under /v2) is a PUT of a route marked `raw`. */
|
|
191
|
+
export const takesBytes = (method, path) => (method === "PUT" || method === "POST") && ROUTES.some((r) => r.raw === true && r.method === method && r.pattern.test(path));
|
|
192
|
+
/** What this server offers. Every flag is present; an off one answers 501 naming it. */
|
|
193
|
+
/** A workflow run's title: its agent's name and a few words of its input, never the input's JSON ("Batch review: 20
|
|
194
|
+
* documents, as_of 2026-10-30"). */
|
|
195
|
+
export function workflowTitle(name, input) {
|
|
196
|
+
const words = Object.entries(input).slice(0, 3).map(([key, value]) => {
|
|
197
|
+
if (Array.isArray(value))
|
|
198
|
+
return value.length === 1 && typeof value[0] === "string" ? value[0] : `${value.length} ${key}`;
|
|
199
|
+
if (typeof value === "string")
|
|
200
|
+
return value.length > 40 ? `${value.slice(0, 39)}…` : value;
|
|
201
|
+
if (typeof value === "number" || typeof value === "boolean")
|
|
202
|
+
return `${key} ${value}`;
|
|
203
|
+
return key;
|
|
204
|
+
});
|
|
205
|
+
// A name that ends in its own punctuation ("Is this certificate valid?") takes no colon after it.
|
|
206
|
+
return words.length ? `${name}${/[?!:.]$/.test(name) ? "" : ":"} ${words.join(", ")}` : name;
|
|
207
|
+
}
|
|
208
|
+
/** `env` as the harnesses' offers are made from it: without the tool keys' fields (TOOL_FIELDS), which no harness reads.
|
|
209
|
+
* So the offers never depend on a tool key, and its save or delete leaves them as they are. */
|
|
210
|
+
export function offersEnvOf(env) {
|
|
211
|
+
const descriptors = Object.getOwnPropertyDescriptors(env);
|
|
212
|
+
for (const name of TOOL_FIELDS)
|
|
213
|
+
delete descriptors[name];
|
|
214
|
+
return Object.defineProperties({}, descriptors);
|
|
215
|
+
}
|
|
216
|
+
/** What of `env` a write can change that the harnesses' offers are made from: each secret but the tool keys' fields (a
|
|
217
|
+
* saved key is one of those; the rest of the environment is the server's start's). Held to tell whether a write needs
|
|
218
|
+
* the offers probed again, never shown. */
|
|
219
|
+
const offersInputs = (env) => SECRET_NAMES.filter((name) => !TOOL_FIELDS.includes(name)).map((name) => env[name]);
|
|
220
|
+
/** What a revision that names no model needs here (capabilities' `models.needs`): null when one runs, else chooseModel's
|
|
221
|
+
* `needs`, a provider's key or another model. Made from `env` alone, so it is remade only when env is. */
|
|
222
|
+
async function needsOf(env) {
|
|
223
|
+
const chosen = await chooseModel(env, undefined);
|
|
224
|
+
return "why" in chosen ? chosen.needs : null;
|
|
225
|
+
}
|
|
226
|
+
/** The server's reading of `base`, whole: its secrets, saved keys among them (`env`), the harnesses' offers, probed from
|
|
227
|
+
* env without the tool keys (offersEnvOf), and its capabilities made from both under its learning switch (`learning`,
|
|
228
|
+
* AGENTRUN_SERVE_LEARNING's when not given), its tool settings (`toolSettings`, what each web tool resolves to) and the
|
|
229
|
+
* box offers (`boxes`, what the box registry set up at the start, boxes.ts), with whether a revision that names no
|
|
230
|
+
* model runs (needsOf). The server makes it once at its start and then remakes only the parts a write changes
|
|
231
|
+
* (startHolding), so a key saved later can make a harness, a provider or the default model available with no restart.
|
|
232
|
+
* `gradeModel` is its `--grade-model`. */
|
|
233
|
+
export async function readingOf(base, maxRuns, stored, learning, toolSettings = {}, boxes = [], gradeModel) {
|
|
234
|
+
const env = withSecrets(base, "all", stored);
|
|
235
|
+
const offers = await harnessOffers(offersEnvOf(env));
|
|
236
|
+
return { env, offers, caps: capabilitiesWith(env, maxRuns, offers, learning ?? learningOf(env), await needsOf(env), toolSettings, boxes, gradeModel) };
|
|
237
|
+
}
|
|
238
|
+
/** The capabilities document GET /v2/capabilities answers for `env`: each harness's offer resolved, its `default_model`
|
|
239
|
+
* included (harnessOffers), and whether a revision that names no model runs here (`models.ready`, and what it `needs`
|
|
240
|
+
* when not), so what this returns is what the route serves and what the document's schema holds.
|
|
241
|
+
* `learning` is the server's learning switch (`--learning`), AGENTRUN_SERVE_LEARNING's when not given; with this
|
|
242
|
+
* server's tool settings, what each web tool resolves to (tool-plane.ts); `boxes`, the box offers its places show;
|
|
243
|
+
* `gradeModel`, its `--grade-model`. */
|
|
244
|
+
export async function capabilities(env = withSecrets(process.env), maxRuns = maxRunsOf(env), learning = learningOf(env), toolSettings = {}, boxes = [], gradeModel) {
|
|
245
|
+
return capabilitiesWith(env, maxRuns, await harnessOffers(env), learning, await needsOf(env), toolSettings, boxes, gradeModel);
|
|
246
|
+
}
|
|
247
|
+
/** The capabilities document as `req`'s caller reads it: approving takes the owner's password session alone, so only
|
|
248
|
+
* that caller reads `approve: true`; every other (a token, a run, accounts off) reads `approve_needs: "password"`. */
|
|
249
|
+
export function forCaller(caps, ownerSession) {
|
|
250
|
+
return ownerSession ? { ...caps, learning: { grade_model: caps.learning.grade_model, pending: caps.learning.pending, approve: true } } : caps;
|
|
251
|
+
}
|
|
252
|
+
/** The capabilities document from offers already resolved, under the server's learning switch, tool settings and box
|
|
253
|
+
* offers: cheap, made again after each key or tool-settings write with the offers the server holds; and `needs` as
|
|
254
|
+
* needsOf says it for a revision that names no model (null when it runs). */
|
|
255
|
+
function capabilitiesWith(env, maxRuns, harnesses, learning, needs, toolSettings, boxes, gradeModel) {
|
|
256
|
+
const models = { ...modelSource(env), ready: needs === null, needs };
|
|
257
|
+
// Both limits apply: the cap on the count, and the memory each run reserves (host.ts).
|
|
258
|
+
const memory = hostMemory();
|
|
259
|
+
return {
|
|
260
|
+
backend: "local",
|
|
261
|
+
contract: CONTRACT,
|
|
262
|
+
server: { name: "@parcha/agentrun-serve", version: VERSION, platform: process.platform },
|
|
263
|
+
runtimes: ["pi-durable-disk"],
|
|
264
|
+
/** The harnesses a revision may name (`definition.harness`), whether this server runs each, and how many at once. */
|
|
265
|
+
// `keys`, what a model key would unlock, is the key rows' (listToolKeys), never served here.
|
|
266
|
+
harnesses: harnesses.map(({ keys: _keys, ...offer }) => ({ ...offer, max_concurrent_runs: Math.min(maxRuns, runsThatFit(offer.id, memory)) })),
|
|
267
|
+
/** The places a revision may name (`definition.place`), this host's default, and whether this server has each box. */
|
|
268
|
+
places: placesOf(boxes),
|
|
269
|
+
models,
|
|
270
|
+
/** What grades a run's proposed notes: the model this server names for it (learning.ts gradeModelOf), or null when
|
|
271
|
+
* each run is graded on its agent's own model; and `pending`: a risky rule, the user's or the run's own, is kept to
|
|
272
|
+
* wait for its owner's OK, served to no run; `approve`: whether the caller can approve one, which takes the owner's
|
|
273
|
+
* password session (forCaller), and `approve_needs` when not. */
|
|
274
|
+
learning: { grade_model: gradeModelOf(env, gradeModel) ?? null, pending: true, approve: false, approve_needs: "password" },
|
|
275
|
+
/** Every tool a revision may name (the closed table in tools.ts): available here, or the variables it is missing; a
|
|
276
|
+
* web tool, what it resolves to on each harness under this server's tool settings; `key`, the tool key that unlocks
|
|
277
|
+
* it (tool-keys.ts), when one does. */
|
|
278
|
+
tools: toolsView(env, toolSettings, noBoxReason(boxes)).map((tool) => (keyOf(tool.name) ? { ...tool, key: keyOf(tool.name) } : tool)),
|
|
279
|
+
/** How this server holds its secrets (secrets.ts, the launcher), and what that does not cover. */
|
|
280
|
+
secrets: {
|
|
281
|
+
names: [...SECRET_NAMES],
|
|
282
|
+
handoff: "pipe",
|
|
283
|
+
condition: "Started by its launcher (the package's agentrun-serve, the image's entrypoint), the server takes each secret named here over a pipe and holds it in memory only, and a run's process gets, over a pipe of its own, a tool key only when its revision names a tool the key unlocks and a model key only when its model needs it: a pi run its model's provider's (per tier for a workflow), or the gateway's behind AGENT_MODEL_BASE_URL; a codex run OPENAI_API_KEY, or the gateway's; a claude-agent run ANTHROPIC_API_KEY. It never gets the server's own (its token, the seal key, the boxes' keys), and the decision keys a run's decision nodes need, and Parallel's where its web_fetch or web_search resolves to Parallel, and no other, go on a descriptor of their own: none of them is in any process's environment or command line. No run's environment holds any variable named like a key (a KEY, TOKEN, SECRET, PASSWORD, PASSWD, PASS, PAT, CREDENTIAL, CREDENTIALS or DSN segment, or a last PWD after another), on this list or not; one not on it stays in the server's own. The launcher runs before any run's process exists; the image starts it as PID 1. Started another way (node dist/cli.js), the server reads them from its environment, where a process of its user can read them.",
|
|
284
|
+
limit: "In memory is not out of reach: a process of the same user can read another's memory (/proc/<pid>/mem) where the kernel lets it attach. Linux's Yama ptrace_scope of 1 or more refuses that to all but a process's own ancestors; a host at 0 exposes the secrets to a run's own code. A run's process holds its model keys in memory, since it calls the model itself. A harness's CLI (codex, claude-agent) holds a key of its own for its session's model proxy in its environment: not a provider's key, but one a process of the same user could spend through that run's proxy while the session lives. Started as the package's bin on a host, until it execs, the launcher and any subshell it forks show the caller's environment, secrets included, to a process of the same user (/proc keeps a process's environment as it was at its exec). A run's process gets its secrets over a socket, read and closed as it starts; another process can take a socket only through pidfd_getfd, which the same ptrace rule refuses.",
|
|
285
|
+
},
|
|
286
|
+
/** What a workflow revision's run gets: each model node runs on the model of its tier (`models.fast`,
|
|
287
|
+
* `models.default`, `models.strong`) with the tools it names of `node_tools`; a node that names no thinking level
|
|
288
|
+
* thinks at the run's effort, or medium. */
|
|
289
|
+
workflows: { nodes: [...MODEL_NODES], node_tools: [...NODE_TOOLS], adapters: [...WORKFLOW_ADAPTERS, ...(decisionsOf(env).some((offer) => offer.available) ? [DECISION_ADAPTER] : [])], decisions: { providers: decisionsOf(env) } },
|
|
290
|
+
/** Each agent's home (its files under `/agents/{id}/home/files`): on this server's disk, the paths in it only the host
|
|
291
|
+
* writes, and the largest file a PUT takes (`limits.max_body_bytes`). */
|
|
292
|
+
home: { disk: "local", host_owned: [...HOME_HOST_OWNED], max_file_bytes: MAX_BODY, writes: writesHeld() },
|
|
293
|
+
features: {
|
|
294
|
+
agents: { create: true, list: true, update: true, revisions: true },
|
|
295
|
+
/** This server's own routes, outside the contract: an archived agent or run is hidden from the lists (`?archived=true`
|
|
296
|
+
* lists only those) and kept, with its history; a run of an archived agent is refused. */
|
|
297
|
+
archive: { agents: true, runs: true, list_param: "archived", routes: ["POST /agents/{id}/archive", "POST /agents/{id}/unarchive", "POST /runs/{id}/archive", "POST /runs/{id}/unarchive"] },
|
|
298
|
+
home: { export: false, import: false, check: false },
|
|
299
|
+
runs: { stop: true, cancel: true, kill: false, list: true, kinds: ["agentic", "workflow"], pause_workflow_runs: true, graph: true },
|
|
300
|
+
messages: { steer: true, answer: true, follow_up: true, steer_workflow_runs: false },
|
|
301
|
+
timeline: { long_poll: true, sse: true, live_rows: true, live_workflow_rows: false },
|
|
302
|
+
files: { upload: true, read: true, range: false, during_run: true },
|
|
303
|
+
quotes: false,
|
|
304
|
+
usage: { basis: "estimate", meters: ["tokens", "tools", "learning"] },
|
|
305
|
+
efforts: [...EFFORTS],
|
|
306
|
+
thinking: [...THINKING_LEVELS],
|
|
307
|
+
browser: "none",
|
|
308
|
+
/** A tool setting's `permission` (definition.tool_settings, /v2/settings/tools): false until the tool gate lands,
|
|
309
|
+
* and a save that names one is refused. */
|
|
310
|
+
tool_permissions: false,
|
|
311
|
+
sign_ins: false,
|
|
312
|
+
vault: false,
|
|
313
|
+
query: false,
|
|
314
|
+
/** GET, PUT and DELETE /settings/tool-keys: a tool's key saved by name, kept sealed under the launcher's seal key
|
|
315
|
+
* (tool-keys.ts); with none handed over, nothing is kept, never in the clear. */
|
|
316
|
+
tool_keys: { routes: true, at_rest: sealKeyOf(env[SEAL_KEY_ENV]) ? "sealed" : "unavailable" },
|
|
317
|
+
/** /settings/mcp-servers: remote MCP servers previewed and saved, each credential sealed under the same seal key
|
|
318
|
+
* (mcp-servers.ts); with none, only servers that take no credential are kept. */
|
|
319
|
+
mcp_client: { routes: true, transports: ["streamable-http"], auth: [...MCP_AUTH_TYPES], at_rest: sealKeyOf(env[SEAL_KEY_ENV]) ? "sealed" : "unavailable" },
|
|
320
|
+
/** This server's learning switch (`--learning`): on, a run learns when its agent says `learning: true`; off, none does. */
|
|
321
|
+
learning,
|
|
322
|
+
/** /settings/webhook: one URL POSTed, signed by the Standard Webhooks spec, when a run needs its person and when it
|
|
323
|
+
* ends (webhooks.ts); its secret kept sealed under the same seal key, so with none no webhook is set. */
|
|
324
|
+
webhooks: { routes: true, events: [...WEBHOOK_EVENTS], signing: "standard-webhooks/v1", at_rest: sealKeyOf(env[SEAL_KEY_ENV]) ? "sealed" : "unavailable" },
|
|
325
|
+
},
|
|
326
|
+
regions: [{ id: "local", jurisdiction: null, state: "live" }],
|
|
327
|
+
/** This server's own: where its OpenAPI document is, beside this one. */
|
|
328
|
+
links: { openapi: "/v2/openapi.json" },
|
|
329
|
+
limits: {
|
|
330
|
+
max_body_bytes: MAX_BODY,
|
|
331
|
+
max_upload_bytes: MAX_UPLOAD_BYTES,
|
|
332
|
+
max_files_per_run: MAX_FILES_PER_RUN,
|
|
333
|
+
max_message_chars: MAX_MESSAGE,
|
|
334
|
+
// pi's: the smallest run, so the most at once. A heavier harness fits fewer (harnesses[].max_concurrent_runs).
|
|
335
|
+
max_concurrent_runs: Math.min(maxRuns, runsThatFit(DEFAULT_HARNESS, memory)),
|
|
336
|
+
timeline_max_wait_ms: MAX_WAIT_MS,
|
|
337
|
+
timeline_page_rows: PAGE_ROWS,
|
|
338
|
+
idempotency_ttl_s: IDEMPOTENCY_TTL_S,
|
|
339
|
+
input_wait_s: null,
|
|
340
|
+
max_cost_usd: null,
|
|
341
|
+
},
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
function cursorOf(value) {
|
|
345
|
+
if (value === null)
|
|
346
|
+
return 0;
|
|
347
|
+
const offset = Number(Buffer.from(value, "base64url").toString("utf8"));
|
|
348
|
+
if (!Number.isSafeInteger(offset) || offset < 0)
|
|
349
|
+
throw new ApiError("bad_request", "cursor is not one this server gave");
|
|
350
|
+
return offset;
|
|
351
|
+
}
|
|
352
|
+
const nextCursor = (offset, total) => (offset < total ? Buffer.from(String(offset)).toString("base64url") : null);
|
|
353
|
+
function limitOf(value) {
|
|
354
|
+
if (value === null)
|
|
355
|
+
return 20;
|
|
356
|
+
const n = Number(value);
|
|
357
|
+
if (!/^\d+$/.test(value) || n < 1 || n > 100)
|
|
358
|
+
throw new ApiError("bad_request", "limit is an integer from 1 to 100");
|
|
359
|
+
return n;
|
|
360
|
+
}
|
|
361
|
+
function integerParam(value, name, max) {
|
|
362
|
+
if (value === null)
|
|
363
|
+
return 0;
|
|
364
|
+
if (!/^\d+$/.test(value) || !Number.isSafeInteger(Number(value)) || Number(value) > max)
|
|
365
|
+
throw new ApiError("bad_request", `${name} is an integer from 0 to ${max}`);
|
|
366
|
+
return Number(value);
|
|
367
|
+
}
|
|
368
|
+
/** The agent homes 0.1.0-beta.26 and earlier kept in the data directory (`<data>/<agent>/agent.sqlite`, an agent named
|
|
369
|
+
* `runs` or a symlinked home included), which this version's store does not read: their agents and runs would not
|
|
370
|
+
* show. This version keeps no `agent.sqlite` under the data directory. */
|
|
371
|
+
async function oldHomes(data) {
|
|
372
|
+
const found = [];
|
|
373
|
+
for (const name of await readdir(data)) {
|
|
374
|
+
const file = join(data, name, "agent.sqlite");
|
|
375
|
+
if (await stat(file).then((info) => info.isFile(), () => false))
|
|
376
|
+
found.push(file);
|
|
377
|
+
}
|
|
378
|
+
return found.sort();
|
|
379
|
+
}
|
|
380
|
+
export async function startServe(options) {
|
|
381
|
+
await mkdir(resolve(options.data), { recursive: true, mode: 0o700 });
|
|
382
|
+
// Canonical once, here: a box's mount source below it must then be its own canonical path, through no link (run-box.ts).
|
|
383
|
+
const data = await realpath(resolve(options.data));
|
|
384
|
+
// What only reads and refuses comes first: a start refused for it creates nothing in the data root, server.lock included.
|
|
385
|
+
const homes = await oldHomes(data);
|
|
386
|
+
if (homes.length) {
|
|
387
|
+
const named = homes.length > 5 ? [...homes.slice(0, 5), `and ${homes.length - 5} more`] : homes;
|
|
388
|
+
throw new Error(`this data directory holds agent homes from AgentRun Server 0.1.0-beta.26 or earlier (${named.join(", ")}), which this version does not read: started here, it would show none of their agents or runs. Keep them with the earlier version, or move those directories out of ${data} to start this one; see "Upgrading from 0.1.0-beta.26" in the serve README.`);
|
|
389
|
+
}
|
|
390
|
+
if (options.token !== undefined && (options.token.length < 32 || /\s/.test(options.token)))
|
|
391
|
+
throw new Error("the token must be 32 characters or more, with no whitespace");
|
|
392
|
+
if (options.drainTimeout !== undefined && durationMs(options.drainTimeout) === undefined)
|
|
393
|
+
throw new Error(`the drain timeout ${options.drainTimeout} is not a duration such as 8s`);
|
|
394
|
+
enabledBoxes(process.env);
|
|
395
|
+
boxLimitsOf(process.env);
|
|
396
|
+
const maxRuns = maxRunsOf(process.env, options.maxRuns);
|
|
397
|
+
const learning = learningOf(process.env, options.learning);
|
|
398
|
+
const learningBudget = learningBudgetOf(process.env, options.learningBudget);
|
|
399
|
+
const minFreeMib = process.env.AGENTRUN_MIN_FREE_MB ? Number(process.env.AGENTRUN_MIN_FREE_MB) : MIN_FREE_MIB;
|
|
400
|
+
if (!(Number.isFinite(minFreeMib) && minFreeMib >= 0))
|
|
401
|
+
throw new Error("AGENTRUN_MIN_FREE_MB is a number of MiB, 0 or more");
|
|
402
|
+
const minFreeBytes = options.minFreeBytes ?? minFreeMib * 2 ** 20;
|
|
403
|
+
// Then one server per data root, before anything writes it: a refused second server writes no token, opens no store,
|
|
404
|
+
// adopts or sweeps no run, binds no port and prints no address (server-lock.ts). A failed start releases the lock and
|
|
405
|
+
// leaves the file, which the next server reuses: unlinking it would race a server that opens it meanwhile. A server
|
|
406
|
+
// that is stopping (its runs' processes still drain) is waited for, up to the time its mark gives, not refused.
|
|
407
|
+
const lock = await takeServerLockAfterStop(data, {
|
|
408
|
+
waiting: ({ pid, until }) => noticeOf(options)(`the server on this data root (pid ${pid}) is stopping; waiting for it, up to ${seconds(until - Date.now())}`),
|
|
409
|
+
});
|
|
410
|
+
// What a start that fails stops before the lock goes: the webhook deliveries it began, which would write the next
|
|
411
|
+
// server's outbox.
|
|
412
|
+
const stops = [];
|
|
413
|
+
try {
|
|
414
|
+
// The server's record, which its stop rewrites in place (server-lock.ts): made now, so the stop makes nothing.
|
|
415
|
+
markRunning(data);
|
|
416
|
+
return await startHolding(options, data, lock, { maxRuns, minFreeBytes, learning, learningBudget }, stops);
|
|
417
|
+
}
|
|
418
|
+
catch (error) {
|
|
419
|
+
for (const stop of stops)
|
|
420
|
+
await stop().catch(() => undefined);
|
|
421
|
+
lock.release();
|
|
422
|
+
throw error;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
async function startHolding(options, data, lock, checked, stops) {
|
|
426
|
+
const { maxRuns, minFreeBytes, learning, learningBudget } = checked;
|
|
427
|
+
const tokenFile = options.token === undefined ? join(data, TOKEN_FILE) : null;
|
|
428
|
+
const stored = options.token === undefined ? await tokenIn(tokenFile) : undefined;
|
|
429
|
+
const token = options.token ?? stored.token;
|
|
430
|
+
const doorTokenFile = join(data, DOOR_TOKEN_FILE);
|
|
431
|
+
const { token: doorToken } = await tokenIn(doorTokenFile);
|
|
432
|
+
const log = options.log;
|
|
433
|
+
const quiet = process.env.AGENTRUN_LOG === "quiet";
|
|
434
|
+
const authFailed = (route, reason) => log?.(logLine("auth_failed", { route, reason }));
|
|
435
|
+
/** The host's secrets as a run's notes are checked against (learning-run.ts), and the keys a person saved on this
|
|
436
|
+
* server (storedKeys, below), read at each call: a person's note, and every learning text read. */
|
|
437
|
+
const learningSecrets = () => [...hostSecrets(process.env, storedKeys), token, doorToken];
|
|
438
|
+
const base = { ...withoutFaux(process.env), [DATA_ENV]: data, ...(options.allowCodeNodes ? { [CODE_NODES_ENV]: "1" } : {}), ...(options.faux ? { [FAUX_ENV]: resolve(options.faux) } : {}), ...(options.fauxHarness ? { [FAUX_HARNESS_ENV]: resolve(options.fauxHarness) } : {}) };
|
|
439
|
+
// Which fields are the server's is read from what it is started with alone: handed the saved keys too, ToolKeys would
|
|
440
|
+
// call each the server's, and none could be deleted.
|
|
441
|
+
const toolKeys = new ToolKeys(data, withSecrets(base, "own"), (fields) => (log ? log(logLine("tool_keys", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("tool_keys", fields)}\n`)));
|
|
442
|
+
// A key's check as it is saved (key-check.ts) goes to its provider; under faux only to the tests' fake for that provider,
|
|
443
|
+
// the one its runs are given (monid, Parallel, TypeSafe's Jev), never to the network: one with no fake is not checked.
|
|
444
|
+
const fakes = { monid: options.fauxMonid, parallel: options.fauxParallel, typesafe: options.fauxJev };
|
|
445
|
+
const checkFetch = async (id) => {
|
|
446
|
+
if (!options.faux)
|
|
447
|
+
return fetch;
|
|
448
|
+
const fake = fakes[id];
|
|
449
|
+
return fake ? (await import(pathToFileURL(resolve(fake)).href)).default : undefined;
|
|
450
|
+
};
|
|
451
|
+
// Aborted as close() begins: a key's check still waiting on its provider stops waiting, and its save stores nothing.
|
|
452
|
+
const stopping = new AbortController();
|
|
453
|
+
// This server's saved keys, read by name: handed to its own reading and its own runs, never shared with another server.
|
|
454
|
+
const storedKeys = (name) => toolKeys.value(name);
|
|
455
|
+
// A stored key that does not open is said once at the start, never a refusal to start.
|
|
456
|
+
toolKeys.view();
|
|
457
|
+
const mcpServers = new McpServers(data, withSecrets(base, "own"), VERSION);
|
|
458
|
+
// The server's tool settings, beside the agent store: capabilities say what they resolve to, again after a PUT.
|
|
459
|
+
const settings = new ToolSettings(data);
|
|
460
|
+
// The server's reading, in parts: `env`, its environment with its secrets, saved keys among them (storedKeys);
|
|
461
|
+
// `offers`, what each harness offers, probed from env without the tool keys (offersEnvOf), the one slow part (each
|
|
462
|
+
// CLI's package and pins, codex's binary hashed); and `caps`, the capabilities document made from both under the tool
|
|
463
|
+
// settings and the box offers. A write remakes only the parts it changes, before it answers: a PUT of the tool
|
|
464
|
+
// settings, caps; a save or delete of a key, env and caps, and the offers only when what they are made from changed,
|
|
465
|
+
// which no tool key is. So a write answers at once, and capabilities, save checks and run checks after it see it, with
|
|
466
|
+
// no restart and no request opening the file. The offers are probed once saved keys are read (below), at the start.
|
|
467
|
+
let env = withSecrets(base, "all", storedKeys);
|
|
468
|
+
let offers;
|
|
469
|
+
let caps;
|
|
470
|
+
// Whether a revision that names no model runs (needsOf): made from env alone, so remade with it, before the caps.
|
|
471
|
+
let needs = await needsOf(env);
|
|
472
|
+
// The box offers are probed once, below, before the first reading is made.
|
|
473
|
+
const recompose = () => void (caps = capabilitiesWith(env, maxRuns, offers, learning, needs, settings.get(), boxOffers, options.gradeModel));
|
|
474
|
+
// What the offers held now were made from (offersInputs), and the latest probe: one a later probe overtook is dropped.
|
|
475
|
+
let offersFrom;
|
|
476
|
+
let probes = 0;
|
|
477
|
+
const probe = async (why) => {
|
|
478
|
+
const mine = ++probes;
|
|
479
|
+
const from = offersInputs(env);
|
|
480
|
+
const started = performance.now();
|
|
481
|
+
const next = await harnessOffers(offersEnvOf(env));
|
|
482
|
+
log?.(logLine("harness_offers", { why, ms: Math.round(performance.now() - started) }));
|
|
483
|
+
if (mine !== probes)
|
|
484
|
+
return;
|
|
485
|
+
[offers, offersFrom] = [next, from];
|
|
486
|
+
recompose();
|
|
487
|
+
};
|
|
488
|
+
/** After a save or delete of a key, the one writer of its file: env again, then what reads it. Writes can overlap
|
|
489
|
+
* (needsOf may wait, and another write lands meanwhile): the latest write's `needs` stands, an earlier one's that
|
|
490
|
+
* finishes after it is dropped. */
|
|
491
|
+
let needsAsked = 0;
|
|
492
|
+
const keysChanged = async () => {
|
|
493
|
+
// A run's learning, as its view, a list and its timeline row show it, is cut of the keys saved now (runs.ts).
|
|
494
|
+
runs.keysChanged();
|
|
495
|
+
env = withSecrets(base, "all", storedKeys);
|
|
496
|
+
const mine = ++needsAsked;
|
|
497
|
+
const next = await needsOf(env);
|
|
498
|
+
if (mine === needsAsked)
|
|
499
|
+
needs = next;
|
|
500
|
+
const inputs = offersInputs(env);
|
|
501
|
+
if (offersFrom && inputs.length === offersFrom.length && inputs.every((value, i) => value === offersFrom[i]))
|
|
502
|
+
recompose();
|
|
503
|
+
else
|
|
504
|
+
await probe("key");
|
|
505
|
+
};
|
|
506
|
+
// The boxes AGENTRUN_BOXES lists, each probed once (boxes.ts); runs execute in Docker's (place.ts). Under --faux, a faux
|
|
507
|
+
// box stands in for Docker, and nothing asks Docker.
|
|
508
|
+
const boxes = await boxRegistry(env);
|
|
509
|
+
const fauxBox = options.faux && options.fauxBox ? await fauxBoxes(resolve(options.fauxBox), data) : undefined;
|
|
510
|
+
// The Docker box's image, asked of Docker now and pulled in the background when Docker has none (box-image.ts): docker
|
|
511
|
+
// is preparing until it is in, and unavailable if the pull fails. Its record tells the run's processes; with no Docker
|
|
512
|
+
// box here there is none, so no run waits on one an earlier start left.
|
|
513
|
+
let image;
|
|
514
|
+
const offersNow = () => boxes.offers().map((offer) => (fauxBox && offer.id === "docker" ? { id: "docker", available: true, reason: "a faux box (tests)" } : offer.id === "docker" && image ? withImage(offer, image.state()) : offer));
|
|
515
|
+
const imageLog = (state, more = {}) => log?.(logLine("box_image", { image: image.image, state: state.state, ...more, ...("reason" in state ? { reason: state.reason } : {}) }));
|
|
516
|
+
let boxOffers = offersNow();
|
|
517
|
+
const boxImage = !fauxBox && boxes.provider("docker") ? boxImageOf(env) : undefined;
|
|
518
|
+
if (boxImage) {
|
|
519
|
+
image = await dockerImage(env, data, boxImage, {
|
|
520
|
+
warn: (message) => (log ? log(logLine("box_image", { image: boxImage, warning: message })) : void process.stderr.write(`agentrun-serve: ${message}\n`)),
|
|
521
|
+
onChange: (state, ms) => {
|
|
522
|
+
boxOffers = offersNow();
|
|
523
|
+
imageLog(state, { ms });
|
|
524
|
+
// The box's state is in caps alone, not in the offers: recomposed now, or, while the start's probe of the offers
|
|
525
|
+
// has not ended, by that probe, which reads the box offers when it does.
|
|
526
|
+
if (offers)
|
|
527
|
+
recompose();
|
|
528
|
+
},
|
|
529
|
+
});
|
|
530
|
+
stops.push(async () => void (await image?.close()));
|
|
531
|
+
}
|
|
532
|
+
else
|
|
533
|
+
await clearImage(data);
|
|
534
|
+
boxOffers = offersNow();
|
|
535
|
+
const runBoxes = fauxBox ?? boxes.provider("docker");
|
|
536
|
+
// Daytona's boxes are made, seeded, pulled and destroyed here, with the key this server holds; a run's process reaches
|
|
537
|
+
// its own through the relay below, which holds the key for it (box-relay.ts).
|
|
538
|
+
const remoteBoxes = boxes.provider("daytona");
|
|
539
|
+
log?.(logLine("boxes", boxesLog(boxOffers, enabledBoxes(env))));
|
|
540
|
+
if (image)
|
|
541
|
+
imageLog(image.state());
|
|
542
|
+
const openapi = openapiDocument((operationId) => ROUTES.find((r) => r.name === operationId)?.capability);
|
|
543
|
+
const agents = new Agents(data);
|
|
544
|
+
const webhooks = new Webhooks(data, env, (fields) => (log ? log(logLine("webhook", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("webhook", fields)}\n`)), options.webhookRetryMs);
|
|
545
|
+
stops.push(() => webhooks.close());
|
|
546
|
+
const uploads = new Uploads(join(data, UPLOADS_DIR));
|
|
547
|
+
// Under the data directory's lock and before this server answers anything, so no PUT of its own is in flight: an upload
|
|
548
|
+
// temp file found now is a crashed one's.
|
|
549
|
+
const swept = await uploads.sweep();
|
|
550
|
+
if (swept > 0)
|
|
551
|
+
log?.(logLine("uploads_swept", { removed: swept }));
|
|
552
|
+
const documents = options.documents ?? process.env[DOCUMENTS_ENV];
|
|
553
|
+
if (documents !== undefined && !(await stat(documents).then((info) => info.isDirectory(), () => false)))
|
|
554
|
+
throw new Error(`the documents directory ${documents} is not a directory`);
|
|
555
|
+
const runs = new Runs({ agents, token, storedKeys, doorTokenFile, doorToken, learning, learningBudget, ...(documents ? { documents: resolve(documents) } : {}), fauxEnv: fauxEnvOf(options), toolSettings: () => settings.get(), ...(runBoxes ? { runBoxes } : {}), ...(remoteBoxes ? { remoteBoxes } : {}), ...(remoteBoxes && daytonaApi(env) ? { remoteApi: daytonaApi(env) } : {}), ...(options.drainTimeout ? { drainTimeout: options.drainTimeout } : {}), ...(options.carryBackRetry ? { carryBackRetry: options.carryBackRetry } : {}), maxRuns, ...(options.box ? { box: { host: options.box, quarantine: await Quarantine.open(join(data, BOX_QUARANTINE)) } } : {}), ...(options.settleRetryMs ? { settleRetryMs: options.settleRetryMs } : {}), ...(options.readyTimeoutMs ? { readyTimeoutMs: options.readyTimeoutMs } : {}), ...(options.reflectTimeoutMs ? { reflectTimeoutMs: options.reflectTimeoutMs } : {}), ...(options.gradeTimeoutMs ? { gradeTimeoutMs: options.gradeTimeoutMs } : {}), ...(options.gradeModel ? { gradeModel: options.gradeModel } : {}), ...(log ? { log: (event, fields) => log(logLine(event, fields)) } : {}), notify: (event, run, marker) => webhooks.emit(event, run, marker) });
|
|
556
|
+
const daytona = daytonaApi(env);
|
|
557
|
+
const relay = remoteBoxes && daytona ? await startBoxRelay({ root: data, tokenOf: (id) => runs.relayToken(id), ...daytona, serves: (id) => runs.servesBox(id), ensure: (id) => runs.ensureBox(id) }) : undefined;
|
|
558
|
+
if (relay)
|
|
559
|
+
stops.push(() => relay.close());
|
|
560
|
+
const expected = digest(`Bearer ${token}`);
|
|
561
|
+
if (options.beforeAbort)
|
|
562
|
+
runs.beforeAbort = options.beforeAbort;
|
|
563
|
+
if (options.beforeReopenLaunch)
|
|
564
|
+
runs.beforeReopenLaunch = options.beforeReopenLaunch;
|
|
565
|
+
if (options.beforeSubmit)
|
|
566
|
+
runs.beforeSubmit = options.beforeSubmit;
|
|
567
|
+
const keptFile = join(data, IDEMPOTENCY_FILE);
|
|
568
|
+
const kept = JSON.parse(await readFile(keptFile, "utf8").catch(() => "null"));
|
|
569
|
+
const idempotency = new Map((kept?.entries ?? []).filter(([, v]) => v?.answer && Date.now() - v.at <= IDEMPOTENCY_TTL_S * 1000));
|
|
570
|
+
// A failed save rejects only its own caller: the next save starts from a settled chain and writes every kept key.
|
|
571
|
+
let saving = Promise.resolve();
|
|
572
|
+
const keep = () => (saving = saving
|
|
573
|
+
.catch(() => undefined)
|
|
574
|
+
.then(async () => {
|
|
575
|
+
const entries = [...idempotency].filter(([, v]) => v.answer);
|
|
576
|
+
await writeFile(`${keptFile}.partial`, JSON.stringify({ version: 1, entries }), { mode: 0o600 });
|
|
577
|
+
await rename(`${keptFile}.partial`, keptFile);
|
|
578
|
+
}));
|
|
579
|
+
const host = options.host ?? "127.0.0.1";
|
|
580
|
+
const owner = options.accounts ? new Owner(data, options.openSetup === true, (line) => void process.stdout.write(`${line}\n`), options.signInAddresses) : undefined;
|
|
581
|
+
// A saved key is read by name from here, past the checks that refuse a start and before any run (a recovered one too)
|
|
582
|
+
// is launched: each launch hands over what is saved then. One server in a process reads them: the last started.
|
|
583
|
+
await probe("start");
|
|
584
|
+
// Decided once, by the probe the confinement walks by: capabilities.home.writes says what PUT and DELETE do.
|
|
585
|
+
const homeWrites = caps.home.writes;
|
|
586
|
+
// Runs an earlier server left: supervised again, carried back when they already ended, or opened again. Then, however
|
|
587
|
+
// that went, the webhook's ledger against the agent store: waits of runs ended or gone dropped, and each end it lacks
|
|
588
|
+
// queued. Each is its own step: a recovery that gives up (a store busy past its wait) still lets the catch-up run, and a
|
|
589
|
+
// step that gives up is said, the next start trying it again.
|
|
590
|
+
void runs
|
|
591
|
+
.recover()
|
|
592
|
+
.catch((error) => void process.stderr.write(`agentrun-serve: recovery: ${error.message}\n`))
|
|
593
|
+
.then(async () => {
|
|
594
|
+
const rows = (await agents.request(() => agents.store.listRuns())).filter((row) => !row.importedFrom);
|
|
595
|
+
const byId = new Map(rows.map((row) => [row.id, row]));
|
|
596
|
+
// An end's notice from its row and its serve.json alone, as the run list reads an ended run (summaryOfRow): never
|
|
597
|
+
// its own store, whose read can fail, so a busy store loses no end. The same body a live end's notice has.
|
|
598
|
+
await webhooks.catchUp(rows, async (id) => {
|
|
599
|
+
const row = byId.get(id);
|
|
600
|
+
if (!row)
|
|
601
|
+
return null;
|
|
602
|
+
const meta = await readJson(join(agents.dir, "runs", id, RUN_META));
|
|
603
|
+
return { run_id: id, agent_id: row.agent, status: await runs.statusOfRow(row), title: isObject(meta) && typeof meta.title === "string" ? meta.title : "" };
|
|
604
|
+
});
|
|
605
|
+
})
|
|
606
|
+
.catch((error) => void process.stderr.write(`agentrun-serve: the webhook's catch-up: ${error.message}\n`));
|
|
607
|
+
// Setup's import of this machine's sessions: offered by a server on this machine only (no public address, listening
|
|
608
|
+
// on loopback), counted once (a listing, no transcript kept), run once, each on a worker thread (import-worker.ts) so
|
|
609
|
+
// a busy store's wait and the sessions' parsing never hold up a request.
|
|
610
|
+
const offersImport = options.openSetup === true && options.publicUrl === undefined && isLoopback(host);
|
|
611
|
+
let closing = false;
|
|
612
|
+
const workers = new Map();
|
|
613
|
+
// Once the server closes, no worker starts: a setup still being answered then leaves its yes for the next start.
|
|
614
|
+
const onWorker = (task) => closing ? Promise.resolve({ stopped: true }) : new Promise((answered, failed) => {
|
|
615
|
+
const worker = new Worker(new URL("./import-worker.js", import.meta.url), {
|
|
616
|
+
// The secrets this process holds (secrets.ts keeps them out of every environment, so the worker's has none), and
|
|
617
|
+
// the keys saved on its Tool keys page, opened now (each cut too, the same rule as the CLI's import: a saved key
|
|
618
|
+
// and the server's own of the same name may differ), in the worker's memory alone: what the import cuts out of
|
|
619
|
+
// everything it writes.
|
|
620
|
+
workerData: { task, data, home: options.sessionsHome?.home ?? homedir(), ...(options.sessionsHome?.temp ? { temp: options.sessionsHome.temp } : {}), secrets: Object.fromEntries(SECRET_NAMES.flatMap((name) => { const value = secret(name); return value === undefined ? [] : [[name, value]]; })), stored: toolKeys.values() },
|
|
621
|
+
// Started from a string (its launcher runs node --input-type=module -e), the server's flags are given again
|
|
622
|
+
// without that string and its type: a worker started from a file with them is refused. Otherwise the worker
|
|
623
|
+
// inherits them as Node passes them on, which leaves out the flags a worker may not take (on Node 24 a test
|
|
624
|
+
// runner's child holds many).
|
|
625
|
+
...(process.execArgv.some((arg) => arg.startsWith("--input-type")) ? { execArgv: workerArgs(process.execArgv) } : {}),
|
|
626
|
+
});
|
|
627
|
+
workers.set(worker, { task, exit: once(worker, "exit").catch(() => undefined) });
|
|
628
|
+
let answer;
|
|
629
|
+
worker.on("message", (message) => void (answer = message));
|
|
630
|
+
worker.once("error", failed);
|
|
631
|
+
worker.once("exit", (code) => {
|
|
632
|
+
workers.delete(worker);
|
|
633
|
+
if (answer)
|
|
634
|
+
answered(answer);
|
|
635
|
+
// A count the close ended: stopped, not failed (the next start counts again).
|
|
636
|
+
else if (closing && task === "plan")
|
|
637
|
+
answered({ stopped: true });
|
|
638
|
+
else
|
|
639
|
+
failed(new Error(`the import's worker ended (${code}) with no answer`));
|
|
640
|
+
});
|
|
641
|
+
});
|
|
642
|
+
// The count of what setup would import: started once (at start, or by the page's first read), read as it stands. One
|
|
643
|
+
// stopped (by close, or by setup) starts again on the next read; one that failed stays failed.
|
|
644
|
+
let count;
|
|
645
|
+
const countSessions = () => {
|
|
646
|
+
if (count)
|
|
647
|
+
return;
|
|
648
|
+
count = { state: "counting" };
|
|
649
|
+
onWorker("plan").then((answer) => void (count = "sessions" in answer ? { state: "counted", projects: answer.projects, sessions: answer.sessions } : undefined), (error) => {
|
|
650
|
+
count = { state: "failed" };
|
|
651
|
+
process.stderr.write(`agentrun-serve: the count of this machine's sessions failed: ${error.message}\n`);
|
|
652
|
+
});
|
|
653
|
+
};
|
|
654
|
+
const stopCount = () => { for (const [worker, { task }] of workers)
|
|
655
|
+
if (task === "plan")
|
|
656
|
+
worker.postMessage("stop"); };
|
|
657
|
+
// The owner's yes, kept until the import ends: a server stopped (or killed) mid-import goes on with it at its next start.
|
|
658
|
+
const importAsked = join(data, IMPORT_ASKED);
|
|
659
|
+
let importing;
|
|
660
|
+
/** The import at setup as the owner's console reads it: running, done with what it took, or stopped (the next start
|
|
661
|
+
* goes on with it). */
|
|
662
|
+
let importState;
|
|
663
|
+
/** Never rejects: whatever stops it (the store held past its wait, a file) is said on stderr, and the server goes on. */
|
|
664
|
+
const importAtSetup = () => (importing ??= (async () => {
|
|
665
|
+
importState = { state: "running" };
|
|
666
|
+
try {
|
|
667
|
+
const answer = await onWorker("import");
|
|
668
|
+
if (!("took" in answer))
|
|
669
|
+
return void (importState = { state: "stopped" });
|
|
670
|
+
// The whole import, every start's part of it: what earlier starts took is kept with the owner's yes.
|
|
671
|
+
// The yes as setup wrote it is empty: no earlier start took anything.
|
|
672
|
+
const before = (await readJson(importAsked));
|
|
673
|
+
const agents = [...new Set([...(Array.isArray(before?.agents) ? before.agents.filter((id) => typeof id === "string") : []), ...answer.took.agents])];
|
|
674
|
+
const runs = (typeof before?.runs === "number" ? before.runs : 0) + answer.took.runs;
|
|
675
|
+
if (answer.stopped) {
|
|
676
|
+
await writeDurable(importAsked, JSON.stringify({ agents, runs }));
|
|
677
|
+
return void (importState = { state: "stopped" });
|
|
678
|
+
}
|
|
679
|
+
await rm(importAsked, { force: true });
|
|
680
|
+
const took = { agents: agents.length, runs, skipped: answer.took.skipped };
|
|
681
|
+
importState = { state: "done", ...took };
|
|
682
|
+
process.stdout.write(`${logLine("import", took)}\n`);
|
|
683
|
+
}
|
|
684
|
+
catch (error) {
|
|
685
|
+
importState = { state: "stopped" };
|
|
686
|
+
if (!closing)
|
|
687
|
+
process.stderr.write(`agentrun-serve: the import at setup stopped (the next start goes on with it): ${error.message}\n`);
|
|
688
|
+
}
|
|
689
|
+
})());
|
|
690
|
+
// ---- helpers --------------------------------------------------------------------------------------------------------
|
|
691
|
+
/** The body's bytes, at most MAX_BODY of them. */
|
|
692
|
+
async function bytesOf(req) {
|
|
693
|
+
const chunks = [];
|
|
694
|
+
let size = 0;
|
|
695
|
+
// An oversized body is read to its end before the refusal, so the client gets the answer and not a reset.
|
|
696
|
+
for await (const chunk of req) {
|
|
697
|
+
size += chunk.length;
|
|
698
|
+
if (size <= MAX_BODY)
|
|
699
|
+
chunks.push(chunk);
|
|
700
|
+
}
|
|
701
|
+
if (size > MAX_BODY)
|
|
702
|
+
throw new ApiError("payload_too_large", `the body is over ${MAX_BODY} bytes`, { details: { limit: "max_body_bytes" } });
|
|
703
|
+
return Buffer.concat(chunks);
|
|
704
|
+
}
|
|
705
|
+
async function bodyOf(req) {
|
|
706
|
+
const type = String(req.headers["content-type"] ?? "");
|
|
707
|
+
if (!type.startsWith("application/json"))
|
|
708
|
+
throw new ApiError("unsupported_media_type", "the body must be application/json");
|
|
709
|
+
const bytes = await bytesOf(req);
|
|
710
|
+
let value;
|
|
711
|
+
try {
|
|
712
|
+
value = JSON.parse(bytes.toString("utf8") || "null");
|
|
713
|
+
}
|
|
714
|
+
catch {
|
|
715
|
+
throw new ApiError("bad_request", "the body is not JSON");
|
|
716
|
+
}
|
|
717
|
+
if (!isObject(value))
|
|
718
|
+
throw new ApiError("bad_request", "the body is not a JSON object");
|
|
719
|
+
return value;
|
|
720
|
+
}
|
|
721
|
+
async function needAgent(id) {
|
|
722
|
+
const entry = ID.test(id) ? await agents.get(id) : null;
|
|
723
|
+
if (!entry)
|
|
724
|
+
throw new ApiError("not_found", `no agent ${id}`);
|
|
725
|
+
return entry;
|
|
726
|
+
}
|
|
727
|
+
async function needRun(id) {
|
|
728
|
+
const run = ID.test(id) ? await runs.get(id) : null;
|
|
729
|
+
if (!run)
|
|
730
|
+
throw new ApiError("not_found", `no run ${id}`);
|
|
731
|
+
return run;
|
|
732
|
+
}
|
|
733
|
+
/** Replays the first answer to a create with the same key and body; another body is a mismatch. */
|
|
734
|
+
async function idempotent(req, path, body, work) {
|
|
735
|
+
const key = req.headers["idempotency-key"];
|
|
736
|
+
if (key === undefined)
|
|
737
|
+
return work();
|
|
738
|
+
if (typeof key !== "string" || key.length < 1 || key.length > 255)
|
|
739
|
+
throw new ApiError("bad_request", "Idempotency-Key is 1 to 255 characters");
|
|
740
|
+
const slot = `${path}\n${key}`;
|
|
741
|
+
const fingerprint = stable(body);
|
|
742
|
+
const now = Date.now();
|
|
743
|
+
for (const [k, v] of idempotency)
|
|
744
|
+
if (now - v.at > IDEMPOTENCY_TTL_S * 1000)
|
|
745
|
+
idempotency.delete(k);
|
|
746
|
+
const known = idempotency.get(slot);
|
|
747
|
+
if (known) {
|
|
748
|
+
if (known.fingerprint !== fingerprint)
|
|
749
|
+
throw new ApiError("idempotency_mismatch", "this Idempotency-Key was used with another body");
|
|
750
|
+
if (!known.answer)
|
|
751
|
+
throw new ApiError("idempotency_in_progress", "the first request with this Idempotency-Key is still in flight", { retry_after_ms: 500 });
|
|
752
|
+
return { ...known.answer, headers: { ...known.answer.headers, "idempotent-replayed": "true" } };
|
|
753
|
+
}
|
|
754
|
+
idempotency.set(slot, { fingerprint, at: now });
|
|
755
|
+
let answer;
|
|
756
|
+
try {
|
|
757
|
+
answer = await work();
|
|
758
|
+
}
|
|
759
|
+
catch (error) {
|
|
760
|
+
idempotency.delete(slot);
|
|
761
|
+
throw error;
|
|
762
|
+
}
|
|
763
|
+
// The work happened, so the key keeps its answer in memory even when the file write fails: a retry replays it
|
|
764
|
+
// instead of doing the work twice. Only a restart before the next good save loses it.
|
|
765
|
+
idempotency.set(slot, { fingerprint, at: now, answer: { status: answer.status, body: answer.body, headers: answer.headers ?? {} } });
|
|
766
|
+
await keep().catch((error) => void process.stderr.write(`agentrun-serve: idempotency save: ${error.message}\n`));
|
|
767
|
+
return answer;
|
|
768
|
+
}
|
|
769
|
+
// ---- runs -----------------------------------------------------------------------------------------------------------
|
|
770
|
+
/** A workflow revision's shape as runnable.ts checks it: its workflow, tools, harness, place and tool settings. */
|
|
771
|
+
const workflowShape = ({ workflow, tools, harness, place, toolSettings }) => ({ kind: "workflow", workflow, tools: tools ?? [], ...(harness ? { harness } : {}), ...(place ? { place } : {}), ...(toolSettings ? { toolSettings } : {}) });
|
|
772
|
+
const shapeOf = (revision) => (revision.kind === "agentic" ? { kind: "agentic", ...revision.body } : workflowShape(revision.body));
|
|
773
|
+
/** What keeps `revision` from running here at `place` (its own, else this host's default), checked before anything
|
|
774
|
+
* starts with the checks a save makes (runnable.ts): one a save refused, or one a setting of this host fixes that it
|
|
775
|
+
* does not have yet. `capped`: the run has a spend cap, which a web tool's resolution reads (tool-plane.ts). */
|
|
776
|
+
async function runnable(revision, place, { capped = false } = {}) {
|
|
777
|
+
const shape = { ...shapeOf(revision), place };
|
|
778
|
+
const blockers = await blockersOf(env, shape, settings.get(), { capped, boxes: boxOffers, offers });
|
|
779
|
+
if (!blockers.length)
|
|
780
|
+
return;
|
|
781
|
+
const message = blockers.map((b) => b.message).join(" ");
|
|
782
|
+
const unbound = blockers.flatMap((b) => (b.tool ? [b.tool] : []));
|
|
783
|
+
const missing = Object.fromEntries(blockers.flatMap((b) => (b.missing ? [[b.missing.tool, b.missing.vars]] : [])));
|
|
784
|
+
const harness = blockers.find((b) => b.harness)?.harness;
|
|
785
|
+
const box = blockers.find((b) => b.box)?.box;
|
|
786
|
+
const named = { ...(harness ? { harness } : {}), ...(box ? { box } : {}) };
|
|
787
|
+
if (revision.kind === "agentic")
|
|
788
|
+
throw new ApiError("agent_not_runnable", message, { details: { unbound, missing, ...named } });
|
|
789
|
+
const tier = blockers.find((b) => b.tier)?.tier;
|
|
790
|
+
const decisions = Object.fromEntries(blockers.flatMap((b) => (b.decision ? [[b.decision.provider, { reason: b.reason, needs: b.decision.needs }]] : [])));
|
|
791
|
+
throw new ApiError("agent_not_runnable", message, { details: { adapters: [...new Set(blockers.flatMap((b) => (b.adapter ? [b.adapter] : [])))], unbound, missing, code: blockers.some((b) => b.codeNodes || b.shell), ...(tier ? { tier } : {}), ...(Object.keys(decisions).length ? { decisions } : {}), ...named } });
|
|
792
|
+
}
|
|
793
|
+
/** A definition being saved: refused (422 by field) when it can never run here; else what this host still lacks. */
|
|
794
|
+
async function saveable(revision) {
|
|
795
|
+
const blockers = await blockersOf(env, revision.kind === "agentic" ? revision : workflowShape(revision), settings.get(), { boxes: boxOffers, offers });
|
|
796
|
+
const never = blockers.filter((b) => !b.host);
|
|
797
|
+
if (never.length)
|
|
798
|
+
throw invalid(never.map(issueOf));
|
|
799
|
+
return blockers.map(issueOf);
|
|
800
|
+
}
|
|
801
|
+
/** A run's input: an agentic run's `{content: string}`, a workflow run's what its workflow's input schema takes. */
|
|
802
|
+
async function inputIssuesOf(revision, input) {
|
|
803
|
+
if (revision.kind === "agentic")
|
|
804
|
+
return inputIssues(input, DEFAULT_INPUT_SCHEMA);
|
|
805
|
+
const { validateWorkflow } = await import("@parcha/agentrun-dsl");
|
|
806
|
+
const checked = validateWorkflow(revision.body.workflow, { executeCode: false, input });
|
|
807
|
+
return checked.ok ? [] : checked.issues.map((i) => ({ field: `input${i.path ? ` at ${i.path}` : ""}`, reason: "invalid", message: `the workflow does not take this input: ${i.code}${i.path ? ` at ${i.path}` : ""}` }));
|
|
808
|
+
}
|
|
809
|
+
async function createRun(req, agentId) {
|
|
810
|
+
const entry = await needAgent(agentId);
|
|
811
|
+
if (entry.agent.archivedAt)
|
|
812
|
+
throw new ApiError("agent_not_runnable", `The agent ${agentId} is archived: unarchive it to run it.`, { details: { archived_at: entry.agent.archivedAt } });
|
|
813
|
+
const body = await bodyOf(req);
|
|
814
|
+
return idempotent(req, `/agents/${agentId}/runs`, body, async () => {
|
|
815
|
+
const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "quote_id"]);
|
|
816
|
+
if (!isObject(body.input))
|
|
817
|
+
issues.push({ field: "input", reason: body.input === undefined ? "missing" : "wrong_type", message: "input is an object" });
|
|
818
|
+
if (body.revision !== undefined && (typeof body.revision !== "string" || !ID.test(body.revision)))
|
|
819
|
+
issues.push({ field: "revision", reason: "wrong_type", message: "revision is a revision id of this agent" });
|
|
820
|
+
if (body.effort !== undefined && !EFFORTS.includes(body.effort))
|
|
821
|
+
issues.push({ field: "effort", reason: "not_an_option", message: `effort is one of ${EFFORTS.join(", ")}` });
|
|
822
|
+
if (body.max_cost_usd !== undefined && !(typeof body.max_cost_usd === "number" && body.max_cost_usd > 0))
|
|
823
|
+
issues.push({ field: "max_cost_usd", reason: "wrong_type", message: "max_cost_usd is a number above 0" });
|
|
824
|
+
if (body.file_ids !== undefined && !Array.isArray(body.file_ids))
|
|
825
|
+
issues.push({ field: "file_ids", reason: "wrong_type", message: "file_ids is a list of file ids" });
|
|
826
|
+
if (issues.length)
|
|
827
|
+
throw invalid(issues);
|
|
828
|
+
if (body.quote_id !== undefined)
|
|
829
|
+
throw unsupported("quotes", "This server has no billing, so it takes no quotes.");
|
|
830
|
+
// Each a ready file, before anything starts: copied into the run's work/inputs/ once its directory is made.
|
|
831
|
+
const files = Array.isArray(body.file_ids) ? await uploads.readyFiles(body.file_ids) : [];
|
|
832
|
+
const pinned = typeof body.revision === "string" ? await agents.revision(entry.agent.id, body.revision) : entry.revision && { revision: entry.revision, version: entry.version };
|
|
833
|
+
if (!pinned)
|
|
834
|
+
throw invalid([{ field: "revision", reason: "not_an_option", message: typeof body.revision === "string" ? `${body.revision} is not a revision of the agent ${entry.agent.id}` : `the agent ${entry.agent.id} has no current revision` }]);
|
|
835
|
+
const { revision, version } = pinned;
|
|
836
|
+
if (revision.kind === "workflow" && body.max_cost_usd !== undefined)
|
|
837
|
+
throw invalid([{ field: "max_cost_usd", reason: "not_allowed", message: "A workflow run's spend is not capped here: its cost shows once it ends." }]);
|
|
838
|
+
const input = body.input;
|
|
839
|
+
const wrong = await inputIssuesOf(revision, input);
|
|
840
|
+
if (wrong.length)
|
|
841
|
+
throw invalid(wrong);
|
|
842
|
+
const place = resolvePlace(revision.body.place);
|
|
843
|
+
await runnable(revision, place, { capped: body.max_cost_usd !== undefined });
|
|
844
|
+
const title = revision.kind === "workflow" ? workflowTitle(entry.agent.name || entry.agent.id, input) : typeof input.content === "string" ? input.content : (Object.values(input).find((v) => typeof v === "string") ?? JSON.stringify(input));
|
|
845
|
+
const run = await runs.create(entry, revision, version, { input, title, place, ...(typeof body.effort === "string" ? { effort: body.effort } : {}), ...(typeof body.max_cost_usd === "number" ? { maxCostUsd: body.max_cost_usd } : {}), ...(files.length ? { inputs: (work) => uploads.copyInto(work, files) } : {}) });
|
|
846
|
+
// Its view from the run itself: it is written, with its first message, so an answer read from the store, which a
|
|
847
|
+
// busy store would turn into home_busy, would refuse a run that runs, and a retry would start a second one.
|
|
848
|
+
return { status: 202, body: await runs.view(run, { stored: null }), headers: { location: `/v2/runs/${run.id}` } };
|
|
849
|
+
});
|
|
850
|
+
}
|
|
851
|
+
/** A page of runs from the store, newest first: `agent`, `revision` and `status` narrow it. */
|
|
852
|
+
/** A list's `archived`: true lists only what is archived, false (the default) only what is not. */
|
|
853
|
+
function archivedParam(url) {
|
|
854
|
+
const value = url.searchParams.get("archived");
|
|
855
|
+
if (value !== null && value !== "true" && value !== "false")
|
|
856
|
+
throw new ApiError("bad_request", "archived is true or false");
|
|
857
|
+
return value === "true";
|
|
858
|
+
}
|
|
859
|
+
async function runsPage(url, filter) {
|
|
860
|
+
const limit = limitOf(url.searchParams.get("limit"));
|
|
861
|
+
const offset = cursorOf(url.searchParams.get("cursor"));
|
|
862
|
+
const status = url.searchParams.get("status");
|
|
863
|
+
if (status !== null && !STATUSES.includes(status))
|
|
864
|
+
throw new ApiError("bad_request", `status is one of ${STATUSES.join(", ")}`);
|
|
865
|
+
for (const [key, value] of Object.entries(filter))
|
|
866
|
+
if (value !== undefined && !ID.test(value))
|
|
867
|
+
throw new ApiError("bad_request", `${key} is an id`);
|
|
868
|
+
const archived = archivedParam(url);
|
|
869
|
+
let rows = (await agents.request(() => agents.store.listRuns(filter))).filter((row) => Boolean(row.archivedAt) === archived);
|
|
870
|
+
if (status !== null) {
|
|
871
|
+
const statuses = await Promise.all(rows.map((row) => runs.statusOfRow(row)));
|
|
872
|
+
rows = rows.filter((_, i) => statuses[i] === status);
|
|
873
|
+
}
|
|
874
|
+
const versions = new Map();
|
|
875
|
+
for (const agent of new Set(rows.slice(offset, offset + limit).map((row) => row.agent)))
|
|
876
|
+
for (const r of await agents.revisions(agent))
|
|
877
|
+
versions.set(r.id, r.version);
|
|
878
|
+
const page = await Promise.all(rows.slice(offset, offset + limit).map((row) => runs.summaryOfRow(row, versions)));
|
|
879
|
+
return { runs: page, next_cursor: nextCursor(offset + limit, rows.length) };
|
|
880
|
+
}
|
|
881
|
+
async function timeline(req, res, url, run) {
|
|
882
|
+
const after = integerParam(url.searchParams.get("after"), "after", Number.MAX_SAFE_INTEGER);
|
|
883
|
+
const waitMs = integerParam(url.searchParams.get("wait_ms"), "wait_ms", MAX_WAIT_MS);
|
|
884
|
+
// This server's own: a page of at most `limit` rows, for a client that reads a little at a time (the MCP tool's).
|
|
885
|
+
const asked = url.searchParams.get("limit");
|
|
886
|
+
if (asked !== null && !(/^\d+$/.test(asked) && Number(asked) >= 1 && Number(asked) <= PAGE_ROWS))
|
|
887
|
+
throw new ApiError("bad_request", `limit is an integer from 1 to ${PAGE_ROWS}`);
|
|
888
|
+
const limit = asked === null ? PAGE_ROWS : Number(asked);
|
|
889
|
+
const pageOf = async (from, wait) => {
|
|
890
|
+
const page = await runs.page(run, from, wait, limit);
|
|
891
|
+
return { run_id: run.id, status: page.status, state: page.state, reset: page.reset, rows: page.rows, drop: page.drop, next_after: page.next_after, unchanged: page.unchanged, has_more: page.has_more, final: page.final, cost: runs.cost(run) };
|
|
892
|
+
};
|
|
893
|
+
if (!String(req.headers.accept ?? "").includes("text/event-stream")) {
|
|
894
|
+
const page = await pageOf(after, waitMs);
|
|
895
|
+
return send(res, 200, { ...page, poll_after_ms: page.final || page.has_more ? 0 : 1000 });
|
|
896
|
+
}
|
|
897
|
+
const last = req.headers["last-event-id"];
|
|
898
|
+
if (last !== undefined && !/^[0-9]+$/.test(String(last)))
|
|
899
|
+
throw new ApiError("bad_request", "Last-Event-ID is a change number");
|
|
900
|
+
let cursor = last !== undefined ? Number(last) : after;
|
|
901
|
+
res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache, no-transform", connection: "keep-alive", "x-content-type-options": "nosniff" });
|
|
902
|
+
const beat = setInterval(() => res.write(": keepalive\n\n"), 15_000);
|
|
903
|
+
let open = true;
|
|
904
|
+
res.once("close", () => void (open = false));
|
|
905
|
+
try {
|
|
906
|
+
for (let first = true; open; first = false) {
|
|
907
|
+
const page = await pageOf(cursor, first ? 0 : 15_000);
|
|
908
|
+
if (!open)
|
|
909
|
+
break;
|
|
910
|
+
if (first || !page.unchanged || page.final)
|
|
911
|
+
res.write(`event: rows\nid: ${page.next_after}\ndata: ${JSON.stringify(page)}\n\n`);
|
|
912
|
+
cursor = page.next_after;
|
|
913
|
+
if (page.final && !page.has_more) {
|
|
914
|
+
res.write(`event: end\ndata: ${JSON.stringify({ reason: "terminal" })}\n\n`);
|
|
915
|
+
break;
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
finally {
|
|
920
|
+
clearInterval(beat);
|
|
921
|
+
res.end();
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
const fileView = (path, st) => ({ path, size_bytes: st.size, modified_at: new Date(st.mtimeMs).toISOString(), content_type: typeOf(path) ?? null });
|
|
925
|
+
/** The files under `base` (a run's work/, an agent's home), through no link (workspace.ts): each regular file's own size
|
|
926
|
+
* and time, a dot-name left out. `deep` when a directory below WALK_DEPTH was there and not entered. In a `home`, a
|
|
927
|
+
* host-owned name at its top is the host's: named in `owned`, and nothing below it walked. */
|
|
928
|
+
async function walk(base, home = false) {
|
|
929
|
+
const out = [];
|
|
930
|
+
const owned = [];
|
|
931
|
+
let deep = false;
|
|
932
|
+
if (!(await lstat(base).catch(() => null))?.isDirectory())
|
|
933
|
+
return { files: out, deep, owned };
|
|
934
|
+
// The directory unreadable as a whole lists nothing; what the walk could not read in it is left out.
|
|
935
|
+
await walkWork(base, (path, st, readable) => {
|
|
936
|
+
if (st.isFile())
|
|
937
|
+
out.push({ ...fileView(path, st), ...(readable ? {} : { unreadable: true }) });
|
|
938
|
+
else if (st.isDirectory() && path.split("/").length > WALK_DEPTH)
|
|
939
|
+
deep = true;
|
|
940
|
+
return out.length <= FILE_LIST_CAP;
|
|
941
|
+
}, {
|
|
942
|
+
skip: (name, path) => {
|
|
943
|
+
if (name.startsWith("."))
|
|
944
|
+
return true;
|
|
945
|
+
if (!home || path !== name || !hostOwnedOf(name))
|
|
946
|
+
return false;
|
|
947
|
+
owned.push(name);
|
|
948
|
+
return true;
|
|
949
|
+
},
|
|
950
|
+
}).catch((error) => {
|
|
951
|
+
if (!(error instanceof WorkRefused))
|
|
952
|
+
throw error;
|
|
953
|
+
});
|
|
954
|
+
return { files: out, deep, owned };
|
|
955
|
+
}
|
|
956
|
+
/** The file `rel` under `root`, raw; `unreadable` says why one this server cannot read is private. */
|
|
957
|
+
async function sendFile(req, res, url, root, rel, unreadable) {
|
|
958
|
+
if (!(await lstat(root).catch(() => null))?.isDirectory())
|
|
959
|
+
throw new ApiError("not_found", "no such file");
|
|
960
|
+
// Through no link, held from the open to the last byte (workspace.ts): a name swapped for one is refused, not followed.
|
|
961
|
+
const opened = await openWorkFile(root, rel).catch((error) => {
|
|
962
|
+
if (error instanceof WorkRefused && error.reason === "unreadable")
|
|
963
|
+
throw new ApiError("system_file_forbidden", `This file was created private by ${unreadable}: this server cannot read it.`, { details: { reason: "unreadable" } });
|
|
964
|
+
return null;
|
|
965
|
+
});
|
|
966
|
+
if (!opened)
|
|
967
|
+
throw new ApiError("not_found", "no such file");
|
|
968
|
+
const { handle, stats: st } = opened;
|
|
969
|
+
const type = typeOf(rel) ?? "application/octet-stream";
|
|
970
|
+
const download = url.searchParams.get("download") === "1" || !INLINE_TYPES.has(type);
|
|
971
|
+
const name = rel.split("/").at(-1).replace(/[^\w.-]/g, "_");
|
|
972
|
+
res.writeHead(200, {
|
|
973
|
+
"content-type": type,
|
|
974
|
+
"content-length": st.size,
|
|
975
|
+
"x-content-type-options": "nosniff",
|
|
976
|
+
"cache-control": "no-store",
|
|
977
|
+
...(type.startsWith("text/html") ? { "content-security-policy": FILE_CSP } : {}),
|
|
978
|
+
...(download ? { "content-disposition": `attachment; filename="${name}"` } : {}),
|
|
979
|
+
});
|
|
980
|
+
if (req.method === "HEAD" || st.size === 0) {
|
|
981
|
+
await handle.close();
|
|
982
|
+
return void res.end();
|
|
983
|
+
}
|
|
984
|
+
await pipeline(handle.createReadStream(), res).catch(() => undefined);
|
|
985
|
+
await handle.close().catch(() => undefined);
|
|
986
|
+
}
|
|
987
|
+
// ---- an agent's home --------------------------------------------------------------------------------------------------
|
|
988
|
+
/** The agent's home, `homes/<its home key>/`: null while nothing was ever written to it, made with homes/ (0700) when
|
|
989
|
+
* `make`. Neither is ever a link: a read finds no home there, and a write is refused. */
|
|
990
|
+
async function homeDir(agentId, make) {
|
|
991
|
+
const home = homeOf(data, agentId);
|
|
992
|
+
for (const dir of [join(data, HOMES_DIR), home]) {
|
|
993
|
+
// One made is synced into its parent, so a write in it that is answered survives a crash of the machine.
|
|
994
|
+
if (make && (await mkdir(dir, { mode: 0o700 }).then(() => true, (error) => (error.code === "EEXIST" ? false : Promise.reject(error)))))
|
|
995
|
+
await syncDir(dirname(dir));
|
|
996
|
+
if ((await lstat(dir).catch(() => null))?.isDirectory())
|
|
997
|
+
continue;
|
|
998
|
+
if (make)
|
|
999
|
+
throw new WorkRefused(dir, "link");
|
|
1000
|
+
return null;
|
|
1001
|
+
}
|
|
1002
|
+
return home;
|
|
1003
|
+
}
|
|
1004
|
+
/** Refused when `rel`'s first segment is, on this disk, the same entry as a host-owned path of the home (home-path.ts):
|
|
1005
|
+
* the name check holds for the spellings it knows, and this for any other a disk takes. */
|
|
1006
|
+
async function notHostOwned(home, rel, agentId, write) {
|
|
1007
|
+
const owned = await ownedByIdentity(home, rel);
|
|
1008
|
+
if (owned)
|
|
1009
|
+
throw hostOwnedRefusal(owned, agentId, write, ownedReadAt(agentId));
|
|
1010
|
+
}
|
|
1011
|
+
/** A write to the home or a removal from it refused (workspace.ts), as its answer. */
|
|
1012
|
+
function homeRefusal(error) {
|
|
1013
|
+
if (!(error instanceof WorkRefused))
|
|
1014
|
+
throw error;
|
|
1015
|
+
if (error.reason === "link")
|
|
1016
|
+
throw new ApiError("system_file_forbidden", "A link is on the way to this path, or is the file: this server follows none.", { details: { reason: "link" } });
|
|
1017
|
+
if (error.reason === "unreadable")
|
|
1018
|
+
throw new ApiError("system_file_forbidden", "This server may not enter a directory on the way to this path.", { details: { reason: "unreadable" } });
|
|
1019
|
+
if (error.reason === "not_regular")
|
|
1020
|
+
throw new ApiError("invalid_file_path", "the path names a directory, or runs through a file");
|
|
1021
|
+
if (error.reason === "unheld")
|
|
1022
|
+
throw new ApiError("unsupported_here", HOME_WRITES_OFF);
|
|
1023
|
+
throw new ApiError("not_found", "no such file");
|
|
1024
|
+
}
|
|
1025
|
+
// ---- usage ----------------------------------------------------------------------------------------------------------
|
|
1026
|
+
// Each ended run's meters, from its store (metersIn): kept, as its store no longer changes, keyed by its end, so a run
|
|
1027
|
+
// opened again and ended again is read again. A store that cannot be read leaves it all tokens.
|
|
1028
|
+
const endedMeters = new Map();
|
|
1029
|
+
const metersOf = (row) => {
|
|
1030
|
+
const key = `${row.id} ${row.endedAt}`;
|
|
1031
|
+
let meters = endedMeters.get(key);
|
|
1032
|
+
if (!meters) {
|
|
1033
|
+
try {
|
|
1034
|
+
meters = metersIn(agents.store.runStorePath(row.id));
|
|
1035
|
+
}
|
|
1036
|
+
catch {
|
|
1037
|
+
meters = { tools: 0, tokens: null };
|
|
1038
|
+
}
|
|
1039
|
+
endedMeters.set(key, meters);
|
|
1040
|
+
}
|
|
1041
|
+
return meters;
|
|
1042
|
+
};
|
|
1043
|
+
async function usage(url) {
|
|
1044
|
+
const now = new Date();
|
|
1045
|
+
const fromText = url.searchParams.get("from");
|
|
1046
|
+
const toText = url.searchParams.get("to");
|
|
1047
|
+
const from = fromText === null ? Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1) : Date.parse(fromText);
|
|
1048
|
+
const to = toText === null ? now.getTime() : Date.parse(toText);
|
|
1049
|
+
if (!Number.isFinite(from) || !Number.isFinite(to))
|
|
1050
|
+
throw new ApiError("bad_request", "from and to are RFC 3339 times");
|
|
1051
|
+
const group = url.searchParams.get("group_by") ?? "meter";
|
|
1052
|
+
if (!["meter", "agent", "key", "day", "region"].includes(group))
|
|
1053
|
+
throw new ApiError("bad_request", "group_by is meter, agent, key, day or region");
|
|
1054
|
+
const lines = new Map();
|
|
1055
|
+
const total = { usd: 0, unpriced: 0 };
|
|
1056
|
+
// A cost that is unknown adds no dollars, so no sum turns unknown; it is counted as unpriced instead, so it never
|
|
1057
|
+
// passes as $0.
|
|
1058
|
+
const add = (key, usd) => {
|
|
1059
|
+
const line = lines.get(key) ?? lines.set(key, { usd: 0, unpriced: 0 }).get(key);
|
|
1060
|
+
for (const sum of [line, total]) {
|
|
1061
|
+
if (usd === null)
|
|
1062
|
+
sum.unpriced++;
|
|
1063
|
+
else
|
|
1064
|
+
sum.usd += usd;
|
|
1065
|
+
}
|
|
1066
|
+
};
|
|
1067
|
+
// A line's key for the ledger's entries, as each run's is above: by agent, by day, by meter, or one line.
|
|
1068
|
+
const lineKey = (agent, at, meter) => (group === "agent" ? agent : group === "day" ? at.slice(0, 10) : group === "meter" ? meter : "local");
|
|
1069
|
+
for (const row of await agents.request(() => agents.store.listRuns())) {
|
|
1070
|
+
const at = Date.parse(row.startedAt);
|
|
1071
|
+
if (!(at >= from && at < to))
|
|
1072
|
+
continue;
|
|
1073
|
+
const live = row.state === "running" ? await runs.get(row.id) : null;
|
|
1074
|
+
const usd = live ? runs.cost(live).usd : (row.costUsd ?? null);
|
|
1075
|
+
const key = group === "agent" ? row.agent : group === "day" ? row.startedAt.slice(0, 10) : group === "meter" ? "tokens" : "local";
|
|
1076
|
+
// By meter, what a run's paid tools charged (monid's) is `tools`, the rest `tokens`, both from the same records: a
|
|
1077
|
+
// live run's rows (a call still marked is no charge), else its store as it ended (a call a crash cut makes `tools`
|
|
1078
|
+
// unknown, never `tokens`). An unknown meter counts the run as unpriced on it.
|
|
1079
|
+
const meters = group !== "meter" || usd === 0 ? undefined : live ? { tools: toolCostOf(live.rows), tokens: null } : metersOf(row);
|
|
1080
|
+
const tokens = meters && (usd !== null && meters.tools !== null ? usd - meters.tools : usd === null && meters.tools === null ? meters.tokens : null);
|
|
1081
|
+
const parts = !meters ? [[key, usd]] : [[key, tokens ?? null], ...(meters.tools !== 0 ? [["tools", meters.tools]] : [])];
|
|
1082
|
+
// A run whose cost is unknown adds no dollars, so no sum turns unknown; it is counted as unpriced instead, so it
|
|
1083
|
+
// never passes as $0.
|
|
1084
|
+
for (const [name, part] of parts) {
|
|
1085
|
+
const line = lines.get(name) ?? lines.set(name, { usd: 0, unpriced: 0 }).get(name);
|
|
1086
|
+
if (part === null)
|
|
1087
|
+
line.unpriced++;
|
|
1088
|
+
else
|
|
1089
|
+
line.usd += part;
|
|
1090
|
+
}
|
|
1091
|
+
if (usd === null)
|
|
1092
|
+
total.unpriced++;
|
|
1093
|
+
else
|
|
1094
|
+
total.usd += usd;
|
|
1095
|
+
}
|
|
1096
|
+
// What learning spent on this server, outside any run (usage.ts): each run's grade, on the day its learning ended.
|
|
1097
|
+
for (const entry of (await outcomes(data)).values()) {
|
|
1098
|
+
const at = Date.parse(entry.at);
|
|
1099
|
+
if (at >= from && at < to)
|
|
1100
|
+
add(lineKey(entry.agent, entry.at, "learning"), entry.cost);
|
|
1101
|
+
}
|
|
1102
|
+
const round = (v) => Math.round(v * 1e6) / 1e6;
|
|
1103
|
+
return {
|
|
1104
|
+
from: new Date(from).toISOString(), to: new Date(to).toISOString(), currency: "USD", basis: "estimate", group_by: group, total_usd: round(total.usd), unpriced_runs: total.unpriced,
|
|
1105
|
+
lines: [...lines].map(([key, line]) => ({ group: key, ...(group === "meter" ? { meter: key } : {}), usd: round(line.usd), unpriced_runs: line.unpriced })),
|
|
1106
|
+
account: null,
|
|
1107
|
+
};
|
|
1108
|
+
}
|
|
1109
|
+
// ---- the owner ------------------------------------------------------------------------------------------------------
|
|
1110
|
+
/** A read only this server's page makes: the browser says so (Sec-Fetch-Site), or its Origin is this server's. A
|
|
1111
|
+
* same-origin GET carries no Origin and no body, so fromPage's checks would refuse the page itself. */
|
|
1112
|
+
function pageRead(req) {
|
|
1113
|
+
if (req.headers["sec-fetch-site"] === "same-origin" || req.headers.origin?.toLowerCase() === ownOrigin(req))
|
|
1114
|
+
return;
|
|
1115
|
+
throw new ApiError("forbidden", "this read must come from this server's page");
|
|
1116
|
+
}
|
|
1117
|
+
/** A write from the page: this server's own origin and a JSON body. A cookie never makes one from anywhere else. */
|
|
1118
|
+
function fromPage(req) {
|
|
1119
|
+
if (req.headers.origin?.toLowerCase() !== ownOrigin(req))
|
|
1120
|
+
throw new ApiError("forbidden", "this write must come from this server's page");
|
|
1121
|
+
if (!isJson(req))
|
|
1122
|
+
throw new ApiError("unsupported_media_type", "the body must be application/json");
|
|
1123
|
+
}
|
|
1124
|
+
/** The body's one field `name`, a password: 422 on any other field, or on one the rules refuse. */
|
|
1125
|
+
async function passwordIn(req, allowed, check = true) {
|
|
1126
|
+
const body = await bodyOf(req);
|
|
1127
|
+
const issues = unknownFields(body, allowed);
|
|
1128
|
+
const problem = check ? passwordProblem(body.password) : typeof body.password === "string" && Buffer.byteLength(body.password) <= 1024 ? undefined : "password is text, at most 1024 bytes";
|
|
1129
|
+
if (problem)
|
|
1130
|
+
issues.push({ field: "password", reason: body.password === undefined ? "missing" : "invalid", message: problem });
|
|
1131
|
+
if (issues.length)
|
|
1132
|
+
throw invalid(issues);
|
|
1133
|
+
return { password: body.password, body };
|
|
1134
|
+
}
|
|
1135
|
+
/** POST /v2/setup, POST /v2/auth/sign-in, POST /v2/auth/sign-out and GET /v2/auth/session, answered before any
|
|
1136
|
+
* credential: their own checks are the setup code (or the token), the password, and the session. */
|
|
1137
|
+
async function ownerRoute(req, res, path, me) {
|
|
1138
|
+
const method = path === "/auth/session" || path === "/setup/import" ? "GET" : "POST";
|
|
1139
|
+
if (req.method !== method)
|
|
1140
|
+
throw new ApiError("method_not_allowed", `${req.method} is not a method of /v2${path}`, {}, { allow: method });
|
|
1141
|
+
switch (path) {
|
|
1142
|
+
case "/setup": {
|
|
1143
|
+
const byToken = req.headers.authorization !== undefined;
|
|
1144
|
+
if (byToken && !timingSafeEqual(digest(String(req.headers.authorization)), expected))
|
|
1145
|
+
throw new ApiError("unauthenticated", "the Bearer here is the server's token, or none", {}, { "www-authenticate": "Bearer" });
|
|
1146
|
+
if (!byToken)
|
|
1147
|
+
fromPage(req);
|
|
1148
|
+
const { password, body } = await passwordIn(req, ["password", "code", "import"]);
|
|
1149
|
+
if (body.import !== undefined && typeof body.import !== "boolean")
|
|
1150
|
+
throw invalid([{ field: "import", reason: "wrong_type", message: "import is true or false" }]);
|
|
1151
|
+
if (body.import === true && !offersImport)
|
|
1152
|
+
throw invalid([{ field: "import", reason: "not_allowed", message: "Only a server on this machine (no public address, on loopback) imports its sessions at setup: run the import command where they are." }]);
|
|
1153
|
+
// The owner's yes, on the box ticked, is kept with the owner: written durably before the password, so a setup that
|
|
1154
|
+
// cannot keep it sets no owner and can be tried again, and taken back if the password is not written.
|
|
1155
|
+
const along = body.import === true ? { keep: () => writeDurable(importAsked, ""), drop: () => rm(importAsked, { force: true }) } : undefined;
|
|
1156
|
+
const made = await me.setFirst(password, body.code, byToken, along);
|
|
1157
|
+
if (made === "exists")
|
|
1158
|
+
throw new ApiError("forbidden", "this server has its owner, or is being set up: sign in");
|
|
1159
|
+
if (made === "code")
|
|
1160
|
+
throw new ApiError("forbidden", "that is not the setup code in the server's log, or it has expired");
|
|
1161
|
+
// The count is for the offer, now answered: it stops.
|
|
1162
|
+
stopCount();
|
|
1163
|
+
// Only on the box ticked: the owner, now set, asked for it. It runs after the answer; agents arrive as it goes.
|
|
1164
|
+
if (body.import === true)
|
|
1165
|
+
void importAtSetup();
|
|
1166
|
+
return send(res, 201, { signed_in: true, ...(body.import === true ? { importing: true } : {}) }, { "set-cookie": ownerCookie(req, me.session(), SESSION_S) });
|
|
1167
|
+
}
|
|
1168
|
+
case "/setup/import": {
|
|
1169
|
+
// No offer is an answer, `{ offer: false }`, never a 404: the console reads this on its first page, and a browser
|
|
1170
|
+
// logs every 404 as an error.
|
|
1171
|
+
// Before the owner is set, to the setup page: none on a server that cannot import, else that it can (202 while it
|
|
1172
|
+
// counts), and then how many projects and sessions it would, or null for each when the count failed.
|
|
1173
|
+
if (!me.hasPassword()) {
|
|
1174
|
+
pageRead(req);
|
|
1175
|
+
if (!offersImport)
|
|
1176
|
+
return send(res, 200, { offer: false });
|
|
1177
|
+
countSessions();
|
|
1178
|
+
if (count?.state === "counted")
|
|
1179
|
+
return send(res, 200, { projects: count.projects, sessions: count.sessions });
|
|
1180
|
+
if (count?.state === "failed")
|
|
1181
|
+
return send(res, 200, { projects: null, sessions: null });
|
|
1182
|
+
return send(res, 202, { counting: true });
|
|
1183
|
+
}
|
|
1184
|
+
// After, to the signed-in owner: the import asked for at setup, running, done or stopped, or none asked.
|
|
1185
|
+
if (!signedIn(req, me))
|
|
1186
|
+
throw new ApiError("not_found", "no route /v2/setup/import");
|
|
1187
|
+
return send(res, 200, importState ?? { offer: false });
|
|
1188
|
+
}
|
|
1189
|
+
case "/auth/sign-in": {
|
|
1190
|
+
fromPage(req);
|
|
1191
|
+
const allowed = me.allow(req.socket.remoteAddress ?? "unknown");
|
|
1192
|
+
if (allowed === "full")
|
|
1193
|
+
authFailed("/v2/auth/sign-in", "sign_in_table_full");
|
|
1194
|
+
if (allowed !== "ok")
|
|
1195
|
+
throw new ApiError("rate_limited", "too many sign-ins; try again later", { retry_after_ms: 900_000 }, { "retry-after": "900" });
|
|
1196
|
+
const { password } = await passwordIn(req, ["password"], false);
|
|
1197
|
+
if (!me.hasPassword())
|
|
1198
|
+
throw new ApiError("forbidden", "this server has no password yet: set it on the setup page");
|
|
1199
|
+
if (!(await me.check(password))) {
|
|
1200
|
+
authFailed("/v2/auth/sign-in", "wrong_password");
|
|
1201
|
+
throw new ApiError("unauthenticated", "that is not the password");
|
|
1202
|
+
}
|
|
1203
|
+
return send(res, 200, { signed_in: true }, { "set-cookie": ownerCookie(req, me.session(), SESSION_S) });
|
|
1204
|
+
}
|
|
1205
|
+
case "/auth/sign-out": {
|
|
1206
|
+
fromPage(req);
|
|
1207
|
+
if (!signedIn(req, me))
|
|
1208
|
+
throw new ApiError("unauthenticated", "this browser is not signed in");
|
|
1209
|
+
me.signOutEverywhere();
|
|
1210
|
+
return send(res, 200, { signed_out: true }, { "set-cookie": ownerCookie(req, "", 0) });
|
|
1211
|
+
}
|
|
1212
|
+
case "/auth/session":
|
|
1213
|
+
return send(res, 200, { password_set: me.hasPassword(), signed_in: signedIn(req, me) });
|
|
1214
|
+
}
|
|
1215
|
+
throw new ApiError("not_found", `no route /v2${path}`);
|
|
1216
|
+
}
|
|
1217
|
+
// ---- routing --------------------------------------------------------------------------------------------------------
|
|
1218
|
+
async function route(req, res, url, path) {
|
|
1219
|
+
const matching = ROUTES.filter((r) => r.pattern.test(path));
|
|
1220
|
+
// `/v2` twice: a path an answer gives (upload.url, a Location) appended to the /v2 base, where it starts at the root.
|
|
1221
|
+
if (!matching.length)
|
|
1222
|
+
throw new ApiError("not_found", path.startsWith("/v2/") ? `no route /v2${path}: /v2 is in it twice. A path an answer gives (upload.url, a Location) starts at the server's root: send it to the server's address, not after the /v2 base.` : `no route ${path}`);
|
|
1223
|
+
const found = matching.find((r) => r.method === req.method || (req.method === "HEAD" && r.method === "GET"));
|
|
1224
|
+
if (!found)
|
|
1225
|
+
throw new ApiError("method_not_allowed", `${req.method} is not a method of ${path}`, {}, { allow: [...new Set(matching.map((r) => r.method))].join(", ") });
|
|
1226
|
+
if (found.name === "getCapabilities")
|
|
1227
|
+
return send(res, 200, forCaller(caps, byOwnerSession(req)));
|
|
1228
|
+
if (found.name === "getOpenapi")
|
|
1229
|
+
return send(res, 200, servedOpenapi(openapi, req.socket.localPort));
|
|
1230
|
+
if (found.name === "getHealth") {
|
|
1231
|
+
const health = await healthOf(data, minFreeBytes);
|
|
1232
|
+
return send(res, health.status === "ok" ? 200 : 503, health);
|
|
1233
|
+
}
|
|
1234
|
+
// Approving a note the grader held for its owner's OK (a risky rule a run's user asked for) takes the owner's
|
|
1235
|
+
// signed-in page alone: never a token, which a run's process, an agent's MCP client or a script may hold, nor a
|
|
1236
|
+
// page cookie a token can mint (accounts off). The page's cookie stands in for the token only on its own origin
|
|
1237
|
+
// with a JSON body (page.ts), so this is CSRF-checked as every page write is. With no credential at all it is 401,
|
|
1238
|
+
// as every route is.
|
|
1239
|
+
if (found.name === "approveLearningFile" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
|
|
1240
|
+
authFailed(`/v2${path}`, "approve_without_session");
|
|
1241
|
+
throw new ApiError("forbidden", owner ? "Approving a note takes the owner's password sign-in in the console, never a token." : "Approving a note takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
|
|
1242
|
+
}
|
|
1243
|
+
if (!timingSafeEqual(digest(String(req.headers.authorization ?? "")), expected)) {
|
|
1244
|
+
authFailed(`/v2${path}`, req.headers.authorization === undefined ? "no_credential" : "wrong_token");
|
|
1245
|
+
throw new ApiError("unauthenticated", "this route needs Authorization: Bearer <the token in the data directory>", {}, { "www-authenticate": "Bearer" });
|
|
1246
|
+
}
|
|
1247
|
+
if (found.capability)
|
|
1248
|
+
throw unsupported(found.capability, UNSUPPORTED[found.capability]);
|
|
1249
|
+
const [, first, second] = found.pattern.exec(path);
|
|
1250
|
+
const id = first ? decodeURIComponent(first) : "";
|
|
1251
|
+
switch (found.name) {
|
|
1252
|
+
case "createAgent": {
|
|
1253
|
+
const body = await bodyOf(req);
|
|
1254
|
+
const answer = await idempotent(req, "/agents", body, async () => {
|
|
1255
|
+
let warnings = [];
|
|
1256
|
+
const entry = await agents.create(checkDefinitionBody(body), async (revision) => void (warnings = await saveable(revision)));
|
|
1257
|
+
return { status: 201, body: { ...agentView(entry), warnings }, headers: { location: `/v2/agents/${entry.agent.id}`, etag: etagOf(entry) } };
|
|
1258
|
+
});
|
|
1259
|
+
return send(res, answer.status, answer.body, answer.headers);
|
|
1260
|
+
}
|
|
1261
|
+
case "listAgents": {
|
|
1262
|
+
const limit = limitOf(url.searchParams.get("limit"));
|
|
1263
|
+
const offset = cursorOf(url.searchParams.get("cursor"));
|
|
1264
|
+
const archived = archivedParam(url);
|
|
1265
|
+
const all = (await agents.list()).filter((entry) => Boolean(entry.agent.archivedAt) === archived);
|
|
1266
|
+
return send(res, 200, { agents: all.slice(offset, offset + limit).map((entry) => agentView(entry)), next_cursor: nextCursor(offset + limit, all.length) });
|
|
1267
|
+
}
|
|
1268
|
+
case "getAgent": {
|
|
1269
|
+
const entry = await needAgent(id);
|
|
1270
|
+
// The tools its current revision grants, as capabilities list them, each with its provider for this agent.
|
|
1271
|
+
const tools = entry.revision ? agentTools(env, settings.get(), await toolingOf(entry.revision), caps.tools.map((tool) => tool.name)) : [];
|
|
1272
|
+
return send(res, 200, { ...agentView(entry), tools }, { etag: etagOf(entry) });
|
|
1273
|
+
}
|
|
1274
|
+
case "updateDefinition": {
|
|
1275
|
+
const entry = await needAgent(id);
|
|
1276
|
+
const match = req.headers["if-match"];
|
|
1277
|
+
if (match !== undefined && match !== etagOf(entry))
|
|
1278
|
+
throw new ApiError("precondition_failed", `If-Match is ${match}, and the agent's current revision is ${etagOf(entry)}`);
|
|
1279
|
+
const body = await bodyOf(req);
|
|
1280
|
+
// Two bodies, told apart by one rule: this server's own form holds the definition under `definition`; the
|
|
1281
|
+
// contract's is the definition itself, and takes the contract's preconditions: If-Match, and a version past the
|
|
1282
|
+
// current one.
|
|
1283
|
+
const contract = !("definition" in body);
|
|
1284
|
+
if (contract) {
|
|
1285
|
+
if (match === undefined)
|
|
1286
|
+
throw new ApiError("precondition_failed", "If-Match is required: the agent's ETag, as GET /agents/{agent_id} returned it.");
|
|
1287
|
+
if (body.version === undefined || (typeof body.version === "number" && body.version <= entry.version))
|
|
1288
|
+
throw invalid([{ field: "definition.version", reason: body.version === undefined ? "missing" : "not_an_option", message: `definition.version must be greater than the current one, ${entry.version}` }]);
|
|
1289
|
+
}
|
|
1290
|
+
// The check above is a fast path; the store compares If-Match again inside the commit, so of two edits that read
|
|
1291
|
+
// the same revision exactly one lands.
|
|
1292
|
+
let warnings = [];
|
|
1293
|
+
const check = async (revision) => void (warnings = await saveable(revision));
|
|
1294
|
+
const edited = await agents.commit(entry, checkDefinitionBody(contract ? { definition: body } : body, { creating: false }), { check, contract, ...(match === undefined ? {} : { ifCurrent: entry.revision?.id ?? null }) });
|
|
1295
|
+
return send(res, 200, { ...agentView(edited), warnings }, { etag: etagOf(edited) });
|
|
1296
|
+
}
|
|
1297
|
+
case "listRevisions": {
|
|
1298
|
+
const entry = await needAgent(id);
|
|
1299
|
+
const limit = limitOf(url.searchParams.get("limit"));
|
|
1300
|
+
const offset = cursorOf(url.searchParams.get("cursor"));
|
|
1301
|
+
const all = await agents.revisions(id);
|
|
1302
|
+
const page = await agents.request(() => all.slice(offset, offset + limit).map((row) => revisionView(entry.agent, row, agents.store.readRevision(row.id))));
|
|
1303
|
+
return send(res, 200, { revisions: page, next_cursor: nextCursor(offset + limit, all.length) });
|
|
1304
|
+
}
|
|
1305
|
+
case "setCurrent": {
|
|
1306
|
+
const entry = await needAgent(id);
|
|
1307
|
+
const body = await bodyOf(req);
|
|
1308
|
+
const extra = unknownFields(body, ["revision"]);
|
|
1309
|
+
if (extra.length)
|
|
1310
|
+
throw invalid(extra);
|
|
1311
|
+
const revision = body.revision;
|
|
1312
|
+
if (typeof revision !== "string" || !ID.test(revision))
|
|
1313
|
+
throw invalid([{ field: "revision", reason: revision === undefined ? "missing" : "wrong_type", message: "revision is a revision id of this agent" }]);
|
|
1314
|
+
if (!(await agents.revision(id, revision)))
|
|
1315
|
+
throw invalid([{ field: "revision", reason: "not_an_option", message: `${revision} is not a revision of the agent ${id}` }]);
|
|
1316
|
+
const moved = await agents.setCurrent(entry, revision);
|
|
1317
|
+
return send(res, 200, agentView(moved), { etag: etagOf(moved) });
|
|
1318
|
+
}
|
|
1319
|
+
case "archiveAgent":
|
|
1320
|
+
case "unarchiveAgent": {
|
|
1321
|
+
await needAgent(id);
|
|
1322
|
+
await agents.setArchived("agent", id, found.name === "archiveAgent");
|
|
1323
|
+
if (found.name === "archiveAgent")
|
|
1324
|
+
await runs.archived();
|
|
1325
|
+
const entry = await needAgent(id);
|
|
1326
|
+
return send(res, 200, agentView(entry), { etag: etagOf(entry) });
|
|
1327
|
+
}
|
|
1328
|
+
case "createRun": {
|
|
1329
|
+
const answer = await createRun(req, id);
|
|
1330
|
+
return send(res, answer.status, answer.body, answer.headers);
|
|
1331
|
+
}
|
|
1332
|
+
case "listRuns":
|
|
1333
|
+
await needAgent(id);
|
|
1334
|
+
return send(res, 200, await runsPage(url, { agent: id }));
|
|
1335
|
+
case "listAllRuns": {
|
|
1336
|
+
const agent = url.searchParams.get("agent") ?? undefined;
|
|
1337
|
+
const revision = url.searchParams.get("revision") ?? undefined;
|
|
1338
|
+
return send(res, 200, await runsPage(url, { ...(agent ? { agent } : {}), ...(revision ? { revision } : {}) }));
|
|
1339
|
+
}
|
|
1340
|
+
case "getRun":
|
|
1341
|
+
return send(res, 200, await runs.view(await needRun(id)));
|
|
1342
|
+
case "getTimeline":
|
|
1343
|
+
return timeline(req, res, url, await needRun(id));
|
|
1344
|
+
case "sendMessage": {
|
|
1345
|
+
const run = await needRun(id);
|
|
1346
|
+
if (run.kind === "workflow")
|
|
1347
|
+
throw unsupported("messages.steer_workflow_runs", "A workflow run takes no messages here: its workflow runs to its end, or a cancel ends it.");
|
|
1348
|
+
const body = await bodyOf(req);
|
|
1349
|
+
const answer = await idempotent(req, `/runs/${id}/messages`, body, async () => {
|
|
1350
|
+
const extra = unknownFields(body, ["content"]);
|
|
1351
|
+
if (extra.length)
|
|
1352
|
+
throw invalid(extra);
|
|
1353
|
+
const content = body.content;
|
|
1354
|
+
if (typeof content !== "string" || !/\S/.test(content))
|
|
1355
|
+
throw invalid([{ field: "content", reason: content === undefined ? "missing" : "wrong_type", message: "content is a non-empty string" }]);
|
|
1356
|
+
if (content.length > MAX_MESSAGE)
|
|
1357
|
+
throw invalid([{ field: "content", reason: "too_long", message: `content is at most ${MAX_MESSAGE} characters` }]);
|
|
1358
|
+
const { mode, messageId } = await runs.message(run, content);
|
|
1359
|
+
// The run's state as the message left it, from the run itself: the stored row (its view's) would make a
|
|
1360
|
+
// message already taken answer home_busy while another connection holds the agent store.
|
|
1361
|
+
const { status, state } = statusOf(run);
|
|
1362
|
+
return { status: 202, body: { run_id: run.id, message_id: messageId, mode, status, state, poll_after_ms: 1000 } };
|
|
1363
|
+
});
|
|
1364
|
+
return send(res, answer.status, answer.body, answer.headers);
|
|
1365
|
+
}
|
|
1366
|
+
case "stopRun": {
|
|
1367
|
+
const run = await needRun(id);
|
|
1368
|
+
const stopped = await runs.stop(run);
|
|
1369
|
+
// From the run itself, as a message's answer: a stop that happened is never answered home_busy.
|
|
1370
|
+
const { status, state } = statusOf(run);
|
|
1371
|
+
return send(res, 200, { run_id: run.id, stopped, status, state });
|
|
1372
|
+
}
|
|
1373
|
+
case "cancelRun": {
|
|
1374
|
+
const run = await needRun(id);
|
|
1375
|
+
const requested = await runs.cancel(run);
|
|
1376
|
+
return send(res, 202, { run_id: run.id, cancel_requested: requested, already_terminal: !requested, status: statusOf(run).status });
|
|
1377
|
+
}
|
|
1378
|
+
case "archiveRun":
|
|
1379
|
+
case "unarchiveRun": {
|
|
1380
|
+
const run = await needRun(id);
|
|
1381
|
+
await agents.setArchived("run", run.id, found.name === "archiveRun");
|
|
1382
|
+
if (found.name === "archiveRun")
|
|
1383
|
+
await runs.archived();
|
|
1384
|
+
return send(res, 200, await runs.view(run));
|
|
1385
|
+
}
|
|
1386
|
+
case "listRunFiles": {
|
|
1387
|
+
const run = await needRun(id);
|
|
1388
|
+
// A remote box's turn just ended: its pull lands first, so the list shows what the box wrote.
|
|
1389
|
+
await runs.pulled(run.id);
|
|
1390
|
+
const { files, deep } = await walk(join(run.dir, "work"));
|
|
1391
|
+
files.sort((a, b) => a.path.localeCompare(b.path));
|
|
1392
|
+
return send(res, 200, { run_id: run.id, files: files.slice(0, FILE_LIST_CAP), complete: true, truncated: deep || files.length > FILE_LIST_CAP });
|
|
1393
|
+
}
|
|
1394
|
+
// An archived agent's home is read and written as any other's: as its definition is.
|
|
1395
|
+
case "listHomeFiles": {
|
|
1396
|
+
await needAgent(id);
|
|
1397
|
+
const home = await homeDir(id, false);
|
|
1398
|
+
const { files, deep, owned } = home ? await walk(home, true) : { files: [], deep: false, owned: [] };
|
|
1399
|
+
// A host-owned path there is one entry by its name, and none of what is in it.
|
|
1400
|
+
const listed = [...files, ...owned.map((path) => ({ path, host_owned: true }))].sort((a, b) => a.path.localeCompare(b.path));
|
|
1401
|
+
return send(res, 200, { agent_id: id, files: listed.slice(0, FILE_LIST_CAP), complete: true, truncated: deep || listed.length > FILE_LIST_CAP });
|
|
1402
|
+
}
|
|
1403
|
+
case "readHomeFile": {
|
|
1404
|
+
await needAgent(id);
|
|
1405
|
+
const rel = homePath(second, id, false, ownedReadAt(id));
|
|
1406
|
+
const home = await homeDir(id, false);
|
|
1407
|
+
if (!home)
|
|
1408
|
+
throw new ApiError("not_found", "no such file");
|
|
1409
|
+
await notHostOwned(home, rel, id, false);
|
|
1410
|
+
return sendFile(req, res, url, home, rel, "another user");
|
|
1411
|
+
}
|
|
1412
|
+
case "writeHomeFile": {
|
|
1413
|
+
await needAgent(id);
|
|
1414
|
+
if (!homeWrites)
|
|
1415
|
+
throw new ApiError("unsupported_here", HOME_WRITES_OFF);
|
|
1416
|
+
const rel = homePath(second, id, true);
|
|
1417
|
+
const bytes = await bytesOf(req);
|
|
1418
|
+
// Each write lands whole (a temporary file renamed over the old one); of two at once, the last rename wins.
|
|
1419
|
+
const st = await homeDir(id, true)
|
|
1420
|
+
.then(async (home) => {
|
|
1421
|
+
await notHostOwned(home, rel, id, true);
|
|
1422
|
+
return writeWorkFile(home, rel, bytes);
|
|
1423
|
+
})
|
|
1424
|
+
.catch(homeRefusal);
|
|
1425
|
+
return send(res, 200, fileView(rel, st));
|
|
1426
|
+
}
|
|
1427
|
+
case "deleteHomeFile": {
|
|
1428
|
+
await needAgent(id);
|
|
1429
|
+
if (!homeWrites)
|
|
1430
|
+
throw new ApiError("unsupported_here", HOME_WRITES_OFF);
|
|
1431
|
+
const rel = homePath(second, id, true);
|
|
1432
|
+
const home = await homeDir(id, false);
|
|
1433
|
+
if (!home)
|
|
1434
|
+
throw new ApiError("not_found", "no such file");
|
|
1435
|
+
await notHostOwned(home, rel, id, true);
|
|
1436
|
+
await removeWorkFile(home, rel).catch(homeRefusal);
|
|
1437
|
+
res.writeHead(204, { "cache-control": "no-store", "x-content-type-options": "nosniff" });
|
|
1438
|
+
return void res.end();
|
|
1439
|
+
}
|
|
1440
|
+
case "validateWorkflow": {
|
|
1441
|
+
const body = await bodyOf(req);
|
|
1442
|
+
const extra = unknownFields(body, ["workflow", "tools"]);
|
|
1443
|
+
if (extra.length)
|
|
1444
|
+
throw invalid(extra);
|
|
1445
|
+
if (!isObject(body.workflow))
|
|
1446
|
+
throw invalid([{ field: "workflow", reason: body.workflow === undefined ? "missing" : "wrong_type", message: "workflow is the workflow definition, an object" }]);
|
|
1447
|
+
if (body.tools !== undefined && !(Array.isArray(body.tools) && body.tools.every((t) => typeof t === "string")))
|
|
1448
|
+
throw invalid([{ field: "tools", reason: "wrong_type", message: "tools is a list of tool names" }]);
|
|
1449
|
+
const { workflowIssues } = await import("@parcha/pi-durable-agent/workflow");
|
|
1450
|
+
const { issues, warnings } = await workflowIssues(body.workflow, body.tools);
|
|
1451
|
+
// What a save refuses on this host (a model node's tool, a code node where none runs), and what it lacks yet.
|
|
1452
|
+
if (!issues.length) {
|
|
1453
|
+
for (const blocker of await blockersOf(env, { kind: "workflow", workflow: body.workflow, ...(body.tools ? { tools: body.tools } : {}) }, settings.get(), { offers }).catch(() => [])) {
|
|
1454
|
+
if (blocker.host)
|
|
1455
|
+
warnings.push(blocker.message);
|
|
1456
|
+
else
|
|
1457
|
+
issues.push({ path: "", code: "NOT_RUNNABLE_HERE", message: blocker.message });
|
|
1458
|
+
}
|
|
1459
|
+
}
|
|
1460
|
+
return send(res, 200, { ok: issues.length === 0, issues, warnings });
|
|
1461
|
+
}
|
|
1462
|
+
case "getRunGraph":
|
|
1463
|
+
return send(res, 200, await runs.graph(await needRun(id)));
|
|
1464
|
+
case "pauseRun":
|
|
1465
|
+
case "resumeRun":
|
|
1466
|
+
return send(res, 200, await runs.pause(await needRun(id), found.name === "pauseRun"));
|
|
1467
|
+
case "readRunFile": {
|
|
1468
|
+
const run = await needRun(id);
|
|
1469
|
+
await runs.pulled(run.id);
|
|
1470
|
+
return sendFile(req, res, url, join(run.dir, "work"), checkedPath(decodedPath(second), "the run's own, not a file it wrote"), "a tool in the run's box");
|
|
1471
|
+
}
|
|
1472
|
+
case "createFile": {
|
|
1473
|
+
// A `path` in the query, or a body that is not JSON: the file sent in one call, its bytes the body. Else the
|
|
1474
|
+
// contract's JSON reservation, its bytes sent after with PUT /files/{file_id}.
|
|
1475
|
+
if (url.searchParams.has("path") || !isJson(req)) {
|
|
1476
|
+
const received = await uploads.take(url.searchParams, req.headers["content-type"], req);
|
|
1477
|
+
try {
|
|
1478
|
+
const answer = await idempotent(req, "/files", received.fingerprint, async () => ({ status: 201, body: await received.commit() }));
|
|
1479
|
+
return send(res, answer.status, answer.body, answer.headers);
|
|
1480
|
+
}
|
|
1481
|
+
finally {
|
|
1482
|
+
await received.discard();
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
const body = await bodyOf(req);
|
|
1486
|
+
const answer = await idempotent(req, "/files", body, async () => ({ status: 201, body: await uploads.reserve(body) }));
|
|
1487
|
+
return send(res, answer.status, answer.body, answer.headers);
|
|
1488
|
+
}
|
|
1489
|
+
case "uploadFile":
|
|
1490
|
+
return send(res, 200, await uploads.receive(id, req));
|
|
1491
|
+
case "listFiles": {
|
|
1492
|
+
// This server's own: its uploads, newest first, a page at a time, so an id is never lost with the answer that gave it.
|
|
1493
|
+
const limit = limitOf(url.searchParams.get("limit"));
|
|
1494
|
+
const offset = cursorOf(url.searchParams.get("cursor"));
|
|
1495
|
+
const ids = await uploads.ids();
|
|
1496
|
+
const files = (await Promise.all(ids.slice(offset, offset + limit).map((fileId) => uploads.get(fileId)))).filter((file) => file !== null);
|
|
1497
|
+
return send(res, 200, { files, next_cursor: nextCursor(offset + limit, ids.length) });
|
|
1498
|
+
}
|
|
1499
|
+
case "getFile": {
|
|
1500
|
+
const file = await uploads.get(id);
|
|
1501
|
+
if (!file)
|
|
1502
|
+
throw new ApiError("not_found", `no file ${id}: GET /v2/files lists the files this server keeps`);
|
|
1503
|
+
return send(res, 200, file);
|
|
1504
|
+
}
|
|
1505
|
+
case "deleteFile":
|
|
1506
|
+
await uploads.remove(id);
|
|
1507
|
+
return void res.writeHead(204, { "cache-control": "no-store" }).end();
|
|
1508
|
+
case "getUsage":
|
|
1509
|
+
return send(res, 200, await usage(url));
|
|
1510
|
+
case "getStats": {
|
|
1511
|
+
const filter = analyticsFilter(url);
|
|
1512
|
+
const [stats, analytics, rows] = await agents.request(() => [agents.store.stats(), agents.store.analytics(filter), agents.store.listRuns()]);
|
|
1513
|
+
// How the runs that tried to learn fared: a held run's learning from memory, any other's end from the ledger.
|
|
1514
|
+
return send(res, 200, { ...statsView(stats, runs), analytics: analyticsView(analytics, filter), learning: await runs.learning.counts(rows, filter) });
|
|
1515
|
+
}
|
|
1516
|
+
case "listToolKeys":
|
|
1517
|
+
// The offers the server holds, not capabilities': a model key's row names the harnesses its key would run too.
|
|
1518
|
+
return send(res, 200, toolKeys.view(offers));
|
|
1519
|
+
case "saveToolKey": {
|
|
1520
|
+
// Never through `idempotent`: its record keeps the body, and this body is the values. Checked against its
|
|
1521
|
+
// provider before it is kept: a key the provider refuses is 422, and nothing is kept.
|
|
1522
|
+
const body = await bodyOf(req);
|
|
1523
|
+
const check = await toolKeys.check(id, body, checkFetch, stopping.signal);
|
|
1524
|
+
// A server that began to close stores nothing: it may have released its lock, and another server may hold this
|
|
1525
|
+
// directory and its keys by now.
|
|
1526
|
+
if (stopping.signal.aborted)
|
|
1527
|
+
throw new ApiError("unavailable", "The server is shutting down: the key was not saved.");
|
|
1528
|
+
toolKeys.save(id, body, check);
|
|
1529
|
+
await keysChanged();
|
|
1530
|
+
return void res.writeHead(204, { "cache-control": "no-store" }).end();
|
|
1531
|
+
}
|
|
1532
|
+
case "deleteToolKey":
|
|
1533
|
+
toolKeys.remove(id);
|
|
1534
|
+
await keysChanged();
|
|
1535
|
+
return void res.writeHead(204, { "cache-control": "no-store" }).end();
|
|
1536
|
+
// Never through `idempotent`: its record keeps the body, and a body may hold a credential.
|
|
1537
|
+
case "listMcpServers":
|
|
1538
|
+
return send(res, 200, mcpServers.list());
|
|
1539
|
+
case "getMcpServer":
|
|
1540
|
+
return send(res, 200, mcpServers.get(id));
|
|
1541
|
+
case "previewMcpServer":
|
|
1542
|
+
return send(res, 200, await mcpServers.preview(await bodyOf(req), stopping.signal));
|
|
1543
|
+
case "saveMcpServer":
|
|
1544
|
+
return send(res, 200, await mcpServers.save(id, await bodyOf(req), stopping.signal));
|
|
1545
|
+
case "refreshMcpServer":
|
|
1546
|
+
return send(res, 200, await mcpServers.refresh(id, stopping.signal));
|
|
1547
|
+
case "deleteMcpServer":
|
|
1548
|
+
mcpServers.remove(id);
|
|
1549
|
+
return void res.writeHead(204, { "cache-control": "no-store" }).end();
|
|
1550
|
+
case "getToolSettings":
|
|
1551
|
+
return send(res, 200, withDefaults(settings.get()));
|
|
1552
|
+
case "putToolSettings": {
|
|
1553
|
+
// Replaces the settings: a capability the body leaves out takes its default. Runs launched from now on resolve
|
|
1554
|
+
// on them, and capabilities say so at once.
|
|
1555
|
+
const body = await bodyOf(req);
|
|
1556
|
+
const issues = settingsIssues(body);
|
|
1557
|
+
if (issues.length)
|
|
1558
|
+
throw invalid(issues);
|
|
1559
|
+
settings.put(body);
|
|
1560
|
+
// A setting changes what the web tools resolve to, never env or what a harness offers: capabilities again.
|
|
1561
|
+
recompose();
|
|
1562
|
+
return send(res, 200, withDefaults(settings.get()));
|
|
1563
|
+
}
|
|
1564
|
+
// A person's view and control of what an agent learned (learning-routes.ts). Every text cut of the host's secrets as
|
|
1565
|
+
// they are now; a write as the definition's: an archived agent's too.
|
|
1566
|
+
case "getAgentLearning": {
|
|
1567
|
+
await needAgent(id);
|
|
1568
|
+
const rows = await agents.request(() => agents.store.listRuns({ agent: id }));
|
|
1569
|
+
// Counted as GET /stats counts (learning-run.ts counts): a held run from memory, any other's end from the ledger;
|
|
1570
|
+
// what learning changed, from the same rows and ledger (learningImpact).
|
|
1571
|
+
const { counts, impact } = await runs.learning.ofAgent(rows, id);
|
|
1572
|
+
return send(res, 200, await agentLearning(data, id, secretsShown(learningSecrets()), counts, impact));
|
|
1573
|
+
}
|
|
1574
|
+
case "listLearningNotes":
|
|
1575
|
+
case "listLearningLog":
|
|
1576
|
+
await needAgent(id);
|
|
1577
|
+
return send(res, 200, await (found.name === "listLearningNotes" ? learningNotes : learningLog)(data, id, url.searchParams, secretsShown(learningSecrets())));
|
|
1578
|
+
case "readLearningFile":
|
|
1579
|
+
await needAgent(id);
|
|
1580
|
+
return sendNote(res, 200, await readNote(data, id, second, secretsShown(learningSecrets())));
|
|
1581
|
+
case "writeLearningFile":
|
|
1582
|
+
case "retireLearningFile":
|
|
1583
|
+
case "approveLearningFile": {
|
|
1584
|
+
await needAgent(id);
|
|
1585
|
+
const header = (name) => (typeof req.headers[name] === "string" ? req.headers[name] : undefined);
|
|
1586
|
+
const body = found.name === "writeLearningFile" ? await noteBody(req, MAX_BODY) : undefined;
|
|
1587
|
+
const written = await writeNote(data, id, second, { ifMatch: header("if-match"), ifNoneMatch: header("if-none-match"), body, refuse: learningSecrets(), approve: found.name === "approveLearningFile" });
|
|
1588
|
+
// A name holding a secret (one the checks let by) is never echoed, not even as where the note is.
|
|
1589
|
+
const shown = secretsShown(learningSecrets());
|
|
1590
|
+
const located = written.status === 201 && shown.name(written.file) === written.file;
|
|
1591
|
+
return sendNote(res, written.status, { ...written, text: shown.text(written.text) }, located ? { location: `/v2/agents/${encodeURIComponent(id)}/learning/files/${written.file}` } : {});
|
|
1592
|
+
}
|
|
1593
|
+
case "getRunLearning":
|
|
1594
|
+
return send(res, 200, await runLearning(await needRun(id), secretsShown(learningSecrets()), learningSecrets()));
|
|
1595
|
+
case "getRunLearningDiff":
|
|
1596
|
+
return send(res, 200, await runDiff(data, await needRun(id), secretsShown(learningSecrets())));
|
|
1597
|
+
case "getWebhook":
|
|
1598
|
+
return send(res, 200, webhooks.view());
|
|
1599
|
+
case "saveWebhook": {
|
|
1600
|
+
// Never through `idempotent`: its record would keep the answer, and the first one holds the secret.
|
|
1601
|
+
const saved = webhooks.save(await bodyOf(req));
|
|
1602
|
+
return send(res, saved.created ? 201 : 200, { ...saved.view, ...(saved.secret ? { secret: saved.secret } : {}) });
|
|
1603
|
+
}
|
|
1604
|
+
case "deleteWebhook":
|
|
1605
|
+
webhooks.remove();
|
|
1606
|
+
return void res.writeHead(204, { "cache-control": "no-store" }).end();
|
|
1607
|
+
case "testWebhook":
|
|
1608
|
+
return send(res, 200, await webhooks.test());
|
|
1609
|
+
case "listWebhookDeliveries":
|
|
1610
|
+
return send(res, 200, webhooks.attemptsView());
|
|
1611
|
+
case "redeliverWebhook":
|
|
1612
|
+
return send(res, 200, await webhooks.redeliver(id));
|
|
1613
|
+
}
|
|
1614
|
+
throw new ApiError("not_found", `no route ${path}`);
|
|
1615
|
+
}
|
|
1616
|
+
// The MCP endpoint's tools are the routes above, called in process with the caller's token (mcp.ts).
|
|
1617
|
+
const mcp = mcpEndpoint({ route, authorized: (header) => timingSafeEqual(digest(header), expected), authFailed, version: VERSION });
|
|
1618
|
+
function send(res, status, body, headers = {}) {
|
|
1619
|
+
const text = JSON.stringify(body);
|
|
1620
|
+
res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store", "x-content-type-options": "nosniff", ...headers });
|
|
1621
|
+
res.end(text);
|
|
1622
|
+
}
|
|
1623
|
+
let names;
|
|
1624
|
+
const server = createServer((req, res) => {
|
|
1625
|
+
const requestId = `req_${randomBytes(8).toString("hex")}`;
|
|
1626
|
+
res.setHeader("x-request-id", requestId);
|
|
1627
|
+
if (log && !quiet) {
|
|
1628
|
+
const started = performance.now();
|
|
1629
|
+
const method = req.method ?? "GET";
|
|
1630
|
+
const path = (req.url ?? "/").split("?")[0];
|
|
1631
|
+
res.once("finish", () => log(logLine("request", { method, path, status: res.statusCode, ms: Math.round(performance.now() - started) })));
|
|
1632
|
+
}
|
|
1633
|
+
const fail = (error) => {
|
|
1634
|
+
if (res.headersSent)
|
|
1635
|
+
return void res.end();
|
|
1636
|
+
// A store still busy past a request's wait is home_busy, whichever read or write met it.
|
|
1637
|
+
const known = error instanceof ApiError ? error : storeBusy(error) ? homeBusy() : new ApiError("internal", error?.message ?? String(error));
|
|
1638
|
+
if (!(error instanceof ApiError) && !storeBusy(error))
|
|
1639
|
+
process.stderr.write(`agentrun-serve: ${error?.stack ?? String(error)}\n`);
|
|
1640
|
+
send(res, known.status, known.body(requestId), known.headers);
|
|
1641
|
+
};
|
|
1642
|
+
let url;
|
|
1643
|
+
try {
|
|
1644
|
+
url = new URL(req.url ?? "/", "http://serve");
|
|
1645
|
+
}
|
|
1646
|
+
catch {
|
|
1647
|
+
return fail(new ApiError("bad_request", "the request target is not a URL"));
|
|
1648
|
+
}
|
|
1649
|
+
// On loopback, a Host that is not a loopback name is a page that rebound a name of its own to this address.
|
|
1650
|
+
if (names && !names.has(String(req.headers.host ?? "").toLowerCase()))
|
|
1651
|
+
return fail(new ApiError("forbidden", "unexpected Host header"));
|
|
1652
|
+
// Routed on the path as sent: a parsed URL folds `..` and `%2E%2E` segments away, and a file path must see them.
|
|
1653
|
+
const raw = (req.url ?? "/").split("?")[0];
|
|
1654
|
+
// Before the page: its cookie must not stand in for the token on the owner's own routes, nor on the MCP endpoint.
|
|
1655
|
+
if (owner && (raw === "/v2/setup" || raw === "/v2/setup/import" || raw.startsWith("/v2/auth/")))
|
|
1656
|
+
return void ownerRoute(req, res, raw.slice(3), owner).catch(fail);
|
|
1657
|
+
if (raw === MCP_PATH)
|
|
1658
|
+
return void mcp(req, res).catch(fail);
|
|
1659
|
+
if (raw === "/llms.txt")
|
|
1660
|
+
return void answerLlms(req, res).catch(fail);
|
|
1661
|
+
if (answerPage(req, res, raw, { token, dir: data, authFailed, console: options.console, takesBytes, ...(owner ? { owner } : {}) }))
|
|
1662
|
+
return;
|
|
1663
|
+
if (!raw.startsWith("/v2/"))
|
|
1664
|
+
return fail(new ApiError("not_found", `no route ${raw}; the API is under /v2`));
|
|
1665
|
+
route(req, res, url, raw.slice(3)).catch(fail);
|
|
1666
|
+
});
|
|
1667
|
+
const first = options.port ?? DEFAULT_PORT;
|
|
1668
|
+
const last = options.nextFreePort && first !== 0 ? Math.min(first + 99, 65_535) : first;
|
|
1669
|
+
for (let port = first;; port++) {
|
|
1670
|
+
try {
|
|
1671
|
+
// Each attempt takes off both its handlers when it ends, so a taken port leaves no listener behind.
|
|
1672
|
+
await new Promise((done, reject) => {
|
|
1673
|
+
const onError = (error) => (server.off("listening", onListening), reject(error));
|
|
1674
|
+
const onListening = () => (server.off("error", onError), done());
|
|
1675
|
+
server.once("error", onError);
|
|
1676
|
+
server.once("listening", onListening);
|
|
1677
|
+
server.listen(port, host);
|
|
1678
|
+
});
|
|
1679
|
+
break;
|
|
1680
|
+
}
|
|
1681
|
+
catch (error) {
|
|
1682
|
+
if (error.code !== "EADDRINUSE")
|
|
1683
|
+
throw error;
|
|
1684
|
+
if (port < last)
|
|
1685
|
+
continue;
|
|
1686
|
+
throw last > first ? Object.assign(new Error(`every port from ${first} to ${last} on ${host} is taken`), { code: "EADDRINUSE" }) : error;
|
|
1687
|
+
}
|
|
1688
|
+
}
|
|
1689
|
+
// Only a server that started takes up the import its owner asked for, or counts for setup's offer: one that failed to
|
|
1690
|
+
// listen hands back no close to stop them.
|
|
1691
|
+
if (offersImport && existsSync(importAsked))
|
|
1692
|
+
void importAtSetup();
|
|
1693
|
+
else if (offersImport && options.countSessions && owner && !owner.hasPassword())
|
|
1694
|
+
countSessions();
|
|
1695
|
+
const address = server.address();
|
|
1696
|
+
if (isLoopback(host))
|
|
1697
|
+
names = new Set(["localhost", "127.0.0.1", "[::1]", host, ...(options.allowHosts ?? [])].map((h) => `${h.toLowerCase()}:${address.port}`));
|
|
1698
|
+
// An address of every interface is reached on this machine at its loopback one.
|
|
1699
|
+
const shown = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
|
|
1700
|
+
const url = `http://${shown.includes(":") ? `[${shown}]` : shown}:${address.port}`;
|
|
1701
|
+
owner?.attach(options.publicUrl ?? url);
|
|
1702
|
+
webhooks.attach(options.publicUrl ?? url);
|
|
1703
|
+
const setupUrl = owner && !owner.hasPassword() ? owner.setupLink() : undefined;
|
|
1704
|
+
/** The server's stop: once (`close` keeps its promise). */
|
|
1705
|
+
let stopped;
|
|
1706
|
+
async function stop() {
|
|
1707
|
+
// First, the record a start on this data root waits on while the runs' processes drain and exit (server-lock.ts),
|
|
1708
|
+
// rewritten in place: this close's bound, with time for the deliveries and the listener after them. One not
|
|
1709
|
+
// written leaves a start refused.
|
|
1710
|
+
const { runs: busy, boundMs } = runs.stopping();
|
|
1711
|
+
try {
|
|
1712
|
+
markStopping(data, Date.now() + boundMs + STOP_MARGIN_MS);
|
|
1713
|
+
}
|
|
1714
|
+
catch (error) {
|
|
1715
|
+
const fields = { reason: error.code ?? error.message };
|
|
1716
|
+
void (log ? log(logLine("stopping_mark_unwritten", fields)) : process.stderr.write(`agentrun-serve: ${logLine("stopping_mark_unwritten", fields)}\n`));
|
|
1717
|
+
}
|
|
1718
|
+
if (busy > 0)
|
|
1719
|
+
noticeOf(options)(`stopping: waiting up to ${seconds(boundMs)} for ${busy === 1 ? "1 run to finish its turn" : `${busy} runs to finish their turn`}`);
|
|
1720
|
+
// An import under way stops between two session files and is waited for: nothing writes the store after close. A
|
|
1721
|
+
// count writes nothing (it lists and reads), so it is ended at once: its listing of a big home checks for no stop.
|
|
1722
|
+
closing = true;
|
|
1723
|
+
stopping.abort();
|
|
1724
|
+
for (const [worker, { task }] of workers) {
|
|
1725
|
+
if (task === "plan")
|
|
1726
|
+
void worker.terminate();
|
|
1727
|
+
else
|
|
1728
|
+
worker.postMessage("stop");
|
|
1729
|
+
}
|
|
1730
|
+
await Promise.all([...workers.values()].map((w) => w.exit));
|
|
1731
|
+
await importing;
|
|
1732
|
+
// Runs that end while their processes stop still give their notices; then the deliveries stop, before the lock goes.
|
|
1733
|
+
await runs.close();
|
|
1734
|
+
await relay?.close();
|
|
1735
|
+
// Before the lock goes: the image's last record lands first (box-image.ts), never after the next server's start.
|
|
1736
|
+
await image?.close();
|
|
1737
|
+
await webhooks.close();
|
|
1738
|
+
await new Promise((done) => (server.close(done), server.closeAllConnections()));
|
|
1739
|
+
agents.close();
|
|
1740
|
+
// The record stays: the next server rewrites it as it starts, and a stopped one whose time has passed is no stop.
|
|
1741
|
+
lock.release();
|
|
1742
|
+
}
|
|
1743
|
+
return {
|
|
1744
|
+
url,
|
|
1745
|
+
baseUrl: `${url}/v2`,
|
|
1746
|
+
port: address.port,
|
|
1747
|
+
token,
|
|
1748
|
+
tokenFile,
|
|
1749
|
+
tokenMade: stored?.made ?? false,
|
|
1750
|
+
...(setupUrl ? { setupUrl } : {}),
|
|
1751
|
+
boxesLine: boxesLine(boxOffers, enabledBoxes(env)),
|
|
1752
|
+
// Once: a second call, at any time, is the first one's promise, so a close repeated after the next server started
|
|
1753
|
+
// never writes this data root's record again (the next server's, by then).
|
|
1754
|
+
close: () => (stopped ??= stop()),
|
|
1755
|
+
};
|
|
1756
|
+
}
|