@parcha/agentrun-serve 0.0.0-stage → 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 +1723 -2
- 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 +94 -4
- package/skills/agentrun-serve/SKILL.md +128 -0
package/dist/runs.js
ADDED
|
@@ -0,0 +1,2279 @@
|
|
|
1
|
+
// Runs: each one a child process (`pi-durable-disk run` on `<data>/runs/<id>` with serve's app), pinned to a revision in
|
|
2
|
+
// the agent store. An agentic run is read live through the door its process serves on loopback; a workflow run is
|
|
3
|
+
// working while its process lives. Once the process has exited the run is read from its store, read-only, and carried
|
|
4
|
+
// back to the agent store (`carryBack`), and it is finished. A run whose process went before the run ended is opened
|
|
5
|
+
// again on its directory, and resumes from its store.
|
|
6
|
+
import { spawn } from "node:child_process";
|
|
7
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
8
|
+
import { closeSync, existsSync, openSync, rmSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { open as openFile, rm, stat } from "node:fs/promises";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
|
|
13
|
+
import { processAlive } from "@parcha/agentrun-kernel/host";
|
|
14
|
+
import { AgentHomeError } from "@parcha/pi-durable-agent";
|
|
15
|
+
import { registerLabel, registerTurnEnding, runMetricsWithDecisions, timelineOf, timelineReducer } from "@parcha/pi-durable-agent/timeline";
|
|
16
|
+
import { HARNESS_LOG_EVENT, harnessModelKeys, thinkingFor } from "./adapters.js";
|
|
17
|
+
import { DEFAULT_HARNESS, harnessOfBody, steersMidTurn } from "./harness.js";
|
|
18
|
+
import { hostMemory, memoryFull, neverFits, runMibOf, runsMemoryMib } from "./host.js";
|
|
19
|
+
import { storeBusy, storeError, whenFree } from "./agents.js";
|
|
20
|
+
import { FOLLOW_UP_OPEN_ENV, LAUNCH_LOST, readJson, RUN_CANCELLED, RUN_DOOR_TOKEN, RUN_LAUNCHING, RUN_META, runDoorToken, writeWhole } from "./files.js";
|
|
21
|
+
import { KEPT_AUTOSTOP_MINUTES, keepWhenIdle, wakeBoxes } from "./daytona-api.js";
|
|
22
|
+
import { LEARNING_LABEL, shortOf } from "./learning.js";
|
|
23
|
+
import { labelled, LearningRuns, reflecting, reflects, withLearning } from "./learning-run.js";
|
|
24
|
+
import { settleBox, sweepBoxes } from "./box/sweep.js";
|
|
25
|
+
import { rowPaths } from "./workspace-paths.js";
|
|
26
|
+
import { ASK_TOOL, toolingOf, workflowTools } from "./tools.js";
|
|
27
|
+
import { withDecisions } from "./decision-rows.js";
|
|
28
|
+
import { DECISION_KEY_FD_ENV, decisionKeysFor, providersNamed } from "./decisions.js";
|
|
29
|
+
import { ApiError, unsupported } from "./errors.js";
|
|
30
|
+
import { DOCUMENTS_ENV } from "./pdf-pages.js";
|
|
31
|
+
import { CAP_ENV, CAP_REFUSAL_PREFIX, SPEND_CAP_REACHED } from "./cap.js";
|
|
32
|
+
import { DEFAULT_MODEL_ENV, EFFORT_ENV, GATEWAY_KEY_ENV, hostModel, llmTiers, modelKeys, nodeTiers, PROVIDER_KEYS, thinkingOf, withoutFaux, workflowNodes } from "./model.js";
|
|
33
|
+
import { llmAnswers, pausedIn, readNodeLog, RUN_PAUSED } from "./pause.js";
|
|
34
|
+
import { durationMs } from "./print.js";
|
|
35
|
+
import { handsParallel, planeFor, recheckPlane, TOOL_PLANE_ENV } from "./tool-plane.js";
|
|
36
|
+
import { ChangeClock, RowLog } from "./rows.js";
|
|
37
|
+
import { TOOL_KEYS } from "./tool-keys.js";
|
|
38
|
+
import { isObject } from "./validate.js";
|
|
39
|
+
import { firstMessage } from "./run-manifest.js";
|
|
40
|
+
import { REFLECT_REQUEST, Turns } from "./turns.js";
|
|
41
|
+
import { DECISION_KEYS, handover, hostSecrets, secret, SECRET_NAMES, SECRETS_FD_ENV, SECRETS_LEN_ENV, withoutSecrets, withSecrets } from "./secrets.js";
|
|
42
|
+
import { MIN_SECRET } from "./learn/secrets.js";
|
|
43
|
+
import { keyRefusal, redacted, redactedAnswer, redactedLive, redactedOutput, runKeyOf, withoutLoopback } from "./key-refusal.js";
|
|
44
|
+
import { BOX_KEYS } from "./boxes.js";
|
|
45
|
+
import { remotePlace, storedPlace } from "./place.js";
|
|
46
|
+
import { destroyRunBoxes, ensureRemoteBox, PullIncomplete, pullRemoteBox, sweepRunBoxes } from "./run-box.js";
|
|
47
|
+
import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
|
|
48
|
+
export const STATUSES = ["queued", "working", "paused", "input_required", "completed", "failed", "cancelled"];
|
|
49
|
+
const TERMINAL = new Set(["completed", "failed", "cancelled"]);
|
|
50
|
+
const RELEASED = new Set(["sleeping", "paused", "done", "failed"]);
|
|
51
|
+
const LEASE_MS = 90_000;
|
|
52
|
+
/** How long an agentic run's process may finish its turn after SIGTERM, unless the server says otherwise. */
|
|
53
|
+
const DRAIN = "30s";
|
|
54
|
+
/** The run process's stderr, beside run.json: a file, so the process outlives a server that stops without stopping it. */
|
|
55
|
+
const PROCESS_LOG = "process.log";
|
|
56
|
+
/** How long a request waits for a run's door: its process coming up, or a settle in progress. */
|
|
57
|
+
const READY_TIMEOUT_MS = 45_000;
|
|
58
|
+
/** The reducer's live "Run started" and "Run finished" rows: a turn's edges, which no store entry makes on any harness,
|
|
59
|
+
* so a run's settled timeline never has them. Never served, live or settled, so no row a reader saw goes at the end. */
|
|
60
|
+
const QUIET = /:run:(start|end)$/;
|
|
61
|
+
const RETRY_CODES = ["OPENING", "PARKING", "RELEASED"];
|
|
62
|
+
/** How often one server opens a run again whose process went before the run ended, before it fails the run. */
|
|
63
|
+
const MAX_RELAUNCHES = 3;
|
|
64
|
+
/** How often a run's end that the agent store refused is written again. */
|
|
65
|
+
const SETTLE_RETRY_MS = 30_000;
|
|
66
|
+
/** How a run ended in the store, as its status: the store's `stopped` is v2's `cancelled`, and an escalated workflow
|
|
67
|
+
* completed its work and waits for a person (its `review`), which is not a failure. */
|
|
68
|
+
const STATUS_OF = { completed: "completed", failed: "failed", escalated: "completed", stopped: "cancelled" };
|
|
69
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
70
|
+
// A run's process that exited and was never reaped (a zombie, under a PID 1 that does not reap) is not alive.
|
|
71
|
+
const alive = processAlive;
|
|
72
|
+
/** Waits between carry backs that found the store busy: each attempt itself waits 5 s for the store's lock. */
|
|
73
|
+
const CARRY_BACK_RETRIES_MS = [500, 1_000, 2_000, 4_000, 8_000];
|
|
74
|
+
/** How long a run's process may live on after it released the run before its store is read anyway: the process holds the
|
|
75
|
+
* store's exclusive lock until it exits. */
|
|
76
|
+
const EXIT_AFTER_RELEASE_MS = 30_000;
|
|
77
|
+
/** How many 500 ms ticks in a row a live run's record is unreadable before the server says so. */
|
|
78
|
+
const UNREADABLE_TICKS = 10;
|
|
79
|
+
const warn = (runId, text) => void process.stderr.write(`agentrun-serve: run ${runId}: ${text}\n`);
|
|
80
|
+
/** How long serve's calls on a run's box (its destroy, the start's sweep) may take. */
|
|
81
|
+
const BOX_CALL_MS = 60_000;
|
|
82
|
+
const boxContext = (ms = BOX_CALL_MS) => withAbortSignal(AbortSignal.timeout(ms), BACKGROUND_CONTEXT);
|
|
83
|
+
/** How long a remote box's making and seed, or one pull of its work/, may take: a sandbox's start, then the copy. */
|
|
84
|
+
const REMOTE_SYNC_MS = 15 * 60_000;
|
|
85
|
+
/** How long a read of a run's files waits for the pull its turn's end began. */
|
|
86
|
+
const PULL_WAIT_MS = 120_000;
|
|
87
|
+
/** A run's end that waits for its remote box's last pull: its settle is tried again until the pull lands. */
|
|
88
|
+
class PullPending extends Error {
|
|
89
|
+
}
|
|
90
|
+
/** Run directory `dir`'s own door token, made now (mode 0600, never through a link) when it has none. */
|
|
91
|
+
function ensureRunDoorToken(dir) {
|
|
92
|
+
const held = runDoorToken(dir);
|
|
93
|
+
if (held)
|
|
94
|
+
return held;
|
|
95
|
+
const token = `ar_door_${randomBytes(24).toString("base64url")}`;
|
|
96
|
+
try {
|
|
97
|
+
writeFileSync(join(dir, RUN_DOOR_TOKEN), `${token}\n`, { mode: 0o600, flag: "wx" });
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
// Made meanwhile: that one is the run's.
|
|
101
|
+
if (error.code !== "EEXIST")
|
|
102
|
+
throw error;
|
|
103
|
+
const made = runDoorToken(dir);
|
|
104
|
+
if (!made)
|
|
105
|
+
throw new Error(`the run's door token at ${RUN_DOOR_TOKEN} is not one`);
|
|
106
|
+
return made;
|
|
107
|
+
}
|
|
108
|
+
return token;
|
|
109
|
+
}
|
|
110
|
+
const clip = (text, max) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);
|
|
111
|
+
const isLoopback = (host) => host === "localhost" || host === "[::1]" || host === "::1" || /^127\./.test(host);
|
|
112
|
+
const holderPid = (record) => (isObject(record?.holder) && Number.isSafeInteger(record.holder.pid) ? record.holder.pid : undefined);
|
|
113
|
+
/** How a workflow run's workflow ended, as its app wrote it in the run's final status: absent until it ended. */
|
|
114
|
+
function workflowEnding(record) {
|
|
115
|
+
const detail = isObject(record?.detail) ? record.detail : undefined;
|
|
116
|
+
if (!RELEASED.has(String(record?.status)) || !["complete", "escalated", "refused", "stopped"].includes(String(detail?.workflow)))
|
|
117
|
+
return undefined;
|
|
118
|
+
return { status: detail.workflow, ...(typeof detail.code === "string" ? { code: detail.code } : {}), ...(typeof detail.message === "string" ? { message: detail.message } : {}) };
|
|
119
|
+
}
|
|
120
|
+
/** `review` at the run's saved end `endedAt`, so review.at and ended_at are one time. */
|
|
121
|
+
const reviewAt = (review, endedAt) => (review ? { kind: review.kind, node: review.node, reason: review.reason, at: endedAt } : null);
|
|
122
|
+
/** A failed run's error from its row and serve.json: its own, else the row's summary. */
|
|
123
|
+
const errorOfRow = (row, meta) => ({ code: meta?.error?.code ?? "run_failed", message: meta?.error?.message ?? row.summary ?? "The run failed.", retryable: false, ...(meta?.error?.details ? { details: meta.error.details } : {}) });
|
|
124
|
+
/** An ended run's review from its row and serve.json: an escalated one's as its end saved it, else (an end saved before
|
|
125
|
+
* reviews were kept) the row's summary; null for every other run. */
|
|
126
|
+
const reviewOfRow = (row, meta) => row.state !== "escalated" ? null : (meta?.review ?? { kind: null, node: null, reason: row.summary ?? "The workflow escalated." });
|
|
127
|
+
const ASKED = "Asked you: ";
|
|
128
|
+
registerLabel(ASK_TOOL, (args) => `${ASKED}${typeof args.question === "string" ? args.question : ""}`, undefined, { name: "Ask you a question" });
|
|
129
|
+
// ask_person ends its turn (tools.ts): the person's reply is their next message, never a steer.
|
|
130
|
+
registerTurnEnding(ASK_TOOL);
|
|
131
|
+
/** The waiting row after each answered `ask_person` call, which the timeline module does not know. The question comes
|
|
132
|
+
* from the call's row, whose label this module registers. */
|
|
133
|
+
export function withAsks(rows) {
|
|
134
|
+
const out = [];
|
|
135
|
+
const questions = new Map();
|
|
136
|
+
for (const row of rows) {
|
|
137
|
+
out.push(row);
|
|
138
|
+
if (row.kind === "tool_use" && row.tool_name === ASK_TOOL && row.tool_use_id && row.summary?.startsWith(ASKED))
|
|
139
|
+
questions.set(row.tool_use_id, row.summary.slice(ASKED.length));
|
|
140
|
+
if (row.kind === "tool_result" && row.tool_name === ASK_TOOL && row.tool_status === "success") {
|
|
141
|
+
const question = questions.get(row.tool_use_id ?? "") || "the agent asked you a question";
|
|
142
|
+
out.push({ ...row, id: `${row.id}:waiting`, kind: "waiting", summary: `Waiting for you: ${clip(question, 480)}`, text: clip(question, 2000), tool_name: null, tool_use_id: null, tool_status: null, tool_input_preview: null, tool_result_preview: null, tool_result_size_bytes: null });
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return out;
|
|
146
|
+
}
|
|
147
|
+
/** The row that says a run's booked spend passed its cap, and by how much, after its usage row: a request's cost is
|
|
148
|
+
* booked once it answers, and one carrying a native web search is held at an allowance, not a bound (cap.ts), so a run
|
|
149
|
+
* can pass its cap by its last request. The next request is then refused, and the run ends spend_cap_reached. */
|
|
150
|
+
export function withOverCap(rows, cap) {
|
|
151
|
+
const at = rows.findLastIndex((row) => row.kind === "usage");
|
|
152
|
+
const usd = rows[at]?.usage?.usd;
|
|
153
|
+
if (cap === undefined || typeof usd !== "number" || usd <= cap)
|
|
154
|
+
return rows;
|
|
155
|
+
const { usage: _, ...usage } = rows[at];
|
|
156
|
+
const over = { ...usage, id: `${usage.id}:over_cap`, kind: "phase", summary: `Spent $${usd.toFixed(4)}, $${(usd - cap).toFixed(4)} over the run's cap of $${cap}`, text: null };
|
|
157
|
+
return [...rows.slice(0, at + 1), over, ...rows.slice(at + 1)];
|
|
158
|
+
}
|
|
159
|
+
/** Notes the messages the run's turns took and how each turn ended, from `entries` (its root's), `submissions` (pi's
|
|
160
|
+
* input submissions) and a reconnect's `snapshot` of them (the door's `inputs`, the run's whole state of them), and the
|
|
161
|
+
* newest entry (learning-run.ts reads it). The end-of-run learning turn's entries are no turn of the run's: none of
|
|
162
|
+
* them, its TURN_END and its settlement included, opens, closes or answers one of the run's messages. */
|
|
163
|
+
function noteTurns(run, entries, submissions = [], snapshot) {
|
|
164
|
+
for (const value of entries) {
|
|
165
|
+
if (!isObject(value) || typeof value.id !== "number")
|
|
166
|
+
continue;
|
|
167
|
+
run.lastEntry = Math.max(run.lastEntry ?? 0, value.id);
|
|
168
|
+
// The end-of-run turn's assistant messages, whole, by entry: what the turn answered, whose notes learning reads
|
|
169
|
+
// (learning-run.ts). The ledger skips them; this is their only reader here.
|
|
170
|
+
if (value.kind === "pi.assistant" && reflects(run.meta.reflect, value.id) && Array.isArray(value.model) && isObject(value.model[0])) {
|
|
171
|
+
const content = value.model[0].content;
|
|
172
|
+
(run.turnText ??= new Map()).set(value.id, typeof content === "string" ? content : Array.isArray(content) ? content.filter((b) => isObject(b) && b.type === "text").map((b) => String(b.text ?? "")).join("\n").trim() : "");
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
const reflect = (id) => reflects(run.meta.reflect, id);
|
|
176
|
+
run.turns.note(entries, submissions, reflect);
|
|
177
|
+
if (snapshot)
|
|
178
|
+
run.turns.snapshot(snapshot, reflect);
|
|
179
|
+
}
|
|
180
|
+
/** Read only on a run's `rows`, which hold no QUIET row (take). */
|
|
181
|
+
const shows = (r) => r.kind !== "usage" && r.kind !== "phase";
|
|
182
|
+
const meaningful = (rows) => rows.findLast((r) => shows(r) && r.agent_label !== LEARNING_LABEL);
|
|
183
|
+
const pendingOf = (rows) => {
|
|
184
|
+
const last = meaningful(rows);
|
|
185
|
+
return last?.kind === "waiting" ? { kind: "question", question: last.text ?? last.summary ?? "", asked_at: last.timestamp } : null;
|
|
186
|
+
};
|
|
187
|
+
/** An import's answer, the one row reading of an answer left: its records hold no turn's end (it ran elsewhere), so its
|
|
188
|
+
* last meaningful row is its answer when that row is one, a final answer's or a text row's. */
|
|
189
|
+
const importAnswerOf = (rows) => {
|
|
190
|
+
const last = meaningful(rows);
|
|
191
|
+
return last?.kind === "final_answer" || last?.kind === "text_block" ? last : undefined;
|
|
192
|
+
};
|
|
193
|
+
const usageOf = (rows) => rows.findLast((r) => r.kind === "usage");
|
|
194
|
+
/** The run's cost from its usage row: null when a response's cost is unknown, 0 before any request. */
|
|
195
|
+
export const costOf = (rows) => {
|
|
196
|
+
const usage = usageOf(rows);
|
|
197
|
+
return usage ? (usage.usage?.usd ?? null) : 0;
|
|
198
|
+
};
|
|
199
|
+
/** What a run's paid tools charged, from the same rows its cost is read from: each charge's line carries it (`usage` on a
|
|
200
|
+
* `phase` row); null when one is unknown. A call still marked, in flight or cut, is no charge here. */
|
|
201
|
+
export const toolCostOf = (rows) => rows.reduce((sum, row) => (row.kind !== "phase" || !row.usage ? sum : sum === null || row.usage.usd === null ? null : sum + row.usage.usd), 0);
|
|
202
|
+
/** A run's cost for its views: its usage row's, else what the store kept when it carried the run back (0 before any
|
|
203
|
+
* request). A usage row that says unknown, or says nothing, stays unknown: what the store kept dates from before a
|
|
204
|
+
* follow-up. */
|
|
205
|
+
export function costView(rows, stored, decisions) {
|
|
206
|
+
const usage = usageOf(rows);
|
|
207
|
+
// A workflow run's decisions, once its end is read: their cost joins its model nodes', and one unknown makes it unknown.
|
|
208
|
+
if (decisions !== undefined) {
|
|
209
|
+
const models = usage ? (usage.usage?.usd ?? null) : 0;
|
|
210
|
+
return models === null || decisions === null ? null : models + decisions;
|
|
211
|
+
}
|
|
212
|
+
if (!usage)
|
|
213
|
+
return stored === undefined ? 0 : stored;
|
|
214
|
+
return usage.usage?.usd ?? null;
|
|
215
|
+
}
|
|
216
|
+
export function soFarOf(rows, decisions) {
|
|
217
|
+
if (decisions === null)
|
|
218
|
+
return undefined;
|
|
219
|
+
const usage = usageOf(rows)?.usage;
|
|
220
|
+
const models = !usage ? { known: 0, unpriced: 0 } : usage.usd !== null ? { known: usage.usd, unpriced: 0 } : usage.so_far_usd !== undefined && usage.unpriced !== undefined ? { known: usage.so_far_usd, unpriced: usage.unpriced } : undefined;
|
|
221
|
+
if (!models)
|
|
222
|
+
return undefined;
|
|
223
|
+
const unpriced = models.unpriced + (decisions?.unpriced ?? 0);
|
|
224
|
+
return unpriced > 0 ? { so_far_usd: Math.round((models.known + (decisions?.known ?? 0)) * 1e6) / 1e6, unpriced } : undefined;
|
|
225
|
+
}
|
|
226
|
+
/** What a run's meta kept of its cost so far at its end, when it is well formed. */
|
|
227
|
+
const soFarOfMeta = (meta) => {
|
|
228
|
+
const kept = meta?.cost_so_far;
|
|
229
|
+
return kept && typeof kept.so_far_usd === "number" && Number.isFinite(kept.so_far_usd) && Number.isInteger(kept.unpriced) && kept.unpriced > 0 ? { so_far_usd: kept.so_far_usd, unpriced: kept.unpriced } : undefined;
|
|
230
|
+
};
|
|
231
|
+
/** The whole text of the run's newest answer with text, paid for: an assistant message's, else its newest answer row's. */
|
|
232
|
+
const lastAnswer = (run) => run.turns.newestText ?? run.rows.findLast((r) => r.kind === "final_answer" && r.agent_label !== LEARNING_LABEL)?.text ?? null;
|
|
233
|
+
/** A row's store entry, from its id (`<conversation>:<entry>[:...]`). */
|
|
234
|
+
const entryOfRow = (id) => Number(id.split(":")[1]);
|
|
235
|
+
/** The answer of a run that completed: the whole text of the entry its turn's end names, "" when that turn showed no text,
|
|
236
|
+
* never an earlier turn's. Without such an end (a run still working, a workflow, a store an older server wrote): the
|
|
237
|
+
* newest answer it gave, whole (lastAnswer); an import's, its last row's when that row is its answer. */
|
|
238
|
+
function answerOfRun(run) {
|
|
239
|
+
const end = run.turns.end();
|
|
240
|
+
if (end?.status === "answered") {
|
|
241
|
+
if (end.answer === null)
|
|
242
|
+
return "";
|
|
243
|
+
// The entry's row when its text was not read here: a final answer's, or a text row's (a stop at the length limit).
|
|
244
|
+
return run.turns.text(end.answer) ?? run.rows.findLast((r) => (r.kind === "final_answer" || r.kind === "text_block") && entryOfRow(r.id) === end.answer)?.text ?? "";
|
|
245
|
+
}
|
|
246
|
+
const imported = run.imported ? importAnswerOf(run.rows) : undefined;
|
|
247
|
+
return lastAnswer(run) ?? imported?.text ?? imported?.summary ?? null;
|
|
248
|
+
}
|
|
249
|
+
const usersOf = (rows) => rows.filter((r) => r.kind === "user_message").length;
|
|
250
|
+
const lastUserMessage = (rows) => rows.findLast((r) => r.kind === "user_message")?.id;
|
|
251
|
+
// A row's place in the store: its entry's id. The store mints conversation and entry ids from one counter, so entry ids
|
|
252
|
+
// order rows across conversations and the conversation is no part of the order.
|
|
253
|
+
const placeOf = (id) => Number(id.slice(id.lastIndexOf(":") + 1));
|
|
254
|
+
/** Whether the turn a stop ended is still where the run stands: no message shown is newer than the stop's. By order,
|
|
255
|
+
* never by a count or by the stopped message itself, which a compaction can take off the rows. */
|
|
256
|
+
export const stoppedAt = (meta, rows) => {
|
|
257
|
+
if (meta.stopped_at === undefined)
|
|
258
|
+
return meta.stopped_after !== undefined && meta.stopped_after === usersOf(rows);
|
|
259
|
+
const at = placeOf(meta.stopped_at);
|
|
260
|
+
return !rows.some((r) => r.kind === "user_message" && placeOf(r.id) > at);
|
|
261
|
+
};
|
|
262
|
+
const stopped = (run) => stoppedAt(run.meta, run.rows);
|
|
263
|
+
/** What a stop keeps of where the run stands: the person's last message, by its id, or the place before any. */
|
|
264
|
+
export const stopMark = (rows) => ({ stopped_at: lastUserMessage(rows) ?? `${ROOT_CONVERSATION_ID}:0` });
|
|
265
|
+
/** The rows a snapshot that no longer holds them leaves served: those committed entries made. A row any connection
|
|
266
|
+
* showed live is not one (`live` holds them for the run), so a live row that ended while the door was away goes. */
|
|
267
|
+
export function keepCommitted(live, rows, isLive) {
|
|
268
|
+
for (const row of rows)
|
|
269
|
+
if (isLive(row.id))
|
|
270
|
+
live.add(row.id);
|
|
271
|
+
return (id) => !live.has(id) && !isLive(id);
|
|
272
|
+
}
|
|
273
|
+
/** A wait's mark: the stop it stands at, while that stop holds, else its newest row (the question it waits on). */
|
|
274
|
+
const waitMark = (run) => (stopped(run) && run.meta.stopped_at) || meaningful(run.rows)?.id || "";
|
|
275
|
+
/** Waits for `work`, or until `deadline` (ms since the epoch), whichever comes first. */
|
|
276
|
+
async function untilDeadline(work, deadline) {
|
|
277
|
+
let timer;
|
|
278
|
+
await Promise.race([work, new Promise((resolve) => (timer = setTimeout(resolve, Math.max(0, deadline - Date.now()))))]);
|
|
279
|
+
clearTimeout(timer);
|
|
280
|
+
}
|
|
281
|
+
/** A run's status and state, by the contract's table. */
|
|
282
|
+
export function statusOf(run) {
|
|
283
|
+
if (run.outcome)
|
|
284
|
+
return { status: run.outcome, state: "idle" };
|
|
285
|
+
if (run.finishing)
|
|
286
|
+
return { status: run.finishing, state: "idle" };
|
|
287
|
+
// A paused workflow run finishes what it has in flight and starts nothing new until it is resumed (pause.ts). A held run
|
|
288
|
+
// read without its directory (a view built for a count) has no mark to read.
|
|
289
|
+
if (run.kind === "workflow")
|
|
290
|
+
return run.dir && pausedIn(run.dir) ? { status: "paused", state: "idle" } : { status: run.working ? "working" : "queued", state: "working" };
|
|
291
|
+
const users = usersOf(run.rows);
|
|
292
|
+
if (run.submitted > 0)
|
|
293
|
+
return { status: users ? "working" : "queued", state: "working" };
|
|
294
|
+
// No rows is a run not shown yet (adopted, before its first snapshot), whatever an old stop says. Rows with no
|
|
295
|
+
// message of the person's are a compaction's (it shows its summary), which can summarize every message of a stop.
|
|
296
|
+
if (!run.rows.length)
|
|
297
|
+
return { status: "queued", state: "working" };
|
|
298
|
+
if (stopped(run))
|
|
299
|
+
return { status: "input_required", state: "idle" };
|
|
300
|
+
if (!users)
|
|
301
|
+
return { status: "queued", state: "working" };
|
|
302
|
+
// Every message's turn is over and the newest one's ended interrupted, with no stop of the person's saying so (the
|
|
303
|
+
// harness ended it on its own): the run waits for the person, as after a stop, never working for good.
|
|
304
|
+
if (run.kind === "agentic" && run.submitted === 0 && run.turns.end()?.status === "interrupted")
|
|
305
|
+
return { status: "input_required", state: "idle" };
|
|
306
|
+
if (run.working)
|
|
307
|
+
return { status: "working", state: "working" };
|
|
308
|
+
if (meaningful(run.rows)?.kind === "waiting")
|
|
309
|
+
return { status: "input_required", state: "waiting" };
|
|
310
|
+
return { status: "working", state: "idle" };
|
|
311
|
+
}
|
|
312
|
+
/** The server's own secrets, which a run's process never gets: the API token, by name or by value, the seal key
|
|
313
|
+
* the tool keys are kept under (tool-keys.ts), and the boxes' keys (boxes.ts), which only the server's box providers use. */
|
|
314
|
+
const SERVER_ONLY = new Set(["AGENTRUN_TOKEN", "AGENTRUN_API_KEY", "AGENTRUN_SEAL_KEY", ...BOX_KEYS]);
|
|
315
|
+
/** The secrets a run's process is handed over its pipe (secrets.ts): every one but the server's own and the decision
|
|
316
|
+
* keys, which go on their own descriptor. */
|
|
317
|
+
export const RUN_SECRETS = SECRET_NAMES.filter((name) => !SERVER_ONLY.has(name) && !DECISION_KEYS.includes(name));
|
|
318
|
+
/** The fields a run gets only when its revision names what they unlock: a `tool` key's. Any other kind's (a model key's)
|
|
319
|
+
* is the model's to need, as every model key is. */
|
|
320
|
+
const scopedOf = (rows) => rows.filter((row) => row.kind === "tool").flatMap((row) => row.fields);
|
|
321
|
+
/** The model keys: every key of pi-ai's providers (model.ts' PROVIDER_KEYS) and the gateway's. A run gets those its model
|
|
322
|
+
* needs and no other (secretsFor). A workflow's decision keys, OpenRouter's among them, go on its decision descriptor
|
|
323
|
+
* (decisions.ts), whatever its model. */
|
|
324
|
+
const MODEL_KEYS = [...new Set([...Object.values(PROVIDER_KEYS).flat(), GATEWAY_KEY_ENV])];
|
|
325
|
+
/** What a run whose revision was not read is handed: no tool key, and no model key. */
|
|
326
|
+
const NO_TOOL_KEYS = RUN_SECRETS.filter((name) => !scopedOf(TOOL_KEYS).includes(name) && !MODEL_KEYS.includes(name));
|
|
327
|
+
/** `revision`'s RunNeeds. */
|
|
328
|
+
export async function needsOf(revision) {
|
|
329
|
+
const workflow = revision.kind === "workflow" ? revision.body.workflow : undefined;
|
|
330
|
+
const nodes = workflow ? workflowNodes(workflow, (await import("@parcha/agentrun-dsl")).inspectWorkflow(workflow)) : undefined;
|
|
331
|
+
const bound = nodes && workflowTools(nodes);
|
|
332
|
+
return {
|
|
333
|
+
harness: revision.body.harness ?? DEFAULT_HARNESS,
|
|
334
|
+
...(revision.kind === "agentic" && revision.body.model ? { model: revision.body.model } : {}),
|
|
335
|
+
tools: bound ? [...bound.nodes, ...bound.calls] : [...(revision.body.tools ?? [])],
|
|
336
|
+
...(nodes ? { tiers: llmTiers(nodes, nodeTiers(nodes)) } : {}),
|
|
337
|
+
decisionProviders: nodes ? providersNamed(nodes) : [],
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
/** The secrets a run of `needs` is handed over its pipe, by the keys `env` holds now: RUN_SECRETS but each field of a
|
|
341
|
+
* `tool` row of `rows` (TOOL_KEYS) that unlocks none of the tools the run binds; and but each model key its model does
|
|
342
|
+
* not need, from the host's model settings and the keys in `env`: a pi run's, its models' providers' keys or the
|
|
343
|
+
* gateway's (model.ts' modelKeys: its own model, or the host's of each tier it runs); codex's and claude-agent's, the
|
|
344
|
+
* one key their route sends for the revision's model (adapters.ts' harnessModelKeys). Read at each launch, so a key
|
|
345
|
+
* saved with no restart counts at the next. */
|
|
346
|
+
export function keysFor(needs, env, rows = TOOL_KEYS) {
|
|
347
|
+
const named = new Set(needs.tools);
|
|
348
|
+
const unlocked = new Set(rows.filter((row) => row.unlocks.some((name) => named.has(name))).flatMap((row) => row.fields));
|
|
349
|
+
const scoped = scopedOf(rows);
|
|
350
|
+
const model = new Set(needs.harness !== DEFAULT_HARNESS ? harnessModelKeys(needs.harness, env, needs.model) : needs.tiers ? modelKeys(env, undefined, needs.tiers) : modelKeys(env, needs.model));
|
|
351
|
+
return RUN_SECRETS.filter((name) => (!scoped.includes(name) || unlocked.has(name)) && (!MODEL_KEYS.includes(name) || model.has(name)));
|
|
352
|
+
}
|
|
353
|
+
/** The secrets a run of `revision` is handed with the keys `env` holds (needsOf, then keysFor). */
|
|
354
|
+
export async function secretsFor(revision, rows = TOOL_KEYS, env = process.env) {
|
|
355
|
+
return keysFor(await needsOf(revision), env, rows);
|
|
356
|
+
}
|
|
357
|
+
/** The decision providers a run of `revision` needs keys for (needsOf). Its web tools' need, Parallel's where one
|
|
358
|
+
* resolves to Parallel, is its tool plane's (tool-plane.ts' handsParallel), read at each launch. */
|
|
359
|
+
export async function decisionProvidersFor(revision) {
|
|
360
|
+
return (await needsOf(revision)).decisionProviders;
|
|
361
|
+
}
|
|
362
|
+
/** The module a run's process preloads (`--import`) to read its pipe before anything else; app.ts gets the same instance. */
|
|
363
|
+
const SECRETS_MODULE = new URL("./secrets.js", import.meta.url).href;
|
|
364
|
+
/** A run's process's environment: no secret in it (they go over its pipe), nor the token by value; the AGENT_MODEL
|
|
365
|
+
* variables and the rest pass, and the door token goes by file. A test hook's name passes never (withoutFaux): the run
|
|
366
|
+
* gets one only from startServe's options. */
|
|
367
|
+
export const childEnv = (env, token) => Object.fromEntries(Object.entries(withoutSecrets(withoutFaux(env))).filter(([, value]) => value !== token));
|
|
368
|
+
/** One line of the run process's log in words: pi-durable-disk writes JSON lines (`{at, event, message, ...}`). */
|
|
369
|
+
function inWords(line) {
|
|
370
|
+
let value;
|
|
371
|
+
try {
|
|
372
|
+
value = JSON.parse(line);
|
|
373
|
+
}
|
|
374
|
+
catch {
|
|
375
|
+
return line;
|
|
376
|
+
}
|
|
377
|
+
if (!isObject(value))
|
|
378
|
+
return line;
|
|
379
|
+
const text = (key) => (typeof value[key] === "string" ? value[key] : undefined);
|
|
380
|
+
return [text("event"), text("message") ?? text("error")].filter(Boolean).join(": ") || "the run's process left no message";
|
|
381
|
+
}
|
|
382
|
+
/** The line of the run process's log a failure's message is made of: its last, past any harness's own lines (a proxy's
|
|
383
|
+
* refusal just before a crash says nothing of why the process went). */
|
|
384
|
+
export function failureLine(log) {
|
|
385
|
+
const lines = log.trim().split("\n");
|
|
386
|
+
return ownLine(lines) ?? lines.at(-1) ?? "";
|
|
387
|
+
}
|
|
388
|
+
/** The last of `lines` that is not a harness's own line, if any. */
|
|
389
|
+
function ownLine(lines) {
|
|
390
|
+
return lines.findLast((line) => {
|
|
391
|
+
if (line.trim() === "")
|
|
392
|
+
return false;
|
|
393
|
+
try {
|
|
394
|
+
return JSON.parse(line)?.event !== HARNESS_LOG_EVENT;
|
|
395
|
+
}
|
|
396
|
+
catch {
|
|
397
|
+
return true;
|
|
398
|
+
}
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
/** How far back from its end a failure's message is looked for in the run's log, in steps of LOG_STEP. */
|
|
402
|
+
const LOG_STEP = 4096;
|
|
403
|
+
const LOG_REACH = 1 << 20;
|
|
404
|
+
/** The last line of the run process's log, in words, for a failure's message. */
|
|
405
|
+
export async function lastLogLine(run) {
|
|
406
|
+
const file = await openFile(join(run.dir, PROCESS_LOG)).catch(() => null);
|
|
407
|
+
if (!file)
|
|
408
|
+
return "";
|
|
409
|
+
try {
|
|
410
|
+
// Backward until a whole line is the process's own: harness lines after it may run past any one read, and a read
|
|
411
|
+
// that starts inside a line has only its tail, which is no line at all. Each step looks only at the lines it
|
|
412
|
+
// completes; what was read is joined once, and failureLine, the one rule, picks the line from it.
|
|
413
|
+
const { size } = await file.stat();
|
|
414
|
+
const chunks = [];
|
|
415
|
+
let start = size;
|
|
416
|
+
// The oldest line read so far, torn at the read's start unless that is the file's start.
|
|
417
|
+
let head = Buffer.alloc(0);
|
|
418
|
+
while (start > 0 && size - start < LOG_REACH) {
|
|
419
|
+
const from = Math.max(0, start - LOG_STEP);
|
|
420
|
+
const { buffer } = await file.read(Buffer.alloc(start - from), 0, start - from, from);
|
|
421
|
+
start = from;
|
|
422
|
+
chunks.unshift(buffer);
|
|
423
|
+
const newline = buffer.indexOf(0x0a);
|
|
424
|
+
const completed = start === 0 ? Buffer.concat([buffer, head]) : newline < 0 ? Buffer.alloc(0) : Buffer.concat([buffer.subarray(newline + 1), head]);
|
|
425
|
+
head = start === 0 ? Buffer.alloc(0) : newline < 0 ? Buffer.concat([buffer, head]) : buffer.subarray(0, newline);
|
|
426
|
+
if (ownLine(completed.toString("utf8").split("\n")) !== undefined)
|
|
427
|
+
break;
|
|
428
|
+
}
|
|
429
|
+
return clip(inWords(failureLine(Buffer.concat(chunks).subarray(head.length).toString("utf8"))), 300);
|
|
430
|
+
}
|
|
431
|
+
finally {
|
|
432
|
+
await file.close();
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
export class Runs {
|
|
436
|
+
options;
|
|
437
|
+
runs = new Map();
|
|
438
|
+
/** Each workflow revision's workflow, by revision id, as a graph read it: a revision never changes. */
|
|
439
|
+
workflows = new Map();
|
|
440
|
+
/** What decides the secrets each revision's runs are handed (needsOf), by revision id: read once, from the revision the
|
|
441
|
+
* run is pinned to, never from a request. The keys themselves are read at each launch (keysFor). */
|
|
442
|
+
needs = new Map();
|
|
443
|
+
/** Each workflow run's last graph read whole: what a poll that met a busy store answers, marked stale. */
|
|
444
|
+
graphs = new Map();
|
|
445
|
+
adopting = new Map();
|
|
446
|
+
clock = new ChangeClock();
|
|
447
|
+
cli = fileURLToPath(new URL("./cli.js", import.meta.resolve("@parcha/pi-durable-disk")));
|
|
448
|
+
app = fileURLToPath(new URL("./app.js", import.meta.url));
|
|
449
|
+
closing = false;
|
|
450
|
+
/** Set once `close` is done: the store is closed, so nothing settles after it. */
|
|
451
|
+
closed = false;
|
|
452
|
+
/** Runs past the cap's check whose process is not started yet. */
|
|
453
|
+
starting = 0;
|
|
454
|
+
/** The memory the starts counted in `starting` reserve, in MiB. */
|
|
455
|
+
startingMib = 0;
|
|
456
|
+
/** This host's memory, out of which each live run reserves what its harness takes (host.ts), beside `maxRuns`. */
|
|
457
|
+
memory = hostMemory();
|
|
458
|
+
/** The start sweep of the boxes runs left: once, before any run opens a box (sweepOnce). */
|
|
459
|
+
swept;
|
|
460
|
+
/** The runs' learning (learning-run.ts): a step this file calls as a run starts, ends, settles, opens again and is
|
|
461
|
+
* recovered, handed what it moves of a run. */
|
|
462
|
+
learning;
|
|
463
|
+
constructor(options) {
|
|
464
|
+
this.options = options;
|
|
465
|
+
this.learning = new LearningRuns(options, {
|
|
466
|
+
held: (id) => this.runs.get(id),
|
|
467
|
+
get: (id) => this.get(id),
|
|
468
|
+
live: (run) => this.live(run),
|
|
469
|
+
toLiveDoor: (run, path, body, turnOrigin) => this.toLiveDoor(run, path, body, turnOrigin),
|
|
470
|
+
toDoor: (run, path, body) => this.toDoor(run, path, body),
|
|
471
|
+
abortTurn: (run) => this.abortTurn(run),
|
|
472
|
+
terminate: (run) => this.terminate(run),
|
|
473
|
+
mark: (run) => this.mark(run),
|
|
474
|
+
show: (run) => this.show(run),
|
|
475
|
+
save: (run) => this.saveMeta(run),
|
|
476
|
+
costOf,
|
|
477
|
+
fauxEnv: () => this.fauxEnv(),
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
/** A test's seam (startServe's `beforeAbort`): awaited by a stop between its mark and its abort, so a test can hold a
|
|
481
|
+
* stop in flight there. */
|
|
482
|
+
beforeAbort;
|
|
483
|
+
/** A test's seam (startServe's `beforeReopenLaunch`): awaited by a reopen after the run reads open again and before its
|
|
484
|
+
* launch, so a test can hold a reopen there. */
|
|
485
|
+
beforeReopenLaunch;
|
|
486
|
+
/** A test's seam (startServe's `beforeSubmit`): awaited by a message before it goes to the run's door. */
|
|
487
|
+
beforeSubmit;
|
|
488
|
+
get store() {
|
|
489
|
+
return this.options.agents.store;
|
|
490
|
+
}
|
|
491
|
+
// ---- reading --------------------------------------------------------------------------------------------------------
|
|
492
|
+
/** Run `id` when this process holds it, never read from disk. */
|
|
493
|
+
held(id) {
|
|
494
|
+
return this.runs.get(id);
|
|
495
|
+
}
|
|
496
|
+
/** Run `id`, read from the agent store the first time this process sees it. */
|
|
497
|
+
async get(id) {
|
|
498
|
+
const known = this.runs.get(id);
|
|
499
|
+
if (known)
|
|
500
|
+
return known;
|
|
501
|
+
const row = await this.options.agents.request(() => this.store.readRun(id));
|
|
502
|
+
return row ? this.adopt(row) : null;
|
|
503
|
+
}
|
|
504
|
+
/** One Run per run id, however many requests ask for it at once. */
|
|
505
|
+
adopt(row) {
|
|
506
|
+
const known = this.runs.get(row.id);
|
|
507
|
+
if (known)
|
|
508
|
+
return Promise.resolve(known);
|
|
509
|
+
let pending = this.adopting.get(row.id);
|
|
510
|
+
if (!pending) {
|
|
511
|
+
pending = this.load(row).finally(() => this.adopting.delete(row.id));
|
|
512
|
+
this.adopting.set(row.id, pending);
|
|
513
|
+
}
|
|
514
|
+
return pending;
|
|
515
|
+
}
|
|
516
|
+
async load(row) {
|
|
517
|
+
const dir = join(this.options.agents.dir, "runs", row.id);
|
|
518
|
+
const stored = (await readJson(join(dir, RUN_META)));
|
|
519
|
+
const meta = {
|
|
520
|
+
title: typeof stored?.title === "string" ? stored.title : "",
|
|
521
|
+
created_at: typeof stored?.created_at === "string" ? stored.created_at : row.startedAt,
|
|
522
|
+
...(isObject(stored?.input) ? { input: stored.input } : {}),
|
|
523
|
+
...(typeof stored?.effort === "string" ? { effort: stored.effort } : {}),
|
|
524
|
+
...(typeof stored?.max_cost_usd === "number" ? { max_cost_usd: stored.max_cost_usd } : {}),
|
|
525
|
+
...(stored?.error ? { error: stored.error } : {}),
|
|
526
|
+
...(stored && "output" in stored ? { output: stored.output } : {}),
|
|
527
|
+
...(isObject(stored?.review) ? { review: stored.review } : {}),
|
|
528
|
+
...(typeof stored?.stopped_at === "string" ? { stopped_at: stored.stopped_at } : {}),
|
|
529
|
+
...(typeof stored?.stopped_after === "number" ? { stopped_after: stored.stopped_after } : {}),
|
|
530
|
+
...(isObject(stored?.launch_thinking) ? { launch_thinking: stored.launch_thinking } : {}),
|
|
531
|
+
...(isObject(stored?.tool_plane) ? { tool_plane: stored.tool_plane } : {}),
|
|
532
|
+
...(stored?.place ? { place: storedPlace(stored.place) } : {}),
|
|
533
|
+
...(isObject(stored?.learning) ? { learning: stored.learning } : {}),
|
|
534
|
+
...(isObject(stored?.reflect) ? { reflect: stored.reflect } : {}),
|
|
535
|
+
};
|
|
536
|
+
// A seed copy a server went down during is taken back before anything holds the run: its relaunch, a settle, a
|
|
537
|
+
// follow-up (learning-run.ts onLoad).
|
|
538
|
+
if (stored)
|
|
539
|
+
await this.learning.onLoad(row, dir, meta, () => writeWhole(join(dir, RUN_META), `${JSON.stringify(meta)}\n`));
|
|
540
|
+
const known = await this.options.agents.revision(row.agent, row.revision);
|
|
541
|
+
const run = this.blank(row, dir, meta, known?.version ?? 0, harnessOfBody(known?.revision.body ?? {}), known ? await toolingOf(known.revision) : undefined, known?.revision);
|
|
542
|
+
this.runs.set(row.id, run);
|
|
543
|
+
run.launching = existsSync(join(dir, RUN_LAUNCHING));
|
|
544
|
+
const record = await this.record(run);
|
|
545
|
+
// An ended run is ended before its rows are read, so they never make it a wait: a last row that asks is no notice.
|
|
546
|
+
if (row.state !== "running")
|
|
547
|
+
run.outcome = STATUS_OF[row.state];
|
|
548
|
+
// Only a store no live instance holds is opened: released, or left by an instance whose lease lapsed.
|
|
549
|
+
if (row.state !== "running" || !this.doorOf(record))
|
|
550
|
+
await this.storeWhenFree(run);
|
|
551
|
+
if (row.state !== "running") {
|
|
552
|
+
run.endedAt = row.endedAt;
|
|
553
|
+
// An ended run the store kept no cost for has an unknown cost, never $0.
|
|
554
|
+
run.costUsd = row.costUsd ?? null;
|
|
555
|
+
// A workflow run's decisions' cost too: an unknown one keeps the run's unknown after a restart. Unread, it is unknown.
|
|
556
|
+
if (run.kind === "workflow")
|
|
557
|
+
await this.readDecisionCost(run).catch(() => void (run.decisionCost = null));
|
|
558
|
+
if (row.importedFrom)
|
|
559
|
+
run.imported = row.importedFrom;
|
|
560
|
+
if (run.outcome === "failed")
|
|
561
|
+
run.error = errorOfRow(row, meta);
|
|
562
|
+
run.settled = true;
|
|
563
|
+
}
|
|
564
|
+
else {
|
|
565
|
+
// A cancel a server took and could not carry back before it went: its mark is written first (cancel()), so it is
|
|
566
|
+
// the run's end, as it was from its 202 on, whatever the turn it cut reads.
|
|
567
|
+
if (run.kind === "agentic" && existsSync(join(dir, RUN_CANCELLED))) {
|
|
568
|
+
run.cancel = true;
|
|
569
|
+
run.finishing = "cancelled";
|
|
570
|
+
}
|
|
571
|
+
const adopted = record && this.doorOf(record) ? record : null;
|
|
572
|
+
if (adopted) {
|
|
573
|
+
// A server that died between saving a stop and its abort reaching the run leaves the turn working.
|
|
574
|
+
run.finishStop = run.meta.stopped_at !== undefined || run.meta.stopped_after !== undefined;
|
|
575
|
+
this.adoptProcess(run, adopted);
|
|
576
|
+
// Its cancel's SIGTERM may never have gone: it is let go now, its turn aborted first.
|
|
577
|
+
if (run.cancel)
|
|
578
|
+
void this.abortTurn(run).then(() => this.terminate(run));
|
|
579
|
+
}
|
|
580
|
+
// One a server left in its end-of-run turn finishes with its job's outcome, and its turn, when its process lives,
|
|
581
|
+
// is asked again (learning-run.ts).
|
|
582
|
+
this.learning.onAdopt(run, adopted !== null);
|
|
583
|
+
}
|
|
584
|
+
this.refresh(run);
|
|
585
|
+
return run;
|
|
586
|
+
}
|
|
587
|
+
blank(row, dir, meta, version, harness, tooling, revision) {
|
|
588
|
+
return {
|
|
589
|
+
id: row.id, agentId: row.agent, kind: row.kind, revision: row.revision, version, dir, meta, log: new RowLog(this.clock), rows: [], harness,
|
|
590
|
+
working: false, submitted: 0, users: new Set(), live: new Set(), cancel: false, relaunches: 0, settled: false, settles: 0, updatedAt: meta.created_at, turns: new Turns(),
|
|
591
|
+
...(tooling ? { tooling } : {}),
|
|
592
|
+
};
|
|
593
|
+
}
|
|
594
|
+
/** Writes the run's serve.json as it is when its turn comes; then tells learning what it now holds (the ledger's line
|
|
595
|
+
* once the run's learning ended). */
|
|
596
|
+
saveMeta(run) {
|
|
597
|
+
run.saving = (run.saving ?? Promise.resolve()).catch(() => undefined).then(async () => {
|
|
598
|
+
const { learning } = run.meta;
|
|
599
|
+
await writeWhole(join(run.dir, RUN_META), `${JSON.stringify(run.meta)}\n`);
|
|
600
|
+
await this.learning.onSaved(run, learning);
|
|
601
|
+
});
|
|
602
|
+
return run.saving;
|
|
603
|
+
}
|
|
604
|
+
record(run) {
|
|
605
|
+
return readJson(join(run.dir, "run.json"));
|
|
606
|
+
}
|
|
607
|
+
/** The door a live run serves, from its run.json: running, a fresh heartbeat, and a loopback address. */
|
|
608
|
+
doorOf(record) {
|
|
609
|
+
if (record?.status !== "running" || !isObject(record.holder) || typeof record.holder.serve !== "string")
|
|
610
|
+
return undefined;
|
|
611
|
+
// A run's process is a process on this machine: one that is gone serves no door, however fresh its heartbeat.
|
|
612
|
+
const pid = holderPid(record);
|
|
613
|
+
if (pid !== undefined && !alive(pid))
|
|
614
|
+
return undefined;
|
|
615
|
+
if (typeof record.heartbeatAt !== "string" || Date.now() - Date.parse(record.heartbeatAt) >= LEASE_MS)
|
|
616
|
+
return undefined;
|
|
617
|
+
const url = URL.parse(record.holder.serve);
|
|
618
|
+
return url?.protocol === "http:" && isLoopback(url.hostname) ? url.origin : undefined;
|
|
619
|
+
}
|
|
620
|
+
storeFile(run) {
|
|
621
|
+
return join(run.dir, "store", "run.sqlite");
|
|
622
|
+
}
|
|
623
|
+
/** The run's rows from its store, opened read-only; only once its claim is released. An agentic run's rows are its
|
|
624
|
+
* root conversation's; a workflow run's are its model nodes'. `atEnd`: a settle's read, which reads every
|
|
625
|
+
* conversation (a workflow's nodes, a harness's session) once and counts the run's metrics from all of them. */
|
|
626
|
+
async readStore(run, atEnd = false) {
|
|
627
|
+
const file = this.storeFile(run);
|
|
628
|
+
if (!(await stat(file).catch(() => null)))
|
|
629
|
+
return;
|
|
630
|
+
const { DatabaseSync } = await import("node:sqlite");
|
|
631
|
+
const read = [];
|
|
632
|
+
const submissions = [];
|
|
633
|
+
const db = new DatabaseSync(file, { readOnly: true });
|
|
634
|
+
try {
|
|
635
|
+
const rows = run.kind === "workflow" || atEnd
|
|
636
|
+
? db.prepare("SELECT conversation_id, record FROM entries ORDER BY id").iterate()
|
|
637
|
+
: db.prepare("SELECT conversation_id, record FROM entries WHERE conversation_id = (SELECT MIN(conversation_id) FROM entries) ORDER BY id").iterate();
|
|
638
|
+
for (const row of rows)
|
|
639
|
+
read.push({ conversation: Number(row.conversation_id), entry: JSON.parse(String(row.record)) });
|
|
640
|
+
// pi's settlements of the person's messages, the root's (turns.ts): its turns' ends.
|
|
641
|
+
if (run.kind === "agentic") {
|
|
642
|
+
const inputs = db.prepare("SELECT record FROM submissions WHERE conversation_id = (SELECT MIN(conversation_id) FROM entries) ORDER BY id").all();
|
|
643
|
+
for (const row of inputs)
|
|
644
|
+
submissions.push(JSON.parse(String(row.record)));
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
finally {
|
|
648
|
+
db.close();
|
|
649
|
+
}
|
|
650
|
+
const root = read.reduce((min, r) => Math.min(min, r.conversation), Infinity);
|
|
651
|
+
const entries = read.flatMap((r) => (run.kind === "workflow" || r.conversation === root ? [r.entry] : []));
|
|
652
|
+
if (run.kind === "workflow") {
|
|
653
|
+
const { durableDecisions } = await import("@parcha/agentrun-pi/durable");
|
|
654
|
+
// Decisions it cannot read add no rows, and leave the served usage row's total unknown, as the run's cost read
|
|
655
|
+
// does (readDecisionCost): never its model nodes' total alone.
|
|
656
|
+
try {
|
|
657
|
+
run.decisions = durableDecisions(file);
|
|
658
|
+
}
|
|
659
|
+
catch {
|
|
660
|
+
run.decisions = null;
|
|
661
|
+
}
|
|
662
|
+
run.llmRead = llmAnswers(await readNodeLog(run.dir)).length;
|
|
663
|
+
}
|
|
664
|
+
// Its decision requests count with its model requests: each receipt's tokens, or unmetered without them.
|
|
665
|
+
if (atEnd)
|
|
666
|
+
run.metrics = runMetricsWithDecisions(read.map((r) => r.entry), run.kind === "workflow" ? (run.decisions ?? []) : []);
|
|
667
|
+
run.working = false;
|
|
668
|
+
noteTurns(run, entries, submissions);
|
|
669
|
+
this.take(run, timelineOf(entries, { settled: true, path: rowPaths(run.dir), redact: this.redactor(run) }));
|
|
670
|
+
}
|
|
671
|
+
/** New rows in: into the log, then the run's status, then whatever the status asks for. */
|
|
672
|
+
/** `keep`: rows that stay served though `rows` no longer holds them (the live path's committed rows). */
|
|
673
|
+
take(run, rows, keep) {
|
|
674
|
+
run.rows = withOverCap(labelled(run.meta.reflect, withAsks(rows.filter((r) => !QUIET.test(r.id)))), run.meta.max_cost_usd);
|
|
675
|
+
// Counted by id: a snapshot of a compacted conversation shows fewer user messages than before, which is not more
|
|
676
|
+
// messages waiting, so a count of rows would leave the run working forever.
|
|
677
|
+
const arrived = run.rows.filter((r) => r.kind === "user_message" && !run.users.has(r.id));
|
|
678
|
+
for (const row of arrived)
|
|
679
|
+
run.users.add(row.id);
|
|
680
|
+
run.submitted = Math.max(0, run.submitted - arrived.length);
|
|
681
|
+
run.keep = keep;
|
|
682
|
+
this.show(run);
|
|
683
|
+
this.refresh(run);
|
|
684
|
+
}
|
|
685
|
+
/** The run's rows into its log, as served: a workflow run's decisions and the run's learning row are the served view's
|
|
686
|
+
* only, never the run's own rows, which its cost and its answer are read from. */
|
|
687
|
+
show(run) {
|
|
688
|
+
// The decisions' rows are the served view's only: the run's own rows, which its cost is read from, stay its model nodes'.
|
|
689
|
+
const own = run.decisions === undefined ? run.rows : withDecisions(run.rows, run.decisions);
|
|
690
|
+
// An error row reads as the run's error does (errorWords): a refused key in plain words, no loopback address.
|
|
691
|
+
const rows = own.map((row) => (row.kind === "error" ? this.servedError(run, row) : row));
|
|
692
|
+
if (run.log.sync(withLearning(rows, run.meta.learning, this.learning.shown()), run.keep))
|
|
693
|
+
run.updatedAt = new Date().toISOString();
|
|
694
|
+
}
|
|
695
|
+
/** A live process: the child this server started, or one an earlier server started that still serves the run. */
|
|
696
|
+
live(run) {
|
|
697
|
+
return Boolean(run.child || run.orphan);
|
|
698
|
+
}
|
|
699
|
+
/** How an agentic run ends: over its cap, or as the turn of the person's newest message ended (turns.ts), once every
|
|
700
|
+
* message the run took has had its turn. Undefined while one is open, or when the run stopped, waits, or its turn
|
|
701
|
+
* ended interrupted (the run then waits for the person), or while its records name no message (a live process of an
|
|
702
|
+
* older server: the run's next process writes its turn's end as it opens). Never from the order of its rows, or from
|
|
703
|
+
* when its door said idle. A workflow run ends when its workflow does. */
|
|
704
|
+
decide(run) {
|
|
705
|
+
if (run.kind === "workflow")
|
|
706
|
+
return undefined;
|
|
707
|
+
// A cancel ends the run cancelled, by its settle (whatever the turn it cut wrote, a cost over the cap too): nothing
|
|
708
|
+
// ends it otherwise meanwhile, so its first terminal status is its last. The cancel has aborted the turn already.
|
|
709
|
+
if (run.cancel)
|
|
710
|
+
return undefined;
|
|
711
|
+
const cap = run.meta.max_cost_usd;
|
|
712
|
+
const cost = costOf(run.rows);
|
|
713
|
+
if (cap !== undefined && cost !== null && cost > cap)
|
|
714
|
+
return { outcome: "failed", abort: true, error: { code: SPEND_CAP_REACHED, message: `The run cost $${cost.toFixed(4)}, $${(cost - cap).toFixed(4)} over its cap of $${cap}.`, retryable: false } };
|
|
715
|
+
if (run.submitted > 0)
|
|
716
|
+
return undefined;
|
|
717
|
+
if (run.turns.open > 0 || stopped(run))
|
|
718
|
+
return undefined;
|
|
719
|
+
const end = run.turns.end();
|
|
720
|
+
if (end?.status === "answered")
|
|
721
|
+
return { outcome: "completed" };
|
|
722
|
+
if (end?.status !== "failed")
|
|
723
|
+
return undefined;
|
|
724
|
+
const message = end.error ?? "The run failed.";
|
|
725
|
+
// The cap's refusal in the run's process (cap.ts); a provider error with this exact prefix would read as one too.
|
|
726
|
+
// Its code is `spend_cap_reached: `, or with a note after it (`spend_cap_reached (out of budget): `, cap.ts); the message is
|
|
727
|
+
// the words after it.
|
|
728
|
+
const capped = CAP_REFUSAL_PREFIX.exec(message);
|
|
729
|
+
if (capped)
|
|
730
|
+
return { outcome: "failed", error: { code: SPEND_CAP_REACHED, message: message.slice(capped[0].length), retryable: false } };
|
|
731
|
+
return { outcome: "failed", error: { code: "run_failed", message: this.errorWords(run, message) ?? message, retryable: false } };
|
|
732
|
+
}
|
|
733
|
+
/** A run's error as a person reads it, in its error box and on its Timeline row alike: a refused key in plain words
|
|
734
|
+
* (plainKey), else the harness's text with no loopback address (withoutLoopback: Codex names serve's own proxy). */
|
|
735
|
+
errorWords(run, text) {
|
|
736
|
+
return text ? this.shown(run, this.plainKey(run, text) ?? text) : text;
|
|
737
|
+
}
|
|
738
|
+
/** An error row as served: its summary and text in errorWords' terms. The run's own rows, which its status reads, keep
|
|
739
|
+
* what the harness said. */
|
|
740
|
+
servedError(run, row) {
|
|
741
|
+
const plain = this.plainKey(run, row.text ?? undefined);
|
|
742
|
+
if (plain) {
|
|
743
|
+
const words = this.shown(run, plain);
|
|
744
|
+
return { ...row, summary: words, text: words };
|
|
745
|
+
}
|
|
746
|
+
return { ...row, ...(row.summary ? { summary: this.shown(run, row.summary) } : {}), ...(row.text ? { text: this.shown(run, row.text) } : {}) };
|
|
747
|
+
}
|
|
748
|
+
/** What serve shows of a run's error text, for every run kind: no held secret (redacted, key-refusal.ts' one rule) and
|
|
749
|
+
* no loopback address. */
|
|
750
|
+
shown(run, text) {
|
|
751
|
+
return withoutLoopback(redacted(text, this.refusedValues(run)));
|
|
752
|
+
}
|
|
753
|
+
/** A run's answer as serve serves it: no held secret, never cut (redactedAnswer). Loopback addresses stay: an answer is
|
|
754
|
+
* the model's own words, and a local address there can be what the person asked about. */
|
|
755
|
+
servedAnswer(run, text) {
|
|
756
|
+
return text ? this.servedOnce(run, "answer", text, (values) => redactedAnswer(text, values)) : text;
|
|
757
|
+
}
|
|
758
|
+
/** A workflow run's output as serve serves it: each string in it as servedAnswer, its shape kept. */
|
|
759
|
+
servedOutput(run, output) {
|
|
760
|
+
return output === null ? null : this.servedOnce(run, "output", output, (values) => redactedOutput(output, values));
|
|
761
|
+
}
|
|
762
|
+
/** `redact(values)` over the values `run` holds, read once per input and held value set: a console polls a run's
|
|
763
|
+
* view, and an answer a run was made to write can be large. The run keeps the one it served last, of each slot; a key
|
|
764
|
+
* saved or deleted changes the values' digest, and the next view redacts again. */
|
|
765
|
+
servedOnce(run, slot, input, redact) {
|
|
766
|
+
const values = this.refusedValues(run);
|
|
767
|
+
const keys = createHash("sha256").update(JSON.stringify([...values].sort())).digest("hex");
|
|
768
|
+
const last = run.served?.[slot];
|
|
769
|
+
if (last && last.keys === keys && last.input === input)
|
|
770
|
+
return last.out;
|
|
771
|
+
const out = redact(values);
|
|
772
|
+
run.served = { ...run.served, [slot]: { keys, input, out } };
|
|
773
|
+
return out;
|
|
774
|
+
}
|
|
775
|
+
/** The timeline's redaction of `run`'s error rows and of what a tool's result shows (its summary and preview), applied
|
|
776
|
+
* before a row is cut (timelineOf's `redact`), so a cut never leaves the head of a key. Every such cut is within
|
|
777
|
+
* redacted()'s SHOWN, so its window holds. */
|
|
778
|
+
redactor(run) {
|
|
779
|
+
return (text) => redacted(text, this.refusedValues(run));
|
|
780
|
+
}
|
|
781
|
+
/** Every secret value `run`'s errors never show, as learning's checker holds them (learning-run.ts refused): this
|
|
782
|
+
* server's secrets wherever its launcher put them and the keys saved on it, what each launch handed the run, and the
|
|
783
|
+
* server's own tokens. */
|
|
784
|
+
refusedValues(run) {
|
|
785
|
+
return [...hostSecrets(process.env, this.options.storedKeys), ...(run.handed ?? []), this.options.token, this.options.doorToken];
|
|
786
|
+
}
|
|
787
|
+
/** A run's model error in a person's words when its provider refused the run's key (key-refusal.ts): the key its
|
|
788
|
+
* harness's route sends, by this server's settings and keys, and no secret's value. */
|
|
789
|
+
plainKey(run, text) {
|
|
790
|
+
// A workflow's nodes run on their own tiers' models, and its error row does not say which one failed: naming the
|
|
791
|
+
// default tier's key could name the wrong one, so its error keeps the provider's own words.
|
|
792
|
+
if (!text || run.kind === "workflow")
|
|
793
|
+
return undefined;
|
|
794
|
+
const env = withSecrets(process.env, "all", this.options.storedKeys);
|
|
795
|
+
return keyRefusal(text, runKeyOf(env, run.harness ?? run.tooling?.harness, run.tooling?.model), this.refusedValues(run));
|
|
796
|
+
}
|
|
797
|
+
/** Records the run's status as a change when it moves, and lets go of a live run that answered, failed or is over its cap. */
|
|
798
|
+
refresh(run) {
|
|
799
|
+
this.mark(run);
|
|
800
|
+
if (!this.live(run) || run.finishing || run.outcome)
|
|
801
|
+
return;
|
|
802
|
+
const end = this.decide(run);
|
|
803
|
+
if (!end)
|
|
804
|
+
return;
|
|
805
|
+
if (end.error)
|
|
806
|
+
run.error = end.error;
|
|
807
|
+
// A run that learns is not let go yet: its end-of-run turn is asked first, unless learning skips it (learning-run.ts).
|
|
808
|
+
if (this.learning.beforeFinish(run, end))
|
|
809
|
+
return;
|
|
810
|
+
this.finish(run, end.outcome, end.abort);
|
|
811
|
+
}
|
|
812
|
+
/** The test hooks startServe's options name, as a run's process and this server's own calls get them. */
|
|
813
|
+
fauxEnv() {
|
|
814
|
+
return { ...this.options.fauxEnv };
|
|
815
|
+
}
|
|
816
|
+
/** Let go of a live run with `outcome`: SIGTERM, after aborting its turn when it is still working. */
|
|
817
|
+
finish(run, outcome, abortFirst = false) {
|
|
818
|
+
run.finishing = outcome;
|
|
819
|
+
run.endedAt = new Date().toISOString();
|
|
820
|
+
this.mark(run);
|
|
821
|
+
void (abortFirst ? this.abortTurn(run) : Promise.resolve()).then(() => this.terminate(run));
|
|
822
|
+
}
|
|
823
|
+
/** SIGTERM to the run's process: it drains, releases the run and exits. */
|
|
824
|
+
terminate(run) {
|
|
825
|
+
if (run.child)
|
|
826
|
+
run.child.kill("SIGTERM");
|
|
827
|
+
else if (run.orphan && alive(run.orphan))
|
|
828
|
+
process.kill(run.orphan, "SIGTERM");
|
|
829
|
+
}
|
|
830
|
+
/** Supervise a run process an earlier server started: follow its door, and settle the run once its run.json says it
|
|
831
|
+
* let go (released, or its lease lapsed) or the process is gone. */
|
|
832
|
+
adoptProcess(run, record) {
|
|
833
|
+
const pid = holderPid(record);
|
|
834
|
+
if (!pid)
|
|
835
|
+
return;
|
|
836
|
+
run.orphan = pid;
|
|
837
|
+
this.reportedBack(run);
|
|
838
|
+
this.connect(run);
|
|
839
|
+
let releasedAt;
|
|
840
|
+
let unreadable = 0;
|
|
841
|
+
const timer = setInterval(() => {
|
|
842
|
+
void this.record(run).then((now) => {
|
|
843
|
+
if (now !== null)
|
|
844
|
+
unreadable = 0;
|
|
845
|
+
if (run.orphan !== pid || (this.doorOf(now) && alive(pid)))
|
|
846
|
+
return;
|
|
847
|
+
// A record that cannot be read while the process lives is read again at every tick: settling on no record could
|
|
848
|
+
// leave the run unsettled and unwatched. The server says so once the record has been unreadable for a while.
|
|
849
|
+
if (now === null && alive(pid)) {
|
|
850
|
+
if (++unreadable === UNREADABLE_TICKS)
|
|
851
|
+
warn(run.id, `its run.json has been unreadable for ${UNREADABLE_TICKS / 2} s; still watching its process ${pid}`);
|
|
852
|
+
return;
|
|
853
|
+
}
|
|
854
|
+
if (RELEASED.has(String(now?.status)) && alive(pid)) {
|
|
855
|
+
releasedAt ??= Date.now();
|
|
856
|
+
if (Date.now() - releasedAt < EXIT_AFTER_RELEASE_MS)
|
|
857
|
+
return;
|
|
858
|
+
warn(run.id, `its process ${pid} released the run ${EXIT_AFTER_RELEASE_MS / 1000} s ago and has not exited; reading its store anyway`);
|
|
859
|
+
}
|
|
860
|
+
clearInterval(timer);
|
|
861
|
+
run.orphan = undefined;
|
|
862
|
+
void this.settle(run, null, !alive(pid) && !RELEASED.has(String(now?.status)));
|
|
863
|
+
});
|
|
864
|
+
}, 500);
|
|
865
|
+
timer.unref();
|
|
866
|
+
}
|
|
867
|
+
/** At start: every run the store says is running is read, supervised when its process lives, carried back when it
|
|
868
|
+
* already ended, and opened again when its process went before it ended. */
|
|
869
|
+
/** Every run's box let go that nothing owns, and every run cgroup no record names: once, before any run of this server
|
|
870
|
+
* starts, opens again or relaunches, so a box or cgroup being made is never swept away. */
|
|
871
|
+
sweepOnce() {
|
|
872
|
+
const { box, runBoxes, remoteBoxes } = this.options;
|
|
873
|
+
if (!box && !runBoxes && !remoteBoxes)
|
|
874
|
+
return Promise.resolve();
|
|
875
|
+
this.swept ??= (async () => {
|
|
876
|
+
const rows = await this.options.agents.request(() => this.store.listRuns());
|
|
877
|
+
// The boxes of sandbox runs, by their label: one whose run has ended, or is archived, is destroyed. A failure only
|
|
878
|
+
// warns: the next start sweeps again, and a box's lifetime bounds it.
|
|
879
|
+
const ended = new Set(rows.filter((row) => row.state !== "running" || row.archivedAt).map((row) => row.id));
|
|
880
|
+
if (runBoxes) {
|
|
881
|
+
await sweepRunBoxes(runBoxes, (id) => ended.has(id), boxContext()).catch((error) => warn("-", `its start's sweep of run boxes failed (${error.message}); the next start sweeps again`));
|
|
882
|
+
}
|
|
883
|
+
// A remote box of an ended run is pulled first, so what it changed after its run's last pull is kept, and goes only
|
|
884
|
+
// once that pull landed: one that fails keeps the box for the next start, its lifetime bounding it.
|
|
885
|
+
if (remoteBoxes) {
|
|
886
|
+
const dirOf = (id) => join(this.options.agents.dir, "runs", id);
|
|
887
|
+
const pulledFirst = (id, boxId) => pullRemoteBox(remoteBoxes, { id, dir: dirOf(id) }, boxContext(REMOTE_SYNC_MS)).then(() => true, async (error) => {
|
|
888
|
+
warn(id, `its box is kept: its pull failed (${error.message}); the next start tries again`);
|
|
889
|
+
await this.keepBox(id, boxId);
|
|
890
|
+
return false;
|
|
891
|
+
});
|
|
892
|
+
// A box kept at a run's end that Daytona stopped once idle is woken first, so this sweep pulls it like the rest.
|
|
893
|
+
const api = this.options.remoteApi;
|
|
894
|
+
if (api)
|
|
895
|
+
await wakeBoxes(api, (id) => ended.has(id)).catch((error) => warn("-", `the stopped boxes of ended runs were not woken (${error.message}); the next start tries again`));
|
|
896
|
+
await sweepRunBoxes(remoteBoxes, (id) => ended.has(id), boxContext(REMOTE_SYNC_MS), pulledFirst).catch((error) => warn("-", `its start's sweep of remote run boxes failed (${error.message}); the next start sweeps again`));
|
|
897
|
+
}
|
|
898
|
+
if (!box)
|
|
899
|
+
return;
|
|
900
|
+
const settled = await sweepBoxes(box.host, box.quarantine, rows.map((row) => ({ id: row.id, dir: join(this.options.agents.dir, "runs", row.id) })));
|
|
901
|
+
for (const [id, how] of Object.entries(settled))
|
|
902
|
+
if (how === "quarantined")
|
|
903
|
+
warn(id, "its box could not be emptied; it is quarantined, and tried again at each start");
|
|
904
|
+
})().catch((error) => {
|
|
905
|
+
// A sweep that failed is not kept: the next start, open or relaunch sweeps again, so one transient error never
|
|
906
|
+
// holds every run back until the server restarts. Nothing of this server's runs has started a box before it.
|
|
907
|
+
this.swept = undefined;
|
|
908
|
+
throw error;
|
|
909
|
+
});
|
|
910
|
+
return this.swept;
|
|
911
|
+
}
|
|
912
|
+
/** A sandbox run's box (run-box.ts), destroyed by its label: at every settle, a cancel included, and at archive. A
|
|
913
|
+
* remote box's work/ is pulled first, and its box goes only once that pull brought it back whole (or there is no box).
|
|
914
|
+
* A copy that stopped for good (an archive the extractor cannot read, a limit it cannot pass) keeps the box, said in
|
|
915
|
+
* the log, its lifetime bounding it, and the run ends. Any other failure at a run's end (`ending`) throws
|
|
916
|
+
* PullPending, and the end is tried again; at an archive it only warns, the box kept for the run's end or the next
|
|
917
|
+
* start's sweep. A destroy that fails only warns: the next start's sweep tries again, and the box's lifetime bounds it. */
|
|
918
|
+
async dropBox(run, ending = false) {
|
|
919
|
+
const place = run.meta.place;
|
|
920
|
+
if (place?.mode !== "sandbox")
|
|
921
|
+
return;
|
|
922
|
+
const remote = remotePlace(place);
|
|
923
|
+
const boxes = remote ? this.options.remoteBoxes : this.options.runBoxes;
|
|
924
|
+
if (!boxes)
|
|
925
|
+
return;
|
|
926
|
+
if (remote) {
|
|
927
|
+
try {
|
|
928
|
+
await this.pullBox(run, true);
|
|
929
|
+
}
|
|
930
|
+
catch (error) {
|
|
931
|
+
if (error instanceof PullIncomplete && error.lasting) {
|
|
932
|
+
await this.keepBox(run.id, error.box);
|
|
933
|
+
return warn(run.id, `its box is kept, not destroyed: ${error.message}; what came back is in its files, and the box stops after ${KEPT_AUTOSTOP_MINUTES} idle minutes, its files kept for the next start's pull`);
|
|
934
|
+
}
|
|
935
|
+
const why = `its box's last pull failed (${error.message})`;
|
|
936
|
+
if (ending)
|
|
937
|
+
throw new PullPending(why);
|
|
938
|
+
return warn(run.id, `${why}; its box is kept for its end`);
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
try {
|
|
942
|
+
await destroyRunBoxes(boxes, run.id, boxContext());
|
|
943
|
+
}
|
|
944
|
+
catch (error) {
|
|
945
|
+
warn(run.id, `its box was not destroyed (${error.message}); the next start sweeps it`);
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
/** A remote box kept because its copy back is not whole: said in the log, and set to stop once idle, so it costs its
|
|
949
|
+
* disk alone until the next start's pull (which wakes it) or its lifetime. */
|
|
950
|
+
async keepBox(runId, boxId) {
|
|
951
|
+
this.options.log?.("box_kept", { run: runId, box: boxId, reason: "pull_incomplete" });
|
|
952
|
+
const api = this.options.remoteApi;
|
|
953
|
+
if (api)
|
|
954
|
+
await keepWhenIdle(api, boxId).catch((error) => warn(runId, `its kept box was not kept from deletion or set to stop when idle (${error.message})`));
|
|
955
|
+
}
|
|
956
|
+
/** What wakes run `runId`'s remote box when Daytona stopped or paused it (a class that pauses when idle, while the run
|
|
957
|
+
* waited for a person): how many it woke. */
|
|
958
|
+
wakeOf(runId) {
|
|
959
|
+
const api = this.options.remoteApi;
|
|
960
|
+
return api && (() => wakeBoxes(api, (id) => id === runId));
|
|
961
|
+
}
|
|
962
|
+
/** Pulls run `run`'s remote box into its work/, after any pull already running: at a turn's end in the background (a
|
|
963
|
+
* failure warns, and the next pull brings it), or awaited (`strict`: a failure throws). */
|
|
964
|
+
pullBox(run, strict = false) {
|
|
965
|
+
const boxes = this.options.remoteBoxes;
|
|
966
|
+
const place = run.meta.place;
|
|
967
|
+
if (!boxes || !place || !remotePlace(place))
|
|
968
|
+
return Promise.resolve();
|
|
969
|
+
// After any pull already running, and after the box's making and seed when one is under way.
|
|
970
|
+
const pull = Promise.all([run.pulling, run.boxing?.catch(() => undefined)]).then(async () => {
|
|
971
|
+
const pulled = await pullRemoteBox(boxes, run, boxContext(REMOTE_SYNC_MS), this.wakeOf(run.id));
|
|
972
|
+
if (pulled)
|
|
973
|
+
this.options.log?.("box_pulled", { run: run.id, changed: pulled.changed, files: pulled.files, bytes: pulled.bytes, removed: pulled.removed });
|
|
974
|
+
});
|
|
975
|
+
const settled = pull.catch((error) => {
|
|
976
|
+
if (!strict)
|
|
977
|
+
warn(run.id, `its box's work/ was not pulled at its turn's end (${error.message}); the next pull brings it`);
|
|
978
|
+
});
|
|
979
|
+
run.pulling = settled;
|
|
980
|
+
void settled.finally(() => {
|
|
981
|
+
if (run.pulling === settled)
|
|
982
|
+
run.pulling = undefined;
|
|
983
|
+
});
|
|
984
|
+
return strict ? pull : settled;
|
|
985
|
+
}
|
|
986
|
+
/** Waits for the pull run `id`'s turn's end began, if any, up to PULL_WAIT_MS: its files then show what its box wrote. */
|
|
987
|
+
async pulled(id) {
|
|
988
|
+
const pulling = this.runs.get(id)?.pulling;
|
|
989
|
+
if (!pulling)
|
|
990
|
+
return;
|
|
991
|
+
let timer;
|
|
992
|
+
await Promise.race([pulling, new Promise((resolve) => (timer = setTimeout(resolve, PULL_WAIT_MS)))]);
|
|
993
|
+
clearTimeout(timer);
|
|
994
|
+
}
|
|
995
|
+
/** Whether run `id` is one this server holds in a remote box and has not ended: the relay serves no other. */
|
|
996
|
+
servesBox(id) {
|
|
997
|
+
const run = this.runs.get(id);
|
|
998
|
+
return Boolean(this.options.remoteBoxes && run && !run.outcome && run.meta.place && remotePlace(run.meta.place));
|
|
999
|
+
}
|
|
1000
|
+
/** Run `id`'s remote box, found or made and seeded: what its process asks the relay for at its first tool call. */
|
|
1001
|
+
ensureBox(id) {
|
|
1002
|
+
const run = this.runs.get(id);
|
|
1003
|
+
const boxes = this.options.remoteBoxes;
|
|
1004
|
+
if (!run || !boxes || !this.servesBox(id))
|
|
1005
|
+
return Promise.reject(new Error(`no run ${id} of this server is in a remote box`));
|
|
1006
|
+
// After any pull of this run's box, so a seed never meets a pull.
|
|
1007
|
+
run.boxing ??= (run.pulling ?? Promise.resolve())
|
|
1008
|
+
.then(() => ensureRemoteBox(boxes, run, boxContext(REMOTE_SYNC_MS), this.wakeOf(run.id)))
|
|
1009
|
+
.finally(() => void (run.boxing = undefined));
|
|
1010
|
+
return run.boxing;
|
|
1011
|
+
}
|
|
1012
|
+
/** The run's box let go (archive, or its process gone after an archive): reaped by the box's own count. */
|
|
1013
|
+
async teardown(run) {
|
|
1014
|
+
const box = this.options.box;
|
|
1015
|
+
if (!box || this.live(run))
|
|
1016
|
+
return;
|
|
1017
|
+
// Never in the way of the run's own end or an archive already saved: a box that could not be let go (its cgroup not
|
|
1018
|
+
// removed, its record not marked) is said, and its unmarked record is tried again by the next start's sweep.
|
|
1019
|
+
try {
|
|
1020
|
+
if ((await settleBox(box.host, box.quarantine, run.id, run.dir)) === "quarantined")
|
|
1021
|
+
warn(run.id, "its box could not be emptied; it is quarantined, and tried again at each start");
|
|
1022
|
+
}
|
|
1023
|
+
catch (error) {
|
|
1024
|
+
warn(run.id, `its box was not let go (${error.message}); the next start tries again`);
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
/** After an archive (a run's, or an agent's, which archives its runs): the box of every run now archived is let go,
|
|
1028
|
+
* now when its process is gone, else when it exits. */
|
|
1029
|
+
async archived() {
|
|
1030
|
+
if (!this.options.box && !this.options.runBoxes && !this.options.remoteBoxes)
|
|
1031
|
+
return;
|
|
1032
|
+
for (const row of await this.options.agents.request(() => this.store.listRuns())) {
|
|
1033
|
+
if (!row.archivedAt)
|
|
1034
|
+
continue;
|
|
1035
|
+
// A run's box needs only the runs this server holds: one it has not read has ended, or was swept at its start.
|
|
1036
|
+
const run = this.options.box ? await this.get(row.id) : this.runs.get(row.id);
|
|
1037
|
+
if (!run)
|
|
1038
|
+
continue;
|
|
1039
|
+
// A run's box goes at its archive, its process live or not (an ended run's went at its end): an archived run takes
|
|
1040
|
+
// no message, and a call it still makes gets a fresh box, which its end or the next start's sweep destroys.
|
|
1041
|
+
if (!run.outcome)
|
|
1042
|
+
await this.dropBox(run);
|
|
1043
|
+
await this.teardown(run);
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
async recover() {
|
|
1047
|
+
// The learning a server left between steps, picked up once every running run is read (learning-run.ts).
|
|
1048
|
+
const recoverLearning = this.learning.recover();
|
|
1049
|
+
await this.sweepOnce();
|
|
1050
|
+
const rows = await this.options.agents.request(() => this.store.listRuns());
|
|
1051
|
+
for (const row of rows) {
|
|
1052
|
+
if (row.state !== "running" || row.importedFrom)
|
|
1053
|
+
continue;
|
|
1054
|
+
const run = await this.adopt(row).catch((error) => (warn(row.id, `not recovered: ${error.message}; the next start tries again`), null));
|
|
1055
|
+
if (run && !this.live(run) && !run.outcome)
|
|
1056
|
+
await this.settle(run, null, false);
|
|
1057
|
+
}
|
|
1058
|
+
await recoverLearning(rows);
|
|
1059
|
+
}
|
|
1060
|
+
/** The run's status, state and whether its rows are all in, as one more change of its log when any of them moves. A wait
|
|
1061
|
+
* is told each time it is seen: webhooks.ts queues each wait once, whichever server sees it first. */
|
|
1062
|
+
mark(run) {
|
|
1063
|
+
const { status, state } = statusOf(run);
|
|
1064
|
+
// A turn's end, or a run first read waiting (a start that finds it so, whose last turn's pull may not have landed):
|
|
1065
|
+
// what its remote box changed is pulled into work/ now, and a read of the files waits for it.
|
|
1066
|
+
const waiting = status === "input_required";
|
|
1067
|
+
if (waiting && run.waited !== true)
|
|
1068
|
+
this.pullBox(run);
|
|
1069
|
+
run.waited = waiting;
|
|
1070
|
+
if (run.log.setState(`${status}/${state}/${run.settled}`))
|
|
1071
|
+
run.updatedAt = new Date().toISOString();
|
|
1072
|
+
// What it waits on: an ask_person question (waiting), else a stopped turn, for the person's next message.
|
|
1073
|
+
if (status === "input_required")
|
|
1074
|
+
this.notice(run, "run.needs_input", waitMark(run), { kind: state === "waiting" ? "question" : "stopped" });
|
|
1075
|
+
}
|
|
1076
|
+
/** Tells webhooks.ts (`notify`) of a moment of the run under `marker`: a wait it reached (mark), or an end the agent store
|
|
1077
|
+
* has (settle, persistLater, reopen). What it already queued it queues no more. */
|
|
1078
|
+
notice(run, event, marker, pending) {
|
|
1079
|
+
if (!this.options.notify || !marker)
|
|
1080
|
+
return undefined;
|
|
1081
|
+
try {
|
|
1082
|
+
return this.options.notify(event, { run_id: run.id, agent_id: run.agentId, status: statusOf(run).status, title: run.meta.title, ...(pending ? { pending } : {}) }, marker);
|
|
1083
|
+
}
|
|
1084
|
+
catch (error) {
|
|
1085
|
+
warn(run.id, `its notice was not queued: ${error.message}`);
|
|
1086
|
+
return undefined;
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
// ---- the door -------------------------------------------------------------------------------------------------------
|
|
1090
|
+
/** A call to run `run`'s door: with its own door token, or, for a process an older server started, the server-wide one. */
|
|
1091
|
+
headers(run, json = false) {
|
|
1092
|
+
run.doorToken ??= runDoorToken(run.dir);
|
|
1093
|
+
return { authorization: `Bearer ${run.doorToken ?? this.options.doorToken}`, ...(json ? { "content-type": "application/json" } : {}) };
|
|
1094
|
+
}
|
|
1095
|
+
/** Run `id`'s own door token, the one its calls to the box relay carry; none for a run it does not hold or that has none. */
|
|
1096
|
+
relayToken(id) {
|
|
1097
|
+
const run = this.runs.get(id);
|
|
1098
|
+
if (!run)
|
|
1099
|
+
return undefined;
|
|
1100
|
+
run.doorToken ??= runDoorToken(run.dir);
|
|
1101
|
+
return run.doorToken;
|
|
1102
|
+
}
|
|
1103
|
+
/** Follow the door's events into an agentic run's rows, again after each drop while the process lives. A workflow
|
|
1104
|
+
* run is only watched: the door's events are a root conversation's, and a workflow run has none. */
|
|
1105
|
+
connect(run) {
|
|
1106
|
+
if (run.feed)
|
|
1107
|
+
return;
|
|
1108
|
+
const abort = new AbortController();
|
|
1109
|
+
run.feed = abort;
|
|
1110
|
+
void (async () => {
|
|
1111
|
+
while (!abort.signal.aborted) {
|
|
1112
|
+
const door = this.doorOf(await this.record(run));
|
|
1113
|
+
if (door)
|
|
1114
|
+
this.reportedBack(run);
|
|
1115
|
+
if (door && run.kind === "workflow") {
|
|
1116
|
+
if (!run.working && !run.outcome) {
|
|
1117
|
+
run.working = true;
|
|
1118
|
+
this.refresh(run);
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
else if (door)
|
|
1122
|
+
await this.follow(run, door, abort.signal).catch(() => undefined);
|
|
1123
|
+
if (abort.signal.aborted || (!this.live(run) && !this.doorOf(await this.record(run))))
|
|
1124
|
+
break;
|
|
1125
|
+
await sleep(run.kind === "workflow" ? 500 : 200);
|
|
1126
|
+
}
|
|
1127
|
+
if (run.feed === abort)
|
|
1128
|
+
run.feed = undefined;
|
|
1129
|
+
})();
|
|
1130
|
+
}
|
|
1131
|
+
async follow(run, door, signal) {
|
|
1132
|
+
// A file a call names by its absolute path in the run's workspace (a harness's CLI sends one) reads by its name there.
|
|
1133
|
+
const reducer = timelineReducer({ path: rowPaths(run.dir), redact: this.redactor(run), redactLive: (text) => redactedLive(text, this.refusedValues(run)) });
|
|
1134
|
+
// `inputs=1`: the snapshot carries pi's newest input submissions, the settlements its turns end on (turns.ts).
|
|
1135
|
+
const up = await fetch(new URL(`/events?inputs=1&skip=${encodeURIComponent(REFLECT_REQUEST)}`, door), { signal, headers: { ...this.headers(run), accept: "text/event-stream" } });
|
|
1136
|
+
if (!up.ok || !up.body)
|
|
1137
|
+
return;
|
|
1138
|
+
const decoder = new TextDecoder();
|
|
1139
|
+
let buffer = "";
|
|
1140
|
+
for await (const chunk of up.body) {
|
|
1141
|
+
buffer += decoder.decode(chunk, { stream: true });
|
|
1142
|
+
for (let end; (end = buffer.indexOf("\n\n")) >= 0;) {
|
|
1143
|
+
const frame = buffer.slice(0, end);
|
|
1144
|
+
buffer = buffer.slice(end + 2);
|
|
1145
|
+
let event = "message";
|
|
1146
|
+
const data = [];
|
|
1147
|
+
for (const line of frame.split("\n")) {
|
|
1148
|
+
if (line.startsWith("event:"))
|
|
1149
|
+
event = line.slice(6).trim();
|
|
1150
|
+
else if (line.startsWith("data:"))
|
|
1151
|
+
data.push(line.slice(5).replace(/^ /, ""));
|
|
1152
|
+
}
|
|
1153
|
+
let value;
|
|
1154
|
+
try {
|
|
1155
|
+
value = JSON.parse(data.join("\n"));
|
|
1156
|
+
}
|
|
1157
|
+
catch {
|
|
1158
|
+
continue;
|
|
1159
|
+
}
|
|
1160
|
+
if (event === "end")
|
|
1161
|
+
return;
|
|
1162
|
+
const events = event === "snapshot" ? [value] : event === "events" && Array.isArray(value) ? value : [];
|
|
1163
|
+
if (event === "snapshot")
|
|
1164
|
+
run.working = Boolean(value.run);
|
|
1165
|
+
for (const e of events)
|
|
1166
|
+
if (e.type === "run_start" || e.type === "run_end")
|
|
1167
|
+
run.working = e.type === "run_start";
|
|
1168
|
+
// The settlements of pi's turns: each a submission event in the commit of its turn's last entry, and the door's
|
|
1169
|
+
// snapshot of them on a (re)connect (pi-durable-disk's `inputs`), read as their whole state.
|
|
1170
|
+
const submissions = events.flatMap((e) => (e.type === "submission" && e.record !== undefined ? [e.record] : []));
|
|
1171
|
+
const inputs = events.find((e) => e.type === "snapshot" && Array.isArray(e.inputs))?.inputs;
|
|
1172
|
+
noteTurns(run, events.flatMap((e) => (Array.isArray(e.entries) ? e.entries : e.entry !== undefined ? [e.entry] : [])), submissions, inputs);
|
|
1173
|
+
reducer.apply(events);
|
|
1174
|
+
// A stopped turn is over while the run's process lives on: a request it cut is a charge with no price (costsofar/1),
|
|
1175
|
+
// as the settled read counts it, never one in flight.
|
|
1176
|
+
if (!run.working && stopped(run))
|
|
1177
|
+
reducer.idle();
|
|
1178
|
+
// A snapshot rebuilds from the conversation's current view: after a compaction it holds fewer of the rows
|
|
1179
|
+
// already shown, which stay; only live rows go when they end.
|
|
1180
|
+
const rows = reducer.rows();
|
|
1181
|
+
this.take(run, rows, keepCommitted(run.live, rows, reducer.isLive));
|
|
1182
|
+
if (event === "snapshot" && run.finishStop) {
|
|
1183
|
+
run.finishStop = false;
|
|
1184
|
+
if (run.working && stopped(run) && run.submitted === 0) {
|
|
1185
|
+
// The run reads stopped already, so a message sent now would go in behind the turn this abort ends, and be
|
|
1186
|
+
// withdrawn with it: it waits for the abort, as for a stop in flight.
|
|
1187
|
+
run.stopping = true;
|
|
1188
|
+
void this.abortTurn(run).catch(() => undefined).finally(() => (run.stopping = undefined));
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
/** The door of a run that is not finished, starting or waking its process when it is not live. */
|
|
1195
|
+
async ensureLive(run, timeoutMs = this.options.readyTimeoutMs ?? READY_TIMEOUT_MS) {
|
|
1196
|
+
const deadline = Date.now() + timeoutMs;
|
|
1197
|
+
// A run brought up by a request (a message before the start's recovery reached it) waits for the sweep as well.
|
|
1198
|
+
await this.sweepOnce();
|
|
1199
|
+
await this.pinNeeds(run);
|
|
1200
|
+
// And for its files, which its start copies before it launches it: within the time left.
|
|
1201
|
+
const copying = run.preparing;
|
|
1202
|
+
if (copying) {
|
|
1203
|
+
await untilDeadline(copying, deadline);
|
|
1204
|
+
if (run.preparing === copying)
|
|
1205
|
+
throw new ApiError("unavailable", "the run's files are still being copied into its workspace", { retry_after_ms: 1000 }, { "retry-after": "1" });
|
|
1206
|
+
}
|
|
1207
|
+
for (let launched = false;; await sleep(100)) {
|
|
1208
|
+
const record = await this.record(run);
|
|
1209
|
+
// Checked after the read: a settle may end the run while it is read, and nothing starts a run that ended.
|
|
1210
|
+
if (run.outcome || run.finishing || run.cancel)
|
|
1211
|
+
throw this.finished(run);
|
|
1212
|
+
const door = this.doorOf(record);
|
|
1213
|
+
if (door)
|
|
1214
|
+
return door;
|
|
1215
|
+
if (!this.live(run)) {
|
|
1216
|
+
// A process that just went is being settled: its run may be over, so nothing starts it again before that.
|
|
1217
|
+
if (run.settles > 0) {
|
|
1218
|
+
// Within the time left: a settle waiting on a busy store must not hold this caller past its deadline.
|
|
1219
|
+
await untilDeadline(run.settling, deadline);
|
|
1220
|
+
if (Date.now() > deadline)
|
|
1221
|
+
throw new ApiError("unavailable", "the run did not come up in time", { retry_after_ms: 1000 }, { "retry-after": "1" });
|
|
1222
|
+
continue;
|
|
1223
|
+
}
|
|
1224
|
+
if (launched)
|
|
1225
|
+
throw new ApiError("internal", `the run's process exited before it served: ${await lastLogLine(run)}`);
|
|
1226
|
+
const pid = holderPid(record);
|
|
1227
|
+
const fresh = record?.status === "running" && typeof record.heartbeatAt === "string" && Date.now() - Date.parse(record.heartbeatAt) < LEASE_MS && (pid === undefined || alive(pid));
|
|
1228
|
+
// A run already going is never refused a place, but one whose harness this host's memory never holds (after a
|
|
1229
|
+
// restart on a smaller one) is not started: said, never tried.
|
|
1230
|
+
const never = fresh ? undefined : neverFits(run.harness, this.memory);
|
|
1231
|
+
if (never)
|
|
1232
|
+
throw new ApiError("agent_not_runnable", never, { details: { unbound: [], missing: {}, harness: run.harness } });
|
|
1233
|
+
if (!fresh)
|
|
1234
|
+
this.launch(run), (launched = true);
|
|
1235
|
+
}
|
|
1236
|
+
if (Date.now() > deadline)
|
|
1237
|
+
throw new ApiError("unavailable", "the run did not come up in time", { retry_after_ms: 1000 }, { "retry-after": "1" });
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
/** The refusal of a message to an imported run: it was run elsewhere, and is kept as history. */
|
|
1241
|
+
importedRefusal(run) {
|
|
1242
|
+
const source = run.imported?.source;
|
|
1243
|
+
return new ApiError("not_continuable", `This run was imported from ${source}: it is history, not run here, so it takes no message. Start a new run of the agent.`, {
|
|
1244
|
+
details: { reason: "imported", imported_from: source },
|
|
1245
|
+
next_action: { type: "request", method: "POST", path: `/agents/${run.agentId}/runs`, caller_supplies: ["input", "Idempotency-Key"] },
|
|
1246
|
+
});
|
|
1247
|
+
}
|
|
1248
|
+
finished(run) {
|
|
1249
|
+
const status = run.cancel ? "cancelled" : statusOf(run).status;
|
|
1250
|
+
const why = status === "completed" ? "This run is finished." : `This run ${status === "failed" ? "failed" : "was cancelled"}.`;
|
|
1251
|
+
return new ApiError("not_continuable", `${why} Start a new run of the agent.`, {
|
|
1252
|
+
next_action: { type: "request", method: "POST", path: `/agents/${run.agentId}/runs`, caller_supplies: ["input", "Idempotency-Key"] },
|
|
1253
|
+
});
|
|
1254
|
+
}
|
|
1255
|
+
/** Abort an agentic run's turn running now through the door, when there is one; never wakes the run. A workflow run
|
|
1256
|
+
* has no turn: the door's abort would give it a root conversation. */
|
|
1257
|
+
async abortTurn(run) {
|
|
1258
|
+
if (run.kind === "workflow")
|
|
1259
|
+
return;
|
|
1260
|
+
const door = this.doorOf(await this.record(run));
|
|
1261
|
+
if (door)
|
|
1262
|
+
await fetch(new URL("/abort", door), { method: "POST", headers: this.headers(run, true), body: "{}", signal: AbortSignal.timeout(5_000) }).catch(() => undefined);
|
|
1263
|
+
}
|
|
1264
|
+
/** One request to the door of a run whose process lives, never waking it (toDoor wakes no run that is finishing): again
|
|
1265
|
+
* while it opens or parks. `turnOrigin`: who sent a turn this request sends (learning-run.ts's REFLECT_ORIGIN), for
|
|
1266
|
+
* the per-tool gate to take once this server has one; nothing reads it until then. */
|
|
1267
|
+
async toLiveDoor(run, path, body, turnOrigin) {
|
|
1268
|
+
for (const deadline = Date.now() + 30_000;; await sleep(200)) {
|
|
1269
|
+
if (!this.live(run) || run.cancel)
|
|
1270
|
+
throw new Error("the run's process is gone");
|
|
1271
|
+
const door = this.doorOf(await this.record(run));
|
|
1272
|
+
const res = door ? await fetch(new URL(path, door), { method: body ? "POST" : "GET", headers: this.headers(run, body !== undefined), body: body && JSON.stringify(body), signal: AbortSignal.timeout(15_000) }).catch(() => null) : null;
|
|
1273
|
+
const data = res ? (await res.json().catch(() => null)) : null;
|
|
1274
|
+
if (res && res.status < 400)
|
|
1275
|
+
return data;
|
|
1276
|
+
if (res && !(res.status === 503 && RETRY_CODES.includes(String(data?.error))))
|
|
1277
|
+
throw new Error(`the run's door answered ${res.status}`);
|
|
1278
|
+
if (Date.now() > deadline)
|
|
1279
|
+
throw new Error("the run's door did not answer");
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
async toDoor(run, path, body, readyMs) {
|
|
1283
|
+
const deadline = Date.now() + 30_000;
|
|
1284
|
+
for (;;) {
|
|
1285
|
+
const door = await this.ensureLive(run, readyMs);
|
|
1286
|
+
const res = await fetch(new URL(path, door), {
|
|
1287
|
+
method: body === undefined ? "GET" : "POST",
|
|
1288
|
+
headers: this.headers(run, body !== undefined),
|
|
1289
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
1290
|
+
signal: AbortSignal.timeout(15_000),
|
|
1291
|
+
}).catch(() => null);
|
|
1292
|
+
const data = res ? (await res.json().catch(() => null)) : null;
|
|
1293
|
+
if (res && !(res.status === 503 && RETRY_CODES.includes(String(data?.error))))
|
|
1294
|
+
return { status: res.status, body: data };
|
|
1295
|
+
if (Date.now() > deadline)
|
|
1296
|
+
throw new ApiError("unavailable", "the run's door did not answer", { retry_after_ms: 1000 }, { "retry-after": "1" });
|
|
1297
|
+
await sleep(200);
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
/** Reads what decides the secrets runs of `run`'s revision are handed (needsOf), once per revision: from `given` (a
|
|
1301
|
+
* start's, read from the store), else from the agent store, waiting out a busy one as a run's end does. */
|
|
1302
|
+
async pinNeeds(run, given) {
|
|
1303
|
+
if (this.needs.has(run.revision))
|
|
1304
|
+
return;
|
|
1305
|
+
const revision = given ?? (await whenFree(() => this.store.readRevision(run.revision), this.busyDelays(), this.onBusy(run.id, "the agent store")));
|
|
1306
|
+
this.needs.set(run.revision, await needsOf(revision));
|
|
1307
|
+
}
|
|
1308
|
+
launch(run, followUp = run.followUpOpen === true) {
|
|
1309
|
+
if (run.child || this.closing || run.cancel || run.outcome || run.finishing || run.preparing)
|
|
1310
|
+
return;
|
|
1311
|
+
// Taken by this launch only: a later launch (a relaunch after its process went) opens the run as any other.
|
|
1312
|
+
run.followUpOpen = undefined;
|
|
1313
|
+
// Its secrets go over fd 3, written whole and closed as it starts; it reads them first (secrets.ts). Each launch path
|
|
1314
|
+
// reads its revision's needs first (pinNeeds); one that did not hands no tool key. Which keys, from the keys this
|
|
1315
|
+
// server holds now (its launcher's and the saved ones, never its environment, which under the launcher holds none),
|
|
1316
|
+
// in this same turn as the handover, so a key saved with no restart counts at the next launch, and none can change
|
|
1317
|
+
// in between.
|
|
1318
|
+
const served = withSecrets(process.env, "all", this.options.storedKeys);
|
|
1319
|
+
const needs = this.needs.get(run.revision);
|
|
1320
|
+
const handed = needs ? keysFor(needs, served) : NO_TOOL_KEYS;
|
|
1321
|
+
const secrets = handover(handed, this.options.storedKeys);
|
|
1322
|
+
// What it was handed, for the check of what its end-of-run turn writes (learning-run.ts).
|
|
1323
|
+
this.learning.onLaunch(run, handed);
|
|
1324
|
+
// And for what its errors show (refusedValues): each value handed, kept past a key's rotation.
|
|
1325
|
+
run.handed ??= new Set();
|
|
1326
|
+
for (const name of handed) {
|
|
1327
|
+
const value = secret(name, this.options.storedKeys);
|
|
1328
|
+
if (value && value.length >= MIN_SECRET)
|
|
1329
|
+
run.handed.add(value);
|
|
1330
|
+
}
|
|
1331
|
+
const env = {
|
|
1332
|
+
...childEnv(process.env, this.options.token),
|
|
1333
|
+
[SECRETS_FD_ENV]: "3",
|
|
1334
|
+
[SECRETS_LEN_ENV]: String(secrets.length),
|
|
1335
|
+
...this.fauxEnv(),
|
|
1336
|
+
...(run.meta.effort ? { [EFFORT_ENV]: run.meta.effort } : {}),
|
|
1337
|
+
...(this.options.documents ? { [DOCUMENTS_ENV]: this.options.documents } : {}),
|
|
1338
|
+
};
|
|
1339
|
+
// Kept for its metrics: the host's level may change before the run ends.
|
|
1340
|
+
run.meta.launch_thinking = { ...(env[EFFORT_ENV] ? { effort: env[EFFORT_ENV] } : {}), ...(env.AGENT_THINKING ? { host: env.AGENT_THINKING } : {}) };
|
|
1341
|
+
void this.saveMeta(run).catch((error) => warn(run.id, `what its process thinks at is not saved: ${error.message}`));
|
|
1342
|
+
delete env[CAP_ENV];
|
|
1343
|
+
if (run.meta.max_cost_usd !== undefined)
|
|
1344
|
+
env[CAP_ENV] = String(run.meta.max_cost_usd);
|
|
1345
|
+
// A run on the host's default (its revision names no model) gets the model the server picks for its harness, never
|
|
1346
|
+
// the key that gave it: behind a gateway its process holds the gateway's key alone (keysFor) and could not tell. It is
|
|
1347
|
+
// the run's last choice (model.ts hostModel: the tier's variable, then AGENT_MODEL where the harness runs it, then a
|
|
1348
|
+
// key the run holds, then this), so a host's setting the harness can run still wins; and one it cannot (AGENT_MODEL
|
|
1349
|
+
// on Anthropic's model, for codex) no longer leaves the run with none. pi and codex choose through the gateway
|
|
1350
|
+
// (chooseModel); claude-agent never does, and holds the key its route sends, which gives its default.
|
|
1351
|
+
delete env[DEFAULT_MODEL_ENV];
|
|
1352
|
+
const harness = run.tooling?.harness ?? DEFAULT_HARNESS;
|
|
1353
|
+
const defaultModel = run.tooling && !run.tooling.model && harness !== "claude-agent" ? hostModel(served, "default", harness) : undefined;
|
|
1354
|
+
if (defaultModel)
|
|
1355
|
+
env[DEFAULT_MODEL_ENV] = defaultModel;
|
|
1356
|
+
// Opened for a person's follow-up to a run whose turn had ended: nothing it resumes was cut (app.ts markResumed).
|
|
1357
|
+
delete env[FOLLOW_UP_OPEN_ENV];
|
|
1358
|
+
if (followUp)
|
|
1359
|
+
env[FOLLOW_UP_OPEN_ENV] = "1";
|
|
1360
|
+
// Its tools' providers (tool-plane.ts): resolved at its first launch from its pinned revision and this server's
|
|
1361
|
+
// settings, and kept in its serve.json, so a later change of the settings never changes a run's tools; at a later
|
|
1362
|
+
// launch only checked again (a Parallel key gone makes Parallel unavailable, never another provider). A new run's are
|
|
1363
|
+
// in the serve.json its start writes (start); resolving here is for a run made before that. A description with no secret
|
|
1364
|
+
// in it, read by the run's process, never by a request. A key saved through the settings API counts as the launcher's
|
|
1365
|
+
// does (secrets.ts), so a saved Parallel key makes Parallel available, and a deleted one unavailable at the next launch.
|
|
1366
|
+
const plane = run.meta.tool_plane ? recheckPlane(run.meta.tool_plane, served) : run.tooling ? planeFor(served, run.tooling, this.options.toolSettings?.() ?? {}, { capped: run.meta.max_cost_usd !== undefined }) : {};
|
|
1367
|
+
if (!run.meta.tool_plane && Object.keys(plane).length) {
|
|
1368
|
+
run.meta.tool_plane = plane;
|
|
1369
|
+
void this.saveMeta(run).catch(() => undefined);
|
|
1370
|
+
}
|
|
1371
|
+
delete env[TOOL_PLANE_ENV];
|
|
1372
|
+
if (Object.keys(plane).length)
|
|
1373
|
+
env[TOOL_PLANE_ENV] = JSON.stringify(plane);
|
|
1374
|
+
// The decision keys are never in a run's environment, which its tools and its model's provider read (childEnv leaves
|
|
1375
|
+
// out every secret): a run's process gets those it needs once on an inherited pipe, by name: its decision
|
|
1376
|
+
// providers' (decisionProvidersFor), and Parallel's where one of its web tools resolves to Parallel (its plane,
|
|
1377
|
+
// handsParallel). A web tool reaches Parallel only where its own capability resolves there. A run that needs none
|
|
1378
|
+
// gets no pipe at all, and one whose revision was not read gets none.
|
|
1379
|
+
delete env[DECISION_KEY_FD_ENV];
|
|
1380
|
+
// Chosen from the secrets this server holds: out of its environment once its launcher hands them over (secrets.ts).
|
|
1381
|
+
const providers = needs?.decisionProviders;
|
|
1382
|
+
const decisionKeys = providers ? decisionKeysFor(served, { providers, parallelWeb: handsParallel(plane) }) : {};
|
|
1383
|
+
const handsKey = Object.keys(decisionKeys).length > 0;
|
|
1384
|
+
this.markLaunching(run);
|
|
1385
|
+
const log = openSync(join(run.dir, PROCESS_LOG), "a", 0o600);
|
|
1386
|
+
const stdio = ["ignore", "ignore", log, "pipe"];
|
|
1387
|
+
// The first descriptor after the others: macOS aborts the parent of a spawn with a pipe at 16 or above.
|
|
1388
|
+
const keyFd = stdio.length;
|
|
1389
|
+
if (handsKey) {
|
|
1390
|
+
stdio.push("pipe");
|
|
1391
|
+
env[DECISION_KEY_FD_ENV] = String(keyFd);
|
|
1392
|
+
}
|
|
1393
|
+
// A workflow run resumes from its journal when it opens again, so SIGTERM lets it go at once, undrained.
|
|
1394
|
+
const drain = run.kind === "workflow" ? "0s" : (this.options.drainTimeout ?? DRAIN);
|
|
1395
|
+
// Its own door token, which its door takes and its calls to the box relay carry: no other run's process holds it.
|
|
1396
|
+
run.doorToken = ensureRunDoorToken(run.dir);
|
|
1397
|
+
const doorTokenFile = join(run.dir, RUN_DOOR_TOKEN);
|
|
1398
|
+
const child = spawn(process.execPath, [
|
|
1399
|
+
// secrets.ts first, as a preload: the pipe is read and closed before pi-durable-disk's CLI loads or starts anything.
|
|
1400
|
+
"--no-warnings=ExperimentalWarning", "--import", SECRETS_MODULE, this.cli, "run", "--dir", run.dir, "--app", this.app,
|
|
1401
|
+
"--serve", "0", "--serve-host", "127.0.0.1", "--serve-token-file", doorTokenFile, "--drain-timeout", drain, // key-gate: loopback-rule the door of a run listens on loopback only, for this server
|
|
1402
|
+
], { stdio, env });
|
|
1403
|
+
closeSync(log);
|
|
1404
|
+
const pipe = child.stdio[3];
|
|
1405
|
+
pipe?.on("error", () => { });
|
|
1406
|
+
pipe?.end(secrets);
|
|
1407
|
+
if (handsKey) {
|
|
1408
|
+
const keyPipe = child.stdio[keyFd];
|
|
1409
|
+
// A process that dies before it reads the key closes the pipe: that is its exit to settle, not an error here.
|
|
1410
|
+
keyPipe?.on("error", () => undefined);
|
|
1411
|
+
keyPipe?.end(JSON.stringify(decisionKeys));
|
|
1412
|
+
}
|
|
1413
|
+
run.child = child;
|
|
1414
|
+
child.once("exit", (code) => {
|
|
1415
|
+
if (run.child === child)
|
|
1416
|
+
run.child = undefined;
|
|
1417
|
+
this.reportedBack(run);
|
|
1418
|
+
void this.settle(run, code, true);
|
|
1419
|
+
});
|
|
1420
|
+
child.once("error", () => {
|
|
1421
|
+
if (run.child === child)
|
|
1422
|
+
run.child = undefined;
|
|
1423
|
+
this.reportedBack(run);
|
|
1424
|
+
});
|
|
1425
|
+
this.connect(run);
|
|
1426
|
+
}
|
|
1427
|
+
/** Writes the run's launch mark before its process is spawned: a spawn that takes the server down leaves it, and the
|
|
1428
|
+
* next start fails the run rather than launch it again and go down with it. The file exists once the call returns,
|
|
1429
|
+
* which a server's death does not undo; no fsync, which would hold the event loop on the disk at every launch. */
|
|
1430
|
+
markLaunching(run) {
|
|
1431
|
+
closeSync(openSync(join(run.dir, RUN_LAUNCHING), "w", 0o600));
|
|
1432
|
+
run.launching = true;
|
|
1433
|
+
}
|
|
1434
|
+
/** The run's newest launch came through with the server up: its process serves, or exited while it was watched. Its
|
|
1435
|
+
* callers are event handlers, so a mark that cannot be removed is logged, never thrown: a throw there stops the
|
|
1436
|
+
* server and every run on it. The mark left behind fails the run at the next start, which never launches it again. */
|
|
1437
|
+
reportedBack(run) {
|
|
1438
|
+
if (!run.launching)
|
|
1439
|
+
return;
|
|
1440
|
+
run.launching = false;
|
|
1441
|
+
try {
|
|
1442
|
+
rmSync(join(run.dir, RUN_LAUNCHING), { force: true });
|
|
1443
|
+
}
|
|
1444
|
+
catch (error) {
|
|
1445
|
+
this.options.log?.("launch_mark_kept", { run: run.id, code: error.code ?? "unknown" });
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
/** Opens the run again on its directory after its process went before the run ended: it resumes from its store. An
|
|
1449
|
+
* agentic run whose first message never landed gets it again, under the same request id. */
|
|
1450
|
+
relaunch(run) {
|
|
1451
|
+
run.relaunches++;
|
|
1452
|
+
warn(run.id, `its process went before the run ended; opening it again (${run.relaunches} of ${MAX_RELAUNCHES})`);
|
|
1453
|
+
this.launch(run);
|
|
1454
|
+
const first = run.meta.input?.content;
|
|
1455
|
+
if (run.kind !== "agentic" || usersOf(run.rows) > 0 || typeof first !== "string")
|
|
1456
|
+
return;
|
|
1457
|
+
run.submitted = 1;
|
|
1458
|
+
this.refresh(run);
|
|
1459
|
+
// As it was first sent: the run never took it, so its work/inputs/ is as its start left it.
|
|
1460
|
+
void firstMessage(first, join(run.dir, "work")).then((content) => this.submit(run, content, "followUp", `first-${run.id}`, READY_TIMEOUT_MS)).catch((error) => warn(run.id, `its first message did not land again: ${error.message}`));
|
|
1461
|
+
}
|
|
1462
|
+
/** After the run's process exited, or was found gone: its rows from its released store, then, when it is over, its
|
|
1463
|
+
* carry back. One at a time per run, and none once the run has its outcome. */
|
|
1464
|
+
settle(run, code, exited) {
|
|
1465
|
+
if (this.closed)
|
|
1466
|
+
return Promise.resolve();
|
|
1467
|
+
run.settles++;
|
|
1468
|
+
run.settling = (run.settling ?? Promise.resolve())
|
|
1469
|
+
.then(() => (run.outcome ? undefined : this.settleOnce(run, code, exited)))
|
|
1470
|
+
.catch((error) => {
|
|
1471
|
+
if (!(storeBusy(error) || error instanceof PullPending) || this.closing)
|
|
1472
|
+
return warn(run.id, `not settled: ${error.message}; the next start tries again`);
|
|
1473
|
+
// A store still held past the run end's retries: settled again later, not left until the next start.
|
|
1474
|
+
const every = this.options.settleRetryMs ?? SETTLE_RETRY_MS;
|
|
1475
|
+
warn(run.id, `not settled: ${error.message}; trying again in ${every / 1000} s`);
|
|
1476
|
+
setTimeout(() => void this.settle(run, code, exited), every).unref();
|
|
1477
|
+
})
|
|
1478
|
+
.finally(() => void run.settles--);
|
|
1479
|
+
return run.settling;
|
|
1480
|
+
}
|
|
1481
|
+
/** `exited`: the process this server supervised exited. Exiting on an error before it released fails the run; going
|
|
1482
|
+
* any other way before the run ended (killed, or found gone at a start) opens it again. */
|
|
1483
|
+
async settleOnce(run, code, exited) {
|
|
1484
|
+
// A run whose files are still being copied has had no process yet: its start launches it, and only a cancel ends it
|
|
1485
|
+
// first (a recovery that lists it meanwhile must not fail it for its launch mark).
|
|
1486
|
+
if (run.preparing && !run.cancel)
|
|
1487
|
+
return;
|
|
1488
|
+
run.feed?.abort();
|
|
1489
|
+
run.feed = undefined;
|
|
1490
|
+
run.working = false;
|
|
1491
|
+
const record = await this.record(run);
|
|
1492
|
+
const released = RELEASED.has(String(record?.status));
|
|
1493
|
+
const pid = holderPid(record);
|
|
1494
|
+
// A process that is gone serves no door, whatever its last heartbeat says.
|
|
1495
|
+
const gone = !this.live(run) && !(pid !== undefined && pid !== process.pid && alive(pid) && this.doorOf(record));
|
|
1496
|
+
// Its metrics are this settle's read, or none: never an earlier end's.
|
|
1497
|
+
run.metrics = undefined;
|
|
1498
|
+
if (released || gone)
|
|
1499
|
+
await this.storeWhenFree(run, true);
|
|
1500
|
+
// Its process gone: an archived run's box is let go now, whatever comes next (an outcome, a wait for the person, a
|
|
1501
|
+
// relaunch), since nothing else would until the next start or archive. This is every archived end that can let a box
|
|
1502
|
+
// go: a settle with the process not gone means another live holder of the run, whose box is its own. That holder is
|
|
1503
|
+
// one this server neither started nor adopted (adoptProcess watches only the holder it adopts), so its later exit
|
|
1504
|
+
// settles nothing here: its box stays held, fail-closed, until the next start's sweep or another archive lets it go.
|
|
1505
|
+
if (gone && (await this.options.agents.request(() => this.store.readRun(run.id)).catch(() => undefined))?.archivedAt)
|
|
1506
|
+
await this.teardown(run);
|
|
1507
|
+
let ended;
|
|
1508
|
+
// A workflow run carries back how its workflow ended, through workflowCarry; cancelled before that, it stopped.
|
|
1509
|
+
// A cancel during the end-of-run turn ends the run's learning, never its job: the run keeps the outcome it had.
|
|
1510
|
+
if (run.cancel && !reflecting(run))
|
|
1511
|
+
ended = run.kind === "workflow" ? await this.workflowEnd(run, workflowEnding(record) ?? { status: "stopped" }) : { outcome: "cancelled" };
|
|
1512
|
+
else if (run.finishing)
|
|
1513
|
+
ended = { outcome: run.finishing };
|
|
1514
|
+
else if (run.launching && gone) {
|
|
1515
|
+
run.error = { code: "run_failed", message: "The server went down while it started the run's process, which never came up; it is not started again, since starting it may be what took the server down.", retryable: false, details: { reason: LAUNCH_LOST } };
|
|
1516
|
+
ended = { outcome: "failed" };
|
|
1517
|
+
}
|
|
1518
|
+
else if (exited && !released && code !== null && code !== 0) {
|
|
1519
|
+
run.error = { code: "run_failed", message: `The run's process exited (${code}) without releasing the run: ${await lastLogLine(run)}`, retryable: false };
|
|
1520
|
+
ended = { outcome: "failed" };
|
|
1521
|
+
}
|
|
1522
|
+
else if (!gone && this.doorOf(record))
|
|
1523
|
+
ended = undefined;
|
|
1524
|
+
else if (run.kind === "workflow")
|
|
1525
|
+
ended = await this.workflowEnd(run, workflowEnding(record));
|
|
1526
|
+
else {
|
|
1527
|
+
const end = this.decide(run);
|
|
1528
|
+
if (end?.error)
|
|
1529
|
+
run.error = end.error;
|
|
1530
|
+
ended = end && { outcome: end.outcome };
|
|
1531
|
+
}
|
|
1532
|
+
if (!ended) {
|
|
1533
|
+
// Work left and no process: opened again. A run that waits for the person waits without one, until a message.
|
|
1534
|
+
const stalled = run.kind === "workflow" || statusOf(run).status !== "input_required";
|
|
1535
|
+
if (!gone || !stalled || this.closing)
|
|
1536
|
+
return this.refresh(run);
|
|
1537
|
+
// Opened again without a place, as a run already going, unless its harness never fits this host (a restart on a
|
|
1538
|
+
// smaller one): that run fails with why.
|
|
1539
|
+
const never = neverFits(run.harness, this.memory);
|
|
1540
|
+
if (!never && run.relaunches < MAX_RELAUNCHES) {
|
|
1541
|
+
await this.pinNeeds(run);
|
|
1542
|
+
return this.relaunch(run);
|
|
1543
|
+
}
|
|
1544
|
+
run.error = { code: "run_failed", message: never ?? `The run's process went ${MAX_RELAUNCHES + 1} times before the run ended: ${await lastLogLine(run)}`, retryable: false };
|
|
1545
|
+
ended = { outcome: "failed" };
|
|
1546
|
+
}
|
|
1547
|
+
await this.carryBack(run, ended.outcome, ended.state, ended.summary);
|
|
1548
|
+
}
|
|
1549
|
+
/** A workflow run's carry back, `workflowCarry` of @parcha/pi-durable-agent/workflow on its released store, and its
|
|
1550
|
+
* output when it completed; undefined while its workflow has not ended. */
|
|
1551
|
+
async workflowEnd(run, ending) {
|
|
1552
|
+
if (!ending)
|
|
1553
|
+
return undefined;
|
|
1554
|
+
const { readWorkflowRun, workflowCarry } = await import("@parcha/pi-durable-agent/workflow");
|
|
1555
|
+
// A run's end waits for a busy store as long as its carry back does, not a request's 2 s.
|
|
1556
|
+
const revision = (await whenFree(() => this.store.readRevision(run.revision), this.busyDelays(), this.onBusy(run.id, "the agent store")));
|
|
1557
|
+
const at = { runId: run.id, storePath: this.storeFile(run), revision };
|
|
1558
|
+
const { state, summary } = await workflowCarry(at, ending);
|
|
1559
|
+
if (state === "completed")
|
|
1560
|
+
run.meta.output = (await readWorkflowRun(at)).output ?? null;
|
|
1561
|
+
else if (state === "escalated") {
|
|
1562
|
+
const { escalation, escalatedAt } = await readWorkflowRun(at);
|
|
1563
|
+
run.meta.review = { kind: escalation?.kind ?? null, node: escalation?.label ?? escalatedAt?.label ?? null, reason: escalation?.summary ?? summary };
|
|
1564
|
+
}
|
|
1565
|
+
else if (state === "failed")
|
|
1566
|
+
run.error = { code: "run_failed", message: `The workflow failed: ${summary}.`, retryable: false };
|
|
1567
|
+
await this.readDecisionCost(run);
|
|
1568
|
+
return { outcome: STATUS_OF[state], state, summary };
|
|
1569
|
+
}
|
|
1570
|
+
/** A workflow run's decisions' cost, from their receipts in its released store: a receipt whose cost is unknown leaves
|
|
1571
|
+
* the run's unknown, never $0. Read at its end and again when a restarted server adopts it as ended. */
|
|
1572
|
+
async readDecisionCost(run) {
|
|
1573
|
+
const { durableDecisions } = await import("@parcha/agentrun-pi/durable");
|
|
1574
|
+
// Not its `llm` calls: each completes on the run's marked models, so its cost is a REQUEST_COST entry its usage row
|
|
1575
|
+
// already sums (request-start.ts).
|
|
1576
|
+
const paid = durableDecisions(this.storeFile(run)).map((row) => row.cost_usd);
|
|
1577
|
+
if (paid.length)
|
|
1578
|
+
run.decisionCost = paid.every((cost) => typeof cost === "number") ? paid.reduce((a, b) => a + b, 0) : null;
|
|
1579
|
+
if (paid.length)
|
|
1580
|
+
run.decisionsPriced = { known: paid.reduce((a, b) => a + (typeof b === "number" ? b : 0), 0), unpriced: paid.filter((cost) => typeof cost !== "number").length };
|
|
1581
|
+
}
|
|
1582
|
+
/** Ends the run in the agent store, once: how it ended, its cost, a line for the list and its metrics. A store held by
|
|
1583
|
+
* another writer is tried again with backoff; past the last try the run stays unsettled, and the next start carries it back. */
|
|
1584
|
+
async carryBack(run, outcome, state, summary) {
|
|
1585
|
+
// Its process is gone: its box goes with its end, whatever the end (a follow-up after it gets a fresh box; work/ stays).
|
|
1586
|
+
// A remote box's last pull lands first: the end is not recorded until its files are in work/.
|
|
1587
|
+
await this.dropBox(run, true);
|
|
1588
|
+
// Its end-of-run turn closed, and what the turn wrote set aside before the run reads ended (learning-run.ts).
|
|
1589
|
+
await this.learning.beforeSettle(run, outcome);
|
|
1590
|
+
const cost = run.decisionCost === undefined ? costOf(run.rows) : costView(run.rows, undefined, run.decisionCost);
|
|
1591
|
+
// An unknown cost keeps what it cost so far beside it, for the list row read from the store.
|
|
1592
|
+
const soFar = cost === null && !run.imported ? soFarOf(run.rows, run.decisionCost === undefined ? undefined : (run.decisionsPriced ?? null)) : undefined;
|
|
1593
|
+
if (soFar)
|
|
1594
|
+
run.meta.cost_so_far = soFar;
|
|
1595
|
+
else
|
|
1596
|
+
delete run.meta.cost_so_far;
|
|
1597
|
+
const line = summary ?? (outcome === "completed" ? answerOfRun(run) : outcome === "cancelled" ? "cancelled" : run.error?.message);
|
|
1598
|
+
if (run.error)
|
|
1599
|
+
run.meta.error = { code: run.error.code, message: run.error.message, ...(run.error.details ? { details: run.error.details } : {}) };
|
|
1600
|
+
// Its end's time, chosen once and given to the store: the row, a retry of the write and its run.ended all name this one
|
|
1601
|
+
// time. A server that settles the run after a kill chooses its own: nothing was sent before the store had an end.
|
|
1602
|
+
const endedAt = (run.endedAt ??= new Date().toISOString());
|
|
1603
|
+
const ending = { state: state ?? (outcome === "cancelled" ? "stopped" : outcome === "completed" ? "completed" : "failed"), ...(cost === null ? {} : { costUsd: cost }), ...(line ? { summary: line } : {}), endedAt };
|
|
1604
|
+
const counted = run.metrics;
|
|
1605
|
+
const end = (metrics) => {
|
|
1606
|
+
try {
|
|
1607
|
+
this.store.carryBack(run.id, metrics ? { ...ending, metrics } : ending);
|
|
1608
|
+
}
|
|
1609
|
+
catch (error) {
|
|
1610
|
+
if (!(error instanceof AgentHomeError && error.code === "exists"))
|
|
1611
|
+
throw error;
|
|
1612
|
+
}
|
|
1613
|
+
};
|
|
1614
|
+
const persist = async () => {
|
|
1615
|
+
await this.saveMeta(run);
|
|
1616
|
+
await whenFree(() => {
|
|
1617
|
+
const metrics = counted && this.storedMetrics(run, counted);
|
|
1618
|
+
try {
|
|
1619
|
+
end(metrics);
|
|
1620
|
+
}
|
|
1621
|
+
catch (error) {
|
|
1622
|
+
// Metrics the store refuses (a name past its limit) never hold up the run's end: it ends without them.
|
|
1623
|
+
if (!(metrics && error instanceof AgentHomeError && error.code === "invalid"))
|
|
1624
|
+
throw error;
|
|
1625
|
+
warn(run.id, `its metrics are not kept: ${error.message}`);
|
|
1626
|
+
end();
|
|
1627
|
+
}
|
|
1628
|
+
}, this.busyDelays(), this.onBusy(run.id, "the agent store"));
|
|
1629
|
+
};
|
|
1630
|
+
try {
|
|
1631
|
+
await persist();
|
|
1632
|
+
}
|
|
1633
|
+
catch (error) {
|
|
1634
|
+
// A store that refuses the write (a full disk, a store fenced by it) must not leave the run unended: it ends here
|
|
1635
|
+
// now, with its cost from its rows, and the write is tried again until it lands. A restart before then reads the
|
|
1636
|
+
// run as it was in the store. Its run.ended waits for the store (persistLater), so a receiver that reads the run
|
|
1637
|
+
// back on its notice reads it ended there too.
|
|
1638
|
+
warn(run.id, `its end could not be written to the agent store (${error.message}); trying again every ${(this.options.settleRetryMs ?? SETTLE_RETRY_MS) / 1000} s`);
|
|
1639
|
+
// An unknown cost stays unknown: never stored as 0.
|
|
1640
|
+
if (cost !== null)
|
|
1641
|
+
run.costUsd = cost;
|
|
1642
|
+
run.outcome = outcome;
|
|
1643
|
+
run.finishing = undefined;
|
|
1644
|
+
run.settled = true;
|
|
1645
|
+
run.updatedAt = new Date().toISOString();
|
|
1646
|
+
this.refresh(run);
|
|
1647
|
+
this.persistLater(run, persist);
|
|
1648
|
+
return;
|
|
1649
|
+
}
|
|
1650
|
+
const row = await this.options.agents.request(() => this.store.readRun(run.id)).catch(() => undefined);
|
|
1651
|
+
// The store's time is the one it was given, unless an earlier end of the run's own landed first (a refused write that
|
|
1652
|
+
// went through after all): the row's then. A read that fails keeps the chosen time, never a new one.
|
|
1653
|
+
if (row?.endedAt)
|
|
1654
|
+
run.endedAt = row.endedAt;
|
|
1655
|
+
if (row?.costUsd !== undefined)
|
|
1656
|
+
run.costUsd = row.costUsd;
|
|
1657
|
+
this.options.log?.("run_ended", { run: run.id, agent: run.agentId, status: outcome, cost_usd: row?.costUsd ?? cost ?? "unknown" });
|
|
1658
|
+
run.outcome = outcome;
|
|
1659
|
+
run.finishing = undefined;
|
|
1660
|
+
run.settled = true;
|
|
1661
|
+
run.updatedAt = new Date().toISOString();
|
|
1662
|
+
this.refresh(run);
|
|
1663
|
+
this.notice(run, "run.ended", run.endedAt);
|
|
1664
|
+
// Only once the run has ended as it would without learning: a slow or failing check never holds the job.
|
|
1665
|
+
void this.learning.afterSettle(run);
|
|
1666
|
+
}
|
|
1667
|
+
/** The run's metrics as the store keeps them: what its entries say it used, the effort its newest process ran at (unknown
|
|
1668
|
+
* for one an older server started), and on a harness other than pi the model its revision names (its entries name the
|
|
1669
|
+
* harness). A busy store throws, for the write's retries; a revision that cannot be read otherwise adds nothing. */
|
|
1670
|
+
storedMetrics(run, counted) {
|
|
1671
|
+
let revision;
|
|
1672
|
+
try {
|
|
1673
|
+
revision = this.store.readRevision(run.revision);
|
|
1674
|
+
}
|
|
1675
|
+
catch (error) {
|
|
1676
|
+
if (storeBusy(error))
|
|
1677
|
+
throw error;
|
|
1678
|
+
return counted;
|
|
1679
|
+
}
|
|
1680
|
+
const body = revision.kind === "agentic" ? revision.body : undefined;
|
|
1681
|
+
const harness = body?.harness ?? DEFAULT_HARNESS;
|
|
1682
|
+
// As its process chose it (app.ts): the run's effort, else its revision's thinking, else the host's, else medium.
|
|
1683
|
+
const launched = run.meta.launch_thinking;
|
|
1684
|
+
const level = launched && thinkingFor(harness, thinkingOf({ [EFFORT_ENV]: launched.effort, AGENT_THINKING: launched.host }, body?.thinking));
|
|
1685
|
+
return { ...counted, ...(level ? { effort: level } : {}), ...(harness !== DEFAULT_HARNESS && body?.model ? { model: body.model } : {}) };
|
|
1686
|
+
}
|
|
1687
|
+
/** Tries `persist` again every settleRetryMs while the server lives, until it lands. */
|
|
1688
|
+
persistLater(run, persist) {
|
|
1689
|
+
const timer = setTimeout(() => {
|
|
1690
|
+
if (this.closing)
|
|
1691
|
+
return;
|
|
1692
|
+
persist().then(async () => {
|
|
1693
|
+
const row = await this.options.agents.request(() => this.store.readRun(run.id)).catch(() => undefined);
|
|
1694
|
+
if (row?.endedAt)
|
|
1695
|
+
run.endedAt = row.endedAt;
|
|
1696
|
+
if (row?.costUsd !== undefined)
|
|
1697
|
+
run.costUsd = row.costUsd;
|
|
1698
|
+
// In the store at last: its run.ended goes now.
|
|
1699
|
+
this.notice(run, "run.ended", run.endedAt);
|
|
1700
|
+
await this.learning.afterSettle(run);
|
|
1701
|
+
}, () => this.persistLater(run, persist));
|
|
1702
|
+
}, this.options.settleRetryMs ?? SETTLE_RETRY_MS);
|
|
1703
|
+
timer.unref();
|
|
1704
|
+
}
|
|
1705
|
+
/** How long a run's end waits for a busy store, step by step. */
|
|
1706
|
+
busyDelays() {
|
|
1707
|
+
return this.options.carryBackRetry?.delaysMs ?? CARRY_BACK_RETRIES_MS;
|
|
1708
|
+
}
|
|
1709
|
+
/** Hears that `what` was busy for run `runId`, and says so when another try follows. */
|
|
1710
|
+
onBusy(runId, what) {
|
|
1711
|
+
return (attempt, delay) => {
|
|
1712
|
+
this.options.carryBackRetry?.onBusy?.(runId, attempt);
|
|
1713
|
+
if (delay !== undefined)
|
|
1714
|
+
warn(runId, `${what} is busy; trying again in ${delay} ms (${attempt + 1} of ${this.busyDelays().length})`);
|
|
1715
|
+
};
|
|
1716
|
+
}
|
|
1717
|
+
/** The run's store, read again while another connection holds it, within the same retries. */
|
|
1718
|
+
storeWhenFree(run, atEnd = false) {
|
|
1719
|
+
return whenFree(() => this.readStore(run, atEnd), this.busyDelays(), this.onBusy(run.id, "its store"));
|
|
1720
|
+
}
|
|
1721
|
+
// ---- acting ---------------------------------------------------------------------------------------------------------
|
|
1722
|
+
/** Start a run of `revision` (number `version`) of `entry`'s agent: `startRun` in the store, then its process, then an
|
|
1723
|
+
* agentic run's first message, `input.content`. */
|
|
1724
|
+
/** A place for one more live run of `harness`, taken for this start (counted in `starting` and `startingMib` from
|
|
1725
|
+
* here, so two starts at once cannot both take the last place), or 429 rate_limited; the function returned gives it
|
|
1726
|
+
* back once the run holds it as a live run, or did not start. A place is one under the cap on the count and the
|
|
1727
|
+
* memory a run of its harness reserves (host.ts): both must be free. A run that has ended (failed, completed,
|
|
1728
|
+
* cancelled) still holds its place until its process exits; a start that needs that place waits for it, up to that
|
|
1729
|
+
* process's drain and kill, never refused for a place already being given back. A harness whose one run is more than
|
|
1730
|
+
* the whole memory for runs is refused at once, never a 429 (capabilities say so too). From the read of what is held
|
|
1731
|
+
* to the reservation nothing awaits, so two starts at once never both take the last of it. */
|
|
1732
|
+
async takePlace(harness) {
|
|
1733
|
+
const { memory, options: { maxRuns: max } } = this;
|
|
1734
|
+
const need = runMibOf(harness);
|
|
1735
|
+
const never = neverFits(harness, memory);
|
|
1736
|
+
if (never)
|
|
1737
|
+
throw new ApiError("agent_not_runnable", never, { details: { unbound: [], missing: {}, harness } });
|
|
1738
|
+
for (const deadline = Date.now() + this.killAfterMs() + 1_000;; await sleep(50)) {
|
|
1739
|
+
const holding = [...this.runs.values()].filter((run) => this.live(run));
|
|
1740
|
+
const counted = max === undefined || holding.length + this.starting < max;
|
|
1741
|
+
const held = holding.reduce((sum, run) => sum + runMibOf(run.harness), this.startingMib);
|
|
1742
|
+
// With nothing held, a run that fits at all starts: pi's one place on a host smaller than a pi run (host.ts).
|
|
1743
|
+
const fits = held === 0 || held + need <= runsMemoryMib(memory);
|
|
1744
|
+
if (counted && fits)
|
|
1745
|
+
break;
|
|
1746
|
+
const leaving = holding.some((run) => run.outcome || run.finishing || run.cancel);
|
|
1747
|
+
if (!leaving || Date.now() > deadline) {
|
|
1748
|
+
if (!counted)
|
|
1749
|
+
throw new ApiError("rate_limited", `This server runs at most ${max} runs at once (max_concurrent_runs); start this one when another ends.`, { retry_after_ms: 5_000, details: { max_concurrent_runs: max } }, { "retry-after": "5" });
|
|
1750
|
+
throw new ApiError("rate_limited", memoryFull(harness, memory, held), { retry_after_ms: 5_000, details: { max_concurrent_runs: max ?? null, harness, needs_mb: need, free_mb: Math.max(0, runsMemoryMib(memory) - held) } }, { "retry-after": "5" });
|
|
1751
|
+
}
|
|
1752
|
+
}
|
|
1753
|
+
this.starting++;
|
|
1754
|
+
this.startingMib += need;
|
|
1755
|
+
return () => {
|
|
1756
|
+
this.starting--;
|
|
1757
|
+
this.startingMib -= need;
|
|
1758
|
+
};
|
|
1759
|
+
}
|
|
1760
|
+
/** `inputs` copies the run's files into its work/ (uploads.ts), after the store made it and before its process starts. */
|
|
1761
|
+
async create(entry, revision, version, options) {
|
|
1762
|
+
await this.sweepOnce();
|
|
1763
|
+
const release = await this.takePlace(harnessOfBody(revision.body));
|
|
1764
|
+
try {
|
|
1765
|
+
// Read again: the place may have been waited for, and the agent archived meanwhile.
|
|
1766
|
+
const now = await this.options.agents.get(entry.agent.id);
|
|
1767
|
+
if (now?.agent.archivedAt)
|
|
1768
|
+
throw new ApiError("agent_not_runnable", `The agent ${entry.agent.id} is archived: unarchive it to run it.`, { details: { archived_at: now.agent.archivedAt } });
|
|
1769
|
+
return await this.start(entry, revision, version, options);
|
|
1770
|
+
}
|
|
1771
|
+
finally {
|
|
1772
|
+
release();
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
/** Writes the serve.json of a run being set up. When it fails, the store has the run as running and no process will
|
|
1776
|
+
* run it: it ends failed here, never left for a later start to open with half its files. */
|
|
1777
|
+
async setUp(runId, dir, meta) {
|
|
1778
|
+
try {
|
|
1779
|
+
await writeWhole(join(dir, RUN_META), `${JSON.stringify(meta)}\n`);
|
|
1780
|
+
}
|
|
1781
|
+
catch (error) {
|
|
1782
|
+
const summary = `The run could not be set up: ${error.message}`;
|
|
1783
|
+
await this.options.agents.request(() => this.store.carryBack(runId, { state: "failed", summary })).catch((undo) => warn(runId, `not ended after its setup failed: ${undo.message}`));
|
|
1784
|
+
throw error;
|
|
1785
|
+
}
|
|
1786
|
+
}
|
|
1787
|
+
async start(entry, revision, version, options) {
|
|
1788
|
+
// Its tools' providers, resolved before the run exists (tool-plane.ts) and kept in the serve.json its start writes first,
|
|
1789
|
+
// so a launch after a crash reads them back, never the settings of that moment, and keeping them is no write of its own.
|
|
1790
|
+
const tooling = await toolingOf(revision);
|
|
1791
|
+
const plane = tooling ? planeFor(withSecrets(process.env, "all", this.options.storedKeys), tooling, this.options.toolSettings?.() ?? {}, { capped: options.maxCostUsd !== undefined }) : {};
|
|
1792
|
+
// A run that learns: its seed read before it is made (learning-run.ts).
|
|
1793
|
+
const pin = await this.learning.onStart(entry.agent.id, revision);
|
|
1794
|
+
const started = await this.options.agents.request(() => this.store.startRun({ agent: entry.agent.id, revision: revision.id })).catch((error) => storeError(error, "revision"));
|
|
1795
|
+
const at = new Date().toISOString();
|
|
1796
|
+
const meta = {
|
|
1797
|
+
title: clip(options.title.trim().replace(/\s+/g, " "), 80),
|
|
1798
|
+
created_at: at,
|
|
1799
|
+
input: options.input,
|
|
1800
|
+
place: options.place,
|
|
1801
|
+
...(options.effort ? { effort: options.effort } : {}),
|
|
1802
|
+
...(options.maxCostUsd !== undefined ? { max_cost_usd: options.maxCostUsd } : {}),
|
|
1803
|
+
...(Object.keys(plane).length ? { tool_plane: plane } : {}),
|
|
1804
|
+
};
|
|
1805
|
+
// The run's input is saved first, as the store has it running: a server that goes down from here on leaves a run the
|
|
1806
|
+
// next one relaunches with its first message.
|
|
1807
|
+
await this.setUp(started.runId, started.dir, meta);
|
|
1808
|
+
if (pin) {
|
|
1809
|
+
// Then its seed copied and pinned, and its learning saved once the copy is whole or gone. A server that goes down
|
|
1810
|
+
// during the copy leaves none saved, and the next one takes the copy back (learning-run.ts onLoad).
|
|
1811
|
+
meta.learning = await pin(started, at);
|
|
1812
|
+
await this.setUp(started.runId, started.dir, meta);
|
|
1813
|
+
}
|
|
1814
|
+
const run = this.blank({ id: started.runId, agent: entry.agent.id, revision: revision.id, kind: revision.kind }, started.dir, meta, version, harnessOfBody(revision.body), tooling, revision);
|
|
1815
|
+
// Before the run is known here, so nothing launches it first.
|
|
1816
|
+
await this.pinNeeds(run, revision);
|
|
1817
|
+
this.runs.set(run.id, run);
|
|
1818
|
+
// A seed that failed is a learning row from the start, and its learning's end is in the ledger.
|
|
1819
|
+
this.show(run);
|
|
1820
|
+
void this.learning.onSaved(run, meta.learning);
|
|
1821
|
+
this.options.log?.("run_started", { run: run.id, agent: run.agentId, kind: run.kind });
|
|
1822
|
+
if (revision.kind === "agentic")
|
|
1823
|
+
run.submitted = 1;
|
|
1824
|
+
this.refresh(run);
|
|
1825
|
+
if (options.inputs) {
|
|
1826
|
+
// Listed from here, so a request may reach it while it copies: `preparing` holds it until its files are in.
|
|
1827
|
+
const prepared = this.prepare(run, started.workspace, options.inputs).finally(() => void (run.preparing = undefined));
|
|
1828
|
+
// Never rejected: a request waiting on it reads how the start ended from the run; the start's own error is the create's.
|
|
1829
|
+
run.preparing = prepared.then(() => undefined, () => undefined);
|
|
1830
|
+
if (!(await prepared))
|
|
1831
|
+
return run;
|
|
1832
|
+
}
|
|
1833
|
+
this.launch(run);
|
|
1834
|
+
if (revision.kind === "workflow")
|
|
1835
|
+
return run;
|
|
1836
|
+
// The first message names the files given to the run (run-manifest.ts), on every harness.
|
|
1837
|
+
void firstMessage(options.input.content, started.workspace).then((content) => this.submit(run, content, "followUp", `first-${run.id}`, READY_TIMEOUT_MS)).catch((error) => {
|
|
1838
|
+
run.submitted = 0;
|
|
1839
|
+
// The run ended before its first message reached it (a process that crashed at its start): how it ended stands.
|
|
1840
|
+
if (run.outcome || run.finishing || run.cancel)
|
|
1841
|
+
return;
|
|
1842
|
+
run.error = { code: "run_failed", message: error.message, retryable: false };
|
|
1843
|
+
if (this.live(run))
|
|
1844
|
+
this.finish(run, "failed");
|
|
1845
|
+
else if (!run.cancel)
|
|
1846
|
+
void this.settle(run, 1, true);
|
|
1847
|
+
});
|
|
1848
|
+
return run;
|
|
1849
|
+
}
|
|
1850
|
+
/** Copies the run's files into its work/ under the launch mark: a server that goes down while it copies leaves the
|
|
1851
|
+
* mark, and the next start fails the run rather than run it on part of its files. Copied whole, the mark goes, and the
|
|
1852
|
+
* launch makes its own. False when the copy failed, and the run ended so (or was cancelled meanwhile). */
|
|
1853
|
+
async prepare(run, work, inputs) {
|
|
1854
|
+
try {
|
|
1855
|
+
// The mark itself may fail (a full disk): the run ends as when the copy does.
|
|
1856
|
+
this.markLaunching(run);
|
|
1857
|
+
await inputs(work);
|
|
1858
|
+
}
|
|
1859
|
+
catch (error) {
|
|
1860
|
+
run.submitted = 0;
|
|
1861
|
+
// Cancelled while it copied: it ends so.
|
|
1862
|
+
if (!(run.outcome || run.cancel)) {
|
|
1863
|
+
run.error = { code: "run_failed", message: `The run's files could not be copied into its workspace: ${error.message}`, retryable: false };
|
|
1864
|
+
await this.carryBack(run, "failed");
|
|
1865
|
+
}
|
|
1866
|
+
// The mark goes only once the store has the run's end: a server that goes down before then finds it, and fails the
|
|
1867
|
+
// run rather than launch it on part of its files.
|
|
1868
|
+
const row = await this.options.agents.request(() => this.store.readRun(run.id)).catch(() => undefined);
|
|
1869
|
+
if (row && row.state !== "running")
|
|
1870
|
+
this.reportedBack(run);
|
|
1871
|
+
return false;
|
|
1872
|
+
}
|
|
1873
|
+
this.reportedBack(run);
|
|
1874
|
+
return true;
|
|
1875
|
+
}
|
|
1876
|
+
async submit(run, content, whenBusy, requestId, readyMs) {
|
|
1877
|
+
await this.beforeSubmit?.(run.id, content);
|
|
1878
|
+
const answer = await this.toDoor(run, "/submit", { requestId, content, whenBusy }, readyMs);
|
|
1879
|
+
if (answer.status >= 400)
|
|
1880
|
+
throw new ApiError(answer.status === 409 ? "not_continuable" : "internal", String(answer.body?.message ?? answer.body?.error ?? "the run refused the message"));
|
|
1881
|
+
}
|
|
1882
|
+
/** Whether the run's harness takes a message mid-turn. */
|
|
1883
|
+
steers(run) {
|
|
1884
|
+
return run.kind !== "agentic" || steersMidTurn(run.harness);
|
|
1885
|
+
}
|
|
1886
|
+
/** One message to an agentic run, its mode chosen by the run's state (the contract's table). */
|
|
1887
|
+
async message(run, content) {
|
|
1888
|
+
if (run.imported)
|
|
1889
|
+
throw this.importedRefusal(run);
|
|
1890
|
+
// A cancelled run takes no message, whether or not its end is written yet.
|
|
1891
|
+
if (run.cancel)
|
|
1892
|
+
throw this.finished(run);
|
|
1893
|
+
// Every wait first, then a last look for a stop in flight, again after any wait a stop came during: from that look
|
|
1894
|
+
// to the count below nothing awaits, so no stop can begin in between.
|
|
1895
|
+
do {
|
|
1896
|
+
// A stop in flight is answered first. Sent between its mark and its abort, a message would read the run stopped, go
|
|
1897
|
+
// to the turn the abort is cutting, and be dropped with it, its row never coming.
|
|
1898
|
+
if (run.stopping)
|
|
1899
|
+
await this.waitWhile(() => run.stopping === true, 50, "The run is being stopped");
|
|
1900
|
+
// A run that reads finished before its end is written (its process still closing, or its carry back waiting on the
|
|
1901
|
+
// store) is answered once the end is in: then it is completed and opens again, or it is failed or cancelled.
|
|
1902
|
+
if (run.finishing && !run.outcome)
|
|
1903
|
+
await this.waitWhile(() => Boolean(run.finishing && !run.outcome), 100, "The run's end is still being written");
|
|
1904
|
+
// A run another message is opening again is answered once that opening is done: reopen() clears the run's end
|
|
1905
|
+
// before it lays the run's notes again (learning-run.ts onReopen), and a message read meanwhile would launch the run
|
|
1906
|
+
// before they are back.
|
|
1907
|
+
if (run.reopening)
|
|
1908
|
+
await run.reopening.catch(() => undefined);
|
|
1909
|
+
if (run.kind === "agentic" && statusOf(run).status === "completed")
|
|
1910
|
+
await (run.reopening ??= this.reopen(run).finally(() => (run.reopening = undefined)));
|
|
1911
|
+
} while (run.stopping);
|
|
1912
|
+
const steers = this.steers(run);
|
|
1913
|
+
const { status, state } = statusOf(run);
|
|
1914
|
+
if (TERMINAL.has(status))
|
|
1915
|
+
throw this.finished(run);
|
|
1916
|
+
// A harness that cannot take a message mid-turn (any but pi, harness.ts) queues it for the turn's end: a new turn of
|
|
1917
|
+
// the same run, which the contract calls follow_up, never a steer it does not do.
|
|
1918
|
+
const working = status === "queued" || (status === "working" && state === "working");
|
|
1919
|
+
const mode = working ? (steers ? "steer" : "follow_up") : status === "input_required" && state === "waiting" ? "answer" : "follow_up";
|
|
1920
|
+
const messageId = `m${Date.now().toString(36)}${randomBytes(4).toString("hex")}`;
|
|
1921
|
+
// A follow-up to a run the person stopped, whose process has gone: its turn had ended, so the process this message
|
|
1922
|
+
// starts resumes nothing. With its process live the message starts none, and a relaunch after that process dies
|
|
1923
|
+
// under the message is a crash's, which keeps its row.
|
|
1924
|
+
if (status === "input_required" && state === "idle" && !this.live(run))
|
|
1925
|
+
run.followUpOpen = true;
|
|
1926
|
+
run.submitted++;
|
|
1927
|
+
this.refresh(run);
|
|
1928
|
+
try {
|
|
1929
|
+
await this.submit(run, content, mode === "steer" ? "steer" : "followUp", messageId);
|
|
1930
|
+
}
|
|
1931
|
+
catch (error) {
|
|
1932
|
+
run.submitted = Math.max(0, run.submitted - 1);
|
|
1933
|
+
this.refresh(run);
|
|
1934
|
+
throw error;
|
|
1935
|
+
}
|
|
1936
|
+
finally {
|
|
1937
|
+
run.followUpOpen = undefined;
|
|
1938
|
+
}
|
|
1939
|
+
return { mode, messageId };
|
|
1940
|
+
}
|
|
1941
|
+
/** Waits, up to a request's deadline, while `holds` (checked every `everyMs`): else 503 `unavailable`, saying `why`. */
|
|
1942
|
+
async waitWhile(holds, everyMs, why) {
|
|
1943
|
+
for (const deadline = Date.now() + (this.options.readyTimeoutMs ?? READY_TIMEOUT_MS); holds(); await sleep(everyMs)) {
|
|
1944
|
+
if (Date.now() > deadline)
|
|
1945
|
+
throw new ApiError("unavailable", `${why}; try again.`, { retry_after_ms: 1000 }, { "retry-after": "1" });
|
|
1946
|
+
}
|
|
1947
|
+
}
|
|
1948
|
+
/** A completed agentic run that gets a follow-up opens again: the same run on its own store and session, under its
|
|
1949
|
+
* cap, taking a place under the server's. Launched here, with no wait after the place is taken, so no start takes
|
|
1950
|
+
* it meanwhile. An archived run, or a run of an archived agent, stays closed. */
|
|
1951
|
+
async reopen(run) {
|
|
1952
|
+
await this.sweepOnce();
|
|
1953
|
+
await this.pinNeeds(run);
|
|
1954
|
+
const row = this.store.readRun(run.id);
|
|
1955
|
+
if (row?.archivedAt)
|
|
1956
|
+
throw new ApiError("not_continuable", "This run is archived: unarchive it to continue it.");
|
|
1957
|
+
// Its end could not be written yet (persistLater tries again): it opens once the store has it.
|
|
1958
|
+
if (row?.state === "running")
|
|
1959
|
+
throw new ApiError("unavailable", "The run's end is still being written to the agent store; try again.", { retry_after_ms: 1000 }, { "retry-after": "1" });
|
|
1960
|
+
const release = await this.takePlace(run.harness);
|
|
1961
|
+
try {
|
|
1962
|
+
// Read again: the place may have been waited for, and the run (or its agent) archived meanwhile.
|
|
1963
|
+
const now = this.store.readRun(run.id);
|
|
1964
|
+
if (now?.archivedAt)
|
|
1965
|
+
throw new ApiError("not_continuable", "This run is archived: unarchive it to continue it.");
|
|
1966
|
+
if (now?.state === "running")
|
|
1967
|
+
throw new ApiError("unavailable", "The run's end is still being written to the agent store; try again.", { retry_after_ms: 1000 }, { "retry-after": "1" });
|
|
1968
|
+
// Its end's run.ended in the outbox on disk before the run opens again, or not opened: once the row runs, no start finds
|
|
1969
|
+
// the end to queue it.
|
|
1970
|
+
if (now?.endedAt && this.notice(run, "run.ended", now.endedAt) === "unsaved")
|
|
1971
|
+
throw new ApiError("unavailable", "The run's end is still being announced to its webhook; try again.", { retry_after_ms: 1000 }, { "retry-after": "1" });
|
|
1972
|
+
try {
|
|
1973
|
+
this.store.reopenRun(run.id);
|
|
1974
|
+
}
|
|
1975
|
+
catch (error) {
|
|
1976
|
+
storeError(error, "run");
|
|
1977
|
+
}
|
|
1978
|
+
run.outcome = undefined;
|
|
1979
|
+
// With its outcome cleared the run reads open. Messages wait for this reopen (message()), so its launch below is
|
|
1980
|
+
// the follow-up's; set here, with the outcome, whichever launch comes first carries the flag (launch() takes it).
|
|
1981
|
+
run.followUpOpen = true;
|
|
1982
|
+
run.settled = false;
|
|
1983
|
+
run.endedAt = undefined;
|
|
1984
|
+
run.error = undefined;
|
|
1985
|
+
delete run.meta.error;
|
|
1986
|
+
run.relaunches = 0;
|
|
1987
|
+
// A run that learns finds its agent's notes in its work again (learning-run.ts).
|
|
1988
|
+
await this.learning.onReopen(run);
|
|
1989
|
+
await this.beforeReopenLaunch?.(run.id);
|
|
1990
|
+
this.refresh(run);
|
|
1991
|
+
// Opened for the follow-up: the run had answered, so its open resumes nothing.
|
|
1992
|
+
this.launch(run, true);
|
|
1993
|
+
}
|
|
1994
|
+
finally {
|
|
1995
|
+
// Launched, it holds its place as a live run.
|
|
1996
|
+
release();
|
|
1997
|
+
}
|
|
1998
|
+
// An end-of-run turn its process went in is aborted before the follow-up is sent (learning-run.ts).
|
|
1999
|
+
await this.learning.afterReopen(run);
|
|
2000
|
+
}
|
|
2001
|
+
/** Waits, up to a request's deadline, until a live run's rows show every message sent to it, and any rows at all: its
|
|
2002
|
+
* record has caught up with its process. Its end, a cancel or its process going ends the wait. */
|
|
2003
|
+
async caughtUp(run) {
|
|
2004
|
+
for (const deadline = Date.now() + (this.options.readyTimeoutMs ?? READY_TIMEOUT_MS); run.submitted > 0 || !run.rows.length; await run.log.changed(100)) {
|
|
2005
|
+
if (!this.live(run) || run.finishing || run.outcome || run.cancel || Date.now() > deadline)
|
|
2006
|
+
return;
|
|
2007
|
+
}
|
|
2008
|
+
}
|
|
2009
|
+
/** Abort the turn that is running; the run stays open, `input_required` and idle. A workflow run has no turn to stop. */
|
|
2010
|
+
async stop(run) {
|
|
2011
|
+
// The contract's stop has no refusal: an imported run answers as any ended one, stopped false, and nothing moves.
|
|
2012
|
+
if (run.imported)
|
|
2013
|
+
return false;
|
|
2014
|
+
// A message sent to the run shows in its rows only once its door's events bring it: until then the run reads queued
|
|
2015
|
+
// (state working), or holds a message not shown, however far its process is into the turn. The stop waits for its
|
|
2016
|
+
// rows first, so the mark it saves (the person's last message) covers the message the turn answers; then it stops
|
|
2017
|
+
// the turn as it stops any working run.
|
|
2018
|
+
if (run.kind !== "workflow")
|
|
2019
|
+
await this.caughtUp(run);
|
|
2020
|
+
const { status, state } = statusOf(run);
|
|
2021
|
+
if (run.kind === "workflow" || !this.live(run) || !(status === "working" && state === "working") || run.submitted > 0)
|
|
2022
|
+
return false;
|
|
2023
|
+
run.stopping = true;
|
|
2024
|
+
try {
|
|
2025
|
+
return await this.stopTurn(run);
|
|
2026
|
+
}
|
|
2027
|
+
finally {
|
|
2028
|
+
run.stopping = undefined;
|
|
2029
|
+
}
|
|
2030
|
+
}
|
|
2031
|
+
/** stop()'s mark and abort, once it took the stop. */
|
|
2032
|
+
async stopTurn(run) {
|
|
2033
|
+
// Set before the abort: the turn's end can arrive before the door answers, and must not read as an answer.
|
|
2034
|
+
const before = { stopped_at: run.meta.stopped_at, stopped_after: run.meta.stopped_after };
|
|
2035
|
+
delete run.meta.stopped_at;
|
|
2036
|
+
delete run.meta.stopped_after;
|
|
2037
|
+
Object.assign(run.meta, stopMark(run.rows));
|
|
2038
|
+
await this.saveMeta(run).catch((error) => warn(run.id, `its stop is not saved, so a restart will not keep it: ${error.message}`));
|
|
2039
|
+
await this.beforeAbort?.(run.id);
|
|
2040
|
+
const answer = await this.toDoor(run, "/abort", {}).catch(() => null);
|
|
2041
|
+
if (!answer || answer.status >= 400) {
|
|
2042
|
+
if (before.stopped_at === undefined)
|
|
2043
|
+
delete run.meta.stopped_at;
|
|
2044
|
+
else
|
|
2045
|
+
run.meta.stopped_at = before.stopped_at;
|
|
2046
|
+
if (before.stopped_after !== undefined)
|
|
2047
|
+
run.meta.stopped_after = before.stopped_after;
|
|
2048
|
+
await this.saveMeta(run).catch(() => undefined);
|
|
2049
|
+
this.refresh(run);
|
|
2050
|
+
return false;
|
|
2051
|
+
}
|
|
2052
|
+
this.refresh(run);
|
|
2053
|
+
return true;
|
|
2054
|
+
}
|
|
2055
|
+
/** Record the cancel and signal the run. An agentic run reads `cancelled` from here on (the first end a run comes to is
|
|
2056
|
+
* its last: nothing its turn writes later moves it), and is carried back so once its process has exited; a workflow
|
|
2057
|
+
* run reads it once it is carried back, with how its workflow stopped. */
|
|
2058
|
+
async cancel(run) {
|
|
2059
|
+
// As stop: already terminal, and no cancel mark is written.
|
|
2060
|
+
if (run.imported)
|
|
2061
|
+
return false;
|
|
2062
|
+
// Finishing is already ending with its outcome (an answer, a failure, the cap): a run's first end is its last.
|
|
2063
|
+
if (run.outcome || run.finishing)
|
|
2064
|
+
return false;
|
|
2065
|
+
run.cancel = true;
|
|
2066
|
+
if (run.kind === "agentic") {
|
|
2067
|
+
run.finishing = "cancelled";
|
|
2068
|
+
run.endedAt = new Date().toISOString();
|
|
2069
|
+
this.mark(run);
|
|
2070
|
+
}
|
|
2071
|
+
// First, so no request leaves after the cancel landed, whether or not the process can be reached yet.
|
|
2072
|
+
await writeWhole(join(run.dir, RUN_CANCELLED), "").catch((error) => warn(run.id, `its cancel mark is not written: ${error.message}`));
|
|
2073
|
+
if (this.live(run)) {
|
|
2074
|
+
// The turn is aborted first, so the drain that SIGTERM starts does not wait for it.
|
|
2075
|
+
await this.abortTurn(run);
|
|
2076
|
+
this.terminate(run);
|
|
2077
|
+
}
|
|
2078
|
+
else
|
|
2079
|
+
await this.settle(run, null, false);
|
|
2080
|
+
return true;
|
|
2081
|
+
}
|
|
2082
|
+
/** Pause a workflow run (`paused` true) or resume it: the mark in its directory, which its process reads before each
|
|
2083
|
+
* node starts. A run that has ended is not continuable. */
|
|
2084
|
+
async pause(run, paused) {
|
|
2085
|
+
if (run.kind !== "workflow")
|
|
2086
|
+
throw unsupported("runs.pause", "Only a workflow run pauses here: an agentic run's turn is stopped with POST /runs/{id}/stop.");
|
|
2087
|
+
if (TERMINAL.has(statusOf(run).status) || run.cancel)
|
|
2088
|
+
throw this.finished(run);
|
|
2089
|
+
const mark = join(run.dir, RUN_PAUSED);
|
|
2090
|
+
if (paused)
|
|
2091
|
+
await writeWhole(mark, `${new Date().toISOString()}\n`);
|
|
2092
|
+
else
|
|
2093
|
+
await rm(mark, { force: true });
|
|
2094
|
+
this.mark(run);
|
|
2095
|
+
return { run_id: run.id, paused, status: statusOf(run).status };
|
|
2096
|
+
}
|
|
2097
|
+
/** A workflow run's graph as it stands (graph-view.ts), live while it runs. */
|
|
2098
|
+
async graph(run) {
|
|
2099
|
+
if (run.kind !== "workflow")
|
|
2100
|
+
throw new ApiError("not_found", `the run ${run.id} is an agentic run; only a workflow run has a graph`);
|
|
2101
|
+
// A revision never changes: read once, waiting out a busy store as a run's end does, never failing a poll on it.
|
|
2102
|
+
let workflow = this.workflows.get(run.revision);
|
|
2103
|
+
if (workflow === undefined) {
|
|
2104
|
+
const revision = (await whenFree(() => this.store.readRevision(run.revision), this.busyDelays(), this.onBusy(run.id, "the agent store")));
|
|
2105
|
+
this.workflows.set(run.revision, (workflow = revision.body.workflow));
|
|
2106
|
+
}
|
|
2107
|
+
// The run's status as this server holds it, with no read of the agent store, which the run's process may be writing.
|
|
2108
|
+
const { status } = statusOf(run);
|
|
2109
|
+
const ended = TERMINAL.has(status);
|
|
2110
|
+
const { runGraph } = await import("./graph-view.js");
|
|
2111
|
+
const given = {
|
|
2112
|
+
run: { id: run.id, agent: run.agentId, revision: run.revision, status, paused: status === "paused", startedAt: run.meta.created_at, endedAt: ended ? (run.endedAt ?? run.updatedAt) : null },
|
|
2113
|
+
ended, workflow, storeFile: this.storeFile(run), root: run.dir, input: run.meta.input ?? {}, modelCost: costOf(run.rows), llmRead: run.llmRead ?? 0,
|
|
2114
|
+
};
|
|
2115
|
+
// A poll never answers home_busy: a store still held answers the live view, or the last whole one, marked stale.
|
|
2116
|
+
try {
|
|
2117
|
+
const view = await runGraph(given);
|
|
2118
|
+
this.graphs.set(run.id, view);
|
|
2119
|
+
return { ...view, stale: false };
|
|
2120
|
+
}
|
|
2121
|
+
catch (error) {
|
|
2122
|
+
if (!storeBusy(error))
|
|
2123
|
+
throw error;
|
|
2124
|
+
warn(run.id, "its store is busy; the graph answers its live view, stale");
|
|
2125
|
+
const held = this.graphs.get(run.id);
|
|
2126
|
+
if (held)
|
|
2127
|
+
return { ...held, run: given.run, stale: true };
|
|
2128
|
+
return { ...(await runGraph({ ...given, liveOnly: true })), stale: true };
|
|
2129
|
+
}
|
|
2130
|
+
}
|
|
2131
|
+
/** How long a run's process gets after SIGTERM before SIGKILL: its drain and a second to exit. */
|
|
2132
|
+
killAfterMs() {
|
|
2133
|
+
return (durationMs(this.options.drainTimeout ?? DRAIN) ?? 30_000) + 1_000;
|
|
2134
|
+
}
|
|
2135
|
+
/** What close() will wait on: the runs whose processes are left to finish their turn (those this server started, and
|
|
2136
|
+
* those it adopted), and the longest it can wait on them: a kill bound for the started ones, and one more for the
|
|
2137
|
+
* adopted ones, which it stops after them. */
|
|
2138
|
+
stopping() {
|
|
2139
|
+
const all = [...this.runs.values()];
|
|
2140
|
+
const started = all.filter((run) => run.child).length;
|
|
2141
|
+
const adopted = all.filter((run) => !run.child && run.orphan && alive(run.orphan)).length;
|
|
2142
|
+
return { runs: started + adopted, boundMs: (started ? this.killAfterMs() : 0) + (adopted ? this.killAfterMs() : 0) };
|
|
2143
|
+
}
|
|
2144
|
+
async close() {
|
|
2145
|
+
this.closing = true;
|
|
2146
|
+
this.learning.close();
|
|
2147
|
+
const live = [...this.runs.values()].filter((run) => run.child);
|
|
2148
|
+
for (const run of live) {
|
|
2149
|
+
run.child.kill("SIGTERM");
|
|
2150
|
+
setTimeout(() => run.child?.exitCode === null && run.child.kill("SIGKILL"), this.killAfterMs()).unref();
|
|
2151
|
+
}
|
|
2152
|
+
await Promise.all(live.map((run) => new Promise((resolve) => (run.child ? run.child.once("exit", resolve) : resolve(undefined)))));
|
|
2153
|
+
// An adopted process is stopped the same way, and watched by its pid.
|
|
2154
|
+
const adopted = [...this.runs.values()].filter((run) => run.orphan && alive(run.orphan));
|
|
2155
|
+
for (const run of adopted)
|
|
2156
|
+
this.terminate(run);
|
|
2157
|
+
for (const deadline = Date.now() + this.killAfterMs(); adopted.some((run) => run.orphan && alive(run.orphan)) && Date.now() < deadline;)
|
|
2158
|
+
await sleep(100);
|
|
2159
|
+
await sleep(0);
|
|
2160
|
+
await Promise.all([...this.runs.values()].map((run) => run.settling));
|
|
2161
|
+
await this.learning.idle();
|
|
2162
|
+
for (const run of this.runs.values())
|
|
2163
|
+
run.feed?.abort();
|
|
2164
|
+
this.closed = true;
|
|
2165
|
+
}
|
|
2166
|
+
// ---- views ------------------------------------------------------------------------------------------------------------
|
|
2167
|
+
/** A run's cost from its rows, else what the store recorded when it carried the run back. */
|
|
2168
|
+
cost(run) {
|
|
2169
|
+
// An imported run's cost is its source's, for the whole session: its requests may not each have a price.
|
|
2170
|
+
const usd = run.imported ? (run.costUsd ?? null) : costView(run.rows, run.costUsd, run.decisionCost);
|
|
2171
|
+
// Unknown: what it cost so far and how many charges have no price (costsofar/1), from its rows, else what it said at
|
|
2172
|
+
// its end (a run carried back with no rows read since).
|
|
2173
|
+
const soFar = usd === null && !run.imported ? (soFarOf(run.rows, run.decisionCost === undefined ? undefined : (run.decisionsPriced ?? null)) ?? (run.rows.length ? undefined : soFarOfMeta(run.meta))) : undefined;
|
|
2174
|
+
return { usd, basis: "estimate", charge_state: null, cap_usd: run.meta.max_cost_usd ?? null, ...(soFar ?? {}) };
|
|
2175
|
+
}
|
|
2176
|
+
/** `Run`, as the contract shows it. `known`: its stored row as the caller already has it, so nothing is read; a run
|
|
2177
|
+
* just written has none worth reading (`{ stored: null }`: it is neither archived nor ended), and its start's answer
|
|
2178
|
+
* must not read the store once the run exists, since a busy store would then refuse a run that runs. */
|
|
2179
|
+
async view(run, known) {
|
|
2180
|
+
const stored = known ? (known.stored ?? undefined) : await this.options.agents.request(() => this.store.readRun(run.id));
|
|
2181
|
+
// After the read: the run may have moved on while it waited, and every field below is of this one moment.
|
|
2182
|
+
const { status, state } = statusOf(run);
|
|
2183
|
+
const row = TERMINAL.has(status) ? stored : undefined;
|
|
2184
|
+
// The whole text of the answer the run's turn ended on (answerOfRun), never the line the store keeps, which is cut;
|
|
2185
|
+
// the store's line only for a run whose rows are not read (an import's).
|
|
2186
|
+
const finalAnswer = run.kind === "workflow" ? null : (answerOfRun(run) ?? row?.summary ?? null);
|
|
2187
|
+
// When the turn of a message still open last wrote: a run working shows it is moving, or not.
|
|
2188
|
+
const progress = TERMINAL.has(status) || run.kind === "workflow" ? undefined : run.turns.progressAt();
|
|
2189
|
+
// A run its cap stopped keeps the answer it paid for.
|
|
2190
|
+
const kept = status === "failed" && run.error?.code === SPEND_CAP_REACHED ? lastAnswer(run) : null;
|
|
2191
|
+
const endedAt = TERMINAL.has(status) ? (row?.endedAt ?? run.endedAt ?? run.updatedAt) : null;
|
|
2192
|
+
return {
|
|
2193
|
+
run_id: run.id,
|
|
2194
|
+
agent_id: run.agentId,
|
|
2195
|
+
agent_version: run.version,
|
|
2196
|
+
revision: run.revision,
|
|
2197
|
+
kind: run.kind,
|
|
2198
|
+
sha: null,
|
|
2199
|
+
status,
|
|
2200
|
+
state,
|
|
2201
|
+
title: run.meta.title,
|
|
2202
|
+
place: run.meta.place ?? { mode: "runner" },
|
|
2203
|
+
...(run.meta.effort ? { effort: run.meta.effort } : {}),
|
|
2204
|
+
created_at: run.meta.created_at,
|
|
2205
|
+
updated_at: run.updatedAt,
|
|
2206
|
+
ended_at: endedAt,
|
|
2207
|
+
// An answer is served with no held secret in it, whole (key-refusal.ts redactedAnswer); the stored one stays as written.
|
|
2208
|
+
result: status === "completed" ? { output: run.kind === "workflow" ? (this.servedOutput(run, run.meta.output ?? null)) : null, final_answer: this.servedAnswer(run, finalAnswer) } : kept ? { output: null, final_answer: this.servedAnswer(run, kept) } : null,
|
|
2209
|
+
error: status === "failed" ? (run.error ?? { code: "run_failed", message: "The run failed.", retryable: false }) : null,
|
|
2210
|
+
review: endedAt === null ? null : reviewAt(run.meta.review ?? (row ? reviewOfRow(row, run.meta) : null), endedAt),
|
|
2211
|
+
pending: status === "input_required" && state === "waiting" ? pendingOf(run.rows) : null,
|
|
2212
|
+
cost: this.cost(run),
|
|
2213
|
+
archived_at: stored?.archivedAt ?? null,
|
|
2214
|
+
imported_from: run.imported ?? null,
|
|
2215
|
+
// The notes it read once it settled: while it runs, or runs again for a follow-up, they are still being read.
|
|
2216
|
+
learning: this.learning.view(run.meta.learning, TERMINAL.has(status) && run.settled),
|
|
2217
|
+
poll_after_ms: TERMINAL.has(status) && run.settled ? 0 : 1000,
|
|
2218
|
+
last_progress_at: progress === undefined ? null : new Date(progress).toISOString(),
|
|
2219
|
+
};
|
|
2220
|
+
}
|
|
2221
|
+
async summary(run) {
|
|
2222
|
+
const { run_id, agent_id, agent_version, revision, kind, sha, status, state, title, effort, created_at, ended_at, error, review, pending, cost, archived_at, imported_from, learning } = await this.view(run);
|
|
2223
|
+
return { run_id, agent_id, agent_version, revision, kind, sha, status, state, title, ...(effort ? { effort } : {}), created_at, ended_at, error, review, pending, cost, archived_at, imported_from, learning: learning && shortOf(learning) };
|
|
2224
|
+
}
|
|
2225
|
+
/** A run's status for a list: an ended run's from its row, a running one's from the run itself. */
|
|
2226
|
+
async statusOfRow(row) {
|
|
2227
|
+
if (row.state !== "running")
|
|
2228
|
+
return STATUS_OF[row.state];
|
|
2229
|
+
const run = await this.get(row.id);
|
|
2230
|
+
return run ? statusOf(run).status : "queued";
|
|
2231
|
+
}
|
|
2232
|
+
/** A run's summary for a list. An ended run this server holds no Run for is read from its row and its serve.json alone,
|
|
2233
|
+
* not its store; `versions` numbers its agent's revisions. */
|
|
2234
|
+
async summaryOfRow(row, versions) {
|
|
2235
|
+
const known = this.runs.get(row.id) ?? (row.state === "running" ? await this.get(row.id) : null);
|
|
2236
|
+
if (known)
|
|
2237
|
+
return this.summary(known);
|
|
2238
|
+
const meta = (await readJson(join(this.options.agents.dir, "runs", row.id, RUN_META)));
|
|
2239
|
+
return {
|
|
2240
|
+
run_id: row.id, agent_id: row.agent, agent_version: versions.get(row.revision) ?? 0, revision: row.revision, kind: row.kind, sha: null,
|
|
2241
|
+
status: STATUS_OF[row.state], state: "idle", title: typeof meta?.title === "string" ? meta.title : "",
|
|
2242
|
+
...(typeof meta?.effort === "string" ? { effort: meta.effort } : {}),
|
|
2243
|
+
created_at: typeof meta?.created_at === "string" ? meta.created_at : row.startedAt, ended_at: row.endedAt ?? null,
|
|
2244
|
+
error: STATUS_OF[row.state] === "failed" ? errorOfRow(row, meta) : null,
|
|
2245
|
+
review: reviewAt(reviewOfRow(row, meta), row.endedAt ?? new Date(0).toISOString()),
|
|
2246
|
+
cost: { usd: row.costUsd ?? null, basis: "estimate", charge_state: null, cap_usd: typeof meta?.max_cost_usd === "number" ? meta.max_cost_usd : null, ...(row.costUsd == null ? (soFarOfMeta(meta) ?? {}) : {}) },
|
|
2247
|
+
archived_at: row.archivedAt ?? null,
|
|
2248
|
+
// A run read from its row alone has ended: it waits on nothing.
|
|
2249
|
+
pending: null,
|
|
2250
|
+
imported_from: row.importedFrom ?? null,
|
|
2251
|
+
// Its row says it ended: what serve.json holds of its learning is as it settled.
|
|
2252
|
+
learning: this.learning.short(isObject(meta?.learning) ? meta.learning : null, true),
|
|
2253
|
+
};
|
|
2254
|
+
}
|
|
2255
|
+
/** A key was saved on this server or deleted from it: each held run's learning row shown again, cut of the keys as
|
|
2256
|
+
* they are now (learning-run.ts shown), as its view and its lists already are from the next read on. */
|
|
2257
|
+
keysChanged() {
|
|
2258
|
+
this.learning.keysChanged();
|
|
2259
|
+
for (const run of this.runs.values())
|
|
2260
|
+
if (run.meta.learning)
|
|
2261
|
+
this.show(run);
|
|
2262
|
+
}
|
|
2263
|
+
/** A held run's learning, in short (learning-run.ts heldLearning). */
|
|
2264
|
+
heldLearning(runId) {
|
|
2265
|
+
return this.learning.heldLearning(runId);
|
|
2266
|
+
}
|
|
2267
|
+
/** The timeline from change `after`, held up to `waitMs` for a change when there is none. */
|
|
2268
|
+
async page(run, after, waitMs, limit) {
|
|
2269
|
+
const deadline = Date.now() + waitMs;
|
|
2270
|
+
for (;;) {
|
|
2271
|
+
const page = run.log.page(after, limit);
|
|
2272
|
+
const { status, state } = statusOf(run);
|
|
2273
|
+
const final = TERMINAL.has(status) && run.settled;
|
|
2274
|
+
if (!page.unchanged || final || Date.now() >= deadline)
|
|
2275
|
+
return { ...page, status, state, final };
|
|
2276
|
+
await run.log.changed(deadline - Date.now());
|
|
2277
|
+
}
|
|
2278
|
+
}
|
|
2279
|
+
}
|