@parcha/agentrun-serve 0.1.0-beta.29 → 0.1.0-beta.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +188 -0
- package/README.md +564 -97
- package/dist/adapters.d.ts +35 -6
- package/dist/adapters.js +152 -26
- package/dist/agents.d.ts +11 -5
- package/dist/agents.js +16 -10
- package/dist/app.js +80 -20
- package/dist/background.d.ts +28 -0
- package/dist/background.js +376 -0
- package/dist/box-egress.d.ts +98 -0
- package/dist/box-egress.js +259 -0
- package/dist/box-image.d.ts +1 -1
- package/dist/box-image.js +9 -7
- package/dist/box-relay-vm.d.ts +80 -0
- package/dist/box-relay-vm.js +389 -0
- package/dist/box-relay.d.ts +8 -5
- package/dist/box-relay.js +14 -9
- package/dist/boxes.d.ts +21 -3
- package/dist/boxes.js +14 -7
- package/dist/browser-cost.d.ts +41 -0
- package/dist/browser-cost.js +158 -0
- package/dist/cap.d.ts +129 -21
- package/dist/cap.js +338 -67
- package/dist/coding-tools.d.ts +7 -3
- package/dist/coding-tools.js +16 -10
- package/dist/console/THIRD-PARTY-NOTICES.txt +580 -0
- package/dist/console/assets/index-34jfpIbQ.js +481 -0
- package/dist/console/assets/index-DUHbWcIP.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/content-filter.d.ts +7 -0
- package/dist/content-filter.js +23 -0
- package/dist/decision-rows.d.ts +11 -3
- package/dist/decision-rows.js +18 -11
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +5 -2
- package/dist/files.d.ts +6 -1
- package/dist/files.js +7 -2
- package/dist/grade.d.ts +7 -10
- package/dist/grade.js +31 -51
- package/dist/graph-served.d.ts +23 -0
- package/dist/graph-served.js +75 -0
- package/dist/graph-view.d.ts +7 -5
- package/dist/graph-view.js +10 -3
- package/dist/harness-app.d.ts +4 -2
- package/dist/harness-app.js +101 -19
- package/dist/harness-opencode/adapter.d.ts +45 -0
- package/dist/harness-opencode/adapter.js +272 -0
- package/dist/harness-opencode/binary.d.ts +18 -0
- package/dist/harness-opencode/binary.js +87 -0
- package/dist/harness-opencode/config.d.ts +24 -0
- package/dist/harness-opencode/config.js +61 -0
- package/dist/harness-opencode/harness.d.ts +77 -0
- package/dist/harness-opencode/harness.js +620 -0
- package/dist/harness-opencode/host/mcp.d.ts +40 -0
- package/dist/harness-opencode/host/mcp.js +208 -0
- package/dist/harness-opencode/host/policy.d.ts +71 -0
- package/dist/harness-opencode/host/policy.js +419 -0
- package/dist/harness-opencode/host/server.d.ts +55 -0
- package/dist/harness-opencode/host/server.js +165 -0
- package/dist/harness-opencode/index.d.ts +9 -0
- package/dist/harness-opencode/index.js +6 -0
- package/dist/harness-opencode/verify.d.ts +32 -0
- package/dist/harness-opencode/verify.js +75 -0
- package/dist/harness-opencode/versions.d.ts +33 -0
- package/dist/harness-opencode/versions.js +64 -0
- package/dist/harness.d.ts +4 -1
- package/dist/harness.js +5 -2
- package/dist/host-tools.d.ts +12 -2
- package/dist/host-tools.js +26 -12
- package/dist/host.js +6 -2
- package/dist/hosted-search.js +5 -1
- package/dist/import.d.ts +2 -2
- package/dist/import.js +4 -3
- package/dist/key-check.d.ts +3 -2
- package/dist/key-check.js +7 -3
- package/dist/key-refusal.js +8 -4
- package/dist/learn/check.d.ts +10 -1
- package/dist/learn/check.js +19 -1
- package/dist/learn/grade.d.ts +3 -2
- package/dist/learn/grade.js +25 -13
- package/dist/learn/index.d.ts +2 -2
- package/dist/learn/index.js +2 -2
- package/dist/learn/notes.js +2 -1
- package/dist/learn/reflect.d.ts +2 -2
- package/dist/learn/reflect.js +51 -5
- package/dist/learn/secrets.js +28 -8
- package/dist/learn/skills.d.ts +17 -4
- package/dist/learn/skills.js +79 -6
- package/dist/learned-workflow.d.ts +59 -0
- package/dist/learned-workflow.js +191 -0
- package/dist/learning-run.d.ts +7 -5
- package/dist/learning-run.js +45 -23
- package/dist/learning-words.d.ts +6 -3
- package/dist/learning-words.js +8 -5
- package/dist/learning.d.ts +44 -3
- package/dist/learning.js +148 -3
- package/dist/mcp-servers.d.ts +7 -4
- package/dist/mcp-servers.js +5 -0
- package/dist/mcp.js +5 -5
- package/dist/model.d.ts +13 -11
- package/dist/model.js +11 -10
- package/dist/openapi/agentrun-v2.openapi.json +1 -0
- package/dist/openapi.js +358 -48
- package/dist/paid-calls.d.ts +5 -1
- package/dist/paid-calls.js +1 -1
- package/dist/pause.d.ts +2 -0
- package/dist/place.d.ts +27 -4
- package/dist/place.js +42 -10
- package/dist/propose.d.ts +2 -0
- package/dist/propose.js +38 -8
- package/dist/request-start.d.ts +12 -4
- package/dist/request-start.js +139 -15
- package/dist/run-box.d.ts +56 -4
- package/dist/run-box.js +173 -23
- package/dist/runnable.d.ts +5 -2
- package/dist/runnable.js +12 -4
- package/dist/runs.d.ts +258 -36
- package/dist/runs.js +830 -89
- package/dist/secrets.d.ts +12 -0
- package/dist/secrets.js +18 -0
- package/dist/server.d.ts +131 -35
- package/dist/server.js +467 -105
- package/dist/sign-ins.d.ts +99 -0
- package/dist/sign-ins.js +288 -0
- package/dist/skills.d.ts +16 -4
- package/dist/skills.js +35 -7
- package/dist/stats.d.ts +7 -2
- package/dist/stats.js +28 -7
- package/dist/tool-gate.d.ts +266 -0
- package/dist/tool-gate.js +554 -0
- package/dist/tool-keys.d.ts +46 -10
- package/dist/tool-keys.js +44 -2
- package/dist/tool-plane.d.ts +112 -27
- package/dist/tool-plane.js +205 -47
- package/dist/tools.d.ts +69 -14
- package/dist/tools.js +143 -24
- package/dist/trigger-secrets.d.ts +32 -0
- package/dist/trigger-secrets.js +143 -0
- package/dist/triggers.d.ts +439 -0
- package/dist/triggers.js +863 -0
- package/dist/turn-end.d.ts +3 -2
- package/dist/turn-end.js +3 -2
- package/dist/usage-lines.d.ts +26 -0
- package/dist/usage-lines.js +28 -0
- package/dist/validate.d.ts +2 -0
- package/dist/validate.js +11 -2
- package/dist/webhooks.d.ts +11 -4
- package/dist/webhooks.js +17 -1
- package/launcher/agentrun-serve +1 -1
- package/package.json +19 -13
- package/dist/console/assets/index-BN7oVcO4.js +0 -445
- package/dist/console/assets/index-By-jkqki.css +0 -1
package/dist/runs.js
CHANGED
|
@@ -5,19 +5,20 @@
|
|
|
5
5
|
// again on its directory, and resumes from its store.
|
|
6
6
|
import { spawn } from "node:child_process";
|
|
7
7
|
import { createHash, randomBytes } from "node:crypto";
|
|
8
|
-
import { closeSync, existsSync, openSync, rmSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { closeSync, existsSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
9
9
|
import { open as openFile, rm, stat } from "node:fs/promises";
|
|
10
10
|
import { join } from "node:path";
|
|
11
11
|
import { fileURLToPath } from "node:url";
|
|
12
12
|
import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
|
|
13
13
|
import { processAlive } from "@parcha/agentrun-kernel/host";
|
|
14
|
+
import { doorTook } from "@parcha/pi-durable-disk";
|
|
14
15
|
import { AgentHomeError } from "@parcha/pi-durable-agent";
|
|
15
|
-
import { registerLabel, registerTurnEnding, runMetricsWithDecisions, timelineOf, timelineReducer } from "@parcha/pi-durable-agent/timeline";
|
|
16
|
+
import { isMessageRow, registerLabel, registerTurnEnding, REQUEST_STARTED, runMetricsWithDecisions, timelineOf, timelineReducer } from "@parcha/pi-durable-agent/timeline";
|
|
16
17
|
import { HARNESS_LOG_EVENT, harnessModelKeys, thinkingFor } from "./adapters.js";
|
|
17
18
|
import { DEFAULT_HARNESS, harnessOfBody, steersMidTurn } from "./harness.js";
|
|
18
19
|
import { hostMemory, memoryFull, neverFits, runMibOf, runsMemoryMib } from "./host.js";
|
|
19
20
|
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 { FOLLOW_UP_OPEN_ENV, LAUNCH_LOST, readJson, RUN_CANCELLED, RUN_DOOR_TOKEN, RUN_LAUNCHING, RUN_META, runDoorToken, SETUP_LOST, writeWhole } from "./files.js";
|
|
21
22
|
import { KEPT_AUTOSTOP_MINUTES, keepWhenIdle, wakeBoxes } from "./daytona-api.js";
|
|
22
23
|
import { LEARNING_LABEL, shortOf } from "./learning.js";
|
|
23
24
|
import { labelled, LearningRuns, reflecting, reflects, withLearning } from "./learning-run.js";
|
|
@@ -26,24 +27,29 @@ import { rowPaths } from "./workspace-paths.js";
|
|
|
26
27
|
import { ASK_TOOL, toolingOf, workflowTools } from "./tools.js";
|
|
27
28
|
import { withDecisions } from "./decision-rows.js";
|
|
28
29
|
import { DECISION_KEY_FD_ENV, decisionKeysFor, providersNamed } from "./decisions.js";
|
|
29
|
-
import { ApiError, unsupported } from "./errors.js";
|
|
30
|
+
import { ApiError, invalid, unsupported } from "./errors.js";
|
|
30
31
|
import { DOCUMENTS_ENV } from "./pdf-pages.js";
|
|
31
|
-
import { CAP_ENV, CAP_REFUSAL_PREFIX, SPEND_CAP_REACHED } from "./cap.js";
|
|
32
|
+
import { CAP_ENV, CAP_REFUSAL_PREFIX, CAP_REFUSED_FIELD, CAP_TOLERANCE, FIT_TOLERANCE, money, roomRefusal, SPEND_CAP_REACHED, spentIn } from "./cap.js";
|
|
32
33
|
import { DEFAULT_MODEL_ENV, EFFORT_ENV, GATEWAY_KEY_ENV, hostModel, llmTiers, modelKeys, nodeTiers, PROVIDER_KEYS, thinkingOf, withoutFaux, workflowNodes } from "./model.js";
|
|
33
34
|
import { llmAnswers, pausedIn, readNodeLog, RUN_PAUSED } from "./pause.js";
|
|
34
35
|
import { durationMs } from "./print.js";
|
|
35
|
-
import { handsParallel, planeFor, recheckPlane, TOOL_PLANE_ENV } from "./tool-plane.js";
|
|
36
|
+
import { handsParallel, keptFromBefore, keptVendor, planeFor, recheckPlane, relaunchPlane, TOOL_PLANE_ENV } from "./tool-plane.js";
|
|
37
|
+
import { APPROVAL_ENTRY, APPROVAL_ROW, NO_APPROVER_ENV, previewOf, RESUME_PREFIX, TURN_ORIGIN_FILE } from "./tool-gate.js";
|
|
36
38
|
import { ChangeClock, RowLog } from "./rows.js";
|
|
37
39
|
import { TOOL_KEYS } from "./tool-keys.js";
|
|
38
40
|
import { isObject } from "./validate.js";
|
|
39
41
|
import { firstMessage } from "./run-manifest.js";
|
|
40
42
|
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";
|
|
43
|
+
import { DECISION_KEYS, handover, handoverSignIn, hostSecrets, secret, SECRET_NAMES, SECRETS_FD_ENV, SECRETS_LEN_ENV, withoutSecrets, withSecrets } from "./secrets.js";
|
|
42
44
|
import { MIN_SECRET } from "./learn/secrets.js";
|
|
43
45
|
import { keyRefusal, redacted, redactedAnswer, redactedLive, redactedOutput, runKeyOf, withoutLoopback } from "./key-refusal.js";
|
|
44
|
-
import {
|
|
46
|
+
import { GRAPH_CACHE_BYTES, PartCache, servedPart } from "./graph-served.js";
|
|
47
|
+
import { CONTENT_FILTER_WORDS, contentFiltered, MODERATED } from "./content-filter.js";
|
|
48
|
+
import { BOX_KEYS, VM_PROVIDER } from "./boxes.js";
|
|
45
49
|
import { remotePlace, storedPlace } from "./place.js";
|
|
46
|
-
import { destroyRunBoxes, ensureRemoteBox, PullIncomplete, pullRemoteBox, sweepRunBoxes } from "./run-box.js";
|
|
50
|
+
import { destroyRunBoxes, ensureRemoteBox, PullIncomplete, pullRemoteBox, RUN_LABEL, sweepRunBoxes } from "./run-box.js";
|
|
51
|
+
import { BACKGROUND_DIR, endBackground } from "./background.js";
|
|
52
|
+
import { removeEgressDir, RUN_BOX_ALLOW_ENV } from "./box-egress.js";
|
|
47
53
|
import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
|
|
48
54
|
export const STATUSES = ["queued", "working", "paused", "input_required", "completed", "failed", "cancelled"];
|
|
49
55
|
const TERMINAL = new Set(["completed", "failed", "cancelled"]);
|
|
@@ -117,6 +123,8 @@ function workflowEnding(record) {
|
|
|
117
123
|
return undefined;
|
|
118
124
|
return { status: detail.workflow, ...(typeof detail.code === "string" ? { code: detail.code } : {}), ...(typeof detail.message === "string" ? { message: detail.message } : {}) };
|
|
119
125
|
}
|
|
126
|
+
/** A call withdrawn with its run (a cancel, or a stop while it waited): never run, and an answer after is 409. */
|
|
127
|
+
const withdrawn = (answer) => answer?.decision === "canceled" || answer?.decision === "withdrawn";
|
|
120
128
|
/** `review` at the run's saved end `endedAt`, so review.at and ended_at are one time. */
|
|
121
129
|
const reviewAt = (review, endedAt) => (review ? { kind: review.kind, node: review.node, reason: review.reason, at: endedAt } : null);
|
|
122
130
|
/** A failed run's error from its row and serve.json: its own, else the row's summary. */
|
|
@@ -124,6 +132,8 @@ const errorOfRow = (row, meta) => ({ code: meta?.error?.code ?? "run_failed", me
|
|
|
124
132
|
/** 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
133
|
* reviews were kept) the row's summary; null for every other run. */
|
|
126
134
|
const reviewOfRow = (row, meta) => row.state !== "escalated" ? null : (meta?.review ?? { kind: null, node: null, reason: row.summary ?? "The workflow escalated." });
|
|
135
|
+
/** A value's sha256, of its JSON. */
|
|
136
|
+
const digestOf = (value) => createHash("sha256").update(JSON.stringify(value) ?? "").digest("hex");
|
|
127
137
|
const ASKED = "Asked you: ";
|
|
128
138
|
registerLabel(ASK_TOOL, (args) => `${ASKED}${typeof args.question === "string" ? args.question : ""}`, undefined, { name: "Ask you a question" });
|
|
129
139
|
// ask_person ends its turn (tools.ts): the person's reply is their next message, never a steer.
|
|
@@ -150,7 +160,7 @@ export function withAsks(rows) {
|
|
|
150
160
|
export function withOverCap(rows, cap) {
|
|
151
161
|
const at = rows.findLastIndex((row) => row.kind === "usage");
|
|
152
162
|
const usd = rows[at]?.usage?.usd;
|
|
153
|
-
if (cap === undefined || typeof usd !== "number" || usd <= cap)
|
|
163
|
+
if (cap === undefined || typeof usd !== "number" || usd <= cap + FIT_TOLERANCE)
|
|
154
164
|
return rows;
|
|
155
165
|
const { usage: _, ...usage } = rows[at];
|
|
156
166
|
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 };
|
|
@@ -165,6 +175,12 @@ function noteTurns(run, entries, submissions = [], snapshot) {
|
|
|
165
175
|
if (!isObject(value) || typeof value.id !== "number")
|
|
166
176
|
continue;
|
|
167
177
|
run.lastEntry = Math.max(run.lastEntry ?? 0, value.id);
|
|
178
|
+
// A refusal for room's own start mark: what the cap counted as taken, and the least the request needed.
|
|
179
|
+
const data = value.kind === REQUEST_STARTED && isObject(value.data) && value.data[CAP_REFUSED_FIELD] === true ? value.data : undefined;
|
|
180
|
+
if (data)
|
|
181
|
+
run.capMark = value.id;
|
|
182
|
+
if (data)
|
|
183
|
+
run.capRefusal = typeof data.spentUsd === "number" && typeof data.needsUsd === "number" ? { spentUsd: data.spentUsd, needsUsd: data.needsUsd } : undefined;
|
|
168
184
|
// The end-of-run turn's assistant messages, whole, by entry: what the turn answered, whose notes learning reads
|
|
169
185
|
// (learning-run.ts). The ledger skips them; this is their only reader here.
|
|
170
186
|
if (value.kind === "pi.assistant" && reflects(run.meta.reflect, value.id) && Array.isArray(value.model) && isObject(value.model[0])) {
|
|
@@ -184,6 +200,112 @@ const pendingOf = (rows) => {
|
|
|
184
200
|
const last = meaningful(rows);
|
|
185
201
|
return last?.kind === "waiting" ? { kind: "question", question: last.text ?? last.summary ?? "", asked_at: last.timestamp } : null;
|
|
186
202
|
};
|
|
203
|
+
/** Notes the tool calls that wait for approval in `entries` (the run's stored entries), and those whose answer its process
|
|
204
|
+
* acted on. */
|
|
205
|
+
function noteApprovals(run, entries) {
|
|
206
|
+
for (const value of entries) {
|
|
207
|
+
if (!isObject(value) || value.kind !== APPROVAL_ENTRY || !isObject(value.data) || typeof value.data.id !== "string")
|
|
208
|
+
continue;
|
|
209
|
+
const data = value.data;
|
|
210
|
+
run.approvals ??= new Map();
|
|
211
|
+
const known = run.approvals.get(data.id);
|
|
212
|
+
if (data.phase === "requested" && !known)
|
|
213
|
+
run.approvals.set(data.id, { id: data.id, tool: String(data.tool), call_id: String(data.call_id), args_json: "args" in data ? (JSON.stringify(data.args ?? {}) ?? "{}") : String(data.args_preview ?? ""), requested_at: String(data.requested_at), ...(typeof data.price === "number" || data.price === "not metered" ? { price: data.price } : {}) });
|
|
214
|
+
else if (data.phase === "resolved" && known)
|
|
215
|
+
known.resolved = true;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
/** The tool call that waits for a person's answer: requested in the run's store, not resolved there, not answered. */
|
|
219
|
+
const waitingApproval = (run) => [...(run.approvals?.values() ?? [])].find((a) => !a.resolved && !run.meta.approvals?.[a.id]);
|
|
220
|
+
/** What is shown of a call's arguments: the whole of them redacted with the run's redactor, then cut (previewOf), so
|
|
221
|
+
* no cut leaves the head of a held key. */
|
|
222
|
+
const shownArgs = (approval, redact) => previewOf(redact(approval.args_json));
|
|
223
|
+
/** `entries` with the gate's resume messages (RESUME_PREFIX) redacted whole with `redact`, before the timeline cuts
|
|
224
|
+
* them: the message carries a call's arguments and its result, which may hold a held key. */
|
|
225
|
+
function redactGateMessages(entries, redact) {
|
|
226
|
+
return entries.map((entry) => {
|
|
227
|
+
const first = isObject(entry) && Array.isArray(entry.model) ? entry.model[0] : undefined;
|
|
228
|
+
if (!isObject(first) || first.role !== "user")
|
|
229
|
+
return entry;
|
|
230
|
+
const content = first.content;
|
|
231
|
+
const text = typeof content === "string" ? content : Array.isArray(content) ? content.map((block) => (isObject(block) && block.type === "text" ? String(block.text ?? "") : "")).join("") : "";
|
|
232
|
+
if (!text.startsWith(RESUME_PREFIX))
|
|
233
|
+
return entry;
|
|
234
|
+
const redacted = typeof content === "string" ? redact(content) : content.map((block) => (isObject(block) && block.type === "text" && typeof block.text === "string" ? { ...block, text: redact(block.text) } : block));
|
|
235
|
+
return { ...entry, model: [{ ...first, content: redacted }, ...entry.model.slice(1)] };
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
/** The run's pending approval (`pending`, kind approval): the call that waits; else undefined. */
|
|
239
|
+
const approvalOf = (run, redact) => {
|
|
240
|
+
const waiting = waitingApproval(run);
|
|
241
|
+
return waiting ? { kind: "approval", id: waiting.id, tool: waiting.tool, call_id: waiting.call_id, args_preview: shownArgs(waiting, redact), requested_at: waiting.requested_at, ...(waiting.price !== undefined ? { price: waiting.price } : {}) } : undefined;
|
|
242
|
+
};
|
|
243
|
+
/** One answered (allow or deny) whose answer the run's process has not acted on yet. */
|
|
244
|
+
const actingOn = (run) => [...(run.approvals?.values() ?? [])].some((a) => !a.resolved && run.meta.approvals?.[a.id] && !withdrawn(run.meta.approvals[a.id]));
|
|
245
|
+
/** The row after each tool call that waited for approval, beside its result's row. Its arguments are redacted whole
|
|
246
|
+
* (`redact`, the Timeline's own: no held key), before any cut. */
|
|
247
|
+
function withApprovals(rows, run, redact) {
|
|
248
|
+
if (!run.approvals?.size)
|
|
249
|
+
return [...rows];
|
|
250
|
+
const byCall = new Map([...run.approvals.values()].map((approval) => [approval.call_id, approval]));
|
|
251
|
+
const waiting = waitingApproval(run);
|
|
252
|
+
return rows.flatMap((row) => {
|
|
253
|
+
const approval = row.kind === "tool_result" && row.tool_use_id ? byCall.get(row.tool_use_id) : undefined;
|
|
254
|
+
if (!approval)
|
|
255
|
+
return [row];
|
|
256
|
+
const args = shownArgs(approval, redact);
|
|
257
|
+
const said = run.meta.approvals?.[approval.id]?.decision;
|
|
258
|
+
const byMessage = run.meta.approvals?.[approval.id]?.by === "message";
|
|
259
|
+
const head = approval === waiting ? "Waiting for your approval" : byMessage ? "Declined by your message" : said === "withdrawn" ? "Withdrawn when the run was stopped" : said === "canceled" ? "Withdrawn when the run was cancelled" : "Asked your approval";
|
|
260
|
+
const summary = `${head}: ${approval.tool} ${clip(args, 400)}`;
|
|
261
|
+
// A message that would have declined the call, which a stop or a cancel overrode: its words were never sent, and
|
|
262
|
+
// the row says so (the record keeps them whole).
|
|
263
|
+
const dropped = run.meta.approvals?.[approval.id]?.superseded;
|
|
264
|
+
const text = dropped?.by === "message" && dropped.note !== undefined ? `${args}\n\nNot sent: the run was ${said === "canceled" ? "cancelled" : "stopped"}. Your message: ${redact(dropped.note)}` : args;
|
|
265
|
+
return [row, { ...row, id: `${row.id}:approval`, kind: APPROVAL_ROW, summary, text, tool_name: approval.tool, tool_status: null, tool_input_preview: clip(args, 500), tool_result_preview: null, tool_result_size_bytes: null }];
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
/** A dollar figure to a millionth, as the timeline's cost.usd is. */
|
|
269
|
+
const micro = (usd) => Math.round(usd * 1e6) / 1e6;
|
|
270
|
+
/** How many tries a raised run's follow-up gets, and the waits between them, before the run fails with why. */
|
|
271
|
+
const CONTINUE_TRIES = 3;
|
|
272
|
+
const CONTINUE_RETRY_MS = [1_000, 3_000];
|
|
273
|
+
/** How many of the refused request's least a run paused at its cap is offered on top of what was taken (suggestedCap). */
|
|
274
|
+
export const SUGGESTED_RAISE_FACTOR = 10;
|
|
275
|
+
/** The raise a run paused at its cap is offered: what the cap counted as taken plus SUGGESTED_RAISE_FACTOR times the
|
|
276
|
+
* refused request's least, rounded up to a whole dollar, and always above the cap (the next dollar above it, if not),
|
|
277
|
+
* so a PATCH with it is a raise. */
|
|
278
|
+
export const suggestedCap = (cap, spentUsd, needsUsd) => {
|
|
279
|
+
// A hair under, so a sum a float puts just past a whole dollar (3.0000000000000004) stays that dollar.
|
|
280
|
+
const up = Math.ceil(spentUsd + SUGGESTED_RAISE_FACTOR * needsUsd - 1e-9);
|
|
281
|
+
// Above the cap as a raise must be (by more than CAP_TOLERANCE, takeRaise), so a PATCH with it is always taken.
|
|
282
|
+
return up > cap + CAP_TOLERANCE ? up : Math.floor(cap + CAP_TOLERANCE) + 1;
|
|
283
|
+
};
|
|
284
|
+
/** A run paused at its cap waits on a raise: its cap, what the cap counted as taken and the least the refused request
|
|
285
|
+
* needs (its refusal's mark; none from a store written before it kept them), the raise it is offered (suggestedCap),
|
|
286
|
+
* the refusal's words, and when it came (its error row's time). The figures are as the cap counts them, never rounded.
|
|
287
|
+
* What was taken is the store's spend once its process is gone (`spentNow`), when that is lower: the refusal counted
|
|
288
|
+
* requests still answering at what it held for them, and they have settled. */
|
|
289
|
+
const budgetPending = (run, spentNow) => {
|
|
290
|
+
const said = pausedAt(run);
|
|
291
|
+
const cap = run.meta.max_cost_usd;
|
|
292
|
+
if (said === undefined || cap === undefined)
|
|
293
|
+
return undefined;
|
|
294
|
+
const r = run.capRefusal;
|
|
295
|
+
const spent = r && spentNow !== undefined ? Math.min(r.spentUsd, spentNow) : r?.spentUsd;
|
|
296
|
+
// Shown as cost.usd is (to a millionth of a dollar), the suggestion from the figures as the cap counts them.
|
|
297
|
+
const figures = r && spent !== undefined ? { spent_usd: micro(spent), needs_usd: micro(r.needsUsd), suggested_cap_usd: suggestedCap(cap, spent, r.needsUsd) } : {};
|
|
298
|
+
return { kind: "budget", cap_usd: cap, ...figures, said, at: meaningful(run.rows)?.timestamp ?? run.updatedAt };
|
|
299
|
+
};
|
|
300
|
+
/** The waiting row of a run paused at its cap, after the refusal's error row: "Paused at the run's $1 cap: Not sent: …". */
|
|
301
|
+
function withPaused(rows, said, cap) {
|
|
302
|
+
const at = rows.findLastIndex((row) => row.kind === "error");
|
|
303
|
+
if (at < 0)
|
|
304
|
+
return [...rows];
|
|
305
|
+
const error = rows[at];
|
|
306
|
+
const paused = { ...error, id: `${error.id}:paused`, kind: "waiting", summary: `Paused at the run's ${money(cap)} cap: ${clip(said, 400)}`, text: clip(said, 2000), tool_name: null, tool_use_id: null, tool_status: null, tool_input_preview: null, tool_result_preview: null, tool_result_size_bytes: null };
|
|
307
|
+
return [...rows.slice(0, at + 1), paused, ...rows.slice(at + 1)];
|
|
308
|
+
}
|
|
187
309
|
/** 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
310
|
* last meaningful row is its answer when that row is one, a final answer's or a text row's. */
|
|
189
311
|
const importAnswerOf = (rows) => {
|
|
@@ -196,9 +318,13 @@ export const costOf = (rows) => {
|
|
|
196
318
|
const usage = usageOf(rows);
|
|
197
319
|
return usage ? (usage.usage?.usd ?? null) : 0;
|
|
198
320
|
};
|
|
199
|
-
/** What a run's paid tools charged, from the same rows its cost is read from: each charge's
|
|
200
|
-
* `phase` row); null when one is unknown. A call still marked, in flight or cut, is no
|
|
201
|
-
|
|
321
|
+
/** What a run's paid tools charged (`tool`'s alone, when given), from the same rows its cost is read from: each charge's
|
|
322
|
+
* line carries it (`usage` on a `phase` row); null when one is unknown. A call still marked, in flight or cut, is no
|
|
323
|
+
* charge here. */
|
|
324
|
+
export const toolCostOf = (rows, tool) => rows.reduce((sum, row) => (row.kind !== "phase" || !row.usage || (tool !== undefined && row.tool_name !== tool) ? sum : sum === null || row.usage.usd === null ? null : sum + row.usage.usd), 0);
|
|
325
|
+
/** What a run's paid tools are known to have charged (`tool`'s alone, when given; every other tool's with `others`): each
|
|
326
|
+
* charge's line that names its cost, a charge of unknown cost adding nothing. */
|
|
327
|
+
export const knownToolCostOf = (rows, tool, others = false) => rows.reduce((sum, row) => (row.kind !== "phase" || !row.usage || typeof row.usage.usd !== "number" || (tool !== undefined && (others ? row.tool_name === tool : row.tool_name !== tool)) ? sum : sum + row.usage.usd), 0);
|
|
202
328
|
/** 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
329
|
* request). A usage row that says unknown, or says nothing, stays unknown: what the store kept dates from before a
|
|
204
330
|
* follow-up. */
|
|
@@ -246,8 +372,9 @@ function answerOfRun(run) {
|
|
|
246
372
|
const imported = run.imported ? importAnswerOf(run.rows) : undefined;
|
|
247
373
|
return lastAnswer(run) ?? imported?.text ?? imported?.summary ?? null;
|
|
248
374
|
}
|
|
249
|
-
|
|
250
|
-
const
|
|
375
|
+
// A run's messages are its message rows (isMessageRow): a person's, and those the server wrote, the message its turn took.
|
|
376
|
+
const usersOf = (rows) => rows.filter(isMessageRow).length;
|
|
377
|
+
const lastUserMessage = (rows) => rows.findLast(isMessageRow)?.id;
|
|
251
378
|
// 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
379
|
// order rows across conversations and the conversation is no part of the order.
|
|
253
380
|
const placeOf = (id) => Number(id.slice(id.lastIndexOf(":") + 1));
|
|
@@ -257,9 +384,57 @@ export const stoppedAt = (meta, rows) => {
|
|
|
257
384
|
if (meta.stopped_at === undefined)
|
|
258
385
|
return meta.stopped_after !== undefined && meta.stopped_after === usersOf(rows);
|
|
259
386
|
const at = placeOf(meta.stopped_at);
|
|
260
|
-
return !rows.some((r) => r
|
|
387
|
+
return !rows.some((r) => isMessageRow(r) && placeOf(r.id) > at);
|
|
261
388
|
};
|
|
262
389
|
const stopped = (run) => stoppedAt(run.meta, run.rows);
|
|
390
|
+
/** The words of the cap's refusal for room an agentic run stands paused at: its newest message's turn ended on it (cap.ts
|
|
391
|
+
* roomRefusal: what is left of its cap cannot buy the next request's least, which a higher cap would send), and nothing
|
|
392
|
+
* came since. The run then waits for its cap to be raised (input_required, `pending.kind` budget), never failed; a
|
|
393
|
+
* refusal no cap fixes (an unknown spend, no price) still fails it (decide). Undefined for any other run. */
|
|
394
|
+
const refusedAt = (run) => {
|
|
395
|
+
if (run.kind !== "agentic" || run.cancel || run.submitted > 0 || run.turns.open > 0 || stopped(run))
|
|
396
|
+
return undefined;
|
|
397
|
+
const end = run.turns.end();
|
|
398
|
+
return end?.status === "failed" ? roomRefusal(end.error) : undefined;
|
|
399
|
+
};
|
|
400
|
+
/** The pause a run stands at, by its refusal's own start mark (its entry), so no row shown after it moves it; a store
|
|
401
|
+
* with no such mark keys it to the refusal's row. Undefined when it stands at no refusal for room. */
|
|
402
|
+
const pauseOf = (run) => {
|
|
403
|
+
if (refusedAt(run) === undefined)
|
|
404
|
+
return undefined;
|
|
405
|
+
if (run.capMark !== undefined)
|
|
406
|
+
return `mark:${run.capMark}`;
|
|
407
|
+
const row = meaningful(run.rows)?.id;
|
|
408
|
+
return row === undefined ? undefined : `row:${row}`;
|
|
409
|
+
};
|
|
410
|
+
/** Its cap was raised since the refusal it stands at (a raise names that pause): it waits for its follow-up then, not
|
|
411
|
+
* for a raise (input_required, idle). */
|
|
412
|
+
const raisedSince = (run) => {
|
|
413
|
+
const pause = pauseOf(run);
|
|
414
|
+
return pause !== undefined && run.meta.cap_raised?.some((raise) => raise.pause === pause) === true;
|
|
415
|
+
};
|
|
416
|
+
/** The follow-up a raise of the pause it stands at asked for and that has not gone yet: one per pause. */
|
|
417
|
+
const continuationOf = (run) => {
|
|
418
|
+
// A run that has ended, or is ending (its follow-up's tries spent: failRaised, a cancel), sends none any more.
|
|
419
|
+
if (run.outcome || run.finishing || run.cancel)
|
|
420
|
+
return undefined;
|
|
421
|
+
const pause = pauseOf(run);
|
|
422
|
+
const next = run.meta.cap_continue;
|
|
423
|
+
return pause !== undefined && next?.pause === pause && !next.sent ? next : undefined;
|
|
424
|
+
};
|
|
425
|
+
/** A process by its pid and start ticks (Linux /proc; the pid alone elsewhere): a pid used again is another process. */
|
|
426
|
+
function processIdentity(pid) {
|
|
427
|
+
if (pid === undefined)
|
|
428
|
+
return undefined;
|
|
429
|
+
try {
|
|
430
|
+
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
431
|
+
return `${pid}:${stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]}`;
|
|
432
|
+
}
|
|
433
|
+
catch {
|
|
434
|
+
return String(pid);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
const pausedAt = (run) => (raisedSince(run) ? undefined : refusedAt(run));
|
|
263
438
|
/** What a stop keeps of where the run stands: the person's last message, by its id, or the place before any. */
|
|
264
439
|
export const stopMark = (rows) => ({ stopped_at: lastUserMessage(rows) ?? `${ROOT_CONVERSATION_ID}:0` });
|
|
265
440
|
/** The rows a snapshot that no longer holds them leaves served: those committed entries made. A row any connection
|
|
@@ -299,16 +474,33 @@ export function statusOf(run) {
|
|
|
299
474
|
return { status: "input_required", state: "idle" };
|
|
300
475
|
if (!users)
|
|
301
476
|
return { status: "queued", state: "working" };
|
|
477
|
+
// A tool call parked for approval (tool-gate.ts) waits for the person; once answered, its process acts on it.
|
|
478
|
+
if (run.kind === "agentic" && run.submitted === 0 && !run.working) {
|
|
479
|
+
if (waitingApproval(run))
|
|
480
|
+
return { status: "input_required", state: "waiting" };
|
|
481
|
+
if (actingOn(run))
|
|
482
|
+
return { status: "working", state: "working" };
|
|
483
|
+
}
|
|
302
484
|
// Every message's turn is over and the newest one's ended interrupted, with no stop of the person's saying so (the
|
|
303
485
|
// harness ended it on its own): the run waits for the person, as after a stop, never working for good.
|
|
304
486
|
if (run.kind === "agentic" && run.submitted === 0 && run.turns.end()?.status === "interrupted")
|
|
305
487
|
return { status: "input_required", state: "idle" };
|
|
488
|
+
// Paused at its cap: it waits for the cap to be raised; raised, for a message, if the raise's own follow-up did not go.
|
|
489
|
+
if (refusedAt(run) !== undefined)
|
|
490
|
+
return pausedAt(run) !== undefined ? { status: "input_required", state: "waiting" } : { status: "input_required", state: "idle" };
|
|
306
491
|
if (run.working)
|
|
307
492
|
return { status: "working", state: "working" };
|
|
308
493
|
if (meaningful(run.rows)?.kind === "waiting")
|
|
309
494
|
return { status: "input_required", state: "waiting" };
|
|
310
495
|
return { status: "working", state: "idle" };
|
|
311
496
|
}
|
|
497
|
+
/** The trigger a serve.json says started its run, as read back: `{id, firing_key}`, or null. */
|
|
498
|
+
function triggerOf(meta) {
|
|
499
|
+
const trigger = meta?.trigger;
|
|
500
|
+
return isObject(trigger) && typeof trigger.id === "string" && typeof trigger.firing_key === "string" ? { id: trigger.id, firing_key: trigger.firing_key } : null;
|
|
501
|
+
}
|
|
502
|
+
/** Why a message that may not answer a person's question is not sent. */
|
|
503
|
+
export const WAITS_ON_A_PERSON = "The run is waiting on a person.";
|
|
312
504
|
/** The server's own secrets, which a run's process never gets: the API token, by name or by value, the seal key
|
|
313
505
|
* the tool keys are kept under (tool-keys.ts), and the boxes' keys (boxes.ts), which only the server's box providers use. */
|
|
314
506
|
const SERVER_ONLY = new Set(["AGENTRUN_TOKEN", "AGENTRUN_API_KEY", "AGENTRUN_SEAL_KEY", ...BOX_KEYS]);
|
|
@@ -432,6 +624,8 @@ export async function lastLogLine(run) {
|
|
|
432
624
|
await file.close();
|
|
433
625
|
}
|
|
434
626
|
}
|
|
627
|
+
/** Seams for tests, each unset in a server: `personsTurn` holds a person's turn just after its origin went. */
|
|
628
|
+
export const runsTestHooks = {};
|
|
435
629
|
export class Runs {
|
|
436
630
|
options;
|
|
437
631
|
runs = new Map();
|
|
@@ -440,9 +634,12 @@ export class Runs {
|
|
|
440
634
|
/** What decides the secrets each revision's runs are handed (needsOf), by revision id: read once, from the revision the
|
|
441
635
|
* run is pinned to, never from a request. The keys themselves are read at each launch (keysFor). */
|
|
442
636
|
needs = new Map();
|
|
443
|
-
/**
|
|
444
|
-
|
|
637
|
+
/** Every run's graph as served, part by part (servedGraph), and each workflow run's last graph read whole, which a
|
|
638
|
+
* poll that met a busy store answers, marked stale: one LRU by bytes across runs (graph-served.ts PartCache). */
|
|
639
|
+
graphCache = new PartCache(GRAPH_CACHE_BYTES);
|
|
445
640
|
adopting = new Map();
|
|
641
|
+
/** The hosts this server's next remote box asks for: the setting's, until the provider cannot keep a list here, then none. */
|
|
642
|
+
remoteAllow;
|
|
446
643
|
clock = new ChangeClock();
|
|
447
644
|
cli = fileURLToPath(new URL("./cli.js", import.meta.resolve("@parcha/pi-durable-disk")));
|
|
448
645
|
app = fileURLToPath(new URL("./app.js", import.meta.url));
|
|
@@ -460,6 +657,8 @@ export class Runs {
|
|
|
460
657
|
/** The runs' learning (learning-run.ts): a step this file calls as a run starts, ends, settles, opens again and is
|
|
461
658
|
* recovered, handed what it moves of a run. */
|
|
462
659
|
learning;
|
|
660
|
+
/** When this server took the data root (one server a root): a run started since is its own, never one to recover. */
|
|
661
|
+
bootedAt = new Date().toISOString();
|
|
463
662
|
constructor(options) {
|
|
464
663
|
this.options = options;
|
|
465
664
|
this.learning = new LearningRuns(options, {
|
|
@@ -483,8 +682,15 @@ export class Runs {
|
|
|
483
682
|
/** A test's seam (startServe's `beforeReopenLaunch`): awaited by a reopen after the run reads open again and before its
|
|
484
683
|
* launch, so a test can hold a reopen there. */
|
|
485
684
|
beforeReopenLaunch;
|
|
685
|
+
/** A test's seam (startServe's `onRunLoad`): told each run read in from its store, its timeline with it. */
|
|
686
|
+
onRunLoad;
|
|
486
687
|
/** A test's seam (startServe's `beforeSubmit`): awaited by a message before it goes to the run's door. */
|
|
487
688
|
beforeSubmit;
|
|
689
|
+
/** A test's seam (startServe's `beforeMetaSave`): awaited before a run's serve.json is written; one that throws fails
|
|
690
|
+
* the write, as a full disk would. */
|
|
691
|
+
beforeMetaSave;
|
|
692
|
+
/** A test's seam (startServe's `messageOrigin`): the origin a message sent through the messages route carries. */
|
|
693
|
+
messageOrigin;
|
|
488
694
|
get store() {
|
|
489
695
|
return this.options.agents.store;
|
|
490
696
|
}
|
|
@@ -514,14 +720,19 @@ export class Runs {
|
|
|
514
720
|
return pending;
|
|
515
721
|
}
|
|
516
722
|
async load(row) {
|
|
723
|
+
this.onRunLoad?.(row.id);
|
|
517
724
|
const dir = join(this.options.agents.dir, "runs", row.id);
|
|
518
725
|
const stored = (await readJson(join(dir, RUN_META)));
|
|
726
|
+
const trigger = triggerOf(stored);
|
|
519
727
|
const meta = {
|
|
520
728
|
title: typeof stored?.title === "string" ? stored.title : "",
|
|
521
729
|
created_at: typeof stored?.created_at === "string" ? stored.created_at : row.startedAt,
|
|
522
730
|
...(isObject(stored?.input) ? { input: stored.input } : {}),
|
|
523
731
|
...(typeof stored?.effort === "string" ? { effort: stored.effort } : {}),
|
|
524
732
|
...(typeof stored?.max_cost_usd === "number" ? { max_cost_usd: stored.max_cost_usd } : {}),
|
|
733
|
+
// Each raise of its cap, and the follow-up a stopped server never sent, which the next sends (resumeRaised).
|
|
734
|
+
...(Array.isArray(stored?.cap_raised) ? { cap_raised: stored.cap_raised } : {}),
|
|
735
|
+
...(isObject(stored?.cap_continue) ? { cap_continue: stored.cap_continue } : {}),
|
|
525
736
|
...(stored?.error ? { error: stored.error } : {}),
|
|
526
737
|
...(stored && "output" in stored ? { output: stored.output } : {}),
|
|
527
738
|
...(isObject(stored?.review) ? { review: stored.review } : {}),
|
|
@@ -532,7 +743,11 @@ export class Runs {
|
|
|
532
743
|
...(stored?.place ? { place: storedPlace(stored.place) } : {}),
|
|
533
744
|
...(isObject(stored?.learning) ? { learning: stored.learning } : {}),
|
|
534
745
|
...(isObject(stored?.reflect) ? { reflect: stored.reflect } : {}),
|
|
746
|
+
...(isObject(stored?.approvals) ? { approvals: stored.approvals } : {}),
|
|
747
|
+
...(trigger ? { trigger } : {}),
|
|
535
748
|
};
|
|
749
|
+
// A turn's origin a server before this one set is not known to be the turn running now: it goes.
|
|
750
|
+
await rm(join(dir, TURN_ORIGIN_FILE), { force: true }).catch(() => undefined);
|
|
536
751
|
// A seed copy a server went down during is taken back before anything holds the run: its relaunch, a settle, a
|
|
537
752
|
// follow-up (learning-run.ts onLoad).
|
|
538
753
|
if (stored)
|
|
@@ -541,6 +756,7 @@ export class Runs {
|
|
|
541
756
|
const run = this.blank(row, dir, meta, known?.version ?? 0, harnessOfBody(known?.revision.body ?? {}), known ? await toolingOf(known.revision) : undefined, known?.revision);
|
|
542
757
|
this.runs.set(row.id, run);
|
|
543
758
|
run.launching = existsSync(join(dir, RUN_LAUNCHING));
|
|
759
|
+
run.notSetUp = row.state === "running" && !isObject(stored?.input);
|
|
544
760
|
const record = await this.record(run);
|
|
545
761
|
// 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
762
|
if (row.state !== "running")
|
|
@@ -593,10 +809,15 @@ export class Runs {
|
|
|
593
809
|
}
|
|
594
810
|
/** 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
811
|
* once the run's learning ended). */
|
|
596
|
-
|
|
812
|
+
/** Writes the run's serve.json, after any write already under way: `meta`, a copy its caller publishes to run.meta
|
|
813
|
+
* only once this resolves (a raise, takeRaise), else run.meta, each as it stands when the write starts. */
|
|
814
|
+
saveMeta(run, meta) {
|
|
597
815
|
run.saving = (run.saving ?? Promise.resolve()).catch(() => undefined).then(async () => {
|
|
598
|
-
|
|
599
|
-
|
|
816
|
+
// A copy is built as its write starts, from run.meta as it stands then.
|
|
817
|
+
const written = meta ? meta() : run.meta;
|
|
818
|
+
const { learning } = written;
|
|
819
|
+
await this.beforeMetaSave?.(run.id, written);
|
|
820
|
+
await writeWhole(join(run.dir, RUN_META), `${JSON.stringify(written)}\n`);
|
|
600
821
|
await this.learning.onSaved(run, learning);
|
|
601
822
|
});
|
|
602
823
|
return run.saving;
|
|
@@ -666,15 +887,16 @@ export class Runs {
|
|
|
666
887
|
run.metrics = runMetricsWithDecisions(read.map((r) => r.entry), run.kind === "workflow" ? (run.decisions ?? []) : []);
|
|
667
888
|
run.working = false;
|
|
668
889
|
noteTurns(run, entries, submissions);
|
|
669
|
-
|
|
890
|
+
noteApprovals(run, entries);
|
|
891
|
+
this.take(run, timelineOf(redactGateMessages(entries, this.redactor(run)), { settled: true, path: rowPaths(run.dir), redact: this.redactor(run) }));
|
|
670
892
|
}
|
|
671
893
|
/** New rows in: into the log, then the run's status, then whatever the status asks for. */
|
|
672
894
|
/** `keep`: rows that stay served though `rows` no longer holds them (the live path's committed rows). */
|
|
673
895
|
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);
|
|
896
|
+
run.rows = withOverCap(labelled(run.meta.reflect, withApprovals(withAsks(rows.filter((r) => !QUIET.test(r.id))), run, this.redactor(run))), run.meta.max_cost_usd);
|
|
675
897
|
// Counted by id: a snapshot of a compacted conversation shows fewer user messages than before, which is not more
|
|
676
898
|
// messages waiting, so a count of rows would leave the run working forever.
|
|
677
|
-
const arrived = run.rows.filter((r) => r
|
|
899
|
+
const arrived = run.rows.filter((r) => isMessageRow(r) && !run.users.has(r.id));
|
|
678
900
|
for (const row of arrived)
|
|
679
901
|
run.users.add(row.id);
|
|
680
902
|
run.submitted = Math.max(0, run.submitted - arrived.length);
|
|
@@ -682,13 +904,25 @@ export class Runs {
|
|
|
682
904
|
this.show(run);
|
|
683
905
|
this.refresh(run);
|
|
684
906
|
}
|
|
907
|
+
/** The approval rows as the run's answers say them now (a stop or a cancel withdraws a call, an answer settles one),
|
|
908
|
+
* shown at once: an answer takes no new rows. */
|
|
909
|
+
restate(run) {
|
|
910
|
+
if (!run.approvals?.size)
|
|
911
|
+
return;
|
|
912
|
+
run.rows = withApprovals(run.rows.filter((row) => row.kind !== APPROVAL_ROW), run, this.redactor(run));
|
|
913
|
+
this.show(run);
|
|
914
|
+
}
|
|
685
915
|
/** 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
916
|
* only, never the run's own rows, which its cost and its answer are read from. */
|
|
687
917
|
show(run) {
|
|
688
918
|
// 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
|
-
|
|
919
|
+
// Their summary and text are redacted whole, then cut (decision-rows.ts): a provider's error can quote a held key.
|
|
920
|
+
const own = run.decisions === undefined ? run.rows : withDecisions(run.rows, run.decisions, this.decisionShown(run));
|
|
690
921
|
// An error row reads as the run's error does (errorWords): a refused key in plain words, no loopback address.
|
|
691
|
-
const
|
|
922
|
+
const served = own.map((row) => (row.kind === "error" ? this.servedError(run, row) : row));
|
|
923
|
+
// A run paused at its cap says so after the refusal, as the row its status reads.
|
|
924
|
+
const said = pausedAt(run);
|
|
925
|
+
const rows = said === undefined || run.meta.max_cost_usd === undefined ? served : withPaused(served, said, run.meta.max_cost_usd);
|
|
692
926
|
if (run.log.sync(withLearning(rows, run.meta.learning, this.learning.shown()), run.keep))
|
|
693
927
|
run.updatedAt = new Date().toISOString();
|
|
694
928
|
}
|
|
@@ -710,24 +944,33 @@ export class Runs {
|
|
|
710
944
|
return undefined;
|
|
711
945
|
const cap = run.meta.max_cost_usd;
|
|
712
946
|
const cost = costOf(run.rows);
|
|
713
|
-
if (cap !== undefined && cost !== null && cost > cap)
|
|
947
|
+
if (cap !== undefined && cost !== null && cost > cap + FIT_TOLERANCE)
|
|
714
948
|
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
949
|
if (run.submitted > 0)
|
|
716
950
|
return undefined;
|
|
717
951
|
if (run.turns.open > 0 || stopped(run))
|
|
718
952
|
return undefined;
|
|
953
|
+
// A tool call waits for a person's approval, or for its answer to be acted on: the run goes on after it.
|
|
954
|
+
if (waitingApproval(run) || actingOn(run))
|
|
955
|
+
return undefined;
|
|
719
956
|
const end = run.turns.end();
|
|
720
957
|
if (end?.status === "answered")
|
|
721
958
|
return { outcome: "completed" };
|
|
722
959
|
if (end?.status !== "failed")
|
|
723
960
|
return undefined;
|
|
724
961
|
const message = end.error ?? "The run failed.";
|
|
962
|
+
// The cap's refusal for room pauses the run instead (pausedAt): a raise sends what was refused.
|
|
963
|
+
if (roomRefusal(message) !== undefined)
|
|
964
|
+
return undefined;
|
|
725
965
|
// The cap's refusal in the run's process (cap.ts); a provider error with this exact prefix would read as one too.
|
|
726
966
|
// Its code is `spend_cap_reached: `, or with a note after it (`spend_cap_reached (out of budget): `, cap.ts); the message is
|
|
727
967
|
// the words after it.
|
|
728
968
|
const capped = CAP_REFUSAL_PREFIX.exec(message);
|
|
729
969
|
if (capped)
|
|
730
970
|
return { outcome: "failed", error: { code: SPEND_CAP_REACHED, message: message.slice(capped[0].length), retryable: false } };
|
|
971
|
+
// The provider's content filter stopped the answer (content-filter.ts): moderated, in words a person can act on.
|
|
972
|
+
if (contentFiltered(message))
|
|
973
|
+
return { outcome: "failed", error: { code: MODERATED, message: CONTENT_FILTER_WORDS, retryable: false } };
|
|
731
974
|
return { outcome: "failed", error: { code: "run_failed", message: this.errorWords(run, message) ?? message, retryable: false } };
|
|
732
975
|
}
|
|
733
976
|
/** 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
|
|
@@ -764,7 +1007,7 @@ export class Runs {
|
|
|
764
1007
|
* saved or deleted changes the values' digest, and the next view redacts again. */
|
|
765
1008
|
servedOnce(run, slot, input, redact) {
|
|
766
1009
|
const values = this.refusedValues(run);
|
|
767
|
-
const keys =
|
|
1010
|
+
const keys = digestOf([...values].sort());
|
|
768
1011
|
const last = run.served?.[slot];
|
|
769
1012
|
if (last && last.keys === keys && last.input === input)
|
|
770
1013
|
return last.out;
|
|
@@ -772,12 +1015,43 @@ export class Runs {
|
|
|
772
1015
|
run.served = { ...run.served, [slot]: { keys, input, out } };
|
|
773
1016
|
return out;
|
|
774
1017
|
}
|
|
1018
|
+
/** A workflow run's graph as serve serves it: its nodes, each decision and each call (its input, output and error) with
|
|
1019
|
+
* no held secret, by its answer's rule (redactedOutput), and only then cut: a map item's label at 200 characters, a
|
|
1020
|
+
* call's error at 2000, and a text stored cut (a decision's state past 64 KB, an error logged cut) less its last 6
|
|
1021
|
+
* times the longest held value plus 16 characters, where a value the stored cut split would sit. The view a busy
|
|
1022
|
+
* store's read keeps is the one graph-view.ts made, whole, so a key saved after it is still found. Each part is
|
|
1023
|
+
* served once per content and held value set: a console polls the graph while the run goes. */
|
|
1024
|
+
servedGraph(run, view) {
|
|
1025
|
+
const values = this.refusedValues(run);
|
|
1026
|
+
const keys = digestOf([...values].sort());
|
|
1027
|
+
const once = (kind, value) => {
|
|
1028
|
+
const at = `part:${keys}:${kind}:${digestOf(value)}`;
|
|
1029
|
+
const kept = this.graphCache.get(at);
|
|
1030
|
+
if (kept !== undefined)
|
|
1031
|
+
return kept;
|
|
1032
|
+
const out = servedPart(kind, value, values);
|
|
1033
|
+
this.graphCache.set(at, out, Buffer.byteLength(JSON.stringify(out) ?? ""));
|
|
1034
|
+
return out;
|
|
1035
|
+
};
|
|
1036
|
+
return { ...view, nodes: once("nodes", view.nodes), decisions: view.decisions.map((value) => once("decision", value)), effects: view.effects.map((value) => once("effect", value)) };
|
|
1037
|
+
}
|
|
775
1038
|
/** The timeline's redaction of `run`'s error rows and of what a tool's result shows (its summary and preview), applied
|
|
776
1039
|
* before a row is cut (timelineOf's `redact`), so a cut never leaves the head of a key. Every such cut is within
|
|
777
1040
|
* redacted()'s SHOWN, so its window holds. */
|
|
1041
|
+
/** How a run's decision rows show a text (decision-rows.ts Shown): the run's redactor, and as many characters held back
|
|
1042
|
+
* from a text stored cut as a held value takes in its widest form. */
|
|
1043
|
+
decisionShown(run) {
|
|
1044
|
+
const values = this.refusedValues(run);
|
|
1045
|
+
return { redact: (text) => redacted(text, values), hold: 6 * values.reduce((most, value) => Math.max(most, value.length), 0) + 16 };
|
|
1046
|
+
}
|
|
778
1047
|
redactor(run) {
|
|
779
1048
|
return (text) => redacted(text, this.refusedValues(run));
|
|
780
1049
|
}
|
|
1050
|
+
/** The last line of the run process's log (lastLogLine) for a failure's message, with every value its errors never
|
|
1051
|
+
* show cut out: its process may have written a secret or its sign-in's pointer there. */
|
|
1052
|
+
async lastLine(run) {
|
|
1053
|
+
return this.redactor(run)(await lastLogLine(run));
|
|
1054
|
+
}
|
|
781
1055
|
/** Every secret value `run`'s errors never show, as learning's checker holds them (learning-run.ts refused): this
|
|
782
1056
|
* server's secrets wherever its launcher put them and the keys saved on it, what each launch handed the run, and the
|
|
783
1057
|
* server's own tokens. */
|
|
@@ -795,11 +1069,49 @@ export class Runs {
|
|
|
795
1069
|
return keyRefusal(text, runKeyOf(env, run.harness ?? run.tooling?.harness, run.tooling?.model), this.refusedValues(run));
|
|
796
1070
|
}
|
|
797
1071
|
/** 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. */
|
|
1072
|
+
/** What a run paused at its cap has spent once its process is gone: its store's spend as the cap reads it (spentIn),
|
|
1073
|
+
* read once per pause (its refusal's row). None while its process lives, nor when the store says unknown or cannot
|
|
1074
|
+
* be read: the refusal's own figure stands then. */
|
|
1075
|
+
spentNow(run) {
|
|
1076
|
+
const mark = meaningful(run.rows)?.id;
|
|
1077
|
+
if (mark === undefined || !run.capRefusal || this.live(run) || pausedAt(run) === undefined)
|
|
1078
|
+
return undefined;
|
|
1079
|
+
// One read per pause, and a failed read again after a while, never kept until a restart.
|
|
1080
|
+
if (run.capSpent?.mark !== mark || (run.capSpent.usd === null && Date.now() - (run.capSpent.at ?? 0) > 30_000)) {
|
|
1081
|
+
let usd = null;
|
|
1082
|
+
try {
|
|
1083
|
+
usd = spentIn(this.storeFile(run));
|
|
1084
|
+
}
|
|
1085
|
+
catch (error) {
|
|
1086
|
+
warn(run.id, `its store's spend was not read (${error.message}); its refusal's figure stands`);
|
|
1087
|
+
}
|
|
1088
|
+
run.capSpent = { mark, usd, at: Date.now() };
|
|
1089
|
+
}
|
|
1090
|
+
return run.capSpent.usd ?? undefined;
|
|
1091
|
+
}
|
|
1092
|
+
/** The run's live process, by its pid and start ticks (processIdentity). */
|
|
1093
|
+
liveIdentity(run) {
|
|
1094
|
+
return processIdentity(run.child?.pid ?? run.orphan);
|
|
1095
|
+
}
|
|
798
1096
|
refresh(run) {
|
|
799
1097
|
this.mark(run);
|
|
1098
|
+
// A run whose cap was raised at its pause goes on once the process paused there is gone (resumeRaised): with no
|
|
1099
|
+
// process, or one another launch started (a server stopped between that launch and its message: the door takes the
|
|
1100
|
+
// message once, by its id). Never while one waits to be tried again.
|
|
1101
|
+
const next = continuationOf(run);
|
|
1102
|
+
const letting = next !== undefined && next.paused !== undefined && this.live(run) && this.liveIdentity(run) === next.paused;
|
|
1103
|
+
if (next && run.resuming === undefined && !this.closing && !run.cancel && !run.finishing && !run.outcome && !letting)
|
|
1104
|
+
void this.resumeRaised(run, next);
|
|
800
1105
|
if (!this.live(run) || run.finishing || run.outcome)
|
|
801
1106
|
return;
|
|
802
1107
|
const end = this.decide(run);
|
|
1108
|
+
// Paused at its cap, its process is let go: it waits without one, holding no place, until its cap is raised. Once
|
|
1109
|
+
// per pause (its refusal's row): SIGTERM drains and releases it, and the settle that follows leaves it waiting. A
|
|
1110
|
+
// raised one's paused process is let go too (a server started again finds it so).
|
|
1111
|
+
if (!end && (pausedAt(run) !== undefined || letting) && run.parked !== waitMark(run)) {
|
|
1112
|
+
run.parked = waitMark(run);
|
|
1113
|
+
this.terminate(run);
|
|
1114
|
+
}
|
|
803
1115
|
if (!end)
|
|
804
1116
|
return;
|
|
805
1117
|
if (end.error)
|
|
@@ -869,8 +1181,8 @@ export class Runs {
|
|
|
869
1181
|
/** Every run's box let go that nothing owns, and every run cgroup no record names: once, before any run of this server
|
|
870
1182
|
* starts, opens again or relaunches, so a box or cgroup being made is never swept away. */
|
|
871
1183
|
sweepOnce() {
|
|
872
|
-
const { box, runBoxes, remoteBoxes } = this.options;
|
|
873
|
-
if (!box && !runBoxes && !remoteBoxes)
|
|
1184
|
+
const { box, runBoxes, remoteBoxes, vmBoxes } = this.options;
|
|
1185
|
+
if (!box && !runBoxes && !remoteBoxes && !vmBoxes)
|
|
874
1186
|
return Promise.resolve();
|
|
875
1187
|
this.swept ??= (async () => {
|
|
876
1188
|
const rows = await this.options.agents.request(() => this.store.listRuns());
|
|
@@ -882,18 +1194,21 @@ export class Runs {
|
|
|
882
1194
|
}
|
|
883
1195
|
// 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
1196
|
// once that pull landed: one that fails keeps the box for the next start, its lifetime bounding it.
|
|
1197
|
+
const dirOf = (id) => join(this.options.agents.dir, "runs", id);
|
|
1198
|
+
const pulledFirst = (boxes, daytona) => (id, boxId) => pullRemoteBox(boxes, { id, dir: dirOf(id) }, boxContext(REMOTE_SYNC_MS)).then(() => true, async (error) => {
|
|
1199
|
+
warn(id, `its box is kept: its pull failed (${error.message}); the next start tries again`);
|
|
1200
|
+
await this.keepBox(id, boxId, daytona);
|
|
1201
|
+
return false;
|
|
1202
|
+
});
|
|
1203
|
+
if (vmBoxes) {
|
|
1204
|
+
await sweepRunBoxes(vmBoxes, (id) => ended.has(id), boxContext(REMOTE_SYNC_MS), pulledFirst(vmBoxes, false)).catch((error) => warn("-", `its start's sweep of Modal sandboxes failed (${error.message}); the next start sweeps again`));
|
|
1205
|
+
}
|
|
885
1206
|
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
1207
|
// 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
1208
|
const api = this.options.remoteApi;
|
|
894
1209
|
if (api)
|
|
895
1210
|
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`));
|
|
1211
|
+
await sweepRunBoxes(remoteBoxes, (id) => ended.has(id), boxContext(REMOTE_SYNC_MS), pulledFirst(remoteBoxes, true)).catch((error) => warn("-", `its start's sweep of remote run boxes failed (${error.message}); the next start sweeps again`));
|
|
897
1212
|
}
|
|
898
1213
|
if (!box)
|
|
899
1214
|
return;
|
|
@@ -919,17 +1234,33 @@ export class Runs {
|
|
|
919
1234
|
const place = run.meta.place;
|
|
920
1235
|
if (place?.mode !== "sandbox")
|
|
921
1236
|
return;
|
|
1237
|
+
// The relay's hold on the run's programs (box-relay-vm.ts) ends with the run, whatever becomes of its box: one kept
|
|
1238
|
+
// for a later pull, or one whose destroy failed, still lets them go, and their output with them.
|
|
1239
|
+
this.options.vmRelay?.drop(run.id);
|
|
922
1240
|
const remote = remotePlace(place);
|
|
923
|
-
const boxes = remote ? this.
|
|
1241
|
+
const boxes = remote ? this.remoteOf(place) : this.options.runBoxes;
|
|
924
1242
|
if (!boxes)
|
|
925
1243
|
return;
|
|
1244
|
+
// Its background processes first (background.ts), so each one's exit code and whole log are in work/ before the
|
|
1245
|
+
// pull and the destroy. A bound box with no work/background/ started none, and costs no command here. A failure only
|
|
1246
|
+
// warns: the destroy ends them all the same.
|
|
1247
|
+
if (remote || existsSync(join(run.dir, "work", BACKGROUND_DIR))) {
|
|
1248
|
+
try {
|
|
1249
|
+
const ended = await endBackground(boxes, { [RUN_LABEL]: run.id }, boxContext());
|
|
1250
|
+
if (ended)
|
|
1251
|
+
this.options.log?.("background_ended", { run: run.id, ended });
|
|
1252
|
+
}
|
|
1253
|
+
catch (error) {
|
|
1254
|
+
warn(run.id, `its background processes were not ended before its box goes (${error.message}); destroying the box ends them`);
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
926
1257
|
if (remote) {
|
|
927
1258
|
try {
|
|
928
1259
|
await this.pullBox(run, true);
|
|
929
1260
|
}
|
|
930
1261
|
catch (error) {
|
|
931
1262
|
if (error instanceof PullIncomplete && error.lasting) {
|
|
932
|
-
await this.keepBox(run.id, error.box);
|
|
1263
|
+
await this.keepBox(run.id, error.box, place.box === "daytona");
|
|
933
1264
|
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
1265
|
}
|
|
935
1266
|
const why = `its box's last pull failed (${error.message})`;
|
|
@@ -940,6 +1271,8 @@ export class Runs {
|
|
|
940
1271
|
}
|
|
941
1272
|
try {
|
|
942
1273
|
await destroyRunBoxes(boxes, run.id, boxContext());
|
|
1274
|
+
// The box's egress proxy directory (box-egress.ts), its socket the run's process left: nothing binds it now.
|
|
1275
|
+
await removeEgressDir(run.id).catch(() => undefined);
|
|
943
1276
|
}
|
|
944
1277
|
catch (error) {
|
|
945
1278
|
warn(run.id, `its box was not destroyed (${error.message}); the next start sweeps it`);
|
|
@@ -947,28 +1280,30 @@ export class Runs {
|
|
|
947
1280
|
}
|
|
948
1281
|
/** 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
1282
|
* disk alone until the next start's pull (which wakes it) or its lifetime. */
|
|
950
|
-
async keepBox(runId, boxId) {
|
|
1283
|
+
async keepBox(runId, boxId, daytona = true) {
|
|
951
1284
|
this.options.log?.("box_kept", { run: runId, box: boxId, reason: "pull_incomplete" });
|
|
952
|
-
|
|
1285
|
+
// A VM box keeps its lifetime alone: the provider has no idle stop to set.
|
|
1286
|
+
const api = daytona ? this.options.remoteApi : undefined;
|
|
953
1287
|
if (api)
|
|
954
1288
|
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
1289
|
}
|
|
956
1290
|
/** What wakes run `runId`'s remote box when Daytona stopped or paused it (a class that pauses when idle, while the run
|
|
957
1291
|
* waited for a person): how many it woke. */
|
|
958
|
-
wakeOf(runId) {
|
|
959
|
-
|
|
1292
|
+
wakeOf(runId, place) {
|
|
1293
|
+
// Only Daytona stops or pauses a box: a VM box that ended is made again.
|
|
1294
|
+
const api = place?.mode === "sandbox" && place.box !== "daytona" ? undefined : this.options.remoteApi;
|
|
960
1295
|
return api && (() => wakeBoxes(api, (id) => id === runId));
|
|
961
1296
|
}
|
|
962
1297
|
/** Pulls run `run`'s remote box into its work/, after any pull already running: at a turn's end in the background (a
|
|
963
1298
|
* failure warns, and the next pull brings it), or awaited (`strict`: a failure throws). */
|
|
964
1299
|
pullBox(run, strict = false) {
|
|
965
|
-
const boxes = this.options.remoteBoxes;
|
|
966
1300
|
const place = run.meta.place;
|
|
967
|
-
|
|
1301
|
+
const boxes = place && remotePlace(place) ? this.remoteOf(place) : undefined;
|
|
1302
|
+
if (!boxes || !place)
|
|
968
1303
|
return Promise.resolve();
|
|
969
1304
|
// After any pull already running, and after the box's making and seed when one is under way.
|
|
970
1305
|
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));
|
|
1306
|
+
const pulled = await pullRemoteBox(boxes, run, boxContext(REMOTE_SYNC_MS), this.wakeOf(run.id, place));
|
|
972
1307
|
if (pulled)
|
|
973
1308
|
this.options.log?.("box_pulled", { run: run.id, changed: pulled.changed, files: pulled.files, bytes: pulled.bytes, removed: pulled.removed });
|
|
974
1309
|
});
|
|
@@ -995,17 +1330,33 @@ export class Runs {
|
|
|
995
1330
|
/** Whether run `id` is one this server holds in a remote box and has not ended: the relay serves no other. */
|
|
996
1331
|
servesBox(id) {
|
|
997
1332
|
const run = this.runs.get(id);
|
|
998
|
-
return Boolean(
|
|
1333
|
+
return Boolean(run && !run.outcome && run.meta.place && remotePlace(run.meta.place) && this.remoteOf(run.meta.place));
|
|
1334
|
+
}
|
|
1335
|
+
/** The server's provider of a remote place's boxes: the VM box's, or Daytona's. */
|
|
1336
|
+
remoteOf(place) {
|
|
1337
|
+
return place.mode === "sandbox" && place.box === VM_PROVIDER.id ? this.options.vmBoxes : this.options.remoteBoxes;
|
|
999
1338
|
}
|
|
1000
1339
|
/** Run `id`'s remote box, found or made and seeded: what its process asks the relay for at its first tool call. */
|
|
1001
1340
|
ensureBox(id) {
|
|
1002
1341
|
const run = this.runs.get(id);
|
|
1003
|
-
const
|
|
1004
|
-
|
|
1342
|
+
const place = run?.meta.place;
|
|
1343
|
+
const boxes = place && this.remoteOf(place);
|
|
1344
|
+
if (!run || !place || !boxes || !this.servesBox(id))
|
|
1005
1345
|
return Promise.reject(new Error(`no run ${id} of this server is in a remote box`));
|
|
1346
|
+
// The VM box has no network (its provider's host list cannot be read back), and takes the box limits.
|
|
1347
|
+
const vm = place.mode === "sandbox" && place.box === VM_PROVIDER.id;
|
|
1006
1348
|
// After any pull of this run's box, so a seed never meets a pull.
|
|
1007
1349
|
run.boxing ??= (run.pulling ?? Promise.resolve())
|
|
1008
|
-
.then(() => ensureRemoteBox(boxes, run, boxContext(REMOTE_SYNC_MS), this.
|
|
1350
|
+
.then(() => ensureRemoteBox(boxes, run, boxContext(REMOTE_SYNC_MS), vm ? { allow: "none", ...(this.options.vmLimits ? { limits: this.options.vmLimits } : {}) } : {
|
|
1351
|
+
wake: this.wakeOf(run.id, place),
|
|
1352
|
+
allow: (this.remoteAllow ??= this.options.boxAllow ?? "none"),
|
|
1353
|
+
onNoList: (code, message) => {
|
|
1354
|
+
if (this.remoteAllow === "none")
|
|
1355
|
+
return;
|
|
1356
|
+
this.remoteAllow = "none";
|
|
1357
|
+
this.options.onNoBoxList?.(code, message);
|
|
1358
|
+
},
|
|
1359
|
+
}))
|
|
1009
1360
|
.finally(() => void (run.boxing = undefined));
|
|
1010
1361
|
return run.boxing;
|
|
1011
1362
|
}
|
|
@@ -1027,7 +1378,7 @@ export class Runs {
|
|
|
1027
1378
|
/** 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
1379
|
* now when its process is gone, else when it exits. */
|
|
1029
1380
|
async archived() {
|
|
1030
|
-
if (!this.options.box && !this.options.runBoxes && !this.options.remoteBoxes)
|
|
1381
|
+
if (!this.options.box && !this.options.runBoxes && !this.options.remoteBoxes && !this.options.vmBoxes)
|
|
1031
1382
|
return;
|
|
1032
1383
|
for (const row of await this.options.agents.request(() => this.store.listRuns())) {
|
|
1033
1384
|
if (!row.archivedAt)
|
|
@@ -1047,7 +1398,8 @@ export class Runs {
|
|
|
1047
1398
|
// The learning a server left between steps, picked up once every running run is read (learning-run.ts).
|
|
1048
1399
|
const recoverLearning = this.learning.recover();
|
|
1049
1400
|
await this.sweepOnce();
|
|
1050
|
-
|
|
1401
|
+
// Only what an earlier server left: a store slow to answer here must not hand back a run a create is setting up now.
|
|
1402
|
+
const rows = (await this.options.agents.request(() => this.store.listRuns())).filter((row) => row.startedAt < this.bootedAt);
|
|
1051
1403
|
for (const row of rows) {
|
|
1052
1404
|
if (row.state !== "running" || row.importedFrom)
|
|
1053
1405
|
continue;
|
|
@@ -1071,7 +1423,7 @@ export class Runs {
|
|
|
1071
1423
|
run.updatedAt = new Date().toISOString();
|
|
1072
1424
|
// What it waits on: an ask_person question (waiting), else a stopped turn, for the person's next message.
|
|
1073
1425
|
if (status === "input_required")
|
|
1074
|
-
this.notice(run, "run.needs_input", waitMark(run), { kind: state
|
|
1426
|
+
this.notice(run, "run.needs_input", waitMark(run), { kind: state !== "waiting" ? "stopped" : waitingApproval(run) ? "approval" : pausedAt(run) !== undefined ? "budget" : "question" });
|
|
1075
1427
|
}
|
|
1076
1428
|
/** Tells webhooks.ts (`notify`) of a moment of the run under `marker`: a wait it reached (mark), or an end the agent store
|
|
1077
1429
|
* has (settle, persistLater, reopen). What it already queued it queues no more. */
|
|
@@ -1169,8 +1521,11 @@ export class Runs {
|
|
|
1169
1521
|
// snapshot of them on a (re)connect (pi-durable-disk's `inputs`), read as their whole state.
|
|
1170
1522
|
const submissions = events.flatMap((e) => (e.type === "submission" && e.record !== undefined ? [e.record] : []));
|
|
1171
1523
|
const inputs = events.find((e) => e.type === "snapshot" && Array.isArray(e.inputs))?.inputs;
|
|
1172
|
-
|
|
1173
|
-
|
|
1524
|
+
const entries = events.flatMap((e) => (Array.isArray(e.entries) ? e.entries : e.entry !== undefined ? [e.entry] : []));
|
|
1525
|
+
noteTurns(run, entries, submissions, inputs);
|
|
1526
|
+
noteApprovals(run, entries);
|
|
1527
|
+
const redact = this.redactor(run);
|
|
1528
|
+
reducer.apply(events.map((e) => (Array.isArray(e.entries) ? { ...e, entries: redactGateMessages(e.entries, redact) } : e.entry !== undefined ? { ...e, entry: redactGateMessages([e.entry], redact)[0] } : e)));
|
|
1174
1529
|
// 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
1530
|
// as the settled read counts it, never one in flight.
|
|
1176
1531
|
if (!run.working && stopped(run))
|
|
@@ -1222,7 +1577,7 @@ export class Runs {
|
|
|
1222
1577
|
continue;
|
|
1223
1578
|
}
|
|
1224
1579
|
if (launched)
|
|
1225
|
-
throw new ApiError("internal", `the run's process exited before it served: ${await
|
|
1580
|
+
throw new ApiError("internal", `the run's process exited before it served: ${await this.lastLine(run)}`);
|
|
1226
1581
|
const pid = holderPid(record);
|
|
1227
1582
|
const fresh = record?.status === "running" && typeof record.heartbeatAt === "string" && Date.now() - Date.parse(record.heartbeatAt) < LEASE_MS && (pid === undefined || alive(pid));
|
|
1228
1583
|
// A run already going is never refused a place, but one whose harness this host's memory never holds (after a
|
|
@@ -1230,8 +1585,14 @@ export class Runs {
|
|
|
1230
1585
|
const never = fresh ? undefined : neverFits(run.harness, this.memory);
|
|
1231
1586
|
if (never)
|
|
1232
1587
|
throw new ApiError("agent_not_runnable", never, { details: { unbound: [], missing: {}, harness: run.harness } });
|
|
1233
|
-
|
|
1234
|
-
|
|
1588
|
+
// Its sign-in pinned only for a launch: a run whose process still serves keeps the one it was handed.
|
|
1589
|
+
if (!fresh) {
|
|
1590
|
+
await this.pinSignIn(run);
|
|
1591
|
+
if (run.outcome || run.finishing || run.cancel || this.live(run))
|
|
1592
|
+
continue;
|
|
1593
|
+
this.launch(run);
|
|
1594
|
+
launched = true;
|
|
1595
|
+
}
|
|
1235
1596
|
}
|
|
1236
1597
|
if (Date.now() > deadline)
|
|
1237
1598
|
throw new ApiError("unavailable", "the run did not come up in time", { retry_after_ms: 1000 }, { "retry-after": "1" });
|
|
@@ -1262,9 +1623,12 @@ export class Runs {
|
|
|
1262
1623
|
await fetch(new URL("/abort", door), { method: "POST", headers: this.headers(run, true), body: "{}", signal: AbortSignal.timeout(5_000) }).catch(() => undefined);
|
|
1263
1624
|
}
|
|
1264
1625
|
/** 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),
|
|
1266
|
-
* the
|
|
1626
|
+
* while it opens or parks. `turnOrigin`: who sent a turn this request sends (learning-run.ts's REFLECT_ORIGIN), kept in
|
|
1627
|
+
* the run's directory before it goes, where the tool gate reads it (tool-gate.ts NOTE_ONLY_TEXT); a person's message
|
|
1628
|
+
* removes it. */
|
|
1267
1629
|
async toLiveDoor(run, path, body, turnOrigin) {
|
|
1630
|
+
if (turnOrigin)
|
|
1631
|
+
await (run.originWrite = writeWhole(join(run.dir, TURN_ORIGIN_FILE), `${JSON.stringify({ origin: turnOrigin })}\n`));
|
|
1268
1632
|
for (const deadline = Date.now() + 30_000;; await sleep(200)) {
|
|
1269
1633
|
if (!this.live(run) || run.cancel)
|
|
1270
1634
|
throw new Error("the run's process is gone");
|
|
@@ -1305,6 +1669,24 @@ export class Runs {
|
|
|
1305
1669
|
const revision = given ?? (await whenFree(() => this.store.readRevision(run.revision), this.busyDelays(), this.onBusy(run.id, "the agent store")));
|
|
1306
1670
|
this.needs.set(run.revision, await needsOf(revision));
|
|
1307
1671
|
}
|
|
1672
|
+
/** The saved sign-in the run's browser starts from (sign-ins.ts), resolved before each launch: made at the vendor when
|
|
1673
|
+
* its agent has none, and leased to this run to save unless another run of the agent holds the lease. One that cannot
|
|
1674
|
+
* be had (the vendor not answering, a seal key changed) leaves its browser signed out, said in its log. */
|
|
1675
|
+
async pinSignIn(run) {
|
|
1676
|
+
// Its browser as this launch will find it (launch: a vendor whose key is gone since is unavailable, and gets none).
|
|
1677
|
+
const browser = run.meta.tool_plane && recheckPlane(run.meta.tool_plane, withSecrets(process.env, "all", this.options.storedKeys)).browser;
|
|
1678
|
+
const signIns = this.options.signIns;
|
|
1679
|
+
run.signIn = browser && signIns ? ((await signIns.forRun(run.agentId, run.id, browser).catch((error) => void warn(run.id, `its browser starts signed out: ${error.message}`))) ?? undefined) : undefined;
|
|
1680
|
+
// Never shown in its errors, from now on: a server started since its launch has handed it nothing yet.
|
|
1681
|
+
if (run.signIn && run.signIn.ref.length >= MIN_SECRET)
|
|
1682
|
+
(run.handed ??= new Set()).add(run.signIn.ref);
|
|
1683
|
+
}
|
|
1684
|
+
/** Lets go of the save lease the run holds on its agent's sign-in, if any: at once when its process let its sessions go
|
|
1685
|
+
* (`clean`), else by the gone rule (sign-ins.ts). */
|
|
1686
|
+
async releaseSignIn(run, clean = true) {
|
|
1687
|
+
run.signIn = undefined;
|
|
1688
|
+
await this.options.signIns?.release(run.agentId, run.id, run.dir, clean).catch((error) => warn(run.id, `its sign-in's save lease is not let go: ${error.message}`));
|
|
1689
|
+
}
|
|
1308
1690
|
launch(run, followUp = run.followUpOpen === true) {
|
|
1309
1691
|
if (run.child || this.closing || run.cancel || run.outcome || run.finishing || run.preparing)
|
|
1310
1692
|
return;
|
|
@@ -1318,7 +1700,8 @@ export class Runs {
|
|
|
1318
1700
|
const served = withSecrets(process.env, "all", this.options.storedKeys);
|
|
1319
1701
|
const needs = this.needs.get(run.revision);
|
|
1320
1702
|
const handed = needs ? keysFor(needs, served) : NO_TOOL_KEYS;
|
|
1321
|
-
|
|
1703
|
+
// And its saved sign-in, on the same pipe after them (pinSignIn): a pointer its browser opens, never in its environment.
|
|
1704
|
+
const secrets = run.signIn ? Buffer.concat([handover(handed, this.options.storedKeys), handoverSignIn(run.signIn)]) : handover(handed, this.options.storedKeys);
|
|
1322
1705
|
// What it was handed, for the check of what its end-of-run turn writes (learning-run.ts).
|
|
1323
1706
|
this.learning.onLaunch(run, handed);
|
|
1324
1707
|
// And for what its errors show (refusedValues): each value handed, kept past a key's rotation.
|
|
@@ -1328,8 +1711,12 @@ export class Runs {
|
|
|
1328
1711
|
if (value && value.length >= MIN_SECRET)
|
|
1329
1712
|
run.handed.add(value);
|
|
1330
1713
|
}
|
|
1714
|
+
if (run.signIn && run.signIn.ref.length >= MIN_SECRET)
|
|
1715
|
+
run.handed.add(run.signIn.ref);
|
|
1331
1716
|
const env = {
|
|
1332
1717
|
...childEnv(process.env, this.options.token),
|
|
1718
|
+
// The run's box's network, as the server resolved it: never the setting itself, which the run's process ignores.
|
|
1719
|
+
[RUN_BOX_ALLOW_ENV]: this.options.dockerAllow === undefined || this.options.dockerAllow === "none" ? "none" : this.options.dockerAllow.join(","),
|
|
1333
1720
|
[SECRETS_FD_ENV]: "3",
|
|
1334
1721
|
[SECRETS_LEN_ENV]: String(secrets.length),
|
|
1335
1722
|
...this.fauxEnv(),
|
|
@@ -1360,17 +1747,31 @@ export class Runs {
|
|
|
1360
1747
|
// Its tools' providers (tool-plane.ts): resolved at its first launch from its pinned revision and this server's
|
|
1361
1748
|
// settings, and kept in its serve.json, so a later change of the settings never changes a run's tools; at a later
|
|
1362
1749
|
// 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
|
|
1750
|
+
// in the serve.json its start writes (start); resolving here is for a run made before that, whose browser stays
|
|
1751
|
+
// Browserbase (keptFromBefore), the vendor it had then, kept as its choice and checked again at each launch like the
|
|
1752
|
+
// rest; a vendor's missing-key refusal an earlier server saved reads as that vendor again (keptVendor), saved back. A
|
|
1753
|
+
// description with no secret
|
|
1364
1754
|
// 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
1755
|
// does (secrets.ts), so a saved Parallel key makes Parallel available, and a deleted one unavailable at the next launch.
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1756
|
+
// A capability set to ask or deny since resolves again (a harness's own search cannot wait for a person). Its first
|
|
1757
|
+
// launch, from its start, is told a deny as under ask; a later one is told it denied (relaunchPlane).
|
|
1758
|
+
const settings = this.options.toolSettings?.() ?? {};
|
|
1759
|
+
const capped = run.meta.max_cost_usd !== undefined;
|
|
1760
|
+
const first = run.firstLaunch === true;
|
|
1761
|
+
run.firstLaunch = undefined;
|
|
1762
|
+
const kept = run.meta.tool_plane ? keptVendor(run.meta.tool_plane) : run.tooling ? keptFromBefore(planeFor(served, run.tooling, settings, { capped })) : {};
|
|
1763
|
+
const plane = relaunchPlane(kept, served, run.tooling, settings, { capped, first });
|
|
1764
|
+
if (kept !== run.meta.tool_plane && Object.keys(kept).length) {
|
|
1765
|
+
run.meta.tool_plane = kept;
|
|
1369
1766
|
void this.saveMeta(run).catch(() => undefined);
|
|
1370
1767
|
}
|
|
1371
1768
|
delete env[TOOL_PLANE_ENV];
|
|
1372
1769
|
if (Object.keys(plane).length)
|
|
1373
1770
|
env[TOOL_PLANE_ENV] = JSON.stringify(plane);
|
|
1771
|
+
// No one can approve here (accounts off): the run's gate refuses an ask instead of parking it (tool-gate.ts).
|
|
1772
|
+
delete env[NO_APPROVER_ENV];
|
|
1773
|
+
if (this.options.approvers === false)
|
|
1774
|
+
env[NO_APPROVER_ENV] = "1";
|
|
1374
1775
|
// The decision keys are never in a run's environment, which its tools and its model's provider read (childEnv leaves
|
|
1375
1776
|
// out every secret): a run's process gets those it needs once on an inherited pipe, by name: its decision
|
|
1376
1777
|
// providers' (decisionProvidersFor), and Parallel's where one of its web tools resolves to Parallel (its plane,
|
|
@@ -1490,9 +1891,13 @@ export class Runs {
|
|
|
1490
1891
|
run.working = false;
|
|
1491
1892
|
const record = await this.record(run);
|
|
1492
1893
|
const released = RELEASED.has(String(record?.status));
|
|
1894
|
+
run.letGo = released;
|
|
1493
1895
|
const pid = holderPid(record);
|
|
1494
1896
|
// A process that is gone serves no door, whatever its last heartbeat says.
|
|
1495
1897
|
const gone = !this.live(run) && !(pid !== undefined && pid !== process.pid && alive(pid) && this.doorOf(record));
|
|
1898
|
+
// Its sign-in's save lease stays with it (below), but no longer than a session it opened could outlive its process.
|
|
1899
|
+
if (gone)
|
|
1900
|
+
await this.options.signIns?.markGone(run.agentId, run.id).catch((error) => warn(run.id, `its sign-in's lease is not marked: ${error.message}`));
|
|
1496
1901
|
// Its metrics are this settle's read, or none: never an earlier end's.
|
|
1497
1902
|
run.metrics = undefined;
|
|
1498
1903
|
if (released || gone)
|
|
@@ -1511,12 +1916,21 @@ export class Runs {
|
|
|
1511
1916
|
ended = run.kind === "workflow" ? await this.workflowEnd(run, workflowEnding(record) ?? { status: "stopped" }) : { outcome: "cancelled" };
|
|
1512
1917
|
else if (run.finishing)
|
|
1513
1918
|
ended = { outcome: run.finishing };
|
|
1919
|
+
else if (run.notSetUp && gone) {
|
|
1920
|
+
run.error = { code: "run_failed", message: "The server went down while it set the run up, before it saved the run's input; the run never started, and a new one can.", retryable: false, details: { reason: SETUP_LOST } };
|
|
1921
|
+
ended = { outcome: "failed" };
|
|
1922
|
+
}
|
|
1514
1923
|
else if (run.launching && gone) {
|
|
1515
1924
|
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
1925
|
ended = { outcome: "failed" };
|
|
1517
1926
|
}
|
|
1927
|
+
else if (exited && !released && code !== null && code !== 0 && (run.resuming !== undefined || continuationOf(run) !== undefined)) {
|
|
1928
|
+
// A raised run's paused process held nothing (its turn had ended at the refusal): its exit without a release, at
|
|
1929
|
+
// its drain's end, say, loses nothing, and the raise's follow-up goes (resumeRaised), never a failed run.
|
|
1930
|
+
return this.refresh(run);
|
|
1931
|
+
}
|
|
1518
1932
|
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
|
|
1933
|
+
run.error = { code: "run_failed", message: `The run's process exited (${code}) without releasing the run: ${await this.lastLine(run)}`, retryable: false };
|
|
1520
1934
|
ended = { outcome: "failed" };
|
|
1521
1935
|
}
|
|
1522
1936
|
else if (!gone && this.doorOf(record))
|
|
@@ -1532,16 +1946,25 @@ export class Runs {
|
|
|
1532
1946
|
if (!ended) {
|
|
1533
1947
|
// Work left and no process: opened again. A run that waits for the person waits without one, until a message.
|
|
1534
1948
|
const stalled = run.kind === "workflow" || statusOf(run).status !== "input_required";
|
|
1535
|
-
|
|
1949
|
+
// Its sign-in's save lease stays with it until it ends (carryBack), through a relaunch or a restart: a session it
|
|
1950
|
+
// opened before its process went may still be live at the vendor, and would write back over another run's. One
|
|
1951
|
+
// that let go cleanly to wait for its person released its sessions first, so its lease goes now.
|
|
1952
|
+
if (gone && released && !stalled)
|
|
1953
|
+
await this.releaseSignIn(run);
|
|
1954
|
+
// A raised run's follow-up, under way or still to go, opens the run's next process itself (resumeRaised): its
|
|
1955
|
+
// paused process going is no process lost, and no relaunch is counted for it.
|
|
1956
|
+
const continuing = run.resuming !== undefined || continuationOf(run) !== undefined || run.child !== undefined;
|
|
1957
|
+
if (!gone || !stalled || this.closing || continuing)
|
|
1536
1958
|
return this.refresh(run);
|
|
1537
1959
|
// Opened again without a place, as a run already going, unless its harness never fits this host (a restart on a
|
|
1538
1960
|
// smaller one): that run fails with why.
|
|
1539
1961
|
const never = neverFits(run.harness, this.memory);
|
|
1540
1962
|
if (!never && run.relaunches < MAX_RELAUNCHES) {
|
|
1541
1963
|
await this.pinNeeds(run);
|
|
1964
|
+
await this.pinSignIn(run);
|
|
1542
1965
|
return this.relaunch(run);
|
|
1543
1966
|
}
|
|
1544
|
-
run.error = { code: "run_failed", message: never ?? `The run's process went ${MAX_RELAUNCHES + 1} times before the run ended: ${await
|
|
1967
|
+
run.error = { code: "run_failed", message: never ?? `The run's process went ${MAX_RELAUNCHES + 1} times before the run ended: ${await this.lastLine(run)}`, retryable: false };
|
|
1545
1968
|
ended = { outcome: "failed" };
|
|
1546
1969
|
}
|
|
1547
1970
|
await this.carryBack(run, ended.outcome, ended.state, ended.summary);
|
|
@@ -1582,6 +2005,9 @@ export class Runs {
|
|
|
1582
2005
|
/** 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
2006
|
* another writer is tried again with backoff; past the last try the run stays unsettled, and the next start carries it back. */
|
|
1584
2007
|
async carryBack(run, outcome, state, summary) {
|
|
2008
|
+
// Ended, it saves to its agent's sign-in no more; but a process that went without letting its sessions go may have
|
|
2009
|
+
// left one live at the vendor, so its lease then ends by the gone rule. One never launched (letGo unset) has none.
|
|
2010
|
+
await this.releaseSignIn(run, run.letGo !== false);
|
|
1585
2011
|
// 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
2012
|
// A remote box's last pull lands first: the end is not recorded until its files are in work/.
|
|
1587
2013
|
await this.dropBox(run, true);
|
|
@@ -1788,18 +2214,23 @@ export class Runs {
|
|
|
1788
2214
|
// Its tools' providers, resolved before the run exists (tool-plane.ts) and kept in the serve.json its start writes first,
|
|
1789
2215
|
// 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
2216
|
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 }) : {};
|
|
2217
|
+
const plane = tooling ? planeFor(withSecrets(process.env, "all", this.options.storedKeys), tooling, this.options.toolSettings?.() ?? {}, { capped: options.maxCostUsd !== undefined, run: true }) : {};
|
|
1792
2218
|
// A run that learns: its seed read before it is made (learning-run.ts).
|
|
1793
2219
|
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"));
|
|
2220
|
+
const started = await this.options.agents.request(() => this.store.startRun({ agent: entry.agent.id, revision: revision.id, ...(options.origin ? { origin: options.origin } : {}) })).catch((error) => storeError(error, "revision"));
|
|
2221
|
+
// Only another writer of the store gets here first under the same origin: its run is the one asked for, set up by it.
|
|
2222
|
+
if (started.existing)
|
|
2223
|
+
return (await this.get(started.runId));
|
|
1795
2224
|
const at = new Date().toISOString();
|
|
1796
2225
|
const meta = {
|
|
1797
|
-
|
|
2226
|
+
// Shown on the run list and its view: no held secret a person pasted into the message it is taken from.
|
|
2227
|
+
title: clip(redacted(options.title.trim().replace(/\s+/g, " "), [...hostSecrets(process.env, this.options.storedKeys), this.options.token, this.options.doorToken]), 80),
|
|
1798
2228
|
created_at: at,
|
|
1799
2229
|
input: options.input,
|
|
1800
2230
|
place: options.place,
|
|
1801
2231
|
...(options.effort ? { effort: options.effort } : {}),
|
|
1802
2232
|
...(options.maxCostUsd !== undefined ? { max_cost_usd: options.maxCostUsd } : {}),
|
|
2233
|
+
...(options.trigger ? { trigger: options.trigger } : {}),
|
|
1803
2234
|
...(Object.keys(plane).length ? { tool_plane: plane } : {}),
|
|
1804
2235
|
};
|
|
1805
2236
|
// 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
|
|
@@ -1814,6 +2245,7 @@ export class Runs {
|
|
|
1814
2245
|
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
2246
|
// Before the run is known here, so nothing launches it first.
|
|
1816
2247
|
await this.pinNeeds(run, revision);
|
|
2248
|
+
await this.pinSignIn(run);
|
|
1817
2249
|
this.runs.set(run.id, run);
|
|
1818
2250
|
// A seed that failed is a learning row from the start, and its learning's end is in the ledger.
|
|
1819
2251
|
this.show(run);
|
|
@@ -1830,6 +2262,7 @@ export class Runs {
|
|
|
1830
2262
|
if (!(await prepared))
|
|
1831
2263
|
return run;
|
|
1832
2264
|
}
|
|
2265
|
+
run.firstLaunch = true;
|
|
1833
2266
|
this.launch(run);
|
|
1834
2267
|
if (revision.kind === "workflow")
|
|
1835
2268
|
return run;
|
|
@@ -1873,9 +2306,18 @@ export class Runs {
|
|
|
1873
2306
|
this.reportedBack(run);
|
|
1874
2307
|
return true;
|
|
1875
2308
|
}
|
|
1876
|
-
|
|
2309
|
+
/** One message to the run's door. `origin`: who wrote it when the person did not (a raised cap's follow-up, an
|
|
2310
|
+
* approval's resume), carried to its user entry so the Timeline shows it as the server's (pi-durable-agent's
|
|
2311
|
+
* MessageOrigin); the model reads the same text either way. `answers: false`: the run's door refuses the message
|
|
2312
|
+
* (WAITING) when the run's turn ended on ask_person, and when the run is busy (BUSY), so it is never queued behind a
|
|
2313
|
+
* turn that may end so; decided at the door's admission, past every wait here. */
|
|
2314
|
+
async submit(run, content, whenBusy, requestId, readyMs, origin, answers = true) {
|
|
1877
2315
|
await this.beforeSubmit?.(run.id, content);
|
|
1878
|
-
const answer = await this.toDoor(run, "/submit", { requestId, content, whenBusy }, readyMs);
|
|
2316
|
+
const answer = await this.toDoor(run, "/submit", { requestId, content, whenBusy, ...(origin ? { origin } : {}), ...(answers ? {} : { answers: false, asks: [ASK_TOOL] }) }, readyMs);
|
|
2317
|
+
if (answer.status === 409 && answer.body?.error === "WAITING")
|
|
2318
|
+
throw new ApiError("not_continuable", WAITS_ON_A_PERSON, { details: { reason: "waiting" } });
|
|
2319
|
+
if (answer.status === 409 && answer.body?.error === "BUSY" && !answers)
|
|
2320
|
+
throw new ApiError("rate_limited", "The run is working: a message that may not answer it waits until it is idle.", { retry_after_ms: 5_000, details: { reason: "working" } });
|
|
1879
2321
|
if (answer.status >= 400)
|
|
1880
2322
|
throw new ApiError(answer.status === 409 ? "not_continuable" : "internal", String(answer.body?.message ?? answer.body?.error ?? "the run refused the message"));
|
|
1881
2323
|
}
|
|
@@ -1883,13 +2325,186 @@ export class Runs {
|
|
|
1883
2325
|
steers(run) {
|
|
1884
2326
|
return run.kind !== "agentic" || steersMidTurn(run.harness);
|
|
1885
2327
|
}
|
|
1886
|
-
/**
|
|
1887
|
-
|
|
2328
|
+
/** Whether the run's store already took a message under `requestId`: a trigger's firing sent it, and the server went
|
|
2329
|
+
* down before it wrote so. Read before sending it again, so a completed run is not opened again for a message it
|
|
2330
|
+
* already has. Only for a run with no live process: a live one holds its store, and takes the message through its
|
|
2331
|
+
* door, which takes one per id anyway. The store keeps the id as JSON text, as pi submits it, or as a harness's door
|
|
2332
|
+
* keeps its journal (doorKey), where a busy refusal is not a message taken (doorTook). A store held past the retries
|
|
2333
|
+
* throws as busy. */
|
|
2334
|
+
async tookMessage(run, requestId) {
|
|
2335
|
+
if (this.live(run))
|
|
2336
|
+
return false;
|
|
2337
|
+
const file = this.storeFile(run);
|
|
2338
|
+
if (!(await stat(file).catch(() => null)))
|
|
2339
|
+
return false;
|
|
2340
|
+
const { DatabaseSync } = await import("node:sqlite");
|
|
2341
|
+
return whenFree(async () => {
|
|
2342
|
+
const db = new DatabaseSync(file, { readOnly: true });
|
|
2343
|
+
try {
|
|
2344
|
+
if (db.prepare("SELECT 1 FROM submissions WHERE request_id = ? LIMIT 1").get(JSON.stringify(requestId)) !== undefined)
|
|
2345
|
+
return true;
|
|
2346
|
+
const status = db.prepare("SELECT json_extract(e.record, '$.data.status') AS status FROM submissions s JOIN entries e ON e.id = json_extract(s.record, '$.entry') WHERE s.request_id = ? LIMIT 1");
|
|
2347
|
+
return await doorTook(requestId, (key) => status.get(JSON.stringify(key))?.status ?? undefined);
|
|
2348
|
+
}
|
|
2349
|
+
catch (error) {
|
|
2350
|
+
// A store that keeps no submissions has taken none.
|
|
2351
|
+
if (/no such table/.test(error.message))
|
|
2352
|
+
return false;
|
|
2353
|
+
throw error;
|
|
2354
|
+
}
|
|
2355
|
+
finally {
|
|
2356
|
+
db.close();
|
|
2357
|
+
}
|
|
2358
|
+
}, this.busyDelays(), this.onBusy(run.id, "its store"));
|
|
2359
|
+
}
|
|
2360
|
+
/** Raises the cap of an agentic run that names one, to `cap`: above its own (by more than CAP_TOLERANCE), or the same as
|
|
2361
|
+
* its newest raise (a retry, which changes nothing). serve.json keeps it before any answer, and a raise it could not keep
|
|
2362
|
+
* is undone, so the run's next process opens under it (CAP_ENV), as does a server started again. A run paused at its
|
|
2363
|
+
* cap goes on: the raise names the pause it answers, and the pause gets one follow-up, "The cap was raised to $X;
|
|
2364
|
+
* continue the task." under an id fixed now, which refresh sends once the paused process is gone (resumeRaised), here
|
|
2365
|
+
* or after a restart; a second raise before it goes raises what it says. A run working keeps the cap its process was
|
|
2366
|
+
* opened with until its next process. Raises of one run are taken one at a time. */
|
|
2367
|
+
async raiseCap(run, cap) {
|
|
2368
|
+
const before = run.raising ?? Promise.resolve();
|
|
2369
|
+
const taking = before.catch(() => undefined).then(() => this.takeRaise(run, cap));
|
|
2370
|
+
run.raising = taking.catch(() => undefined);
|
|
2371
|
+
return taking;
|
|
2372
|
+
}
|
|
2373
|
+
async takeRaise(run, cap) {
|
|
2374
|
+
if (run.imported)
|
|
2375
|
+
throw this.importedRefusal(run);
|
|
2376
|
+
if (run.cancel || run.finishing || TERMINAL.has(statusOf(run).status))
|
|
2377
|
+
throw this.finished(run);
|
|
2378
|
+
const from = run.meta.max_cost_usd;
|
|
2379
|
+
if (from === undefined)
|
|
2380
|
+
throw invalid([{ field: "max_cost_usd", reason: "not_allowed", message: "This run has no cap to raise: a cap is named when a run starts." }]);
|
|
2381
|
+
const last = run.meta.cap_raised?.at(-1);
|
|
2382
|
+
const pause = pauseOf(run);
|
|
2383
|
+
const next = continuationOf(run);
|
|
2384
|
+
// The same raise again (a retry): what the first one did stands.
|
|
2385
|
+
if (Math.abs(cap - from) <= CAP_TOLERANCE && last && Math.abs(last.to - cap) <= CAP_TOLERANCE) {
|
|
2386
|
+
// Resumed, as the first answer said, unless the run has since paused anew at another refusal: no raise of that one.
|
|
2387
|
+
const answered = last.pause !== undefined && run.meta.cap_continue?.pause === last.pause && (pause === undefined || pause === last.pause) ? run.meta.cap_continue : undefined;
|
|
2388
|
+
return answered ? { resumed: true, messageId: answered.message_id } : { resumed: false };
|
|
2389
|
+
}
|
|
2390
|
+
if (!(cap > from + CAP_TOLERANCE))
|
|
2391
|
+
throw invalid([{ field: "max_cost_usd", reason: "invalid", message: `A cap is only raised: name more than the run's ${money(from)}.` }]);
|
|
2392
|
+
// Built on a copy and written first: nothing reads the raise (its cap, the pause it answers, its follow-up) before
|
|
2393
|
+
// serve.json keeps it, so until then a message is still 409 budget_reached, the run reads its old cap and no
|
|
2394
|
+
// follow-up goes; a raise the write fails leaves the run as it was, and a retry raises it again.
|
|
2395
|
+
const raised = [...(run.meta.cap_raised ?? []), { from, to: cap, at: new Date().toISOString(), ...(pause ? { pause } : {}) }];
|
|
2396
|
+
let follow = run.meta.cap_continue;
|
|
2397
|
+
if (pause !== undefined && next === undefined) {
|
|
2398
|
+
// The pause's one follow-up, by an id fixed now, and the process being let go then, which it waits out.
|
|
2399
|
+
const paused = this.live(run) ? this.liveIdentity(run) : undefined;
|
|
2400
|
+
follow = { pause, message_id: `cap-${raised.length}-${randomBytes(4).toString("hex")}`, sent: false, tries: 0, ...(paused ? { paused } : {}) };
|
|
2401
|
+
}
|
|
2402
|
+
else if (next) {
|
|
2403
|
+
// A raise of a pause whose follow-up has not gone: that one follow-up goes, under this cap, with its tries anew.
|
|
2404
|
+
const { error: _, ...rest } = next;
|
|
2405
|
+
follow = { ...rest, tries: 0 };
|
|
2406
|
+
}
|
|
2407
|
+
await this.saveMeta(run, () => ({ ...run.meta, max_cost_usd: cap, cap_raised: raised, ...(follow ? { cap_continue: follow } : {}) }));
|
|
2408
|
+
run.meta.max_cost_usd = cap;
|
|
2409
|
+
run.meta.cap_raised = raised;
|
|
2410
|
+
if (next && follow) {
|
|
2411
|
+
// The same follow-up object resumeRaised may hold, renewed in place.
|
|
2412
|
+
next.tries = 0;
|
|
2413
|
+
delete next.error;
|
|
2414
|
+
}
|
|
2415
|
+
else if (follow)
|
|
2416
|
+
run.meta.cap_continue = follow;
|
|
2417
|
+
if (next && typeof run.resuming === "number")
|
|
2418
|
+
run.resuming = undefined;
|
|
2419
|
+
this.refresh(run);
|
|
2420
|
+
const answered = pause !== undefined ? run.meta.cap_continue : undefined;
|
|
2421
|
+
if (!answered)
|
|
2422
|
+
return { resumed: false, ...(this.live(run) ? { note: `The run's process keeps the ${money(from)} cap it was opened with; the ${money(cap)} cap holds from its next process.` } : {}) };
|
|
2423
|
+
return { resumed: true, messageId: answered.message_id };
|
|
2424
|
+
}
|
|
2425
|
+
/** Sends a raised run its pause's follow-up, under its id (the door takes one id once), at the run's cap now: as a
|
|
2426
|
+
* follow-up to a run whose process has gone (message()), so the process it starts resumes nothing and opens under the
|
|
2427
|
+
* new cap, or to the process another launch started. Marked sent in serve.json. One that cannot be sent is tried
|
|
2428
|
+
* again (CONTINUE_RETRY_MS), and after CONTINUE_TRIES the run fails, saying why: never a pause stuck in silence. */
|
|
2429
|
+
async resumeRaised(run, next) {
|
|
2430
|
+
run.resuming = "sending";
|
|
2431
|
+
if (!this.live(run))
|
|
2432
|
+
run.followUpOpen = true;
|
|
2433
|
+
run.submitted++;
|
|
2434
|
+
this.refresh(run);
|
|
2435
|
+
const cap = run.meta.max_cost_usd ?? 0;
|
|
2436
|
+
try {
|
|
2437
|
+
// The server's line, shown as the server's (MessageOrigin), never as the person's: the model reads the same text.
|
|
2438
|
+
await this.submit(run, `The cap was raised to ${money(cap)}; continue the task.`, "followUp", next.message_id, undefined, { kind: "server", reason: "cap_raised" });
|
|
2439
|
+
// Marked sent once serve.json says so. Should that write fail, it went all the same (the door holds it), and its
|
|
2440
|
+
// run no longer stands at the pause, so nothing sends it again.
|
|
2441
|
+
await this.saveMeta(run, () => ({ ...run.meta, cap_continue: { ...next, sent: true } })).then(() => void (next.sent = true), (error) => warn(run.id, `its raised cap's follow-up went, but is not marked sent: ${error.message}`));
|
|
2442
|
+
run.resuming = undefined;
|
|
2443
|
+
}
|
|
2444
|
+
catch (error) {
|
|
2445
|
+
run.submitted = Math.max(0, run.submitted - 1);
|
|
2446
|
+
// The try counts here whether or not serve.json can say so, so its tries stay bounded.
|
|
2447
|
+
const tried = { tries: next.tries + 1, error: error.message };
|
|
2448
|
+
await this.saveMeta(run, () => ({ ...run.meta, cap_continue: { ...next, ...tried } })).catch(() => undefined);
|
|
2449
|
+
Object.assign(next, tried);
|
|
2450
|
+
if (next.tries >= CONTINUE_TRIES) {
|
|
2451
|
+
run.resuming = undefined;
|
|
2452
|
+
warn(run.id, `its raised cap's follow-up was not sent in ${next.tries} tries (${next.error}); the run fails`);
|
|
2453
|
+
return this.failRaised(run, cap, next.error);
|
|
2454
|
+
}
|
|
2455
|
+
const wait = CONTINUE_RETRY_MS[next.tries - 1] ?? CONTINUE_RETRY_MS.at(-1);
|
|
2456
|
+
warn(run.id, `its raised cap's follow-up was not sent (${next.error}); tried again in ${wait / 1000} s`);
|
|
2457
|
+
const at = Date.now() + wait;
|
|
2458
|
+
run.resuming = at;
|
|
2459
|
+
setTimeout(() => {
|
|
2460
|
+
if (run.resuming !== at)
|
|
2461
|
+
return;
|
|
2462
|
+
run.resuming = undefined;
|
|
2463
|
+
this.refresh(run);
|
|
2464
|
+
}, wait).unref();
|
|
2465
|
+
this.refresh(run);
|
|
2466
|
+
}
|
|
2467
|
+
finally {
|
|
2468
|
+
run.followUpOpen = undefined;
|
|
2469
|
+
}
|
|
2470
|
+
}
|
|
2471
|
+
/** Ends a raised run whose follow-up could not be sent: failed, in words a person can act on. */
|
|
2472
|
+
async failRaised(run, cap, why) {
|
|
2473
|
+
if (run.outcome || run.finishing || run.cancel)
|
|
2474
|
+
return;
|
|
2475
|
+
run.error = { code: "run_failed", message: `The run's cap was raised to ${money(cap)}, but the run could not be sent on (${why ?? "no answer"}). Start it again to go on.`, retryable: false };
|
|
2476
|
+
run.finishing = "failed";
|
|
2477
|
+
run.endedAt = new Date().toISOString();
|
|
2478
|
+
this.mark(run);
|
|
2479
|
+
if (this.live(run))
|
|
2480
|
+
this.terminate(run);
|
|
2481
|
+
else
|
|
2482
|
+
await this.settle(run, null, false);
|
|
2483
|
+
}
|
|
2484
|
+
/** One message to an agentic run, its mode chosen by the run's state (the contract's table). `requestId`: the message's
|
|
2485
|
+
* id in the run's store, which takes one message per id (a trigger's firing key); default a new one. */
|
|
2486
|
+
async message(run, content, requestId, { answers = true } = {}) {
|
|
1888
2487
|
if (run.imported)
|
|
1889
2488
|
throw this.importedRefusal(run);
|
|
1890
2489
|
// A cancelled run takes no message, whether or not its end is written yet.
|
|
1891
2490
|
if (run.cancel)
|
|
1892
2491
|
throw this.finished(run);
|
|
2492
|
+
// A message while a tool call waits for approval declines it, with the message as the reason (as Claude Code takes
|
|
2493
|
+
// what is typed at its permission prompt): the gate's resume carries the refusal and their words in one turn, and
|
|
2494
|
+
// nothing else is sent, so no second turn races the parked call.
|
|
2495
|
+
const read = run.kind === "agentic" ? waitingApproval(run) : undefined;
|
|
2496
|
+
if (read) {
|
|
2497
|
+
await this.personsTurn(run);
|
|
2498
|
+
// Read again after that wait, with nothing awaited from here to the decline's own write: an answer, a stop or a
|
|
2499
|
+
// cancel that landed meanwhile stands (the first answer wins, and a stop's withdrawal is never replaced), and the
|
|
2500
|
+
// message is then a message, under the run's state now. It declines only the call it read, which the person saw:
|
|
2501
|
+
// another parked since waits for its own answer.
|
|
2502
|
+
const waiting = waitingApproval(run);
|
|
2503
|
+
if (waiting?.id === read.id && !run.cancel && !run.stopping)
|
|
2504
|
+
return this.declineBy(run, waiting, content);
|
|
2505
|
+
if (run.cancel)
|
|
2506
|
+
throw this.finished(run);
|
|
2507
|
+
}
|
|
1893
2508
|
// Every wait first, then a last look for a stop in flight, again after any wait a stop came during: from that look
|
|
1894
2509
|
// to the count below nothing awaits, so no stop can begin in between.
|
|
1895
2510
|
do {
|
|
@@ -1906,6 +2521,15 @@ export class Runs {
|
|
|
1906
2521
|
// before they are back.
|
|
1907
2522
|
if (run.reopening)
|
|
1908
2523
|
await run.reopening.catch(() => undefined);
|
|
2524
|
+
// A raised run whose follow-up has not gone yet (its paused process still letting go, or the follow-up being sent)
|
|
2525
|
+
// takes a message once it has: after it, as the next turn, never into the process being let go.
|
|
2526
|
+
const following = () => continuationOf(run) !== undefined || run.resuming === "sending";
|
|
2527
|
+
if (following()) {
|
|
2528
|
+
await this.waitWhile(following, 100, "The run's raised cap's follow-up is still being sent");
|
|
2529
|
+
// Its follow-up's turn may have ended the run meanwhile (a quick answer): its end is written first, so the message
|
|
2530
|
+
// then opens it again, as one to any ended run does, never refused for an end still being written.
|
|
2531
|
+
await this.waitWhile(() => run.settles > 0 || Boolean(run.finishing && !run.outcome), 100, "The run's end is still being written");
|
|
2532
|
+
}
|
|
1909
2533
|
if (run.kind === "agentic" && statusOf(run).status === "completed")
|
|
1910
2534
|
await (run.reopening ??= this.reopen(run).finally(() => (run.reopening = undefined)));
|
|
1911
2535
|
} while (run.stopping);
|
|
@@ -1913,11 +2537,18 @@ export class Runs {
|
|
|
1913
2537
|
const { status, state } = statusOf(run);
|
|
1914
2538
|
if (TERMINAL.has(status))
|
|
1915
2539
|
throw this.finished(run);
|
|
2540
|
+
// Paused at its cap: a message would be refused for the same room, so the cap is raised first.
|
|
2541
|
+
const paused = pausedAt(run);
|
|
2542
|
+
if (paused !== undefined)
|
|
2543
|
+
throw new ApiError("budget_reached", `The run is paused at its ${money(run.meta.max_cost_usd ?? 0)} cap: raise the cap first. ${paused}`, { details: { cap_usd: run.meta.max_cost_usd ?? null } });
|
|
1916
2544
|
// 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
2545
|
// the same run, which the contract calls follow_up, never a steer it does not do.
|
|
1918
2546
|
const working = status === "queued" || (status === "working" && state === "working");
|
|
1919
2547
|
const mode = working ? (steers ? "steer" : "follow_up") : status === "input_required" && state === "waiting" ? "answer" : "follow_up";
|
|
1920
|
-
|
|
2548
|
+
// A message that may not answer (a trigger's): one that would is refused here, past every wait, before it is sent.
|
|
2549
|
+
if (mode === "answer" && !answers)
|
|
2550
|
+
throw new ApiError("not_continuable", WAITS_ON_A_PERSON, { details: { reason: "waiting" } });
|
|
2551
|
+
const messageId = requestId ?? `m${Date.now().toString(36)}${randomBytes(4).toString("hex")}`;
|
|
1921
2552
|
// A follow-up to a run the person stopped, whose process has gone: its turn had ended, so the process this message
|
|
1922
2553
|
// starts resumes nothing. With its process live the message starts none, and a relaunch after that process dies
|
|
1923
2554
|
// under the message is a crash's, which keeps its row.
|
|
@@ -1926,7 +2557,10 @@ export class Runs {
|
|
|
1926
2557
|
run.submitted++;
|
|
1927
2558
|
this.refresh(run);
|
|
1928
2559
|
try {
|
|
1929
|
-
|
|
2560
|
+
// After every wait, and once the count above holds the run from ending (so no end-of-run turn is asked from here):
|
|
2561
|
+
// one asked while this message waited for the run's end wrote its origin then, after any earlier removal.
|
|
2562
|
+
await this.personsTurn(run);
|
|
2563
|
+
await this.submit(run, content, mode === "steer" ? "steer" : "followUp", messageId, undefined, answers ? this.messageOrigin?.(run.id, content) : undefined, answers);
|
|
1930
2564
|
}
|
|
1931
2565
|
catch (error) {
|
|
1932
2566
|
run.submitted = Math.max(0, run.submitted - 1);
|
|
@@ -1938,6 +2572,14 @@ export class Runs {
|
|
|
1938
2572
|
}
|
|
1939
2573
|
return { mode, messageId };
|
|
1940
2574
|
}
|
|
2575
|
+
/** A person's turn is sent next: no turn from here on is the server's own end-of-run turn (tool-gate.ts NOTE_ONLY_TEXT),
|
|
2576
|
+
* so its origin goes, right before the turn is sent. */
|
|
2577
|
+
async personsTurn(run) {
|
|
2578
|
+
// A write of the origin still in flight lands first, then goes: none starts from here (learning-run.ts reflectTurn).
|
|
2579
|
+
await run.originWrite?.catch(() => undefined);
|
|
2580
|
+
await rm(join(run.dir, TURN_ORIGIN_FILE), { force: true }).catch((error) => warn(run.id, `its turn's origin is not removed: ${error.message}`));
|
|
2581
|
+
await runsTestHooks.personsTurn?.(run.dir);
|
|
2582
|
+
}
|
|
1941
2583
|
/** Waits, up to a request's deadline, while `holds` (checked every `everyMs`): else 503 `unavailable`, saying `why`. */
|
|
1942
2584
|
async waitWhile(holds, everyMs, why) {
|
|
1943
2585
|
for (const deadline = Date.now() + (this.options.readyTimeoutMs ?? READY_TIMEOUT_MS); holds(); await sleep(everyMs)) {
|
|
@@ -1986,6 +2628,7 @@ export class Runs {
|
|
|
1986
2628
|
run.relaunches = 0;
|
|
1987
2629
|
// A run that learns finds its agent's notes in its work again (learning-run.ts).
|
|
1988
2630
|
await this.learning.onReopen(run);
|
|
2631
|
+
await this.pinSignIn(run);
|
|
1989
2632
|
await this.beforeReopenLaunch?.(run.id);
|
|
1990
2633
|
this.refresh(run);
|
|
1991
2634
|
// Opened for the follow-up: the run had answered, so its open resumes nothing.
|
|
@@ -2017,9 +2660,15 @@ export class Runs {
|
|
|
2017
2660
|
// the turn as it stops any working run.
|
|
2018
2661
|
if (run.kind !== "workflow")
|
|
2019
2662
|
await this.caughtUp(run);
|
|
2663
|
+
// A tool call that waits for approval is withdrawn by the stop (never run, an answer after is 409); then a turn that
|
|
2664
|
+
// runs meanwhile is stopped as any working run's is, and with none the run is stopped as a stop leaves one.
|
|
2665
|
+
const open = run.kind === "agentic" && !run.cancel && !run.outcome && !run.finishing;
|
|
2666
|
+
const withdrawn = open && waitingApproval(run) ? await this.withdraw(run) : false;
|
|
2667
|
+
// An answer the run's process has not acted on yet is overridden too: a stop wins, so nothing runs and nothing resumes.
|
|
2668
|
+
const superseded = open ? await this.supersede(run, "withdrawn") : false;
|
|
2020
2669
|
const { status, state } = statusOf(run);
|
|
2021
2670
|
if (run.kind === "workflow" || !this.live(run) || !(status === "working" && state === "working") || run.submitted > 0)
|
|
2022
|
-
return false;
|
|
2671
|
+
return withdrawn || superseded ? this.stopIdle(run) : false;
|
|
2023
2672
|
run.stopping = true;
|
|
2024
2673
|
try {
|
|
2025
2674
|
return await this.stopTurn(run);
|
|
@@ -2028,6 +2677,58 @@ export class Runs {
|
|
|
2028
2677
|
run.stopping = undefined;
|
|
2029
2678
|
}
|
|
2030
2679
|
}
|
|
2680
|
+
/** message()'s decline of the tool call that waits for approval: a deny with the message as its note, which the
|
|
2681
|
+
* run's gate acts on as any deny, resuming the session with the refusal and the person's words in one message. */
|
|
2682
|
+
async declineBy(run, waiting, content) {
|
|
2683
|
+
// The person's message, whole: it is the reason the model reads. Nothing shows the note, so nothing cuts it.
|
|
2684
|
+
run.meta.approvals = { ...run.meta.approvals, [waiting.id]: { decision: "deny", note: content, answered_at: new Date().toISOString(), args_shown: shownArgs(waiting, this.redactor(run)), by: "message" } };
|
|
2685
|
+
await this.saveMeta(run);
|
|
2686
|
+
this.restate(run);
|
|
2687
|
+
this.refresh(run);
|
|
2688
|
+
if (!run.outcome && !run.finishing && !run.cancel)
|
|
2689
|
+
void this.ensureLive(run).catch((error) => warn(run.id, `its declined approval waits for its process: ${error.message}`));
|
|
2690
|
+
return { mode: "answer", messageId: `m${Date.now().toString(36)}${randomBytes(4).toString("hex")}` };
|
|
2691
|
+
}
|
|
2692
|
+
/** The answers given and not acted on yet (the run's process has not resolved them), overridden by a stop or a cancel:
|
|
2693
|
+
* `withdrawn` or `canceled`, each keeping the answer it superseded, so nothing runs and nothing resumes, and the
|
|
2694
|
+
* history shows what was given. The run's gate reads the answer again just before it acts (tool-gate.ts). */
|
|
2695
|
+
async supersede(run, decision) {
|
|
2696
|
+
const given = [...(run.approvals?.values() ?? [])].filter((a) => !a.resolved && run.meta.approvals?.[a.id] && !withdrawn(run.meta.approvals[a.id]));
|
|
2697
|
+
if (!given.length)
|
|
2698
|
+
return false;
|
|
2699
|
+
const now = new Date().toISOString();
|
|
2700
|
+
const overridden = given.map((a) => {
|
|
2701
|
+
const was = run.meta.approvals[a.id];
|
|
2702
|
+
return [a.id, { decision, answered_at: now, superseded: { decision: was.decision, answered_at: was.answered_at, ...(was.note !== undefined ? { note: was.note } : {}), ...(was.by ? { by: was.by } : {}) } }];
|
|
2703
|
+
});
|
|
2704
|
+
run.meta.approvals = { ...run.meta.approvals, ...Object.fromEntries(overridden) };
|
|
2705
|
+
await this.saveMeta(run);
|
|
2706
|
+
this.restate(run);
|
|
2707
|
+
return true;
|
|
2708
|
+
}
|
|
2709
|
+
/** Until every tool call of the run that waited for approval is resolved in its store (its process acted on its answer,
|
|
2710
|
+
* or cut it), or `ms` pass. */
|
|
2711
|
+
async untilResolved(run, ms) {
|
|
2712
|
+
for (const end = Date.now() + ms; [...(run.approvals?.values() ?? [])].some((approval) => !approval.resolved) && Date.now() < end;)
|
|
2713
|
+
await sleep(50);
|
|
2714
|
+
}
|
|
2715
|
+
/** stop()'s withdrawal of the tool call that waits for approval: never run, and an answer after is 409. */
|
|
2716
|
+
async withdraw(run) {
|
|
2717
|
+
const waiting = waitingApproval(run);
|
|
2718
|
+
run.meta.approvals = { ...run.meta.approvals, [waiting.id]: { decision: "withdrawn", answered_at: new Date().toISOString() } };
|
|
2719
|
+
await this.saveMeta(run);
|
|
2720
|
+
this.restate(run);
|
|
2721
|
+
return true;
|
|
2722
|
+
}
|
|
2723
|
+
/** stop() of a run with no turn to abort (parked on an approval it withdrew): the stop's mark, as a stop saves it. */
|
|
2724
|
+
async stopIdle(run) {
|
|
2725
|
+
delete run.meta.stopped_at;
|
|
2726
|
+
delete run.meta.stopped_after;
|
|
2727
|
+
Object.assign(run.meta, stopMark(run.rows));
|
|
2728
|
+
await this.saveMeta(run);
|
|
2729
|
+
this.refresh(run);
|
|
2730
|
+
return true;
|
|
2731
|
+
}
|
|
2031
2732
|
/** stop()'s mark and abort, once it took the stop. */
|
|
2032
2733
|
async stopTurn(run) {
|
|
2033
2734
|
// Set before the abort: the turn's end can arrive before the door answers, and must not read as an answer.
|
|
@@ -2052,6 +2753,25 @@ export class Runs {
|
|
|
2052
2753
|
this.refresh(run);
|
|
2053
2754
|
return true;
|
|
2054
2755
|
}
|
|
2756
|
+
/** A person's answer to the tool call `id` that waits for approval (tool-gate.ts): kept in the run's serve.json before
|
|
2757
|
+
* it returns, the first answer winning (the same one again changes nothing; another is 409, `already_answered`). The
|
|
2758
|
+
* run's process reads it there, runs or refuses the call, and resumes; a run with no process gets one. */
|
|
2759
|
+
async approve(run, id, decision, note) {
|
|
2760
|
+
const given = run.meta.approvals?.[id];
|
|
2761
|
+
if (!given && !run.approvals?.has(id))
|
|
2762
|
+
throw new ApiError("not_found", `The run ${run.id} has no tool call ${id} waiting for approval.`);
|
|
2763
|
+
if (given) {
|
|
2764
|
+
if (given.decision === decision)
|
|
2765
|
+
return;
|
|
2766
|
+
throw new ApiError("not_continuable", `The tool call ${id} was already ${given.decision === "canceled" ? "canceled with its run" : given.decision === "withdrawn" ? "withdrawn when its run was stopped" : `answered: ${given.decision}`}.`, { details: { reason: "already_answered", decision: given.decision } });
|
|
2767
|
+
}
|
|
2768
|
+
run.meta.approvals = { ...run.meta.approvals, [id]: { decision, ...(note ? { note } : {}), answered_at: new Date().toISOString(), args_shown: shownArgs(run.approvals.get(id), this.redactor(run)) } };
|
|
2769
|
+
await this.saveMeta(run);
|
|
2770
|
+
this.restate(run);
|
|
2771
|
+
this.refresh(run);
|
|
2772
|
+
if (!run.outcome && !run.finishing && !run.cancel)
|
|
2773
|
+
void this.ensureLive(run).catch((error) => warn(run.id, `its answered approval waits for its process: ${error.message}`));
|
|
2774
|
+
}
|
|
2055
2775
|
/** Record the cancel and signal the run. An agentic run reads `cancelled` from here on (the first end a run comes to is
|
|
2056
2776
|
* its last: nothing its turn writes later moves it), and is carried back so once its process has exited; a workflow
|
|
2057
2777
|
* run reads it once it is carried back, with how its workflow stopped. */
|
|
@@ -2063,6 +2783,15 @@ export class Runs {
|
|
|
2063
2783
|
if (run.outcome || run.finishing)
|
|
2064
2784
|
return false;
|
|
2065
2785
|
run.cancel = true;
|
|
2786
|
+
// A tool call that waits for approval is canceled with its run: an answer after this one is refused.
|
|
2787
|
+
const waiting = waitingApproval(run);
|
|
2788
|
+
if (waiting) {
|
|
2789
|
+
run.meta.approvals = { ...run.meta.approvals, [waiting.id]: { decision: "canceled", answered_at: new Date().toISOString() } };
|
|
2790
|
+
await this.saveMeta(run).catch((error) => warn(run.id, `its canceled approval is not saved: ${error.message}`));
|
|
2791
|
+
this.restate(run);
|
|
2792
|
+
}
|
|
2793
|
+
// An answer its process has not acted on yet is overridden too: nothing runs and nothing resumes.
|
|
2794
|
+
const superseded = await this.supersede(run, "canceled").catch((error) => (warn(run.id, `its superseded approval is not saved: ${error.message}`), false));
|
|
2066
2795
|
if (run.kind === "agentic") {
|
|
2067
2796
|
run.finishing = "cancelled";
|
|
2068
2797
|
run.endedAt = new Date().toISOString();
|
|
@@ -2073,6 +2802,13 @@ export class Runs {
|
|
|
2073
2802
|
if (this.live(run)) {
|
|
2074
2803
|
// The turn is aborted first, so the drain that SIGTERM starts does not wait for it.
|
|
2075
2804
|
await this.abortTurn(run);
|
|
2805
|
+
// An approved call in flight runs outside any turn: its process's gate cuts it once it reads the cancel (tool-gate.ts),
|
|
2806
|
+
// which ending the process at once would forestall. A short wait for that, never a refusal.
|
|
2807
|
+
if (superseded) {
|
|
2808
|
+
run.meta.cancel_waits_for = [...(run.approvals?.values() ?? [])].filter((approval) => !approval.resolved).map((approval) => approval.id);
|
|
2809
|
+
await this.saveMeta(run).catch((error) => warn(run.id, `its cancel's wait is not saved: ${error.message}`));
|
|
2810
|
+
await this.untilResolved(run, 3_000);
|
|
2811
|
+
}
|
|
2076
2812
|
this.terminate(run);
|
|
2077
2813
|
}
|
|
2078
2814
|
else
|
|
@@ -2115,17 +2851,17 @@ export class Runs {
|
|
|
2115
2851
|
// A poll never answers home_busy: a store still held answers the live view, or the last whole one, marked stale.
|
|
2116
2852
|
try {
|
|
2117
2853
|
const view = await runGraph(given);
|
|
2118
|
-
this.
|
|
2119
|
-
return { ...view, stale: false };
|
|
2854
|
+
this.graphCache.set(`view:${run.id}`, view, Buffer.byteLength(JSON.stringify(view)));
|
|
2855
|
+
return this.servedGraph(run, { ...view, stale: false });
|
|
2120
2856
|
}
|
|
2121
2857
|
catch (error) {
|
|
2122
2858
|
if (!storeBusy(error))
|
|
2123
2859
|
throw error;
|
|
2124
2860
|
warn(run.id, "its store is busy; the graph answers its live view, stale");
|
|
2125
|
-
const held = this.
|
|
2861
|
+
const held = this.graphCache.get(`view:${run.id}`);
|
|
2126
2862
|
if (held)
|
|
2127
|
-
return { ...held, run: given.run, stale: true };
|
|
2128
|
-
return { ...(await runGraph({ ...given, liveOnly: true })), stale: true };
|
|
2863
|
+
return this.servedGraph(run, { ...held, run: given.run, stale: true });
|
|
2864
|
+
return this.servedGraph(run, { ...(await runGraph({ ...given, liveOnly: true })), stale: true });
|
|
2129
2865
|
}
|
|
2130
2866
|
}
|
|
2131
2867
|
/** How long a run's process gets after SIGTERM before SIGKILL: its drain and a second to exit. */
|
|
@@ -2208,10 +2944,11 @@ export class Runs {
|
|
|
2208
2944
|
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
2945
|
error: status === "failed" ? (run.error ?? { code: "run_failed", message: "The run failed.", retryable: false }) : null,
|
|
2210
2946
|
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,
|
|
2947
|
+
pending: status === "input_required" && state === "waiting" ? (approvalOf(run, this.redactor(run)) ?? budgetPending(run, this.spentNow(run)) ?? pendingOf(run.rows)) : null,
|
|
2212
2948
|
cost: this.cost(run),
|
|
2213
2949
|
archived_at: stored?.archivedAt ?? null,
|
|
2214
2950
|
imported_from: run.imported ?? null,
|
|
2951
|
+
trigger: run.meta.trigger ?? null,
|
|
2215
2952
|
// The notes it read once it settled: while it runs, or runs again for a follow-up, they are still being read.
|
|
2216
2953
|
learning: this.learning.view(run.meta.learning, TERMINAL.has(status) && run.settled),
|
|
2217
2954
|
poll_after_ms: TERMINAL.has(status) && run.settled ? 0 : 1000,
|
|
@@ -2219,8 +2956,8 @@ export class Runs {
|
|
|
2219
2956
|
};
|
|
2220
2957
|
}
|
|
2221
2958
|
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) };
|
|
2959
|
+
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, trigger, learning } = await this.view(run);
|
|
2960
|
+
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, trigger, learning: learning && shortOf(learning) };
|
|
2224
2961
|
}
|
|
2225
2962
|
/** A run's status for a list: an ended run's from its row, a running one's from the run itself. */
|
|
2226
2963
|
async statusOfRow(row) {
|
|
@@ -2248,16 +2985,20 @@ export class Runs {
|
|
|
2248
2985
|
// A run read from its row alone has ended: it waits on nothing.
|
|
2249
2986
|
pending: null,
|
|
2250
2987
|
imported_from: row.importedFrom ?? null,
|
|
2988
|
+
trigger: triggerOf(meta),
|
|
2251
2989
|
// Its row says it ended: what serve.json holds of its learning is as it settled.
|
|
2252
2990
|
learning: this.learning.short(isObject(meta?.learning) ? meta.learning : null, true),
|
|
2253
2991
|
};
|
|
2254
2992
|
}
|
|
2255
|
-
/** A key was saved on this server or deleted from it: each held run's learning row shown again, cut
|
|
2256
|
-
* they are now (learning-run.ts shown), as its view and its lists already are from
|
|
2993
|
+
/** A key was saved on this server or deleted from it: each held run's learning row and decision rows shown again, cut
|
|
2994
|
+
* of the keys as they are now (learning-run.ts shown, decision-rows.ts), as its view and its lists already are from
|
|
2995
|
+
* the next read on. */
|
|
2257
2996
|
keysChanged() {
|
|
2258
2997
|
this.learning.keysChanged();
|
|
2998
|
+
// A run's learning row and its decision rows are shown again with the keys as they are now (show): a key saved after
|
|
2999
|
+
// a workflow ended is redacted from its decisions on the next read, learning or not.
|
|
2259
3000
|
for (const run of this.runs.values())
|
|
2260
|
-
if (run.meta.learning)
|
|
3001
|
+
if (run.meta.learning || run.decisions)
|
|
2261
3002
|
this.show(run);
|
|
2262
3003
|
}
|
|
2263
3004
|
/** A held run's learning, in short (learning-run.ts heldLearning). */
|