@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/server.js
CHANGED
|
@@ -8,7 +8,7 @@ import { pipeline } from "node:stream/promises";
|
|
|
8
8
|
import { pathToFileURL } from "node:url";
|
|
9
9
|
import { Worker } from "node:worker_threads";
|
|
10
10
|
import { once } from "node:events";
|
|
11
|
-
import { existsSync } from "node:fs";
|
|
11
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
12
12
|
import { rm } from "node:fs/promises";
|
|
13
13
|
import { homedir } from "node:os";
|
|
14
14
|
import { agentView, Agents, etagOf, homeBusy, revisionView, storeBusy } from "./agents.js";
|
|
@@ -17,9 +17,9 @@ import { DECISION_ADAPTER, decisionsOf, FAUX_JEV_ENV, FAUX_OPENROUTER_ENV, FAUX_
|
|
|
17
17
|
import { FAUX_WEB_ENV } from "./fetch-page.js";
|
|
18
18
|
import { FAUX_MONID_ENV } from "./monid.js";
|
|
19
19
|
import { FAUX_EXA_ENV } from "./exa-keyless.js";
|
|
20
|
-
import { FAUX_BROWSER_ENV, NODE_TOOLS, toolingOf, toolsView } from "./tools.js";
|
|
20
|
+
import { FAUX_BROWSER_ENV, NODE_TOOLS, toolingOf, toolOf, toolsView } from "./tools.js";
|
|
21
21
|
import { ApiError, invalid, unsupported } from "./errors.js";
|
|
22
|
-
import { DATA_ENV, DOOR_TOKEN_FILE, HOME_HOST_OWNED, HOMES_DIR, homeOf, readJson, RUN_META, syncDir, TOKEN_FILE, writeDurable } from "./files.js";
|
|
22
|
+
import { DATA_ENV, DOOR_TOKEN_FILE, HOME_HOST_OWNED, HOMES_DIR, homeOf, readJson, RUN_META, SETUP_LOST, syncDir, TOKEN_FILE, writeDurable } from "./files.js";
|
|
23
23
|
import { checkedPath, decodedPath, homePath, hostOwnedOf, hostOwnedRefusal, ownedByIdentity } from "./home-path.js";
|
|
24
24
|
import { chooseModel, EFFORTS, FAUX_ENV, FAUX_UPSTREAM_ENV, MODEL_NODES, modelSource, THINKING_LEVELS, withoutFaux } from "./model.js";
|
|
25
25
|
import { DEFAULT_HARNESS, FAUX_HARNESS_ENV, harnessOffers } from "./harness.js";
|
|
@@ -29,27 +29,35 @@ import { gradeModelOf, learningBudgetOf, learningOf } from "./learning.js";
|
|
|
29
29
|
import { agentLearning, learningLog, learningNotes, noteBody, readNote, runDiff, runLearning, secretsShown, sendNote, writeNote } from "./learning-routes.js";
|
|
30
30
|
import { answerLlms, MCP_PATH, mcpEndpoint } from "./mcp.js";
|
|
31
31
|
import { openapiDocument, servedOpenapi, UNSUPPORTED } from "./openapi.js";
|
|
32
|
-
import { boxesLine, noBoxReason, placesOf, resolvePlace } from "./place.js";
|
|
33
|
-
import { boxLimitsOf, FAUX_BOX_ENV, fauxBoxes } from "./run-box.js";
|
|
32
|
+
import { boxesLine, NEW_AGENT_TOOLS, newAgentPlace, noBoxReason, placesOf, resolvePlace } from "./place.js";
|
|
33
|
+
import { BOX_ALLOW_ENV, boxAllowOf, boxLimitsOf, boxNetworkOf, FAUX_BOX_ENV, fauxBoxes } from "./run-box.js";
|
|
34
34
|
import { Owner, passwordProblem, SESSION_MS } from "./owner.js";
|
|
35
35
|
import { answerPage, byOwnerSession, isJson, ownerCookie, ownOrigin, signedIn } from "./page.js";
|
|
36
36
|
import { durationMs, logLine } from "./print.js";
|
|
37
|
-
import { Runs, STATUSES, statusOf, toolCostOf } from "./runs.js";
|
|
37
|
+
import { knownToolCostOf, Runs, STATUSES, statusOf, toolCostOf, WAITS_ON_A_PERSON } from "./runs.js";
|
|
38
|
+
import { runLines } from "./usage-lines.js";
|
|
38
39
|
import { BOX_QUARANTINE, Quarantine } from "./box/sweep.js";
|
|
39
|
-
import { boxesLog, boxRegistry, daytonaApi, enabledBoxes } from "./boxes.js";
|
|
40
|
+
import { boxesLog, boxRegistry, daytonaApi, enabledBoxes, VM_NO_LIST, VM_PROVIDER } from "./boxes.js";
|
|
41
|
+
import { FAUX_EGRESS_ENV, sweepEgressDirs } from "./box-egress.js";
|
|
40
42
|
import { boxImageOf, clearImage, dockerImage, withImage } from "./box-image.js";
|
|
41
43
|
import { startBoxRelay } from "./box-relay.js";
|
|
44
|
+
import { vmRelay } from "./box-relay-vm.js";
|
|
45
|
+
import { memoryMbOf } from "./run-box.js";
|
|
42
46
|
import { DOCUMENTS_ENV } from "./pdf-pages.js";
|
|
43
|
-
import {
|
|
47
|
+
import { meterFiguresIn } from "./cap.js";
|
|
44
48
|
import { blockersOf, CODE_NODES_ENV, issueOf } from "./runnable.js";
|
|
45
49
|
import { hostSecrets, SECRET_NAMES, secret, withSecrets } from "./secrets.js";
|
|
46
|
-
import {
|
|
50
|
+
import { redactedOutput } from "./key-refusal.js";
|
|
51
|
+
import { analyticsFilter, analyticsView, pendingOf, statsView } from "./stats.js";
|
|
47
52
|
import { outcomes } from "./usage.js";
|
|
48
53
|
import { keyOf, SEAL_KEY_ENV, sealKeyOf, TOOL_FIELDS, ToolKeys } from "./tool-keys.js";
|
|
54
|
+
import { SIGN_INS_DIR, SignIns, vendorsOver } from "./sign-ins.js";
|
|
49
55
|
import { MCP_AUTH_TYPES, McpServers } from "./mcp-servers.js";
|
|
50
56
|
import { WEBHOOK_EVENTS, Webhooks } from "./webhooks.js";
|
|
51
|
-
import {
|
|
52
|
-
import {
|
|
57
|
+
import { HOOK_TOLERANCE_S, hookHeadersRefusal, hookRefusal, TriggerSecrets } from "./trigger-secrets.js";
|
|
58
|
+
import { CATCHUP_WINDOW_S, FAILURES_TO_PAUSE, HISTORY_KEPT, MIN_EVERY_S, OVERLAP, PAYLOAD_KEPT_BYTES, SOURCE_KINDS, TARGET_KINDS, Triggers } from "./triggers.js";
|
|
59
|
+
import { checkDefinitionBody, DEFAULT_INPUT_SCHEMA, ID, IDEMPOTENCY_TTL_S, inputIssues, isObject, stable, unknownFields } from "./validate.js";
|
|
60
|
+
import { agentTools, browserKeyRow, settingsIssues, ToolSettings, withDefaults } from "./tool-plane.js";
|
|
53
61
|
import { MAX_FILES_PER_RUN, MAX_UPLOAD_BYTES, Uploads, UPLOADS_DIR } from "./uploads.js";
|
|
54
62
|
import { INLINE_TYPES, openWorkFile, removeWorkFile, typeOf, WALK_DEPTH, walkWork, WorkRefused, writesHeld, writeWorkFile } from "./workspace.js";
|
|
55
63
|
import { markRunning, markStopping, takeServerLockAfterStop } from "./server-lock.js";
|
|
@@ -60,10 +68,11 @@ export const DEFAULT_PORT = 7340;
|
|
|
60
68
|
const VERSION = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
61
69
|
const IDEMPOTENCY_FILE = ".idempotency.json";
|
|
62
70
|
const MAX_BODY = 1 << 20;
|
|
71
|
+
/** The largest body a webhook trigger takes (POST /v2/hooks/{id}). */
|
|
72
|
+
const HOOK_MAX_BODY = 256 << 10;
|
|
63
73
|
const MAX_MESSAGE = 20_000;
|
|
64
74
|
const MAX_WAIT_MS = 25_000;
|
|
65
75
|
const PAGE_ROWS = 500;
|
|
66
|
-
const IDEMPOTENCY_TTL_S = 86_400;
|
|
67
76
|
const FILE_LIST_CAP = 2_000;
|
|
68
77
|
/** What a stopping server's record allows past its runs' kill bound, the cap a start waits under: the runs' carry backs,
|
|
69
78
|
* retried while the agent store is held (about 15.5 s), their boxes' cleanup (up to a minute), and the deliveries', the
|
|
@@ -85,7 +94,7 @@ const HOME_WRITES_OFF = "This server can't write a home's files safely here: a w
|
|
|
85
94
|
const FILE_CSP = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox; form-action 'none'";
|
|
86
95
|
/** Each test switch a run's process reads, by the variable it reads it from: set only under `faux`, but the faux
|
|
87
96
|
* harness's, which scripts the harnesses with or without it. */
|
|
88
|
-
const FAUX_SWITCHES = [["fauxBrowser", FAUX_BROWSER_ENV], ["fauxWeb", FAUX_WEB_ENV], ["fauxJev", FAUX_JEV_ENV], ["fauxParallel", FAUX_PARALLEL_ENV], ["fauxOpenrouter", FAUX_OPENROUTER_ENV], ["fauxMonid", FAUX_MONID_ENV], ["fauxUpstream", FAUX_UPSTREAM_ENV], ["fauxExa", FAUX_EXA_ENV], ["fauxBox", FAUX_BOX_ENV]];
|
|
97
|
+
const FAUX_SWITCHES = [["fauxBrowser", FAUX_BROWSER_ENV], ["fauxWeb", FAUX_WEB_ENV], ["fauxJev", FAUX_JEV_ENV], ["fauxParallel", FAUX_PARALLEL_ENV], ["fauxOpenrouter", FAUX_OPENROUTER_ENV], ["fauxMonid", FAUX_MONID_ENV], ["fauxUpstream", FAUX_UPSTREAM_ENV], ["fauxExa", FAUX_EXA_ENV], ["fauxBox", FAUX_BOX_ENV], ["fauxEgress", FAUX_EGRESS_ENV]];
|
|
89
98
|
/** The test switches a run's process gets, each module path resolved: empty outside tests. */
|
|
90
99
|
function fauxEnvOf(options) {
|
|
91
100
|
const env = options.fauxHarness ? { [FAUX_HARNESS_ENV]: resolve(options.fauxHarness) } : {};
|
|
@@ -111,6 +120,11 @@ async function tokenIn(file) {
|
|
|
111
120
|
return { token, made: true };
|
|
112
121
|
}
|
|
113
122
|
const digest = (text) => createHash("sha256").update(text).digest();
|
|
123
|
+
/** Why a trigger never messages a run: it has no spend cap, and every turn a trigger drives is capped. */
|
|
124
|
+
const NO_CAP = "The run has no spend cap: a trigger only messages a run with one, as every turn it drives is capped.";
|
|
125
|
+
/** What an unknown trigger's request is checked against, so it is refused in a known trigger's time. */
|
|
126
|
+
const NO_TRIGGER_SECRET = `whsec_${randomBytes(32).toString("base64")}`;
|
|
127
|
+
const sha256Hex = (text) => createHash("sha256").update(text).digest("hex");
|
|
114
128
|
const SESSION_S = SESSION_MS / 1000;
|
|
115
129
|
export const ROUTES = [
|
|
116
130
|
{ method: "GET", pattern: /^\/capabilities$/, name: "getCapabilities" },
|
|
@@ -124,6 +138,7 @@ export const ROUTES = [
|
|
|
124
138
|
{ method: "POST", pattern: /^\/agents\/([^/]+)\/current$/, name: "setCurrent" },
|
|
125
139
|
{ method: "POST", pattern: /^\/agents\/([^/]+)\/archive$/, name: "archiveAgent" },
|
|
126
140
|
{ method: "POST", pattern: /^\/agents\/([^/]+)\/unarchive$/, name: "unarchiveAgent" },
|
|
141
|
+
{ method: "DELETE", pattern: /^\/agents\/([^/]+)\/sign-ins\/([^/]+)$/, name: "forgetSignIn" },
|
|
127
142
|
{ method: "POST", pattern: /^\/agents\/([^/]+)\/runs$/, name: "createRun" },
|
|
128
143
|
{ method: "GET", pattern: /^\/agents\/([^/]+)\/runs$/, name: "listRuns" },
|
|
129
144
|
{ method: "GET", pattern: /^\/agents\/([^/]+)\/home$/, name: "exportHome", capability: "home.export" },
|
|
@@ -134,10 +149,12 @@ export const ROUTES = [
|
|
|
134
149
|
{ method: "DELETE", pattern: /^\/agents\/([^/]+)\/home\/files\/(.+)$/, name: "deleteHomeFile" },
|
|
135
150
|
{ method: "GET", pattern: /^\/runs$/, name: "listAllRuns" },
|
|
136
151
|
{ method: "GET", pattern: /^\/runs\/([^/]+)$/, name: "getRun" },
|
|
152
|
+
{ method: "PATCH", pattern: /^\/runs\/([^/]+)$/, name: "raiseRunCap" },
|
|
137
153
|
{ method: "GET", pattern: /^\/runs\/([^/]+)\/timeline$/, name: "getTimeline" },
|
|
138
154
|
{ method: "POST", pattern: /^\/runs\/([^/]+)\/messages$/, name: "sendMessage" },
|
|
139
155
|
{ method: "POST", pattern: /^\/runs\/([^/]+)\/stop$/, name: "stopRun" },
|
|
140
156
|
{ method: "POST", pattern: /^\/runs\/([^/]+)\/cancel$/, name: "cancelRun" },
|
|
157
|
+
{ method: "POST", pattern: /^\/runs\/([^/]+)\/approvals\/([^/]+)$/, name: "answerApproval" },
|
|
141
158
|
{ method: "POST", pattern: /^\/runs\/([^/]+)\/archive$/, name: "archiveRun" },
|
|
142
159
|
{ method: "POST", pattern: /^\/runs\/([^/]+)\/unarchive$/, name: "unarchiveRun" },
|
|
143
160
|
{ method: "POST", pattern: /^\/runs\/([^/]+)\/kill$/, name: "killRun", capability: "runs.kill" },
|
|
@@ -172,6 +189,16 @@ export const ROUTES = [
|
|
|
172
189
|
{ method: "POST", pattern: /^\/settings\/webhook\/test$/, name: "testWebhook" },
|
|
173
190
|
{ method: "GET", pattern: /^\/settings\/webhook\/deliveries$/, name: "listWebhookDeliveries" },
|
|
174
191
|
{ method: "POST", pattern: /^\/settings\/webhook\/deliveries\/([^/]+)\/redeliver$/, name: "redeliverWebhook" },
|
|
192
|
+
{ method: "GET", pattern: /^\/triggers$/, name: "listTriggers" },
|
|
193
|
+
{ method: "POST", pattern: /^\/triggers$/, name: "createTrigger" },
|
|
194
|
+
{ method: "GET", pattern: /^\/triggers\/([^/]+)$/, name: "getTrigger" },
|
|
195
|
+
{ method: "PATCH", pattern: /^\/triggers\/([^/]+)$/, name: "updateTrigger" },
|
|
196
|
+
{ method: "DELETE", pattern: /^\/triggers\/([^/]+)$/, name: "deleteTrigger" },
|
|
197
|
+
{ method: "POST", pattern: /^\/triggers\/([^/]+)\/fire$/, name: "fireTrigger" },
|
|
198
|
+
{ method: "GET", pattern: /^\/triggers\/([^/]+)\/firings$/, name: "listTriggerFirings" },
|
|
199
|
+
{ method: "POST", pattern: /^\/triggers\/([^/]+)\/secret$/, name: "rotateTriggerSecret" },
|
|
200
|
+
// Answered before the bearer check: the request's signature is its credential.
|
|
201
|
+
{ method: "POST", pattern: /^\/hooks\/([^/]+)$/, name: "receiveHook" },
|
|
175
202
|
// Answered before routing (mcp.ts), with the token only: listed here for the document.
|
|
176
203
|
{ method: "POST", pattern: /^\/mcp$/, name: "callMcp" },
|
|
177
204
|
{ method: "GET", pattern: /^\/agents\/([^/]+)\/learning$/, name: "getAgentLearning" },
|
|
@@ -185,8 +212,8 @@ export const ROUTES = [
|
|
|
185
212
|
{ method: "GET", pattern: /^\/runs\/([^/]+)\/learning\/diff$/, name: "getRunLearningDiff" },
|
|
186
213
|
];
|
|
187
214
|
/** Where agent `agentId`'s host-owned path is read on this server: its route, when ROUTES has one (the learning API, for
|
|
188
|
-
* learning/). */
|
|
189
|
-
const ownedReadAt = (agentId) => (owned) => (ROUTES.some((r) => r.method === "GET" && r.pattern.test(`/agents/${agentId}/${owned}`)) ? `/v2/agents/${agentId}/${owned}` : undefined);
|
|
215
|
+
* learning/); sign-ins/ only as the agent's `sign_ins`, never a pointer. */
|
|
216
|
+
const ownedReadAt = (agentId) => (owned) => (owned === SIGN_INS_DIR ? `/v2/agents/${agentId}` : ROUTES.some((r) => r.method === "GET" && r.pattern.test(`/agents/${agentId}/${owned}`)) ? `/v2/agents/${agentId}/${owned}` : undefined);
|
|
190
217
|
/** Whether the request to `path` (under /v2) is a PUT of a route marked `raw`. */
|
|
191
218
|
export const takesBytes = (method, path) => (method === "PUT" || method === "POST") && ROUTES.some((r) => r.raw === true && r.method === method && r.pattern.test(path));
|
|
192
219
|
/** What this server offers. Every flag is present; an off one answers 501 naming it. */
|
|
@@ -241,6 +268,8 @@ export async function readingOf(base, maxRuns, stored, learning, toolSettings =
|
|
|
241
268
|
* `learning` is the server's learning switch (`--learning`), AGENTRUN_SERVE_LEARNING's when not given; with this
|
|
242
269
|
* server's tool settings, what each web tool resolves to (tool-plane.ts); `boxes`, the box offers its places show;
|
|
243
270
|
* `gradeModel`, its `--grade-model`. */
|
|
271
|
+
/** Why a Daytona box has no network although AGENTRUN_BOX_ALLOW names hosts: Daytona refused its domain list (`code`). */
|
|
272
|
+
const noListReason = (code) => `Daytona did not keep a sandbox's domain list (${code}), so this server's Daytona boxes have no network until it starts again: Daytona takes a domain list on its tier 3 and 4 only. To keep them closed without trying, set ${BOX_ALLOW_ENV}=none`;
|
|
244
273
|
export async function capabilities(env = withSecrets(process.env), maxRuns = maxRunsOf(env), learning = learningOf(env), toolSettings = {}, boxes = [], gradeModel) {
|
|
245
274
|
return capabilitiesWith(env, maxRuns, await harnessOffers(env), learning, await needsOf(env), toolSettings, boxes, gradeModel);
|
|
246
275
|
}
|
|
@@ -252,10 +281,14 @@ export function forCaller(caps, ownerSession) {
|
|
|
252
281
|
/** The capabilities document from offers already resolved, under the server's learning switch, tool settings and box
|
|
253
282
|
* offers: cheap, made again after each key or tool-settings write with the offers the server holds; and `needs` as
|
|
254
283
|
* needsOf says it for a revision that names no model (null when it runs). */
|
|
255
|
-
function capabilitiesWith(env, maxRuns, harnesses, learning, needs, toolSettings, boxes, gradeModel) {
|
|
284
|
+
function capabilitiesWith(env, maxRuns, harnesses, learning, needs, toolSettings, boxes, gradeModel, refused = {}) {
|
|
256
285
|
const models = { ...modelSource(env), ready: needs === null, needs };
|
|
257
286
|
// Both limits apply: the cap on the count, and the memory each run reserves (host.ts).
|
|
258
287
|
const memory = hostMemory();
|
|
288
|
+
// The browser's key is its vendor's row: Kernel's where Kernel is picked or resolved (tool-plane.ts browserKeyRow).
|
|
289
|
+
const keyFor = (tool) => (tool.name === "browser" ? browserKeyRow(tool.provider, tool.resolves?.[DEFAULT_HARNESS]) : keyOf(tool.name));
|
|
290
|
+
const tools = toolsView(env, toolSettings, noBoxReason(boxes), refused).map((tool) => (keyFor(tool) ? { ...tool, key: keyFor(tool) } : tool));
|
|
291
|
+
const browser = tools.find((tool) => tool.name === "browser");
|
|
259
292
|
return {
|
|
260
293
|
backend: "local",
|
|
261
294
|
contract: CONTRACT,
|
|
@@ -265,7 +298,7 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, needs, toolSettings
|
|
|
265
298
|
// `keys`, what a model key would unlock, is the key rows' (listToolKeys), never served here.
|
|
266
299
|
harnesses: harnesses.map(({ keys: _keys, ...offer }) => ({ ...offer, max_concurrent_runs: Math.min(maxRuns, runsThatFit(offer.id, memory)) })),
|
|
267
300
|
/** The places a revision may name (`definition.place`), this host's default, and whether this server has each box. */
|
|
268
|
-
places: placesOf(boxes),
|
|
301
|
+
places: placesOf(boxes, boxAllowOf(env)),
|
|
269
302
|
models,
|
|
270
303
|
/** What grades a run's proposed notes: the model this server names for it (learning.ts gradeModelOf), or null when
|
|
271
304
|
* each run is graded on its agent's own model; and `pending`: a risky rule, the user's or the run's own, is kept to
|
|
@@ -275,7 +308,7 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, needs, toolSettings
|
|
|
275
308
|
/** Every tool a revision may name (the closed table in tools.ts): available here, or the variables it is missing; a
|
|
276
309
|
* web tool, what it resolves to on each harness under this server's tool settings; `key`, the tool key that unlocks
|
|
277
310
|
* it (tool-keys.ts), when one does. */
|
|
278
|
-
tools
|
|
311
|
+
tools,
|
|
279
312
|
/** How this server holds its secrets (secrets.ts, the launcher), and what that does not cover. */
|
|
280
313
|
secrets: {
|
|
281
314
|
names: [...SECRET_NAMES],
|
|
@@ -301,14 +334,18 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, needs, toolSettings
|
|
|
301
334
|
timeline: { long_poll: true, sse: true, live_rows: true, live_workflow_rows: false },
|
|
302
335
|
files: { upload: true, read: true, range: false, during_run: true },
|
|
303
336
|
quotes: false,
|
|
304
|
-
usage: { basis: "estimate", meters: ["tokens", "tools", "learning"] },
|
|
337
|
+
usage: { basis: "estimate", meters: ["tokens", "tools", "browser_time", "learning"] },
|
|
305
338
|
efforts: [...EFFORTS],
|
|
306
339
|
thinking: [...THINKING_LEVELS],
|
|
307
|
-
browser:
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
340
|
+
/** The browser a run's `browser` tool drives: the vendor it resolves to under the server's settings when the tool is
|
|
341
|
+
* available here (tools[]), Browserbase's or Kernel's, else none. */
|
|
342
|
+
browser: browser?.available ? (browser.resolves?.[DEFAULT_HARNESS] === "kernel" ? "kernel" : "browserbase") : "none",
|
|
343
|
+
/** A tool setting's `permission` (definition.tool_settings, /v2/settings/tools): allow, ask or deny, which the tool
|
|
344
|
+
* gate holds every tool call to (tool-gate.ts); an ask is answered at POST /runs/{id}/approvals/{approval_id}. */
|
|
345
|
+
tool_permissions: true,
|
|
346
|
+
/** An agent's browser stays signed in between its runs (sign-ins.ts): with a seal key to keep each pointer under, and a
|
|
347
|
+
* browser vendor here (Browserbase's or Kernel's; local Chrome keeps none). */
|
|
348
|
+
sign_ins: sealKeyOf(env[SEAL_KEY_ENV]) !== undefined && tools.some((tool) => tool.name === "browser" && tool.available),
|
|
312
349
|
vault: false,
|
|
313
350
|
query: false,
|
|
314
351
|
/** GET, PUT and DELETE /settings/tool-keys: a tool's key saved by name, kept sealed under the launcher's seal key
|
|
@@ -322,6 +359,8 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, needs, toolSettings
|
|
|
322
359
|
/** /settings/webhook: one URL POSTed, signed by the Standard Webhooks spec, when a run needs its person and when it
|
|
323
360
|
* ends (webhooks.ts); its secret kept sealed under the same seal key, so with none no webhook is set. */
|
|
324
361
|
webhooks: { routes: true, events: [...WEBHOOK_EVENTS], signing: "standard-webhooks/v1", at_rest: sealKeyOf(env[SEAL_KEY_ENV]) ? "sealed" : "unavailable" },
|
|
362
|
+
/** /triggers: what starts an agent's capped runs with no caller (triggers.ts). */
|
|
363
|
+
triggers: { routes: true, sources: [...SOURCE_KINDS], targets: [...TARGET_KINDS], overlap: [...OVERLAP], min_every_s: MIN_EVERY_S, history_kept: HISTORY_KEPT, catchup_window_s: CATCHUP_WINDOW_S, failures_to_pause: FAILURES_TO_PAUSE, webhook: { signing: "standard-webhooks/v1", tolerance_s: HOOK_TOLERANCE_S, max_body_bytes: HOOK_MAX_BODY, payload_kept_bytes: PAYLOAD_KEPT_BYTES, at_rest: sealKeyOf(env[SEAL_KEY_ENV]) ? "sealed" : "unavailable" } },
|
|
325
364
|
},
|
|
326
365
|
regions: [{ id: "local", jurisdiction: null, state: "live" }],
|
|
327
366
|
/** This server's own: where its OpenAPI document is, beside this one. */
|
|
@@ -393,6 +432,7 @@ export async function startServe(options) {
|
|
|
393
432
|
throw new Error(`the drain timeout ${options.drainTimeout} is not a duration such as 8s`);
|
|
394
433
|
enabledBoxes(process.env);
|
|
395
434
|
boxLimitsOf(process.env);
|
|
435
|
+
const boxAllow = boxAllowOf(process.env);
|
|
396
436
|
const maxRuns = maxRunsOf(process.env, options.maxRuns);
|
|
397
437
|
const learning = learningOf(process.env, options.learning);
|
|
398
438
|
const learningBudget = learningBudgetOf(process.env, options.learningBudget);
|
|
@@ -413,7 +453,7 @@ export async function startServe(options) {
|
|
|
413
453
|
try {
|
|
414
454
|
// The server's record, which its stop rewrites in place (server-lock.ts): made now, so the stop makes nothing.
|
|
415
455
|
markRunning(data);
|
|
416
|
-
return await startHolding(options, data, lock, { maxRuns, minFreeBytes, learning, learningBudget }, stops);
|
|
456
|
+
return await startHolding(options, data, lock, { maxRuns, minFreeBytes, learning, learningBudget, boxAllow }, stops);
|
|
417
457
|
}
|
|
418
458
|
catch (error) {
|
|
419
459
|
for (const stop of stops)
|
|
@@ -423,7 +463,7 @@ export async function startServe(options) {
|
|
|
423
463
|
}
|
|
424
464
|
}
|
|
425
465
|
async function startHolding(options, data, lock, checked, stops) {
|
|
426
|
-
const { maxRuns, minFreeBytes, learning, learningBudget } = checked;
|
|
466
|
+
const { maxRuns, minFreeBytes, learning, learningBudget, boxAllow } = checked;
|
|
427
467
|
const tokenFile = options.token === undefined ? join(data, TOKEN_FILE) : null;
|
|
428
468
|
const stored = options.token === undefined ? await tokenIn(tokenFile) : undefined;
|
|
429
469
|
const token = options.token ?? stored.token;
|
|
@@ -434,14 +474,16 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
434
474
|
const authFailed = (route, reason) => log?.(logLine("auth_failed", { route, reason }));
|
|
435
475
|
/** The host's secrets as a run's notes are checked against (learning-run.ts), and the keys a person saved on this
|
|
436
476
|
* server (storedKeys, below), read at each call: a person's note, and every learning text read. */
|
|
437
|
-
const learningSecrets = () => [...hostSecrets(process.env, storedKeys), token, doorToken];
|
|
477
|
+
const learningSecrets = () => [...hostSecrets(process.env, storedKeys), token, doorToken, ...(triggerSecrets?.values() ?? [])];
|
|
478
|
+
// Each webhook trigger's secret, made below once the environment is read; shown nowhere, as the server's own are not.
|
|
479
|
+
let triggerSecrets;
|
|
438
480
|
const base = { ...withoutFaux(process.env), [DATA_ENV]: data, ...(options.allowCodeNodes ? { [CODE_NODES_ENV]: "1" } : {}), ...(options.faux ? { [FAUX_ENV]: resolve(options.faux) } : {}), ...(options.fauxHarness ? { [FAUX_HARNESS_ENV]: resolve(options.fauxHarness) } : {}) };
|
|
439
481
|
// Which fields are the server's is read from what it is started with alone: handed the saved keys too, ToolKeys would
|
|
440
482
|
// call each the server's, and none could be deleted.
|
|
441
483
|
const toolKeys = new ToolKeys(data, withSecrets(base, "own"), (fields) => (log ? log(logLine("tool_keys", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("tool_keys", fields)}\n`)));
|
|
442
484
|
// A key's check as it is saved (key-check.ts) goes to its provider; under faux only to the tests' fake for that provider,
|
|
443
485
|
// the one its runs are given (monid, Parallel, TypeSafe's Jev), never to the network: one with no fake is not checked.
|
|
444
|
-
const fakes = { monid: options.fauxMonid, parallel: options.fauxParallel, typesafe: options.fauxJev };
|
|
486
|
+
const fakes = { monid: options.fauxMonid, parallel: options.fauxParallel, typesafe: options.fauxJev, browserbase: options.fauxBrowserbase, kernel: options.fauxKernel };
|
|
445
487
|
const checkFetch = async (id) => {
|
|
446
488
|
if (!options.faux)
|
|
447
489
|
return fetch;
|
|
@@ -470,7 +512,10 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
470
512
|
// Whether a revision that names no model runs (needsOf): made from env alone, so remade with it, before the caps.
|
|
471
513
|
let needs = await needsOf(env);
|
|
472
514
|
// The box offers are probed once, below, before the first reading is made.
|
|
473
|
-
|
|
515
|
+
// With accounts off no one can answer an ask (the answer route takes the owner's session alone): each tool ask is
|
|
516
|
+
// offered for says it needs the password sign-in, as learning's approve does.
|
|
517
|
+
const askNeeds = (made) => (options.accounts ? made : { ...made, tools: made.tools.map((tool) => (tool.permissions.includes("ask") ? { ...tool, ask_needs: "password" } : tool)) });
|
|
518
|
+
const recompose = () => void (caps = askNeeds(capabilitiesWith(env, maxRuns, offers, learning, needs, settings.get(), boxOffers, options.gradeModel, toolKeys.refused())));
|
|
474
519
|
// What the offers held now were made from (offersInputs), and the latest probe: one a later probe overtook is dropped.
|
|
475
520
|
let offersFrom;
|
|
476
521
|
let probes = 0;
|
|
@@ -505,13 +550,28 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
505
550
|
};
|
|
506
551
|
// The boxes AGENTRUN_BOXES lists, each probed once (boxes.ts); runs execute in Docker's (place.ts). Under --faux, a faux
|
|
507
552
|
// box stands in for Docker, and nothing asks Docker.
|
|
508
|
-
|
|
553
|
+
// Under --faux, the tests' fake stands in for the VM provider's SDK (startServe's `fauxVm`), never the provider.
|
|
554
|
+
const boxes = await boxRegistry(env, options.faux && options.fauxVm ? { vmSdk: () => import(pathToFileURL(resolve(options.fauxVm)).href) } : {});
|
|
509
555
|
const fauxBox = options.faux && options.fauxBox ? await fauxBoxes(resolve(options.fauxBox), data) : undefined;
|
|
510
556
|
// The Docker box's image, asked of Docker now and pulled in the background when Docker has none (box-image.ts): docker
|
|
511
557
|
// is preparing until it is in, and unavailable if the pull fails. Its record tells the run's processes; with no Docker
|
|
512
558
|
// box here there is none, so no run waits on one an earlier start left.
|
|
513
559
|
let image;
|
|
514
|
-
|
|
560
|
+
// What a Docker box's programs reach, resolved once here (run-box.ts boxNetworkOf): the setting's list, on a Docker
|
|
561
|
+
// daemon of this Linux machine's own; else none, and why. A run's process gets the list or none (RUN_BOX_ALLOW_ENV).
|
|
562
|
+
const boxNetwork = fauxBox ? { allow: "none", reason: "a faux box (tests)" } : boxes.provider("docker") ? await boxNetworkOf(env) : { allow: "none", reason: "no Docker box on this server" };
|
|
563
|
+
// The proxy directories runs that are gone left in /tmp (box-egress.ts): a live run's, any server's, stays.
|
|
564
|
+
if (!fauxBox && boxes.provider("docker"))
|
|
565
|
+
await sweepEgressDirs().catch(() => 0);
|
|
566
|
+
const dockerNetwork = (offer) => !offer.available ? offer : boxNetwork.allow === "none" ? { ...offer, network: "none", network_reason: boxNetwork.reason } : { ...offer, network: "allowlist" };
|
|
567
|
+
// A Daytona box reaches the hosts AGENTRUN_BOX_ALLOW names, through Daytona's domain list, until Daytona cannot keep
|
|
568
|
+
// one here (an organization whose tier takes none): from then on each is made with no network, and capabilities say why.
|
|
569
|
+
let daytonaNoList;
|
|
570
|
+
const daytonaNetwork = (offer) => !offer.available ? offer : boxAllow === "none" ? { ...offer, network: "none" } : daytonaNoList ? { ...offer, network: "none", network_reason: noListReason(daytonaNoList) } : { ...offer, network: "allowlist" };
|
|
571
|
+
// The VM box has no network whatever AGENTRUN_BOX_ALLOW names: its provider takes a host list, but has no read of a
|
|
572
|
+
// box's list back, so the server cannot check one held (run-box.ts ensureRemoteBox makes it blocked). Said, with why.
|
|
573
|
+
const vmNetwork = (offer) => (!offer.available ? offer : boxAllow === "none" ? { ...offer, network: "none" } : { ...offer, network: "none", network_reason: VM_NO_LIST });
|
|
574
|
+
const offersNow = () => boxes.offers().map((offer) => (fauxBox && offer.id === "docker" ? dockerNetwork({ id: "docker", available: true, reason: "a faux box (tests)" }) : offer.id === "docker" ? dockerNetwork(image ? withImage(offer, image.state()) : offer) : offer.id === "daytona" ? daytonaNetwork(offer) : offer.id === VM_PROVIDER.id ? vmNetwork(offer) : offer));
|
|
515
575
|
const imageLog = (state, more = {}) => log?.(logLine("box_image", { image: image.image, state: state.state, ...more, ...("reason" in state ? { reason: state.reason } : {}) }));
|
|
516
576
|
let boxOffers = offersNow();
|
|
517
577
|
const boxImage = !fauxBox && boxes.provider("docker") ? boxImageOf(env) : undefined;
|
|
@@ -536,11 +596,35 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
536
596
|
// Daytona's boxes are made, seeded, pulled and destroyed here, with the key this server holds; a run's process reaches
|
|
537
597
|
// its own through the relay below, which holds the key for it (box-relay.ts).
|
|
538
598
|
const remoteBoxes = boxes.provider("daytona");
|
|
599
|
+
// And the VM box's, the same way, with this server's SDK client: the relay's VM half makes a run's calls with it.
|
|
600
|
+
const vmBoxes = boxes.provider(VM_PROVIDER.id);
|
|
601
|
+
const vmClient = boxes.vmClient();
|
|
602
|
+
// What the provider says in an error is cut of every value this server holds (the VM token among them) before a run's
|
|
603
|
+
// process sees it.
|
|
604
|
+
const vmSecrets = () => [...learningSecrets(), ...VM_PROVIDER.keys.map((name) => env[name] ?? "").filter(Boolean)];
|
|
605
|
+
const vmRelayHalf = vmBoxes && vmClient ? vmRelay(vmClient, vmSecrets) : undefined;
|
|
606
|
+
const vmLimits = (() => {
|
|
607
|
+
const limits = boxLimitsOf(env);
|
|
608
|
+
return { cpus: limits.cpus, memoryMb: memoryMbOf(limits.memory) };
|
|
609
|
+
})();
|
|
610
|
+
// Daytona could not keep a run's box's domain list: said in the log and in capabilities, which recompose now.
|
|
611
|
+
// Daytona's own words go to the log, so a refusal for another cause is not taken silently for a tier that takes no list.
|
|
612
|
+
const onNoBoxList = (code, message) => {
|
|
613
|
+
daytonaNoList = code;
|
|
614
|
+
log?.(logLine("box_network", { box: "daytona", network: "none", refused: code, message }));
|
|
615
|
+
boxOffers = offersNow();
|
|
616
|
+
if (offers)
|
|
617
|
+
recompose();
|
|
618
|
+
};
|
|
539
619
|
log?.(logLine("boxes", boxesLog(boxOffers, enabledBoxes(env))));
|
|
540
620
|
if (image)
|
|
541
621
|
imageLog(image.state());
|
|
542
622
|
const openapi = openapiDocument((operationId) => ROUTES.find((r) => r.name === operationId)?.capability);
|
|
543
623
|
const agents = new Agents(data);
|
|
624
|
+
triggerSecrets = new TriggerSecrets(data, env, (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)));
|
|
625
|
+
// Each agent's saved sign-ins (sign-ins.ts), under the seal key the tool keys are kept under: its vendor's calls on the
|
|
626
|
+
// server's keys (under faux, the vendor's fake alone), and a lease held while the run it names has not ended.
|
|
627
|
+
const signIns = new SignIns(data, sealKeyOf(withSecrets(base, "own")[SEAL_KEY_ENV]), vendorsOver(() => env, checkFetch), async (runId) => (await agents.request(() => agents.store.readRun(runId)))?.state === "running");
|
|
544
628
|
const webhooks = new Webhooks(data, env, (fields) => (log ? log(logLine("webhook", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("webhook", fields)}\n`)), options.webhookRetryMs);
|
|
545
629
|
stops.push(() => webhooks.close());
|
|
546
630
|
const uploads = new Uploads(join(data, UPLOADS_DIR));
|
|
@@ -552,9 +636,9 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
552
636
|
const documents = options.documents ?? process.env[DOCUMENTS_ENV];
|
|
553
637
|
if (documents !== undefined && !(await stat(documents).then((info) => info.isDirectory(), () => false)))
|
|
554
638
|
throw new Error(`the documents directory ${documents} is not a directory`);
|
|
555
|
-
const runs = new Runs({ agents, token, storedKeys, doorTokenFile, doorToken, learning, learningBudget, ...(documents ? { documents: resolve(documents) } : {}), fauxEnv: fauxEnvOf(options), toolSettings: () => settings.get(), ...(runBoxes ? { runBoxes } : {}), ...(remoteBoxes ? { remoteBoxes } : {}), ...(remoteBoxes && daytonaApi(env) ? { remoteApi: daytonaApi(env) } : {}), ...(options.drainTimeout ? { drainTimeout: options.drainTimeout } : {}), ...(options.carryBackRetry ? { carryBackRetry: options.carryBackRetry } : {}), maxRuns, ...(options.box ? { box: { host: options.box, quarantine: await Quarantine.open(join(data, BOX_QUARANTINE)) } } : {}), ...(options.settleRetryMs ? { settleRetryMs: options.settleRetryMs } : {}), ...(options.readyTimeoutMs ? { readyTimeoutMs: options.readyTimeoutMs } : {}), ...(options.reflectTimeoutMs ? { reflectTimeoutMs: options.reflectTimeoutMs } : {}), ...(options.gradeTimeoutMs ? { gradeTimeoutMs: options.gradeTimeoutMs } : {}), ...(options.gradeModel ? { gradeModel: options.gradeModel } : {}), ...(log ? { log: (event, fields) => log(logLine(event, fields)) } : {}), notify: (event, run, marker) => webhooks.emit(event, run, marker) });
|
|
639
|
+
const runs = new Runs({ dockerAllow: boxNetwork.allow, agents, token, storedKeys, doorTokenFile, doorToken, learning, learningBudget, ...(documents ? { documents: resolve(documents) } : {}), fauxEnv: fauxEnvOf(options), toolSettings: () => settings.get(), ...(runBoxes ? { runBoxes } : {}), ...(remoteBoxes ? { remoteBoxes } : {}), ...(vmBoxes && vmRelayHalf ? { vmBoxes, vmLimits, vmRelay: vmRelayHalf } : {}), ...(remoteBoxes && daytonaApi(env) ? { remoteApi: daytonaApi(env) } : {}), ...(remoteBoxes ? { boxAllow, onNoBoxList } : {}), ...(options.drainTimeout ? { drainTimeout: options.drainTimeout } : {}), ...(options.carryBackRetry ? { carryBackRetry: options.carryBackRetry } : {}), maxRuns, ...(options.box ? { box: { host: options.box, quarantine: await Quarantine.open(join(data, BOX_QUARANTINE)) } } : {}), ...(options.settleRetryMs ? { settleRetryMs: options.settleRetryMs } : {}), ...(options.readyTimeoutMs ? { readyTimeoutMs: options.readyTimeoutMs } : {}), ...(options.reflectTimeoutMs ? { reflectTimeoutMs: options.reflectTimeoutMs } : {}), ...(options.gradeTimeoutMs ? { gradeTimeoutMs: options.gradeTimeoutMs } : {}), ...(options.gradeModel ? { gradeModel: options.gradeModel } : {}), ...(log ? { log: (event, fields) => log(logLine(event, fields)) } : {}), notify: (event, run, marker) => webhooks.emit(event, run, marker), ownSecrets: () => triggerSecrets?.values() ?? [], signIns, approvers: options.accounts === true });
|
|
556
640
|
const daytona = daytonaApi(env);
|
|
557
|
-
const relay = remoteBoxes && daytona ? await startBoxRelay({ root: data, tokenOf: (id) => runs.relayToken(id), ...daytona, serves: (id) => runs.servesBox(id), ensure: (id) => runs.ensureBox(id) }) : undefined;
|
|
641
|
+
const relay = (remoteBoxes && daytona) || vmRelayHalf ? await startBoxRelay({ root: data, tokenOf: (id) => runs.relayToken(id), ...(remoteBoxes && daytona ? daytona : {}), ...(vmRelayHalf ? { vm: vmRelayHalf } : {}), serves: (id) => runs.servesBox(id), ensure: (id) => runs.ensureBox(id) }) : undefined;
|
|
558
642
|
if (relay)
|
|
559
643
|
stops.push(() => relay.close());
|
|
560
644
|
const expected = digest(`Bearer ${token}`);
|
|
@@ -564,6 +648,12 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
564
648
|
runs.beforeReopenLaunch = options.beforeReopenLaunch;
|
|
565
649
|
if (options.beforeSubmit)
|
|
566
650
|
runs.beforeSubmit = options.beforeSubmit;
|
|
651
|
+
if (options.beforeMetaSave)
|
|
652
|
+
runs.beforeMetaSave = options.beforeMetaSave;
|
|
653
|
+
if (options.onRunLoad)
|
|
654
|
+
runs.onRunLoad = options.onRunLoad;
|
|
655
|
+
if (options.messageOrigin)
|
|
656
|
+
runs.messageOrigin = options.messageOrigin;
|
|
567
657
|
const keptFile = join(data, IDEMPOTENCY_FILE);
|
|
568
658
|
const kept = JSON.parse(await readFile(keptFile, "utf8").catch(() => "null"));
|
|
569
659
|
const idempotency = new Map((kept?.entries ?? []).filter(([, v]) => v?.answer && Date.now() - v.at <= IDEMPOTENCY_TTL_S * 1000));
|
|
@@ -581,6 +671,16 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
581
671
|
// A saved key is read by name from here, past the checks that refuse a start and before any run (a recovered one too)
|
|
582
672
|
// is launched: each launch hands over what is saved then. One server in a process reads them: the last started.
|
|
583
673
|
await probe("start");
|
|
674
|
+
// Under faux, a key the server starts with is checked only against a check's own fake (fauxBrowserbase,
|
|
675
|
+
// fauxMonidCheck, fauxKernel): the fakes the runs use (monid, Parallel, Jev) see the runs' calls alone, and a key with no check fake
|
|
676
|
+
// is not checked.
|
|
677
|
+
const checkFakes = { browserbase: options.fauxBrowserbase, monid: options.fauxMonidCheck, kernel: options.fauxKernel };
|
|
678
|
+
const startFetch = async (id) => {
|
|
679
|
+
if (!options.faux)
|
|
680
|
+
return fetch;
|
|
681
|
+
const fake = checkFakes[id];
|
|
682
|
+
return fake ? (await import(pathToFileURL(resolve(fake)).href)).default : null;
|
|
683
|
+
};
|
|
584
684
|
// Decided once, by the probe the confinement walks by: capabilities.home.writes says what PUT and DELETE do.
|
|
585
685
|
const homeWrites = caps.home.writes;
|
|
586
686
|
// Runs an earlier server left: supervised again, carried back when they already ended, or opened again. Then, however
|
|
@@ -604,6 +704,77 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
604
704
|
});
|
|
605
705
|
})
|
|
606
706
|
.catch((error) => void process.stderr.write(`agentrun-serve: the webhook's catch-up: ${error.message}\n`));
|
|
707
|
+
// Schedules: each firing starts its run as POST /agents/{id}/runs does, capped, under the firing's key (triggers.ts).
|
|
708
|
+
// Firings an earlier server left due are driven again now, beside the recovery above.
|
|
709
|
+
const triggers = new Triggers(data, {
|
|
710
|
+
clock: options.triggerClock,
|
|
711
|
+
say: (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)),
|
|
712
|
+
async targetIssues(target) {
|
|
713
|
+
if (target.kind === "message_run") {
|
|
714
|
+
const run = await runs.get(target.run_id);
|
|
715
|
+
if (!run)
|
|
716
|
+
return [{ field: "target.run_id", reason: "not_found", message: `no run ${target.run_id}` }];
|
|
717
|
+
if (run.kind === "workflow")
|
|
718
|
+
return [{ field: "target.run_id", reason: "not_allowed", message: "A workflow run takes no messages here." }];
|
|
719
|
+
return run.meta.max_cost_usd === undefined ? [{ field: "target.run_id", reason: "not_allowed", message: NO_CAP }] : [];
|
|
720
|
+
}
|
|
721
|
+
const entry = await agents.get(target.agent_id);
|
|
722
|
+
if (!entry)
|
|
723
|
+
return [{ field: "target.agent_id", reason: "not_found", message: `no agent ${target.agent_id}` }];
|
|
724
|
+
if (!entry.revision)
|
|
725
|
+
return [{ field: "target.agent_id", reason: "invalid", message: `the agent ${target.agent_id} has no current revision` }];
|
|
726
|
+
if (entry.revision.kind === "workflow")
|
|
727
|
+
return [{ field: "target.agent_id", reason: "not_allowed", message: "A trigger's runs are capped, and a workflow run's spend is not capped here: name an agent that is not a workflow." }];
|
|
728
|
+
const uncapped = target.max_cost_usd === undefined && entry.revision.body.maxCostUsd === undefined ? [{ field: "target.max_cost_usd", reason: "missing", message: `Every run a trigger starts is capped: give the target a max_cost_usd or set the agent's (the agent ${target.agent_id} has none).` }] : [];
|
|
729
|
+
return [...uncapped, ...(await inputIssuesOf(entry.revision, target.input)).map((issue) => ({ ...issue, field: `target.${issue.field}` }))];
|
|
730
|
+
},
|
|
731
|
+
async start(target, input, trigger) {
|
|
732
|
+
const entry = await needAgent(target.agent_id);
|
|
733
|
+
// The target's cap, else the agent's default as it stands now: a run a trigger starts is never uncapped.
|
|
734
|
+
const run = await startRunOf(entry, { input, ...(target.max_cost_usd !== undefined ? { max_cost_usd: target.max_cost_usd } : {}), ...(target.effort ? { effort: target.effort } : {}) }, { trigger, origin: { key: trigger.firing_key }, capped: true });
|
|
735
|
+
return { run_id: run.id };
|
|
736
|
+
},
|
|
737
|
+
async message(target, input, key) {
|
|
738
|
+
const run = await needRun(target.run_id);
|
|
739
|
+
if (run.kind === "workflow")
|
|
740
|
+
throw unsupported("messages.steer_workflow_runs", "A workflow run takes no messages here.");
|
|
741
|
+
// A store held past its retries is a busy store: the firing stays due and is tried again, never failed.
|
|
742
|
+
if (await runs.tookMessage(run, key).catch((error) => { throw storeBusy(error) ? homeBusy() : error; }))
|
|
743
|
+
return;
|
|
744
|
+
// Never an uncapped turn, nor an answer to a person's question, an approval or a budget pause: a run that waits on
|
|
745
|
+
// its person is told nothing by a trigger.
|
|
746
|
+
if (run.meta.max_cost_usd === undefined)
|
|
747
|
+
throw new ApiError("not_continuable", NO_CAP);
|
|
748
|
+
const { status, state } = statusOf(run);
|
|
749
|
+
if (status === "input_required" && state === "waiting")
|
|
750
|
+
return { skipped: WAITS_ON_A_PERSON };
|
|
751
|
+
try {
|
|
752
|
+
await runs.message(run, String(input.content), key, { answers: false });
|
|
753
|
+
}
|
|
754
|
+
catch (error) {
|
|
755
|
+
if (error instanceof ApiError && error.message === WAITS_ON_A_PERSON)
|
|
756
|
+
return { skipped: WAITS_ON_A_PERSON };
|
|
757
|
+
throw error;
|
|
758
|
+
}
|
|
759
|
+
},
|
|
760
|
+
secrets: { mint: (id) => triggerSecrets.mint(id), remove: (id) => triggerSecrets.remove(id) },
|
|
761
|
+
notify: (failed, key) => webhooks.emitTrigger(failed, key),
|
|
762
|
+
async runOf(key) {
|
|
763
|
+
const started = await agents.request(() => agents.store.runOfOrigin(key));
|
|
764
|
+
if (!started)
|
|
765
|
+
return null;
|
|
766
|
+
// Never set up as runs.ts load reads it (notSetUp: the store has it running and its serve.json holds no input), which
|
|
767
|
+
// this start's recovery fails as server_lost_at_setup; or failed so already.
|
|
768
|
+
const run = await runs.get(started.runId);
|
|
769
|
+
return { run_id: started.runId, setup_lost: run?.notSetUp === true || run?.error?.details?.reason === SETUP_LOST };
|
|
770
|
+
},
|
|
771
|
+
async statusOf(runId) {
|
|
772
|
+
const row = await agents.request(() => agents.store.readRun(runId));
|
|
773
|
+
return row ? runs.statusOfRow(row) : null;
|
|
774
|
+
},
|
|
775
|
+
});
|
|
776
|
+
stops.push(async () => triggers.close());
|
|
777
|
+
triggers.start();
|
|
607
778
|
// Setup's import of this machine's sessions: offered by a server on this machine only (no public address, listening
|
|
608
779
|
// on loopback), counted once (a listing, no transcript kept), run once, each on a worker thread (import-worker.ts) so
|
|
609
780
|
// a busy store's wait and the sessions' parsing never hold up a request.
|
|
@@ -688,20 +859,46 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
688
859
|
}
|
|
689
860
|
})());
|
|
690
861
|
// ---- helpers --------------------------------------------------------------------------------------------------------
|
|
691
|
-
/** The body's bytes, at most
|
|
692
|
-
async function bytesOf(req) {
|
|
862
|
+
/** The body's bytes, at most `max` of them. */
|
|
863
|
+
async function bytesOf(req, max = MAX_BODY) {
|
|
693
864
|
const chunks = [];
|
|
694
865
|
let size = 0;
|
|
695
866
|
// An oversized body is read to its end before the refusal, so the client gets the answer and not a reset.
|
|
696
867
|
for await (const chunk of req) {
|
|
697
868
|
size += chunk.length;
|
|
698
|
-
if (size <=
|
|
869
|
+
if (size <= max)
|
|
699
870
|
chunks.push(chunk);
|
|
700
871
|
}
|
|
701
|
-
if (size >
|
|
702
|
-
throw new ApiError("payload_too_large", `the body is over ${
|
|
872
|
+
if (size > max)
|
|
873
|
+
throw new ApiError("payload_too_large", `the body is over ${max} bytes`, { details: { limit: "max_body_bytes" } });
|
|
703
874
|
return Buffer.concat(chunks);
|
|
704
875
|
}
|
|
876
|
+
/** POST /v2/hooks/{trigger_id}: a webhook trigger's firing, signed by the Standard Webhooks spec under its secret
|
|
877
|
+
* (trigger-secrets.ts), checked on the raw body before anything else. An unknown trigger, one that is off or not a
|
|
878
|
+
* webhook's, and a check that fails are one answer, so no trigger id can be found by asking; an unknown one is
|
|
879
|
+
* checked against a secret of no trigger's, so it takes the same time. A webhook-id already fired answers its firing. */
|
|
880
|
+
async function hook(req, res, path) {
|
|
881
|
+
const refuse = (reason) => {
|
|
882
|
+
authFailed(`/v2${path}`, reason);
|
|
883
|
+
return new ApiError("unauthenticated", "this route needs a request signed by the webhook trigger's secret");
|
|
884
|
+
};
|
|
885
|
+
// Headers that can never pass are refused before a byte of the body is read; they say nothing of the trigger.
|
|
886
|
+
const early = hookHeadersRefusal(req.headers, Date.now());
|
|
887
|
+
if (early)
|
|
888
|
+
throw refuse(early);
|
|
889
|
+
const body = await bytesOf(req, HOOK_MAX_BODY);
|
|
890
|
+
let id = "";
|
|
891
|
+
try {
|
|
892
|
+
id = decodeURIComponent(/^\/hooks\/([^/]+)$/.exec(path)[1]);
|
|
893
|
+
}
|
|
894
|
+
catch { }
|
|
895
|
+
const secret = ID.test(id) && triggers.hookable(id) ? triggerSecrets.value(id) : undefined;
|
|
896
|
+
const refusal = hookRefusal(secret ?? NO_TRIGGER_SECRET, req.headers, body, Date.now());
|
|
897
|
+
if (!secret || refusal)
|
|
898
|
+
throw refuse(secret ? refusal : "no_webhook_trigger");
|
|
899
|
+
const { created, firing } = triggers.receive(id, String(req.headers["webhook-id"]), body.toString("utf8"));
|
|
900
|
+
return send(res, created ? 202 : 200, firing, created ? {} : { "idempotent-replayed": "true" });
|
|
901
|
+
}
|
|
705
902
|
async function bodyOf(req) {
|
|
706
903
|
const type = String(req.headers["content-type"] ?? "");
|
|
707
904
|
if (!type.startsWith("application/json"))
|
|
@@ -730,7 +927,9 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
730
927
|
throw new ApiError("not_found", `no run ${id}`);
|
|
731
928
|
return run;
|
|
732
929
|
}
|
|
733
|
-
|
|
930
|
+
const mismatch = () => new ApiError("idempotency_mismatch", "this Idempotency-Key was used with another body");
|
|
931
|
+
/** Replays the first answer to a create with the same key and body; another body is a mismatch. `work` gets the key's
|
|
932
|
+
* origin (its slot and the body, hashed) for a create the agent store records with the run it starts. */
|
|
734
933
|
async function idempotent(req, path, body, work) {
|
|
735
934
|
const key = req.headers["idempotency-key"];
|
|
736
935
|
if (key === undefined)
|
|
@@ -746,7 +945,7 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
746
945
|
const known = idempotency.get(slot);
|
|
747
946
|
if (known) {
|
|
748
947
|
if (known.fingerprint !== fingerprint)
|
|
749
|
-
throw
|
|
948
|
+
throw mismatch();
|
|
750
949
|
if (!known.answer)
|
|
751
950
|
throw new ApiError("idempotency_in_progress", "the first request with this Idempotency-Key is still in flight", { retry_after_ms: 500 });
|
|
752
951
|
return { ...known.answer, headers: { ...known.answer.headers, "idempotent-replayed": "true" } };
|
|
@@ -754,14 +953,15 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
754
953
|
idempotency.set(slot, { fingerprint, at: now });
|
|
755
954
|
let answer;
|
|
756
955
|
try {
|
|
757
|
-
answer = await work();
|
|
956
|
+
answer = await work({ key: `idk_${sha256Hex(slot).slice(0, 32)}`, fingerprint: sha256Hex(fingerprint) });
|
|
758
957
|
}
|
|
759
958
|
catch (error) {
|
|
760
959
|
idempotency.delete(slot);
|
|
761
960
|
throw error;
|
|
762
961
|
}
|
|
763
962
|
// The work happened, so the key keeps its answer in memory even when the file write fails: a retry replays it
|
|
764
|
-
// instead of doing the work twice. Only a restart before the next good save loses it
|
|
963
|
+
// instead of doing the work twice. Only a restart before the next good save loses it, and a run's create not even
|
|
964
|
+
// then: the store keeps its run under the key's origin.
|
|
765
965
|
idempotency.set(slot, { fingerprint, at: now, answer: { status: answer.status, body: answer.body, headers: answer.headers ?? {} } });
|
|
766
966
|
await keep().catch((error) => void process.stderr.write(`agentrun-serve: idempotency save: ${error.message}\n`));
|
|
767
967
|
return answer;
|
|
@@ -788,11 +988,23 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
788
988
|
throw new ApiError("agent_not_runnable", message, { details: { unbound, missing, ...named } });
|
|
789
989
|
const tier = blockers.find((b) => b.tier)?.tier;
|
|
790
990
|
const decisions = Object.fromEntries(blockers.flatMap((b) => (b.decision ? [[b.decision.provider, { reason: b.reason, needs: b.decision.needs }]] : [])));
|
|
791
|
-
|
|
991
|
+
const denied = blockers.flatMap((b) => (b.denied ? [b.denied] : []));
|
|
992
|
+
const asks = blockers.flatMap((b) => (b.asks ? [b.asks] : []));
|
|
993
|
+
throw new ApiError("agent_not_runnable", message, { details: { adapters: [...new Set(blockers.flatMap((b) => (b.adapter ? [b.adapter] : [])))], unbound, missing, code: blockers.some((b) => b.codeNodes || b.shell), ...(tier ? { tier } : {}), ...(Object.keys(decisions).length ? { decisions } : {}), ...(denied.length ? { denied } : {}), ...(asks.length ? { asks } : {}), ...named } });
|
|
792
994
|
}
|
|
793
995
|
/** A definition being saved: refused (422 by field) when it can never run here; else what this host still lacks. */
|
|
794
996
|
async function saveable(revision) {
|
|
795
|
-
const
|
|
997
|
+
const shape = revision.kind === "agentic" ? revision : workflowShape(revision);
|
|
998
|
+
const blockers = await blockersOf(env, shape, settings.get(), { boxes: boxOffers, offers });
|
|
999
|
+
// An agent's default cap caps each run started without one of its own, and a web tool resolves by the cap: what a cap
|
|
1000
|
+
// alone keeps from running under the definition's own picks, whatever this host's settings, would keep every such run
|
|
1001
|
+
// from running, so the save is refused, not each run (claude-agent's or codex's own search, picked, under a cap).
|
|
1002
|
+
if (revision.kind === "agentic" && (revision.maxCostUsd ?? 0) > 0) {
|
|
1003
|
+
const key = (b) => `${b.field}\n${b.message}`;
|
|
1004
|
+
const plain = new Set((await blockersOf(env, shape, {}, { boxes: boxOffers, offers })).map(key));
|
|
1005
|
+
const capped = await blockersOf(env, shape, {}, { capped: true, boxes: boxOffers, offers });
|
|
1006
|
+
blockers.push(...capped.filter((b) => !plain.has(key(b))).map((b) => ({ ...b, reason: "not_an_option", fix: "Pick another provider for this tool in definition.tool_settings, or clear the agent's default cap (max_cost_usd: 0).", host: false })));
|
|
1007
|
+
}
|
|
796
1008
|
const never = blockers.filter((b) => !b.host);
|
|
797
1009
|
if (never.length)
|
|
798
1010
|
throw invalid(never.map(issueOf));
|
|
@@ -811,43 +1023,65 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
811
1023
|
if (entry.agent.archivedAt)
|
|
812
1024
|
throw new ApiError("agent_not_runnable", `The agent ${agentId} is archived: unarchive it to run it.`, { details: { archived_at: entry.agent.archivedAt } });
|
|
813
1025
|
const body = await bodyOf(req);
|
|
814
|
-
return idempotent(req, `/agents/${agentId}/runs`, body, async () => {
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
if (body.file_ids !== undefined && !Array.isArray(body.file_ids))
|
|
825
|
-
issues.push({ field: "file_ids", reason: "wrong_type", message: "file_ids is a list of file ids" });
|
|
826
|
-
if (issues.length)
|
|
827
|
-
throw invalid(issues);
|
|
828
|
-
if (body.quote_id !== undefined)
|
|
829
|
-
throw unsupported("quotes", "This server has no billing, so it takes no quotes.");
|
|
830
|
-
// Each a ready file, before anything starts: copied into the run's work/inputs/ once its directory is made.
|
|
831
|
-
const files = Array.isArray(body.file_ids) ? await uploads.readyFiles(body.file_ids) : [];
|
|
832
|
-
const pinned = typeof body.revision === "string" ? await agents.revision(entry.agent.id, body.revision) : entry.revision && { revision: entry.revision, version: entry.version };
|
|
833
|
-
if (!pinned)
|
|
834
|
-
throw invalid([{ field: "revision", reason: "not_an_option", message: typeof body.revision === "string" ? `${body.revision} is not a revision of the agent ${entry.agent.id}` : `the agent ${entry.agent.id} has no current revision` }]);
|
|
835
|
-
const { revision, version } = pinned;
|
|
836
|
-
if (revision.kind === "workflow" && body.max_cost_usd !== undefined)
|
|
837
|
-
throw invalid([{ field: "max_cost_usd", reason: "not_allowed", message: "A workflow run's spend is not capped here: its cost shows once it ends." }]);
|
|
838
|
-
const input = body.input;
|
|
839
|
-
const wrong = await inputIssuesOf(revision, input);
|
|
840
|
-
if (wrong.length)
|
|
841
|
-
throw invalid(wrong);
|
|
842
|
-
const place = resolvePlace(revision.body.place);
|
|
843
|
-
await runnable(revision, place, { capped: body.max_cost_usd !== undefined });
|
|
844
|
-
const title = revision.kind === "workflow" ? workflowTitle(entry.agent.name || entry.agent.id, input) : typeof input.content === "string" ? input.content : (Object.values(input).find((v) => typeof v === "string") ?? JSON.stringify(input));
|
|
845
|
-
const run = await runs.create(entry, revision, version, { input, title, place, ...(typeof body.effort === "string" ? { effort: body.effort } : {}), ...(typeof body.max_cost_usd === "number" ? { maxCostUsd: body.max_cost_usd } : {}), ...(files.length ? { inputs: (work) => uploads.copyInto(work, files) } : {}) });
|
|
1026
|
+
return idempotent(req, `/agents/${agentId}/runs`, body, async (origin) => {
|
|
1027
|
+
// A run the store started under this key, though no answer was kept (its server went down first): that run, as it is now.
|
|
1028
|
+
const first = origin && (await agents.request(() => agents.store.runOfOrigin(origin.key)));
|
|
1029
|
+
if (first) {
|
|
1030
|
+
if (first.existing?.fingerprint !== origin.fingerprint)
|
|
1031
|
+
throw mismatch();
|
|
1032
|
+
const headers = { location: `/v2/runs/${first.runId}`, "idempotent-replayed": "true" };
|
|
1033
|
+
return { status: 202, body: await runs.view(await needRun(first.runId)), headers };
|
|
1034
|
+
}
|
|
1035
|
+
const run = await startRunOf(entry, body, { ...(origin ? { origin } : {}) });
|
|
846
1036
|
// Its view from the run itself: it is written, with its first message, so an answer read from the store, which a
|
|
847
1037
|
// busy store would turn into home_busy, would refuse a run that runs, and a retry would start a second one.
|
|
848
1038
|
return { status: 202, body: await runs.view(run, { stored: null }), headers: { location: `/v2/runs/${run.id}` } };
|
|
849
1039
|
});
|
|
850
1040
|
}
|
|
1041
|
+
/** A run of `entry`'s agent from a create's body, checked as POST /agents/{id}/runs checks it: that route's, and a
|
|
1042
|
+
* trigger's firing's, which names itself as the run's `trigger`. Under `origin`, a key that already started a run
|
|
1043
|
+
* gets that run (the agent store's run_origins). */
|
|
1044
|
+
/** `capped`: the run must have a cap (a trigger's), its own or else its agent's default. */
|
|
1045
|
+
async function startRunOf(entry, body, { trigger, origin, capped = false } = {}) {
|
|
1046
|
+
const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "quote_id"]);
|
|
1047
|
+
if (!isObject(body.input))
|
|
1048
|
+
issues.push({ field: "input", reason: body.input === undefined ? "missing" : "wrong_type", message: "input is an object" });
|
|
1049
|
+
if (body.revision !== undefined && (typeof body.revision !== "string" || !ID.test(body.revision)))
|
|
1050
|
+
issues.push({ field: "revision", reason: "wrong_type", message: "revision is a revision id of this agent" });
|
|
1051
|
+
if (body.effort !== undefined && !EFFORTS.includes(body.effort))
|
|
1052
|
+
issues.push({ field: "effort", reason: "not_an_option", message: `effort is one of ${EFFORTS.join(", ")}` });
|
|
1053
|
+
if (body.max_cost_usd !== undefined && !(typeof body.max_cost_usd === "number" && body.max_cost_usd > 0 && Number.isFinite(body.max_cost_usd)))
|
|
1054
|
+
issues.push({ field: "max_cost_usd", reason: "wrong_type", message: "max_cost_usd is a number above 0" });
|
|
1055
|
+
if (body.file_ids !== undefined && !Array.isArray(body.file_ids))
|
|
1056
|
+
issues.push({ field: "file_ids", reason: "wrong_type", message: "file_ids is a list of file ids" });
|
|
1057
|
+
if (issues.length)
|
|
1058
|
+
throw invalid(issues);
|
|
1059
|
+
if (body.quote_id !== undefined)
|
|
1060
|
+
throw unsupported("quotes", "This server has no billing, so it takes no quotes.");
|
|
1061
|
+
// Each a ready file, before anything starts: copied into the run's work/inputs/ once its directory is made.
|
|
1062
|
+
const files = Array.isArray(body.file_ids) ? await uploads.readyFiles(body.file_ids) : [];
|
|
1063
|
+
const pinned = typeof body.revision === "string" ? await agents.revision(entry.agent.id, body.revision) : entry.revision && { revision: entry.revision, version: entry.version };
|
|
1064
|
+
if (!pinned)
|
|
1065
|
+
throw invalid([{ field: "revision", reason: "not_an_option", message: typeof body.revision === "string" ? `${body.revision} is not a revision of the agent ${entry.agent.id}` : `the agent ${entry.agent.id} has no current revision` }]);
|
|
1066
|
+
const { revision, version } = pinned;
|
|
1067
|
+
if (revision.kind === "workflow" && body.max_cost_usd !== undefined)
|
|
1068
|
+
throw invalid([{ field: "max_cost_usd", reason: "not_allowed", message: "A workflow run's spend is not capped here: its cost shows once it ends." }]);
|
|
1069
|
+
const input = body.input;
|
|
1070
|
+
const wrong = await inputIssuesOf(revision, input);
|
|
1071
|
+
if (wrong.length)
|
|
1072
|
+
throw invalid(wrong);
|
|
1073
|
+
// The run's own cap, else the agent's default (an agentic revision's): the caller chose its own.
|
|
1074
|
+
const cap = typeof body.max_cost_usd === "number" ? body.max_cost_usd : revision.kind === "agentic" ? revision.body.maxCostUsd : undefined;
|
|
1075
|
+
if (capped && cap === undefined)
|
|
1076
|
+
throw invalid([{ field: "max_cost_usd", reason: "missing", message: "Every run a trigger starts is capped: give the trigger's target a max_cost_usd or set the agent's." }]);
|
|
1077
|
+
const place = resolvePlace(revision.body.place);
|
|
1078
|
+
await runnable(revision, place, { capped: cap !== undefined });
|
|
1079
|
+
// The title shows on the run's page, the runs list and Mission Control: built from its input as shown, each held
|
|
1080
|
+
// value redacted before a long one is cut (a cut key could no longer be found), and the run gets its input as given.
|
|
1081
|
+
const shown = redactedOutput(input, learningSecrets());
|
|
1082
|
+
const title = revision.kind === "workflow" ? workflowTitle(entry.agent.name || entry.agent.id, isObject(shown) ? shown : {}) : typeof input.content === "string" ? input.content : (Object.values(input).find((v) => typeof v === "string") ?? JSON.stringify(input));
|
|
1083
|
+
return runs.create(entry, revision, version, { input, title, place, ...(typeof body.effort === "string" ? { effort: body.effort } : {}), ...(cap !== undefined ? { maxCostUsd: cap } : {}), ...(trigger ? { trigger } : {}), ...(origin ? { origin } : {}), ...(files.length ? { inputs: (work) => uploads.copyInto(work, files) } : {}) });
|
|
1084
|
+
}
|
|
851
1085
|
/** A page of runs from the store, newest first: `agent`, `revision` and `status` narrow it. */
|
|
852
1086
|
/** A list's `archived`: true lists only what is archived, false (the default) only what is not. */
|
|
853
1087
|
function archivedParam(url) {
|
|
@@ -1023,18 +1257,37 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1023
1257
|
throw new ApiError("not_found", "no such file");
|
|
1024
1258
|
}
|
|
1025
1259
|
// ---- usage ----------------------------------------------------------------------------------------------------------
|
|
1026
|
-
// Each ended run's meters, from its store (
|
|
1260
|
+
// Each ended run's meters, from its store (meterFiguresIn): kept, as its store no longer changes, keyed by its end, so a run
|
|
1027
1261
|
// opened again and ended again is read again. A store that cannot be read leaves it all tokens.
|
|
1028
1262
|
const endedMeters = new Map();
|
|
1263
|
+
// Each ended run's spend so far as it saved it at its end (serve.json's cost_so_far: every conversation's charges and
|
|
1264
|
+
// its decisions' receipts, which its root store alone does not hold), kept as its meters are; undefined when it saved
|
|
1265
|
+
// none (a run whose cost is known, or one ended before the figure was kept).
|
|
1266
|
+
const endedSoFar = new Map();
|
|
1267
|
+
const savedSoFarOf = (row) => {
|
|
1268
|
+
const key = `${row.id} ${row.endedAt}`;
|
|
1269
|
+
if (!endedSoFar.has(key)) {
|
|
1270
|
+
let usd;
|
|
1271
|
+
try {
|
|
1272
|
+
const kept = JSON.parse(readFileSync(join(dirname(dirname(agents.store.runStorePath(row.id))), RUN_META), "utf8")).cost_so_far?.so_far_usd;
|
|
1273
|
+
usd = typeof kept === "number" && Number.isFinite(kept) ? kept : undefined;
|
|
1274
|
+
}
|
|
1275
|
+
catch {
|
|
1276
|
+
usd = undefined;
|
|
1277
|
+
}
|
|
1278
|
+
endedSoFar.set(key, usd);
|
|
1279
|
+
}
|
|
1280
|
+
return endedSoFar.get(key);
|
|
1281
|
+
};
|
|
1029
1282
|
const metersOf = (row) => {
|
|
1030
1283
|
const key = `${row.id} ${row.endedAt}`;
|
|
1031
1284
|
let meters = endedMeters.get(key);
|
|
1032
1285
|
if (!meters) {
|
|
1033
1286
|
try {
|
|
1034
|
-
meters =
|
|
1287
|
+
meters = meterFiguresIn(agents.store.runStorePath(row.id));
|
|
1035
1288
|
}
|
|
1036
1289
|
catch {
|
|
1037
|
-
meters = { tools: 0, tokens: null };
|
|
1290
|
+
meters = { tools: 0, tokens: null, browser: { usd: 0, seconds: 0 }, others: 0, known: { tokens: 0, browser: 0, others: 0 } };
|
|
1038
1291
|
}
|
|
1039
1292
|
endedMeters.set(key, meters);
|
|
1040
1293
|
}
|
|
@@ -1053,6 +1306,8 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1053
1306
|
throw new ApiError("bad_request", "group_by is meter, agent, key, day or region");
|
|
1054
1307
|
const lines = new Map();
|
|
1055
1308
|
const total = { usd: 0, unpriced: 0 };
|
|
1309
|
+
// The browser_time line's seconds: its ended runs' (their stores keep each charge's), none once a live run is in it.
|
|
1310
|
+
let browserSeconds = 0;
|
|
1056
1311
|
// A cost that is unknown adds no dollars, so no sum turns unknown; it is counted as unpriced instead, so it never
|
|
1057
1312
|
// passes as $0.
|
|
1058
1313
|
const add = (key, usd) => {
|
|
@@ -1073,25 +1328,29 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1073
1328
|
const live = row.state === "running" ? await runs.get(row.id) : null;
|
|
1074
1329
|
const usd = live ? runs.cost(live).usd : (row.costUsd ?? null);
|
|
1075
1330
|
const key = group === "agent" ? row.agent : group === "day" ? row.startedAt.slice(0, 10) : group === "meter" ? "tokens" : "local";
|
|
1076
|
-
// By meter, what a run's paid tools charged (monid's) is `tools`,
|
|
1077
|
-
// live run's rows (a call still marked is no charge), else its store as it
|
|
1078
|
-
// unknown, never `tokens`). An unknown meter counts the run as unpriced on it.
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
const
|
|
1082
|
-
// A run whose cost is unknown
|
|
1083
|
-
// never
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1331
|
+
// By meter, what a run's paid tools charged (monid's) is `tools`, its browser session time `browser_time`, the rest
|
|
1332
|
+
// `tokens`, all from the same records: a live run's rows (a call still marked is no charge), else its store as it
|
|
1333
|
+
// ended (a call a crash cut makes `tools` unknown, never `tokens`). An unknown meter counts the run as unpriced on it.
|
|
1334
|
+
// An ended run's are its store's figures (metersOf keeps them, never its timeline), read for its lines by meter and,
|
|
1335
|
+
// by any group, for what a run of unknown cost is known to have spent.
|
|
1336
|
+
const read = (group === "meter" && usd !== 0) || usd === null ? (live ? { tools: toolCostOf(live.rows), tokens: null, browser: { usd: toolCostOf(live.rows, "browser"), seconds: null }, others: toolCostOf(live.rows.filter((r) => r.tool_name !== "browser")), known: { tokens: 0, browser: knownToolCostOf(live.rows, "browser"), others: knownToolCostOf(live.rows, "browser", true) } } : metersOf(row)) : undefined;
|
|
1337
|
+
// A run whose cost is unknown still spent what is known of it (so_far: each meter's known dollars): that is in the
|
|
1338
|
+
// total and its lines, and the run is counted unpriced, so a total is never below a line of its own and reads as
|
|
1339
|
+
// the lower bound unpriced_runs says it is.
|
|
1340
|
+
const soFar = usd !== null || !read ? 0 : live ? (runs.cost(live).so_far_usd ?? 0) : (savedSoFarOf(row) ?? read.known.tokens + read.known.browser + read.known.others);
|
|
1341
|
+
const meters = group === "meter" && usd !== 0 ? read : undefined;
|
|
1342
|
+
if (meters && meters.browser.usd !== 0)
|
|
1343
|
+
browserSeconds = browserSeconds === null || meters.browser.seconds === null ? null : browserSeconds + meters.browser.seconds;
|
|
1344
|
+
// Its parts of the lines (usage-lines.ts): an unknown one counts the run unpriced there and adds what is known of it.
|
|
1345
|
+
for (const part of runLines({ usd, soFar, key, meters })) {
|
|
1346
|
+
const line = lines.get(part.name) ?? lines.set(part.name, { usd: 0, unpriced: 0 }).get(part.name);
|
|
1347
|
+
line.usd += part.usd;
|
|
1348
|
+
if (part.unpriced)
|
|
1087
1349
|
line.unpriced++;
|
|
1088
|
-
else
|
|
1089
|
-
line.usd += part;
|
|
1090
1350
|
}
|
|
1091
1351
|
if (usd === null)
|
|
1092
1352
|
total.unpriced++;
|
|
1093
|
-
|
|
1094
|
-
total.usd += usd;
|
|
1353
|
+
total.usd += usd ?? soFar;
|
|
1095
1354
|
}
|
|
1096
1355
|
// What learning spent on this server, outside any run (usage.ts): each run's grade, on the day its learning ended.
|
|
1097
1356
|
for (const entry of (await outcomes(data)).values()) {
|
|
@@ -1102,7 +1361,7 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1102
1361
|
const round = (v) => Math.round(v * 1e6) / 1e6;
|
|
1103
1362
|
return {
|
|
1104
1363
|
from: new Date(from).toISOString(), to: new Date(to).toISOString(), currency: "USD", basis: "estimate", group_by: group, total_usd: round(total.usd), unpriced_runs: total.unpriced,
|
|
1105
|
-
lines: [...lines].map(([key, line]) => ({ group: key, ...(group === "meter" ? { meter: key } : {}), usd: round(line.usd), unpriced_runs: line.unpriced })),
|
|
1364
|
+
lines: [...lines].map(([key, line]) => ({ group: key, ...(group === "meter" ? { meter: key } : {}), ...(key === "browser_time" && group === "meter" && browserSeconds !== null ? { quantity: round(browserSeconds), unit: "second" } : {}), usd: round(line.usd), unpriced_runs: line.unpriced })),
|
|
1106
1365
|
account: null,
|
|
1107
1366
|
};
|
|
1108
1367
|
}
|
|
@@ -1227,6 +1486,9 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1227
1486
|
return send(res, 200, forCaller(caps, byOwnerSession(req)));
|
|
1228
1487
|
if (found.name === "getOpenapi")
|
|
1229
1488
|
return send(res, 200, servedOpenapi(openapi, req.socket.localPort));
|
|
1489
|
+
// The one route with no token: a webhook trigger's request, checked by its signature before anything else is read.
|
|
1490
|
+
if (found.name === "receiveHook")
|
|
1491
|
+
return hook(req, res, path);
|
|
1230
1492
|
if (found.name === "getHealth") {
|
|
1231
1493
|
const health = await healthOf(data, minFreeBytes);
|
|
1232
1494
|
return send(res, health.status === "ok" ? 200 : 503, health);
|
|
@@ -1240,6 +1502,12 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1240
1502
|
authFailed(`/v2${path}`, "approve_without_session");
|
|
1241
1503
|
throw new ApiError("forbidden", owner ? "Approving a note takes the owner's password sign-in in the console, never a token." : "Approving a note takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
|
|
1242
1504
|
}
|
|
1505
|
+
// Answering a tool call that waits for approval (tool-gate.ts) is the same: the owner's signed-in page alone, never a
|
|
1506
|
+
// token, which the run's own process, an agent's MCP client or a script may hold.
|
|
1507
|
+
if (found.name === "answerApproval" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
|
|
1508
|
+
authFailed(`/v2${path}`, "approve_without_session");
|
|
1509
|
+
throw new ApiError("forbidden", owner ? "Answering a tool call's approval takes the owner's password sign-in in the console, never a token." : "Answering a tool call's approval takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
|
|
1510
|
+
}
|
|
1243
1511
|
if (!timingSafeEqual(digest(String(req.headers.authorization ?? "")), expected)) {
|
|
1244
1512
|
authFailed(`/v2${path}`, req.headers.authorization === undefined ? "no_credential" : "wrong_token");
|
|
1245
1513
|
throw new ApiError("unauthenticated", "this route needs Authorization: Bearer <the token in the data directory>", {}, { "www-authenticate": "Bearer" });
|
|
@@ -1253,8 +1521,13 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1253
1521
|
const body = await bodyOf(req);
|
|
1254
1522
|
const answer = await idempotent(req, "/agents", body, async () => {
|
|
1255
1523
|
let warnings = [];
|
|
1256
|
-
|
|
1257
|
-
|
|
1524
|
+
// A new agent that names no place is given this server's box (place.ts newAgentPlace), stamped on its revision;
|
|
1525
|
+
// one that names a tool the box refuses (browser) keeps the runner, as before.
|
|
1526
|
+
const definition = checkDefinitionBody(body);
|
|
1527
|
+
const named = Array.isArray(definition.definition.tools) ? definition.definition.tools : [];
|
|
1528
|
+
const fresh = named.some((tool) => typeof tool === "string" && toolOf(tool)?.runnerOnly) ? { reason: "" } : newAgentPlace(boxOffers);
|
|
1529
|
+
const entry = await agents.create(definition, async (revision) => void (warnings = await saveable(revision)), "place" in fresh ? { place: fresh.place, tools: NEW_AGENT_TOOLS } : undefined);
|
|
1530
|
+
return { status: 201, body: { ...agentView(entry, await signIns.view(entry.agent.id)), warnings }, headers: { location: `/v2/agents/${entry.agent.id}`, etag: etagOf(entry) } };
|
|
1258
1531
|
});
|
|
1259
1532
|
return send(res, answer.status, answer.body, answer.headers);
|
|
1260
1533
|
}
|
|
@@ -1263,13 +1536,13 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1263
1536
|
const offset = cursorOf(url.searchParams.get("cursor"));
|
|
1264
1537
|
const archived = archivedParam(url);
|
|
1265
1538
|
const all = (await agents.list()).filter((entry) => Boolean(entry.agent.archivedAt) === archived);
|
|
1266
|
-
return send(res, 200, { agents: all.slice(offset, offset + limit).map((entry) => agentView(entry)), next_cursor: nextCursor(offset + limit, all.length) });
|
|
1539
|
+
return send(res, 200, { agents: await Promise.all(all.slice(offset, offset + limit).map(async (entry) => agentView(entry, await signIns.view(entry.agent.id)))), next_cursor: nextCursor(offset + limit, all.length) });
|
|
1267
1540
|
}
|
|
1268
1541
|
case "getAgent": {
|
|
1269
1542
|
const entry = await needAgent(id);
|
|
1270
1543
|
// The tools its current revision grants, as capabilities list them, each with its provider for this agent.
|
|
1271
1544
|
const tools = entry.revision ? agentTools(env, settings.get(), await toolingOf(entry.revision), caps.tools.map((tool) => tool.name)) : [];
|
|
1272
|
-
return send(res, 200, { ...agentView(entry), tools }, { etag: etagOf(entry) });
|
|
1545
|
+
return send(res, 200, { ...agentView(entry, await signIns.view(entry.agent.id)), tools }, { etag: etagOf(entry) });
|
|
1273
1546
|
}
|
|
1274
1547
|
case "updateDefinition": {
|
|
1275
1548
|
const entry = await needAgent(id);
|
|
@@ -1292,7 +1565,7 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1292
1565
|
let warnings = [];
|
|
1293
1566
|
const check = async (revision) => void (warnings = await saveable(revision));
|
|
1294
1567
|
const edited = await agents.commit(entry, checkDefinitionBody(contract ? { definition: body } : body, { creating: false }), { check, contract, ...(match === undefined ? {} : { ifCurrent: entry.revision?.id ?? null }) });
|
|
1295
|
-
return send(res, 200, { ...agentView(edited), warnings }, { etag: etagOf(edited) });
|
|
1568
|
+
return send(res, 200, { ...agentView(edited, await signIns.view(edited.agent.id)), warnings }, { etag: etagOf(edited) });
|
|
1296
1569
|
}
|
|
1297
1570
|
case "listRevisions": {
|
|
1298
1571
|
const entry = await needAgent(id);
|
|
@@ -1314,7 +1587,7 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1314
1587
|
if (!(await agents.revision(id, revision)))
|
|
1315
1588
|
throw invalid([{ field: "revision", reason: "not_an_option", message: `${revision} is not a revision of the agent ${id}` }]);
|
|
1316
1589
|
const moved = await agents.setCurrent(entry, revision);
|
|
1317
|
-
return send(res, 200, agentView(moved), { etag: etagOf(moved) });
|
|
1590
|
+
return send(res, 200, agentView(moved, await signIns.view(moved.agent.id)), { etag: etagOf(moved) });
|
|
1318
1591
|
}
|
|
1319
1592
|
case "archiveAgent":
|
|
1320
1593
|
case "unarchiveAgent": {
|
|
@@ -1323,7 +1596,18 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1323
1596
|
if (found.name === "archiveAgent")
|
|
1324
1597
|
await runs.archived();
|
|
1325
1598
|
const entry = await needAgent(id);
|
|
1326
|
-
return send(res, 200, agentView(entry), { etag: etagOf(entry) });
|
|
1599
|
+
return send(res, 200, agentView(entry, await signIns.view(entry.agent.id)), { etag: etagOf(entry) });
|
|
1600
|
+
}
|
|
1601
|
+
case "forgetSignIn": {
|
|
1602
|
+
await needAgent(id);
|
|
1603
|
+
let key;
|
|
1604
|
+
try {
|
|
1605
|
+
key = decodeURIComponent(second);
|
|
1606
|
+
}
|
|
1607
|
+
catch {
|
|
1608
|
+
throw new ApiError("bad_request", "the sign-in's key is not a valid path segment");
|
|
1609
|
+
}
|
|
1610
|
+
return send(res, 200, await signIns.forget(id, key));
|
|
1327
1611
|
}
|
|
1328
1612
|
case "createRun": {
|
|
1329
1613
|
const answer = await createRun(req, id);
|
|
@@ -1363,6 +1647,24 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1363
1647
|
});
|
|
1364
1648
|
return send(res, answer.status, answer.body, answer.headers);
|
|
1365
1649
|
}
|
|
1650
|
+
case "raiseRunCap": {
|
|
1651
|
+
const run = await needRun(id);
|
|
1652
|
+
const body = await bodyOf(req);
|
|
1653
|
+
const extra = unknownFields(body, ["max_cost_usd"]);
|
|
1654
|
+
if (extra.length)
|
|
1655
|
+
throw invalid(extra);
|
|
1656
|
+
const cap = body.max_cost_usd;
|
|
1657
|
+
if (!(typeof cap === "number" && Number.isFinite(cap) && cap > 0))
|
|
1658
|
+
throw invalid([{ field: "max_cost_usd", reason: cap === undefined ? "missing" : "wrong_type", message: "max_cost_usd is a number above 0" }]);
|
|
1659
|
+
if (run.kind === "workflow")
|
|
1660
|
+
throw invalid([{ field: "max_cost_usd", reason: "not_allowed", message: "A workflow run's spend is not capped here, so it has no cap to raise." }]);
|
|
1661
|
+
const now = run.meta.max_cost_usd;
|
|
1662
|
+
if (now === undefined)
|
|
1663
|
+
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." }]);
|
|
1664
|
+
const { resumed, messageId, note } = await runs.raiseCap(run, cap);
|
|
1665
|
+
const { status, state } = statusOf(run);
|
|
1666
|
+
return send(res, 200, { run_id: run.id, max_cost_usd: cap, resumed, ...(messageId ? { message_id: messageId } : {}), ...(note ? { note } : {}), status, state });
|
|
1667
|
+
}
|
|
1366
1668
|
case "stopRun": {
|
|
1367
1669
|
const run = await needRun(id);
|
|
1368
1670
|
const stopped = await runs.stop(run);
|
|
@@ -1375,6 +1677,21 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1375
1677
|
const requested = await runs.cancel(run);
|
|
1376
1678
|
return send(res, 202, { run_id: run.id, cancel_requested: requested, already_terminal: !requested, status: statusOf(run).status });
|
|
1377
1679
|
}
|
|
1680
|
+
case "answerApproval": {
|
|
1681
|
+
// The owner's answer to a tool call that waits for approval (tool-gate.ts): the first answer wins.
|
|
1682
|
+
const run = await needRun(id);
|
|
1683
|
+
const body = await bodyOf(req);
|
|
1684
|
+
const issues = Object.keys(body).filter((k) => k !== "decision" && k !== "note").map((k) => ({ field: k, reason: "not_allowed", message: `The body keeps no field ${k}.` }));
|
|
1685
|
+
if (body.decision !== "allow" && body.decision !== "deny")
|
|
1686
|
+
issues.push({ field: "decision", reason: body.decision === undefined ? "missing" : "not_an_option", message: "decision is allow or deny" });
|
|
1687
|
+
if (body.note !== undefined && (typeof body.note !== "string" || body.note.length > 2000))
|
|
1688
|
+
issues.push({ field: "note", reason: "wrong_type", message: "note is a string of at most 2000 characters" });
|
|
1689
|
+
if (issues.length)
|
|
1690
|
+
throw invalid(issues);
|
|
1691
|
+
await runs.approve(run, decodeURIComponent(second), body.decision, typeof body.note === "string" && body.note.trim() ? body.note.trim() : undefined);
|
|
1692
|
+
res.writeHead(204, { "cache-control": "no-store", "x-content-type-options": "nosniff" });
|
|
1693
|
+
return void res.end();
|
|
1694
|
+
}
|
|
1378
1695
|
case "archiveRun":
|
|
1379
1696
|
case "unarchiveRun": {
|
|
1380
1697
|
const run = await needRun(id);
|
|
@@ -1509,9 +1826,15 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1509
1826
|
return send(res, 200, await usage(url));
|
|
1510
1827
|
case "getStats": {
|
|
1511
1828
|
const filter = analyticsFilter(url);
|
|
1512
|
-
|
|
1829
|
+
// A run this server holds as ended whose end the store does not have yet is pending: counted as it ended, its
|
|
1830
|
+
// metrics left out until the store has them (stats.ts pendingOf).
|
|
1831
|
+
const [stats, analytics, rows, pending] = await agents.request(() => {
|
|
1832
|
+
const stats = agents.store.stats();
|
|
1833
|
+
const pending = pendingOf(stats.running, runs);
|
|
1834
|
+
return [stats, agents.store.analytics({ ...filter, pending }), agents.store.listRuns(), pending];
|
|
1835
|
+
});
|
|
1513
1836
|
// How the runs that tried to learn fared: a held run's learning from memory, any other's end from the ledger.
|
|
1514
|
-
return send(res, 200, { ...statsView(stats, runs), analytics: analyticsView(analytics, filter), learning: await runs.learning.counts(rows, filter) });
|
|
1837
|
+
return send(res, 200, { ...statsView(stats, runs, pending), analytics: analyticsView(analytics, filter), learning: await runs.learning.counts(rows, filter) });
|
|
1515
1838
|
}
|
|
1516
1839
|
case "listToolKeys":
|
|
1517
1840
|
// The offers the server holds, not capabilities': a model key's row names the harnesses its key would run too.
|
|
@@ -1610,6 +1933,40 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1610
1933
|
return send(res, 200, webhooks.attemptsView());
|
|
1611
1934
|
case "redeliverWebhook":
|
|
1612
1935
|
return send(res, 200, await webhooks.redeliver(id));
|
|
1936
|
+
case "listTriggers":
|
|
1937
|
+
return send(res, 200, triggers.list());
|
|
1938
|
+
case "createTrigger": {
|
|
1939
|
+
const body = await bodyOf(req);
|
|
1940
|
+
// A webhook trigger's secret is in its first answer alone: the Idempotency-Key's record keeps the trigger and a
|
|
1941
|
+
// note, so a retry under the key gets the same trigger, never a second one, and never the secret.
|
|
1942
|
+
let secret;
|
|
1943
|
+
const answer = await idempotent(req, "/triggers", body, async () => {
|
|
1944
|
+
const { secret: shown, ...made } = await triggers.create(body);
|
|
1945
|
+
secret = shown;
|
|
1946
|
+
return { status: 201, body: shown ? { ...made, note: `Its secret was shown once, in the first answer; POST /v2/triggers/${made.id}/secret makes a new one.` } : made, headers: { location: `/v2/triggers/${made.id}` } };
|
|
1947
|
+
});
|
|
1948
|
+
const replayed = answer.headers?.["idempotent-replayed"] === "true";
|
|
1949
|
+
const { note: _, ...first } = answer.body;
|
|
1950
|
+
return send(res, answer.status, secret && !replayed ? { ...first, secret } : answer.body, answer.headers);
|
|
1951
|
+
}
|
|
1952
|
+
case "rotateTriggerSecret":
|
|
1953
|
+
return send(res, 200, triggers.rotate(id));
|
|
1954
|
+
case "getTrigger":
|
|
1955
|
+
return send(res, 200, triggers.get(id));
|
|
1956
|
+
case "updateTrigger":
|
|
1957
|
+
return send(res, 200, await triggers.update(id, await bodyOf(req)));
|
|
1958
|
+
case "deleteTrigger":
|
|
1959
|
+
triggers.remove(id);
|
|
1960
|
+
return void res.writeHead(204, { "cache-control": "no-store" }).end();
|
|
1961
|
+
case "fireTrigger": {
|
|
1962
|
+
const key = req.headers["idempotency-key"];
|
|
1963
|
+
if (typeof key !== "string" || key.length < 1 || key.length > 255)
|
|
1964
|
+
throw new ApiError("bad_request", "Running a trigger now takes an Idempotency-Key of 1 to 255 characters: a retry with the same key fires it once.");
|
|
1965
|
+
const fired = await triggers.fire(id, key);
|
|
1966
|
+
return send(res, fired.created ? 202 : 200, fired.firing, fired.created ? {} : { "idempotent-replayed": "true" });
|
|
1967
|
+
}
|
|
1968
|
+
case "listTriggerFirings":
|
|
1969
|
+
return send(res, 200, triggers.firings(id));
|
|
1613
1970
|
}
|
|
1614
1971
|
throw new ApiError("not_found", `no route ${path}`);
|
|
1615
1972
|
}
|
|
@@ -1686,6 +2043,10 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1686
2043
|
throw last > first ? Object.assign(new Error(`every port from ${first} to ${last} on ${host} is taken`), { code: "EADDRINUSE" }) : error;
|
|
1687
2044
|
}
|
|
1688
2045
|
}
|
|
2046
|
+
// The tool keys the server is started with, each checked once against its provider, in the background, once it
|
|
2047
|
+
// listens: a start that fails sends no check, and the start never waits on one. Capabilities are made again as each
|
|
2048
|
+
// answers (a refused one leaves its tools unavailable); close() aborts one still waiting. It never rejects.
|
|
2049
|
+
void toolKeys.checkServer(startFetch, stopping.signal, () => recompose()).catch(() => undefined);
|
|
1689
2050
|
// Only a server that started takes up the import its owner asked for, or counts for setup's offer: one that failed to
|
|
1690
2051
|
// listen hands back no close to stop them.
|
|
1691
2052
|
if (offersImport && existsSync(importAsked))
|
|
@@ -1721,6 +2082,7 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1721
2082
|
// count writes nothing (it lists and reads), so it is ended at once: its listing of a big home checks for no stop.
|
|
1722
2083
|
closing = true;
|
|
1723
2084
|
stopping.abort();
|
|
2085
|
+
triggers.close();
|
|
1724
2086
|
for (const [worker, { task }] of workers) {
|
|
1725
2087
|
if (task === "plan")
|
|
1726
2088
|
void worker.terminate();
|
|
@@ -1748,7 +2110,7 @@ async function startHolding(options, data, lock, checked, stops) {
|
|
|
1748
2110
|
tokenFile,
|
|
1749
2111
|
tokenMade: stored?.made ?? false,
|
|
1750
2112
|
...(setupUrl ? { setupUrl } : {}),
|
|
1751
|
-
boxesLine: boxesLine(boxOffers, enabledBoxes(env)),
|
|
2113
|
+
boxesLine: boxesLine(boxOffers, enabledBoxes(env), boxAllow),
|
|
1752
2114
|
// Once: a second call, at any time, is the first one's promise, so a close repeated after the next server started
|
|
1753
2115
|
// never writes this data root's record again (the next server's, by then).
|
|
1754
2116
|
close: () => (stopped ??= stop()),
|