@parcha/agentrun-serve 0.1.0-beta.48 → 0.1.0-beta.50
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 +37 -0
- package/README.md +236 -26
- package/dist/agent-delete.d.ts +36 -12
- package/dist/agent-delete.js +213 -30
- package/dist/agents-store.d.ts +6 -2
- package/dist/agents-store.js +18 -5
- package/dist/agents.d.ts +8 -1
- package/dist/agents.js +14 -4
- package/dist/answer-json.d.ts +2 -2
- package/dist/answer-json.js +3 -4
- package/dist/api-only.d.ts +7 -10
- package/dist/api-only.js +9 -11
- package/dist/archil-routes.d.ts +1 -1
- package/dist/archil-routes.js +4 -3
- package/dist/browser-sessions.d.ts +56 -0
- package/dist/browser-sessions.js +117 -0
- package/dist/compute-cost.d.ts +101 -0
- package/dist/compute-cost.js +250 -0
- package/dist/computer-routes.d.ts +4 -15
- package/dist/computer-routes.js +6 -10
- package/dist/console/assets/index-D0mr9wfZ.css +1 -0
- package/dist/console/assets/index-D7G6o-1E.js +720 -0
- package/dist/console/index.html +2 -2
- package/dist/errors.d.ts +4 -1
- package/dist/errors.js +15 -5
- package/dist/eval-previous.d.ts +52 -0
- package/dist/eval-previous.js +164 -0
- package/dist/file-types.d.ts +2 -0
- package/dist/file-types.js +3 -1
- package/dist/harness.js +2 -1
- package/dist/import.js +4 -3
- package/dist/learn/check.d.ts +16 -4
- package/dist/learn/check.js +30 -26
- package/dist/learn/promote.d.ts +7 -1
- package/dist/learn/promote.js +47 -0
- package/dist/learn/repick.d.ts +43 -0
- package/dist/learn/repick.js +202 -0
- package/dist/learn/workflow-draft.d.ts +4 -0
- package/dist/learn/workflow-draft.js +10 -7
- package/dist/learned-workflow.d.ts +2 -0
- package/dist/learned-workflow.js +19 -2
- package/dist/learning-setting.d.ts +13 -0
- package/dist/learning-setting.js +23 -1
- package/dist/llms.txt +1 -1
- package/dist/openapi.js +180 -14
- package/dist/paid-calls.d.ts +17 -7
- package/dist/paid-calls.js +15 -9
- package/dist/run-launch.d.ts +2 -2
- package/dist/run-launch.js +2 -1
- package/dist/run-learning-served.d.ts +1 -1
- package/dist/run-timeline-served.js +5 -3
- package/dist/run-usage.d.ts +125 -0
- package/dist/run-usage.js +394 -0
- package/dist/runner/adapter-loop.d.ts +4 -0
- package/dist/runner/adapter-loop.js +66 -21
- package/dist/runner/adapter-run-spec.d.ts +8 -3
- package/dist/runner/adapter-run-spec.js +13 -6
- package/dist/runner/big-writes.d.ts +33 -0
- package/dist/runner/big-writes.js +105 -0
- package/dist/runner/cli-run-spec.js +14 -6
- package/dist/runner/conformance/harness.d.ts +2 -0
- package/dist/runner/conformance/harness.js +18 -4
- package/dist/runner/feedback-round.d.ts +29 -1
- package/dist/runner/feedback-round.js +54 -3
- package/dist/runner/held.d.ts +4 -1
- package/dist/runner/journal-kinds.d.ts +3 -1
- package/dist/runner/learning-end.js +54 -18
- package/dist/runner/loop-contract.d.ts +3 -0
- package/dist/runner/metrics.d.ts +4 -0
- package/dist/runner/metrics.js +9 -0
- package/dist/runner/monid-run.js +2 -2
- package/dist/runner/promotion.js +8 -2
- package/dist/runner/reflect-hook.js +3 -2
- package/dist/runner/run-child-host.d.ts +15 -2
- package/dist/runner/run-child-host.js +24 -8
- package/dist/runner/run-child.js +3 -0
- package/dist/runner/save-slots.d.ts +9 -0
- package/dist/runner/save-slots.js +91 -0
- package/dist/runs-over-store.d.ts +3 -2
- package/dist/runs-over-store.js +9 -7
- package/dist/sdk/runs.d.ts +3 -4
- package/dist/sdk/runs.js +10 -7
- package/dist/sdk/runtimes.d.ts +19 -0
- package/dist/sdk/runtimes.js +23 -0
- package/dist/sdk/schema.d.ts +14 -8
- package/dist/sdk/schema.js +18 -6
- package/dist/server.d.ts +7 -3
- package/dist/server.js +223 -100
- package/dist/store/agent-body.d.ts +2 -3
- package/dist/store/agent-body.js +3 -2
- package/dist/store/index.d.ts +2 -2
- package/dist/store/index.js +1 -1
- package/dist/store/journal/storage.js +1 -1
- package/dist/store/open.d.ts +1 -1
- package/dist/store/open.js +1 -1
- package/dist/store/postgres/migrations/0021_purged.sql +13 -0
- package/dist/store/postgres/migrations/0022_computer_intervals.sql +27 -0
- package/dist/store/postgres/migrations/0023_computer_interval_resources.sql +14 -0
- package/dist/store/schema.d.ts +20 -1
- package/dist/store/schema.js +60 -5
- package/dist/store/sqlite/connection.d.ts +4 -1
- package/dist/store/sqlite/connection.js +5 -0
- package/dist/store/sqlite/run-patch.d.ts +8 -3
- package/dist/store/sqlite/run-patch.js +15 -7
- package/dist/store/sqlite/store.d.ts +2 -1
- package/dist/store/sqlite/store.js +279 -68
- package/dist/store/sqlite/worker.d.ts +9 -0
- package/dist/store/sqlite/worker.js +18 -1
- package/dist/store/store.d.ts +149 -9
- package/dist/store/store.js +63 -0
- package/dist/store-reads/analytics.js +2 -1
- package/dist/store-reads/cap.d.ts +17 -7
- package/dist/store-reads/cap.js +54 -4
- package/dist/store-reads/decisions.d.ts +21 -0
- package/dist/store-reads/decisions.js +22 -0
- package/dist/store-reads/journal.d.ts +8 -2
- package/dist/store-reads/journal.js +27 -8
- package/dist/store-reads/learning.d.ts +1 -1
- package/dist/store-reads/learning.js +5 -2
- package/dist/store-reads/runs.js +2 -0
- package/dist/store-reads/stats.js +4 -2
- package/dist/store-view.d.ts +12 -1
- package/dist/store-view.js +98 -38
- package/dist/template-eval.d.ts +15 -1
- package/dist/template-eval.js +92 -13
- package/dist/templates.d.ts +1 -1
- package/dist/templates.js +4 -3
- package/dist/timeline/labels.js +17 -0
- package/dist/tool-list.js +1 -0
- package/dist/tools.d.ts +6 -2
- package/dist/tools.js +22 -1
- package/dist/trigger-targets.d.ts +28 -9
- package/dist/trigger-targets.js +19 -16
- package/dist/triggers.d.ts +2 -1
- package/dist/triggers.js +5 -2
- package/dist/validate.d.ts +4 -2
- package/dist/validate.js +13 -3
- package/dist/viewer-credential.d.ts +3 -4
- package/dist/viewer-credential.js +6 -4
- package/dist/web-fake.d.ts +25 -0
- package/dist/web-fake.js +38 -1
- package/dist/web-save.d.ts +75 -0
- package/dist/web-save.js +235 -0
- package/dist/workspace/archil-claim.d.ts +5 -2
- package/dist/workspace/archil-claim.js +5 -2
- package/dist/workspace/archil-disk.d.ts +10 -1
- package/dist/workspace/archil-disk.js +19 -1
- package/dist/workspace/archil.d.ts +3 -0
- package/dist/workspace/archil.js +101 -16
- package/dist/workspace/computer-for-claim.d.ts +19 -1
- package/dist/workspace/computer-for-claim.js +88 -20
- package/dist/workspace/computer-intervals.d.ts +26 -0
- package/dist/workspace/computer-intervals.js +58 -0
- package/dist/workspace/computer-janitor.d.ts +7 -3
- package/dist/workspace/computer-janitor.js +14 -6
- package/dist/workspace/computer-kept.d.ts +7 -2
- package/dist/workspace/computer-kept.js +9 -2
- package/dist/workspace/pieced.d.ts +14 -0
- package/dist/workspace/pieced.js +23 -0
- package/dist/workspace/resolve-computer.d.ts +7 -4
- package/dist/workspace/resolve-computer.js +21 -32
- package/dist/workspace/run-disk.js +32 -12
- package/dist/workspace/run-end-computers.d.ts +1 -0
- package/dist/workspace/run-end-computers.js +4 -1
- package/dist/workspace/run-workspace.d.ts +1 -1
- package/dist/workspace/run-workspace.js +11 -6
- package/package.json +10 -10
- package/templates/README.md +36 -7
- package/dist/console/assets/index-CTGegcKt.css +0 -1
- package/dist/console/assets/index-D1Se6mgG.js +0 -715
package/dist/server.js
CHANGED
|
@@ -67,12 +67,13 @@ import { screenWaitEnded } from "./browser-wait-ended.js";
|
|
|
67
67
|
import { durationMs, logLine } from "./print.js";
|
|
68
68
|
import { keepPresence, refusedEnd, runnersRefused } from "./runner/presence.js";
|
|
69
69
|
import { approve, archiveRun, cancel, message, pause as pauseRunOverStore, prepareLaunch, raiseCap, resume as resumeRunOverStore, startInline, startRun, stop as stopRunOverStore } from "./runs-over-store.js";
|
|
70
|
-
import { builtOfNow, factsOverStore, listedItem, momentOverStore, summaryOverStore, timelineOverStore, toolsUsdOverStore, viewOverStore, withheldOverStore } from "./store-view.js";
|
|
70
|
+
import { builtOfNow, factsOverStore, listedItem, lookingBackEnd, momentOverStore, summaryOverStore, timelineOverStore, toolsUsdOverStore, viewOverStore, withheldOverStore } from "./store-view.js";
|
|
71
71
|
import { healEndedCosts } from "./cost-heal.js";
|
|
72
72
|
import { createLister } from "./run-listing.js";
|
|
73
73
|
import { HELD_WAITS } from "./runner/journal-kinds.js";
|
|
74
74
|
import { servedTimelineRows } from "./run-timeline-served.js";
|
|
75
75
|
import { servedRunTrace } from "./run-trace.js";
|
|
76
|
+
import { servedRunUsage } from "./run-usage.js";
|
|
76
77
|
import { servedRunDiff, servedRunLearning } from "./run-learning-served.js";
|
|
77
78
|
import { agentPointers, WITHHELD_LEARNING } from "./handed-values.js";
|
|
78
79
|
import { runCutValues } from "./run-cut.js";
|
|
@@ -83,19 +84,19 @@ import { triggerTargets } from "./trigger-targets.js";
|
|
|
83
84
|
import { labelFilter, labelsIssues } from "./run-labels.js";
|
|
84
85
|
import { listRuns as listRunsOverStore, readRun as readRunOverStore, runOfOrigin as runOfOriginOverStore } from "./store-reads/runs.js";
|
|
85
86
|
import { runEntries } from "./store-reads/journal.js";
|
|
86
|
-
import { metersOverStore } from "./store-reads/cap.js";
|
|
87
|
+
import { metersOverStore, spendOverStore } from "./store-reads/cap.js";
|
|
87
88
|
import { watchRun } from "./live/stream.js";
|
|
88
89
|
import { stats as statsOverStore } from "./store-reads/stats.js";
|
|
89
90
|
import { analytics as analyticsOverStore } from "./store-reads/analytics.js";
|
|
90
91
|
import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
|
|
91
92
|
import { openStore, openRunLaunch, sealRunLaunch, StoreLaunchMissing, StoreOwned, storeTarget } from "./store/index.js";
|
|
92
|
-
import { agentDeleting, answerOf, logged } from "./agents.js";
|
|
93
|
+
import { agentDeleting, answerOf, logged, purgedAgent } from "./agents.js";
|
|
93
94
|
import { keepGrade } from "./runner/feedback-round.js";
|
|
94
95
|
import { gradeRow, notAuditableOf } from "./runner/audit.js";
|
|
95
|
-
import { auditsOffWords, auditWriterOf, isShadowRun, readAudits, servingLinesOf } from "./learn/audit.js";
|
|
96
|
+
import { auditsOffWords, auditWriterOf, isShadowRun, readAudits, servingLinesOf, shadowRunId } from "./learn/audit.js";
|
|
96
97
|
import { auditLoopOf, COMPILE_AFTER_MAX } from "./learning-setting.js";
|
|
97
98
|
import { FINAL_STATES, RUN_CHANGES_PAGE } from "./store/store.js";
|
|
98
|
-
import { championOf, GRADE_SOURCES, gradeView, LABEL_MAX, promotionsOf, promotionsShown, servingOf, servingStateOf, shownDeep } from "./learn/promote.js";
|
|
99
|
+
import { championOf, forgetRunCopies, GRADE_SOURCES, gradeView, LABEL_MAX, promotionsOf, promotionsShown, servingOf, servingStateOf, shownDeep } from "./learn/promote.js";
|
|
99
100
|
import { workflowNodesOf } from "./learn/workflow-nodes.js";
|
|
100
101
|
import { deleteLearning } from "./learn/delete.js";
|
|
101
102
|
import { runModelRef } from "./model.js";
|
|
@@ -121,7 +122,7 @@ import { analyticsFilter, analyticsView, statsView } from "./stats.js";
|
|
|
121
122
|
import { joinedBasis } from "./runner/metrics.js";
|
|
122
123
|
import { agentLoopOverStore } from "./store-reads/loop.js";
|
|
123
124
|
import { printable } from "./learn/index.js";
|
|
124
|
-
import { agentCostOverStore, agentLearningOverStore, costStopOverStore, learningCountsOverStore, learningSpendOverStore, runAllInOverStore } from "./store-reads/learning.js";
|
|
125
|
+
import { agentCostOverStore, agentLearningOverStore, costStopOverStore, learningCountsOverStore, learningSpendOverStore, runAllInOverStore, runLearningEnd } from "./store-reads/learning.js";
|
|
125
126
|
import { costCsv, learningCostQuery, RUN_PATHS } from "./learning-cost.js";
|
|
126
127
|
import { keyOf, SEAL_KEY_ENV, TOOL_FIELDS } from "./tool-keys.js";
|
|
127
128
|
import { toolKeysOverStore } from "./tool-keys-store.js";
|
|
@@ -173,7 +174,7 @@ import { recordingsFolder } from "./workspace/paths.js";
|
|
|
173
174
|
import { heldRoute, holdIssues, runComputerRead } from "./computer-held-routes.js";
|
|
174
175
|
import { COMPUTER_ROUTES, computerHoldOf, computerRoute, runComputerKind } from "./computer-routes.js";
|
|
175
176
|
import { runOver } from "./computer-commands.js";
|
|
176
|
-
import { mintViewerCredential, VIEWER_PARAM, viewerCookie, viewerCredentialFor, viewerCredentialKey, viewerCredentialOf
|
|
177
|
+
import { mintViewerCredential, VIEWER_PARAM, viewerCookie, viewerCredentialFor, viewerCredentialKey, viewerCredentialOf } from "./viewer-credential.js";
|
|
177
178
|
import { ATTACH_PATH, AttachHub, PROVIDERS as COMPUTER_PROVIDERS, SETTING_KINDS, servingRefusals } from "@parcha/agentrun-computer";
|
|
178
179
|
import { createAttachRoutes, liveRelays, pairedView } from "./computer-attach.js";
|
|
179
180
|
import { pairedRefusal, withPaired } from "./workspace/attached-computers.js";
|
|
@@ -184,12 +185,12 @@ import { noAccount, openAccount } from "./email/account.js";
|
|
|
184
185
|
import { emailRoute } from "./email/routes.js";
|
|
185
186
|
import { addressForms, openCalendar } from "./calendar/address.js";
|
|
186
187
|
import { calendarRoute } from "./calendar/routes.js";
|
|
187
|
-
import { agentDiskOf, ARCHIL_DISK_ID, archilSettingsFromEnv, inArchilMode, runDiskKey } from "./archil-settings.js";
|
|
188
|
+
import { agentDiskOf, ARCHIL_DISK_ID, archilSettingsFromEnv, inArchilMode, runDiskKept, runDiskKey } from "./archil-settings.js";
|
|
188
189
|
import { computerOfPlace } from "./computer-setting.js";
|
|
189
190
|
import { computerCapabilities, createComputerRoutes, folderModeOf, hostCommandRefusals, settingsComputerRoute } from "./computers.js";
|
|
190
191
|
import { fauxComputers } from "./faux-computers.js";
|
|
191
192
|
import { writesHeld } from "./workspace.js";
|
|
192
|
-
import { deleteExternalAgent, oneAtATime } from "./agent-delete.js";
|
|
193
|
+
import { deleteExternalAgent, oneAtATime, purgeAgent, purgeRun, purgingKey } from "./agent-delete.js";
|
|
193
194
|
import { agentComputerHoldKey } from "./workspace/agent-computer.js";
|
|
194
195
|
import { sdkRunKey } from "./sdk/runs.js";
|
|
195
196
|
import { waitEndedKey } from "./browser-wait-ended.js";
|
|
@@ -267,6 +268,19 @@ async function tokenIn(file) {
|
|
|
267
268
|
}
|
|
268
269
|
const sha256Hex = (text) => createHash("sha256").update(text).digest("hex");
|
|
269
270
|
const SESSION_S = SESSION_MS / 1000;
|
|
271
|
+
const isoOrNull = (ms) => (ms === null ? null : new Date(ms).toISOString());
|
|
272
|
+
/** 410 purged for a route of a purged run (Runs.purge): its tombstone, what is kept of it. `tools_usd`: its paid tools'
|
|
273
|
+
* meter as /usage read it at its purge (null: unknown, or none read). */
|
|
274
|
+
function purgedRun(row) {
|
|
275
|
+
const meters = row.metrics?.purged?.meters;
|
|
276
|
+
return new ApiError("purged", `The run ${row.id} was purged: what it was given and did is gone, and its cost stays in every total.`, {
|
|
277
|
+
details: {
|
|
278
|
+
run_id: row.id, agent_id: row.agentId, state: row.state, started_at: isoOrNull(row.startedAt), ended_at: isoOrNull(row.endedAt),
|
|
279
|
+
cost_usd: row.costUsd ?? row.costAtMostUsd, cost_upper_bound: row.costUsd === null && row.costAtMostUsd !== null, tools_usd: typeof meters?.tools === "number" ? meters.tools : null,
|
|
280
|
+
purged_at: isoOrNull(row.purgedAt),
|
|
281
|
+
},
|
|
282
|
+
});
|
|
283
|
+
}
|
|
270
284
|
export const ROUTES = [
|
|
271
285
|
{ method: "GET", pattern: /^\/observations$/, name: "getObservations" },
|
|
272
286
|
{ method: "GET", pattern: /^\/connectors$/, name: "listRemoteConnectors" },
|
|
@@ -315,6 +329,8 @@ export const ROUTES = [
|
|
|
315
329
|
{ method: "POST", pattern: /^\/runs$/, name: "createInlineRun" },
|
|
316
330
|
{ method: "GET", pattern: /^\/runs\/([^/]+)$/, name: "getRun" },
|
|
317
331
|
{ method: "PATCH", pattern: /^\/runs\/([^/]+)$/, name: "raiseRunCap" },
|
|
332
|
+
// A run purged, its cost kept, with the runs made from it (agent-delete.ts purgeRun).
|
|
333
|
+
{ method: "DELETE", pattern: /^\/runs\/([^/]+)$/, name: "deleteRun" },
|
|
318
334
|
{ method: "GET", pattern: /^\/runs\/([^/]+)\/timeline$/, name: "getTimeline" },
|
|
319
335
|
{ method: "POST", pattern: /^\/runs\/([^/]+)\/messages$/, name: "sendMessage" },
|
|
320
336
|
{ method: "POST", pattern: /^\/runs\/([^/]+)\/stop$/, name: "stopRun" },
|
|
@@ -327,6 +343,8 @@ export const ROUTES = [
|
|
|
327
343
|
{ method: "GET", pattern: /^\/runs\/([^/]+)\/graph$/, name: "getRunGraph" },
|
|
328
344
|
// A run's trace (run-trace.ts): each model request and tool call as a span, with its time, tokens and cost.
|
|
329
345
|
{ method: "GET", pattern: /^\/runs\/([^/]+)\/trace$/, name: "getRunTrace" },
|
|
346
|
+
// A run's usage lines (run-usage.ts): by meter, model, charger and provider, each with its quantity and its cost.
|
|
347
|
+
{ method: "GET", pattern: /^\/runs\/([^/]+)\/usage$/, name: "getRunUsage" },
|
|
330
348
|
{ method: "POST", pattern: /^\/workflows\/validate$/, name: "validateWorkflow" },
|
|
331
349
|
{ method: "POST", pattern: /^\/runs\/([^/]+)\/pause$/, name: "pauseRun" },
|
|
332
350
|
{ method: "POST", pattern: /^\/runs\/([^/]+)\/resume$/, name: "resumeRun" },
|
|
@@ -1144,12 +1162,8 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1144
1162
|
const sealKey = seal.key;
|
|
1145
1163
|
// SDK runs' credentials are signed with a key from the seal key, never an API token: a rotation leaves them working.
|
|
1146
1164
|
const sdkSecret = sdkRunSecret(sealKey);
|
|
1147
|
-
// An API-only server's viewer credentials
|
|
1148
|
-
// this store checks them alike, across restarts.
|
|
1165
|
+
// An API-only server's viewer credentials: viewer-credential.ts.
|
|
1149
1166
|
const viewerKey = viewerCredentialKey(sealKey);
|
|
1150
|
-
/** Whether `credential` opens run `runId`'s live view now: minted for that run, not expired, and its run not ended,
|
|
1151
|
-
* read from the store each time (its revocation). */
|
|
1152
|
-
const viewerHolds = async (credential, runId) => credential !== undefined && viewerCredentialFor(viewerKey, runId, credential, Date.now()) && !(await runOver(store, runId));
|
|
1153
1167
|
// Each run's viewers are asked under that run's key (live-reach.ts reachForRun).
|
|
1154
1168
|
const answers = (runId) => (handover) => viewerAnswers(handover, reachForRun(reach, runId));
|
|
1155
1169
|
// Settings → Computers and the owner's Archil settings, over the one store (computers.ts, archil-routes.ts), built once
|
|
@@ -1587,6 +1601,8 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1587
1601
|
getAgent: async (agentId) => (await getAgent(store, agentId)) ?? undefined,
|
|
1588
1602
|
needAgent,
|
|
1589
1603
|
momentOf: (runId) => momentOverStore(store, runId, viewDepsFor(ownOriginOf())),
|
|
1604
|
+
// Read when a firing's message is sent (declared below, with the delete turn).
|
|
1605
|
+
runWrite: (agentId, runId, work) => runWrite(agentId, runId, work),
|
|
1590
1606
|
runStatus: async (runId) => (await viewOverStore(store, runId, viewDepsFor(ownOriginOf())))?.status ?? null,
|
|
1591
1607
|
completedOutput: async (runId) => {
|
|
1592
1608
|
const view = await viewOverStore(store, runId, viewDepsFor(ownOriginOf()));
|
|
@@ -2210,28 +2226,49 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2210
2226
|
idempotency.delete(slot);
|
|
2211
2227
|
await keep();
|
|
2212
2228
|
};
|
|
2213
|
-
const deleteInTurn = oneAtATime();
|
|
2229
|
+
const deleteInTurn = oneAtATime(options.deleteTurnQueued);
|
|
2214
2230
|
/** `work`, a write to agent `id`'s home or learning (files a delete removes with the agent's folders, settings it leaves
|
|
2215
2231
|
* to deleteLearning, answers kept under its path), done in the agent's delete turn, the agent read there: a write sent
|
|
2216
2232
|
* while a DELETE runs waits for it, then finds the agent gone (404) or still being deleted (409 agent_not_runnable),
|
|
2217
2233
|
* so nothing is written after the delete passed over it. The request's body is read before, outside the turn. */
|
|
2218
2234
|
const agentWrite = (id, work) => deleteInTurn(id, async () => {
|
|
2219
2235
|
const entry = await needAgent(id);
|
|
2236
|
+
// A purged agent's row stays as its tombstone: a write that waited on its purge is 410, never a folder made again.
|
|
2237
|
+
if (entry.agent.purgedAt !== null)
|
|
2238
|
+
throw purgedAgent(entry.agent);
|
|
2220
2239
|
if (entry.agent.archivedAt && entry.agent.externalRef !== null)
|
|
2221
2240
|
throw agentDeleting(id);
|
|
2241
|
+
// A purge stopped part way (its mark still there): nothing of the agent is written, nor is it unarchived, until a
|
|
2242
|
+
// DELETE finishes it.
|
|
2243
|
+
if (entry.agent.archivedAt && (await store.settings.get(purgingKey(id))) !== undefined)
|
|
2244
|
+
throw agentDeleting(id);
|
|
2245
|
+
return work();
|
|
2246
|
+
});
|
|
2247
|
+
/** `work`, a write that names run `runId` of agent `agentId` (a message, which may open it again; a grade, which keeps its
|
|
2248
|
+
* id and expected answer), done in the agent's delete turn, the agent and the run read there: a purge of the run (or of
|
|
2249
|
+
* its agent) holds that turn from its live check to its tombstone, so such a write waits for it and is then 410, never
|
|
2250
|
+
* a run opened again under a purge nor a grade saved after one. */
|
|
2251
|
+
const runWrite = (agentId, runId, work) => agentWrite(agentId, async () => {
|
|
2252
|
+
const row = await store.runs.get(runId);
|
|
2253
|
+
if (!row)
|
|
2254
|
+
throw new ApiError("not_found", `no run ${runId}`);
|
|
2255
|
+
if (row.purgedAt !== null)
|
|
2256
|
+
throw purgedRun(row);
|
|
2222
2257
|
return work();
|
|
2223
2258
|
});
|
|
2224
2259
|
const AGAIN = "It starts no run meanwhile: send the DELETE again to finish it.";
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2260
|
+
const RUN_AGAIN = "The run is kept: send the DELETE again to finish it.";
|
|
2261
|
+
/** `work`, a thing a deleted agent or run owns elsewhere deleted there: a refusal of one of `codes` (it is not deleted
|
|
2262
|
+
* there yet) answered as the delete answers each such one, 503 unavailable, retryable, saying to send the DELETE again
|
|
2263
|
+
* (`again`: the words for an agent's delete, or a run's). */
|
|
2264
|
+
const notYetWith = async (work, codes = ["unavailable"], again = AGAIN) => {
|
|
2228
2265
|
try {
|
|
2229
2266
|
await work();
|
|
2230
2267
|
}
|
|
2231
2268
|
catch (error) {
|
|
2232
2269
|
if (!(error instanceof ApiError && codes.includes(error.code)))
|
|
2233
2270
|
throw error;
|
|
2234
|
-
throw new ApiError("unavailable", `${error.message.replace(/[.\s]*$/, "")}. ${
|
|
2271
|
+
throw new ApiError("unavailable", `${error.message.replace(/[.\s]*$/, "")}. ${again}`, { retry_after_ms: 5_000 });
|
|
2235
2272
|
}
|
|
2236
2273
|
};
|
|
2237
2274
|
/** What DELETE /agents/{id} does outside the store's rows, on this server (agent-delete.ts AgentDeleteHost). */
|
|
@@ -2283,13 +2320,20 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2283
2320
|
// Archil's failure (424), a live run of another agent on the disk (412) or no key (503): each is retried by the next DELETE.
|
|
2284
2321
|
await notYetWith(() => archil.removeAgentDisk({ id: agentId, archived: true, external: true, liveOn: (diskId) => liveRunsOnDisk(store.runs, agentId, diskId) }), ["upstream_failed", "precondition_failed", "unavailable"]);
|
|
2285
2322
|
},
|
|
2286
|
-
forgetRun: async (agentId, runId) => {
|
|
2323
|
+
forgetRun: async (agentId, runId, alone) => {
|
|
2324
|
+
const again = alone ? RUN_AGAIN : AGAIN;
|
|
2287
2325
|
// Its own folder on a disk its launch named (the caller's disk, which stays): read from its launch record, which goes
|
|
2288
2326
|
// with the run's rows after this, so a failure or a stop here leaves the record that names the disk for the next
|
|
2289
|
-
// DELETE. A run on its agent's own disk
|
|
2327
|
+
// DELETE. A run on its agent's own disk: with its agent's delete that disk went whole (removeDisk), its folder with
|
|
2328
|
+
// it; deleted alone, its folder there is deleted, the disk kept, read from its disk setting, which goes after.
|
|
2290
2329
|
const launched = await store.runs.launch(runId).then((row) => readLaunchBody(row.body)?.archilDisk, (error) => (error instanceof StoreLaunchMissing ? undefined : Promise.reject(error)));
|
|
2291
2330
|
if (launched?.kind === "launch")
|
|
2292
|
-
await notYetWith(() => archil.removeRunFolder(agentId, runId, launched.diskId), ["unavailable", "upstream_failed"]);
|
|
2331
|
+
await notYetWith(() => archil.removeRunFolder(agentId, runId, launched.diskId), ["unavailable", "upstream_failed"], again);
|
|
2332
|
+
else if (alone) {
|
|
2333
|
+
const own = launched?.diskId ?? (await runDiskKept(store, runId));
|
|
2334
|
+
if (own)
|
|
2335
|
+
await notYetWith(() => archil.removeRunFolder(agentId, runId, own, "agent"), ["unavailable", "upstream_failed"], again);
|
|
2336
|
+
}
|
|
2293
2337
|
// The run's folder (its work and what sits beside it), its scratch and its native context, on this machine.
|
|
2294
2338
|
for (const folder of [dirname(runFolder(data, agentId, runId)), scratchFolder(data, agentId, runId), join(data, "native-context", runId)])
|
|
2295
2339
|
await rm(folder, { recursive: true, force: true });
|
|
@@ -2307,6 +2351,25 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2307
2351
|
await rm(join(data, "scratch", agentDirName(agentId)), { recursive: true, force: true });
|
|
2308
2352
|
await forgetKept("agent", agentId);
|
|
2309
2353
|
},
|
|
2354
|
+
// The replay runs of its input, its audit's shadow run and a learning run it names (the store's), and its audit's shadow
|
|
2355
|
+
// run by its id (one whose launch is gone too).
|
|
2356
|
+
madeFrom: async (runId) => [...new Set([...(await store.runs.madeFrom(runId)), shadowRunId(runId)])],
|
|
2357
|
+
forgetCopies: (agentId, runId) => forgetRunCopies(store.settings, agentId, runId),
|
|
2358
|
+
// /usage's meters and a live read's spend, from its journal, as they read now (store-reads/cap.ts), and how its
|
|
2359
|
+
// learning ended as /stats counts it (its state and reason alone).
|
|
2360
|
+
kept: async (runId) => {
|
|
2361
|
+
const spend = await spendOverStore(store, runId, ctx);
|
|
2362
|
+
const learning = await runLearningEnd(store, runId);
|
|
2363
|
+
return {
|
|
2364
|
+
meters: await metersOverStore(store, runId, ctx),
|
|
2365
|
+
spend: { usd: spend.usd, ...(spend.basis === undefined ? {} : { basis: spend.basis }) },
|
|
2366
|
+
learning: learning ? { state: learning.state, reason: learning.reason } : null,
|
|
2367
|
+
};
|
|
2368
|
+
},
|
|
2369
|
+
turnOver: async (runId) => {
|
|
2370
|
+
const read = await runStatusState(runId);
|
|
2371
|
+
return read.state === "idle" && read.status !== "paused";
|
|
2372
|
+
},
|
|
2310
2373
|
waitMs: options.agentDeleteWaitMs ?? 30_000,
|
|
2311
2374
|
pollMs: 200,
|
|
2312
2375
|
...(options.agentDeleteAt ? { at: options.agentDeleteAt } : {}),
|
|
@@ -2676,7 +2739,10 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2676
2739
|
warnings = saved.warnings;
|
|
2677
2740
|
return saved.stamp;
|
|
2678
2741
|
};
|
|
2679
|
-
|
|
2742
|
+
// Its last read and its commit in the agent's delete turn (agentWrite), the check outside it: an edit or a template
|
|
2743
|
+
// update whose commit comes once the agent is purged is 410, and one after a purge stopped part way is 409, nothing
|
|
2744
|
+
// written (the store refuses a purged agent's revision too, AgentPurged).
|
|
2745
|
+
const edited = await agents.commit(entry, checkDefinitionBody(body, { creating: false, harnesses }), { check, ...options, inTurn: (work) => agentWrite(entry.agent.id, work) });
|
|
2680
2746
|
reconcileComputer(entry.agent.id);
|
|
2681
2747
|
return { entry: edited, warnings };
|
|
2682
2748
|
}
|
|
@@ -3029,7 +3095,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3029
3095
|
const minted = new Map(secrets.map(({ trigger_id, secret }) => [trigger_id, secret]));
|
|
3030
3096
|
// Which saved server each MCP need runs on (null: none here, said under mcp.<toolkit>).
|
|
3031
3097
|
const used = Object.fromEntries(mapped.map(({ need, server }) => [need.toolkit, server]));
|
|
3032
|
-
const applied = { template: pkg.id, version: pkg.version, agent_id: entry.agent.id, servers: used, trigger_ids: ids, ...templateWebhookSecrets([...minted.keys()], new Date().toISOString()), warnings: [...skipped, ...kept, ...modelWarnings, ...computerWarnings, ...unpinned, ...warnings, ...hooks, ...githubTriggers, ...composioSkipped, ...feedsSkipped, ...leftThere, ...appShort, ...twins] };
|
|
3098
|
+
const applied = { template: pkg.id, version: pkg.version, agent_id: entry.agent.id, revision_version: entry.version, servers: used, trigger_ids: ids, ...templateWebhookSecrets([...minted.keys()], new Date().toISOString()), warnings: [...skipped, ...kept, ...modelWarnings, ...computerWarnings, ...unpinned, ...warnings, ...hooks, ...githubTriggers, ...composioSkipped, ...feedsSkipped, ...leftThere, ...appShort, ...twins] };
|
|
3033
3099
|
return { applied, minted, updated: onto !== undefined };
|
|
3034
3100
|
}
|
|
3035
3101
|
/** A run create's issues told from the input this server checks (explain.ts): an agentic run's input schema in force
|
|
@@ -3499,11 +3565,12 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3499
3565
|
}
|
|
3500
3566
|
// ---- usage ----------------------------------------------------------------------------------------------------------
|
|
3501
3567
|
// Each ended run's meters, over the one store (store-reads/cap metersOverStore, cap.ts meterFiguresFrom over A's journal):
|
|
3502
|
-
// kept, as a settled run's journal no longer changes, keyed by its end, so a run opened again and ended
|
|
3503
|
-
// again
|
|
3568
|
+
// kept, as a settled run's journal no longer changes, keyed by its end and its cost, so a run opened again and ended
|
|
3569
|
+
// again is read again: a grade's round ends it again at the same end time (its look-back keeps the end), its cost moved
|
|
3570
|
+
// by the round's spend. A run whose journal cannot be read leaves it all tokens.
|
|
3504
3571
|
const endedMeters = new Map();
|
|
3505
3572
|
const metersOf = async (row) => {
|
|
3506
|
-
const key = `${row.id} ${row.endedAt}`;
|
|
3573
|
+
const key = `${row.id} ${row.endedAt} ${row.costUsd}`;
|
|
3507
3574
|
let meters = endedMeters.get(key);
|
|
3508
3575
|
if (!meters) {
|
|
3509
3576
|
// An ended run's meter figures over the one store: cap.ts meterFiguresFrom over A's journal, its paid tools' charges
|
|
@@ -3945,23 +4012,30 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3945
4012
|
authFailed(`/v2${path}`, "replay_without_session");
|
|
3946
4013
|
throw new ApiError("forbidden", owner ? "Replaying a learned workflow's revision takes the owner's password sign-in in the console, never a token." : "Replaying a learned workflow's revision takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
|
|
3947
4014
|
}
|
|
3948
|
-
// A run's live computer view
|
|
3949
|
-
// approving a note is (never a token a run, an MCP client or a script
|
|
3950
|
-
// the server's token, its backend's own, takes a run's computer,
|
|
3951
|
-
|
|
4015
|
+
// A run's live computer view, and its take-over and hand-back (COMPUTER_ROUTES), are a full-control credential for its
|
|
4016
|
+
// computer: the owner's signed-in page alone, as approving a note is (never a token a run, an MCP client or a script
|
|
4017
|
+
// may hold). An API-only server has no owner: there the server's token, its backend's own, takes a run's computer,
|
|
4018
|
+
// checked below as every route's token is.
|
|
4019
|
+
const runComputer = found.name === "getRunComputer" || COMPUTER_ROUTES.has(found.name);
|
|
4020
|
+
if ((found.name === "getRunBrowser" || found.name === "handBackRunBrowser" || (runComputer && !options.apiOnly)) && !byOwnerSession(req) && req.headers.authorization !== undefined) {
|
|
3952
4021
|
const what = found.name.endsWith("Browser") ? "browser" : "computer";
|
|
3953
4022
|
authFailed(`/v2${path}`, `${what}_without_session`);
|
|
3954
4023
|
throw new ApiError("forbidden", owner ? `A run's live ${what} takes the owner's password sign-in in the console, never a token.` : `A run's live ${what} takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).`);
|
|
3955
4024
|
}
|
|
3956
|
-
// A run's desktop or phone view drives it once taken over: the owner's signed-in page alone (computer-routes.ts decides).
|
|
3957
|
-
if (COMPUTER_ROUTES.has(found.name) && !options.apiOnly && !byOwnerSession(req) && req.headers.authorization !== undefined)
|
|
3958
|
-
authFailed(`/v2${path}`, "computer_without_session");
|
|
3959
4025
|
// Answering a tool call that waits for approval (tool-gate.ts) is the same: the owner's signed-in page alone, never a
|
|
3960
4026
|
// token, which the run's own process, an agent's MCP client or a script may hold.
|
|
3961
4027
|
if (found.name === "answerApproval" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
|
|
3962
4028
|
authFailed(`/v2${path}`, "approve_without_session");
|
|
3963
4029
|
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).");
|
|
3964
4030
|
}
|
|
4031
|
+
// Purging a run or an agent, or deleting another system's agent, cannot be undone: the owner's session or the API
|
|
4032
|
+
// token. A console session counts as the owner's only where it does for a secret (secret-writes.ts: accounts off on a
|
|
4033
|
+
// loopback-bound server); bound off loopback with accounts off, whoever opened the console is no owner. With no
|
|
4034
|
+
// credential at all it is 401, as every route is.
|
|
4035
|
+
if ((found.name === "deleteRun" || found.name === "deleteAgent") && byConsoleSession(req) && !writesSecretsAllowed(req, { accounts: owner !== undefined, loopbackBound: isLoopback(host) })) {
|
|
4036
|
+
authFailed(`/v2${path}`, "delete_without_owner");
|
|
4037
|
+
throw new ApiError("forbidden", "Deleting a run or an agent takes the owner's session (the password sign-in, or the console on a server bound to loopback) or the API token.");
|
|
4038
|
+
}
|
|
3965
4039
|
// Saving, replacing or removing a secret (secret-writes.ts): the one check. Who may is mayWriteSecrets' alone (the
|
|
3966
4040
|
// owner's session); which writes are secret is each plane's registered predicate, read from the body, so a token's
|
|
3967
4041
|
// non-secret edit on the same route still goes through. A body that does not read counts as the plane says of none.
|
|
@@ -4040,6 +4114,20 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4040
4114
|
throw new ApiError("forbidden", "Native connections require AgentRun on the source machine, bound to loopback without a public URL. A hosted browser cannot discover your laptop.");
|
|
4041
4115
|
const [, first, second] = found.pattern.exec(path);
|
|
4042
4116
|
const id = first ? decodeURIComponent(first) : "";
|
|
4117
|
+
// A purged run or agent (DELETE /runs/{id}, /agents/{id}): every route of it but its DELETE answers 410 purged, with
|
|
4118
|
+
// its tombstone in the details.
|
|
4119
|
+
if (id && ID.test(id)) {
|
|
4120
|
+
if (found.name !== "deleteRun" && found.pattern.source.startsWith("^\\/runs\\/([^/]+)")) {
|
|
4121
|
+
const row = await store.runs.get(id);
|
|
4122
|
+
if (row && row.purgedAt !== null)
|
|
4123
|
+
throw purgedRun(row);
|
|
4124
|
+
}
|
|
4125
|
+
if (found.name !== "deleteAgent" && found.pattern.source.startsWith("^\\/agents\\/([^/]+)")) {
|
|
4126
|
+
const agent = await store.agents.get(id);
|
|
4127
|
+
if (agent && agent.purgedAt !== null)
|
|
4128
|
+
throw purgedAgent(agent);
|
|
4129
|
+
}
|
|
4130
|
+
}
|
|
4043
4131
|
switch (found.name) {
|
|
4044
4132
|
case "startSdkRun": {
|
|
4045
4133
|
if (!req.headers["idempotency-key"])
|
|
@@ -4170,8 +4258,10 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4170
4258
|
if (body.version === undefined || (typeof body.version === "number" && body.version <= entry.version))
|
|
4171
4259
|
throw invalid([{ field: "definition.version", reason: body.version === undefined ? "missing" : "not_an_option", message: `definition.version must be greater than the current one, ${entry.version}` }]);
|
|
4172
4260
|
}
|
|
4173
|
-
// The
|
|
4174
|
-
//
|
|
4261
|
+
// The checks above are a fast path on the agent as the request found it, its body read after. The commit reads the
|
|
4262
|
+
// agent again in its delete turn (reviseAgentOf, agentWrite): one whose body arrived once the agent was purged is
|
|
4263
|
+
// 410, nothing written. The store compares If-Match again inside the commit, so of two edits that read the same
|
|
4264
|
+
// revision exactly one lands.
|
|
4175
4265
|
const { entry: edited, warnings } = await reviseAgentOf(entry, contract ? { definition: body } : body, { contract, ...(match === undefined ? {} : { ifCurrent: entry.revision?.id ?? null }) });
|
|
4176
4266
|
return send(res, 200, { ...agentView(edited, linkOrigin(req), await agentExtra(edited)), warnings }, { etag: etagOf(edited) });
|
|
4177
4267
|
}
|
|
@@ -4185,39 +4275,47 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4185
4275
|
return send(res, 200, { revisions: page, next_cursor: nextCursor(offset + limit, all.length) });
|
|
4186
4276
|
}
|
|
4187
4277
|
case "setCurrent": {
|
|
4188
|
-
|
|
4278
|
+
// The body read first, outside the agent's delete turn; the move made in it (agentWrite), as an edit's revision is:
|
|
4279
|
+
// one whose body arrives while the agent is purged is 410 (the store refuses it too, AgentPurged).
|
|
4189
4280
|
const body = await bodyOf(req);
|
|
4190
|
-
const
|
|
4191
|
-
|
|
4192
|
-
|
|
4193
|
-
|
|
4194
|
-
|
|
4195
|
-
|
|
4196
|
-
|
|
4197
|
-
|
|
4198
|
-
|
|
4199
|
-
|
|
4200
|
-
|
|
4201
|
-
|
|
4202
|
-
|
|
4203
|
-
if (
|
|
4204
|
-
|
|
4205
|
-
|
|
4206
|
-
|
|
4207
|
-
|
|
4208
|
-
|
|
4209
|
-
|
|
4281
|
+
const moved = await agentWrite(id, async () => {
|
|
4282
|
+
const entry = await needAgent(id);
|
|
4283
|
+
const extra = unknownFields(body, ["revision"]);
|
|
4284
|
+
if (extra.length)
|
|
4285
|
+
throw invalid(extra);
|
|
4286
|
+
const revision = body.revision;
|
|
4287
|
+
if (typeof revision !== "string" || !ID.test(revision))
|
|
4288
|
+
throw invalid([{ field: "revision", reason: revision === undefined ? "missing" : "wrong_type", message: "revision is a revision id of this agent" }]);
|
|
4289
|
+
const candidate = await agents.revision(id, revision);
|
|
4290
|
+
if (!candidate)
|
|
4291
|
+
throw invalid([{ field: "revision", reason: "not_an_option", message: `${revision} is not a revision of the agent ${id}` }]);
|
|
4292
|
+
if (stable(nativeOf(candidate.revision.body)) !== stable(nativeOf(entry.revision?.body)))
|
|
4293
|
+
throw new ApiError("input_invalid", "This revision changes the native connection. Reconnect or verify through the native connection controls; ordinary revision restore cannot change its source or connection state.");
|
|
4294
|
+
if (nativeOf(candidate.revision.body)) {
|
|
4295
|
+
const overrides = nativeModelOverrides(candidate.revision.body);
|
|
4296
|
+
if (overrides.length)
|
|
4297
|
+
throw invalid(overrides.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_MODEL_SETTINGS_UNSUPPORTED })));
|
|
4298
|
+
const execution = nativeExecutionOverrides(candidate.revision.body);
|
|
4299
|
+
if (execution.length)
|
|
4300
|
+
throw invalid(execution.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_EXECUTION_SETTINGS_UNSUPPORTED })));
|
|
4301
|
+
}
|
|
4302
|
+
return agents.setCurrent(entry, revision);
|
|
4303
|
+
});
|
|
4210
4304
|
reconcileComputer(id);
|
|
4211
4305
|
return send(res, 200, agentView(moved, linkOrigin(req), await agentExtra(moved)), { etag: etagOf(moved) });
|
|
4212
4306
|
}
|
|
4213
4307
|
case "deleteAgent": {
|
|
4214
|
-
// Another system's agent
|
|
4215
|
-
// turn, so a DELETE after one that finished is 404.
|
|
4308
|
+
// Another system's agent deleted whole; one made here purged once archived (agent-delete.ts). One delete of an agent
|
|
4309
|
+
// at a time, the agent read in its turn, so a DELETE after one that finished is 404 (deleted) or 204 (purged).
|
|
4216
4310
|
await deleteInTurn(id, async () => {
|
|
4217
|
-
const
|
|
4218
|
-
if (
|
|
4219
|
-
|
|
4220
|
-
|
|
4311
|
+
const { agent } = await needAgent(id);
|
|
4312
|
+
if (agent.purgedAt !== null)
|
|
4313
|
+
return;
|
|
4314
|
+
if (agent.externalRef !== null)
|
|
4315
|
+
return deleteExternalAgent(agentDeleteHost, id);
|
|
4316
|
+
if (agent.archivedAt === null)
|
|
4317
|
+
throw new ApiError("agent_not_archived", `The agent ${id} is not archived: archive it first (POST /v2/agents/${id}/archive), which stops new runs and turns its triggers off, then send the DELETE again. Nothing was purged.`);
|
|
4318
|
+
await purgeAgent(agentDeleteHost, id);
|
|
4221
4319
|
});
|
|
4222
4320
|
res.writeHead(204, { "cache-control": "no-store", "x-content-type-options": "nosniff" });
|
|
4223
4321
|
return void res.end();
|
|
@@ -4231,7 +4329,9 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4231
4329
|
// agent_archived in that same store transaction; unarchived, none turns on. Never archived first by another path,
|
|
4232
4330
|
// which would turn its triggers off with no reason and leave the answer empty. Both answer the triggers off for
|
|
4233
4331
|
// the archive, each turned on again by PATCH /triggers/{id} {enabled: true}.
|
|
4234
|
-
|
|
4332
|
+
// In the agent's delete turn (agentWrite): an unarchive sent while its purge runs waits for it and is 410, so no
|
|
4333
|
+
// run of it starts between the purge's live check and its tombstone.
|
|
4334
|
+
const triggersOff = await agentWrite(id, () => (found.name === "archiveAgent" ? triggers.agentArchived(id) : triggers.agentUnarchived(id)));
|
|
4235
4335
|
// An archived agent's own computer is deleted (an unarchived one gets a new one at its next persistent run).
|
|
4236
4336
|
if (found.name === "archiveAgent")
|
|
4237
4337
|
reconcileComputer(id);
|
|
@@ -4302,7 +4402,8 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4302
4402
|
if (content.length > MAX_MESSAGE)
|
|
4303
4403
|
throw invalid([{ field: "content", reason: "too_long", message: `content is at most ${MAX_MESSAGE} characters` }]);
|
|
4304
4404
|
// Its mcp_auth and model_key replace the run's in the steer's own write, so the turn it starts uses them.
|
|
4305
|
-
|
|
4405
|
+
// In its agent's delete turn (runWrite): a message that may open the run again never lands under its purge.
|
|
4406
|
+
const { mode, messageId } = await runWrite(run.agentId, run.id, () => message(store, run, content, { ...(seal ? { launchSealed: seal } : {}), ...(options.beforeSubmit ? { beforeSubmit: options.beforeSubmit } : {}) }));
|
|
4306
4407
|
// The run's state after the command row is written (the run view): the runner applies the steer; the client polls.
|
|
4307
4408
|
const { status, state } = await runStatusState(run.id);
|
|
4308
4409
|
return { status: 202, body: { run_id: run.id, message_id: messageId, mode, status, state, poll_after_ms: 1000 } };
|
|
@@ -4330,9 +4431,19 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4330
4431
|
const { status, state } = await runStatusState(run.id);
|
|
4331
4432
|
return send(res, 200, { run_id: run.id, max_cost_usd: cap, resumed, ...(messageId ? { message_id: messageId } : {}), ...(note ? { note } : {}), status, state });
|
|
4332
4433
|
}
|
|
4434
|
+
case "deleteRun": {
|
|
4435
|
+
// In its agent's delete turn (an agent's delete or purge, or another purge of one of its runs, finishes first), the
|
|
4436
|
+
// run read in that turn, so a DELETE after one that finished is 204 again (purgeRun: a purged run is no work).
|
|
4437
|
+
const row = ID.test(id) ? await store.runs.get(id) : undefined;
|
|
4438
|
+
if (!row)
|
|
4439
|
+
throw new ApiError("not_found", `no run ${id}`);
|
|
4440
|
+
await deleteInTurn(row.agentId, () => purgeRun(agentDeleteHost, id));
|
|
4441
|
+
res.writeHead(204, { "cache-control": "no-store", "x-content-type-options": "nosniff" });
|
|
4442
|
+
return void res.end();
|
|
4443
|
+
}
|
|
4333
4444
|
case "stopRun": {
|
|
4334
4445
|
const run = await needRun(id);
|
|
4335
|
-
const stopped = await stopRunOverStore(store, run
|
|
4446
|
+
const stopped = await stopRunOverStore(store, run);
|
|
4336
4447
|
const { status, state } = await runStatusState(run.id);
|
|
4337
4448
|
return send(res, 200, { run_id: run.id, stopped, status, state });
|
|
4338
4449
|
}
|
|
@@ -4374,6 +4485,10 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4374
4485
|
throw invalid([{ field: "source", reason: "not_an_option", message: `source is one of ${GRADE_SOURCES.join(", ")}` }]);
|
|
4375
4486
|
if (body.label !== undefined && (typeof body.label !== "string" || body.label.length > LABEL_MAX))
|
|
4376
4487
|
throw invalid([{ field: "label", reason: "wrong_type", message: `label is a string of at most ${LABEL_MAX} characters: the grade's words` }]);
|
|
4488
|
+
// A run that reads ended while it still learns from that end (its look-back: store-view.ts lookingBackEnd) is graded
|
|
4489
|
+
// once that ends: its row is not ended yet, and the round a grade opens reopens only an ended run.
|
|
4490
|
+
if (!FINAL_STATES.includes(row.state) && (await lookingBackEnd(store, row.id)))
|
|
4491
|
+
throw new ApiError("run_learning", "The run is still learning from its answer: grade it once that ends.");
|
|
4377
4492
|
if (!FINAL_STATES.includes(row.state))
|
|
4378
4493
|
throw invalid([{ field: "run_id", reason: "not_allowed", message: "A run is graded once it has ended." }]);
|
|
4379
4494
|
const m = (isObject(row.metrics) ? row.metrics : {});
|
|
@@ -4389,7 +4504,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4389
4504
|
};
|
|
4390
4505
|
// The grade and its audit row are written to the agent's learning in its delete turn (agentWrite): a grade whose body
|
|
4391
4506
|
// came in while a DELETE ran waits for it and finds the agent gone, so nothing is written after its learning went.
|
|
4392
|
-
const kept = await
|
|
4507
|
+
const kept = await runWrite(row.agentId, row.id, async () => {
|
|
4393
4508
|
// Kept with what it asks of the run's learning (runner/feedback-round.ts): nothing, or a look-back.
|
|
4394
4509
|
// Its feedback round is a turn with no caller's model key: on the server's key for the run's route, else not opened.
|
|
4395
4510
|
const graded = gradeView(await keepGrade(store, row.agentId, grade, typeof body.label === "string" ? body.label : undefined, (launch) => !serverKeyMissing(env, { kind: "agentic", model: launch.model, native: Boolean(launch.native) })));
|
|
@@ -4475,9 +4590,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4475
4590
|
// store: the hold is the run's journal, a take-over and a hand-back are command rows its runner applies; a browser's
|
|
4476
4591
|
// hand-back is the browser's own answer row, as POST .../browser/hand-back writes it.
|
|
4477
4592
|
const run = await needRun(id);
|
|
4478
|
-
const answer = await computerRoute(found.name, run.id, {
|
|
4479
|
-
ownerSession: byOwnerSession(req), token: req.headers.authorization !== undefined, apiOnly: options.apiOnly === true, accounts: owner !== undefined, body: await bodyOf(req),
|
|
4480
|
-
}, store, { context: ctx });
|
|
4593
|
+
const answer = await computerRoute(found.name, run.id, await bodyOf(req), store, { context: ctx });
|
|
4481
4594
|
return send(res, 200, answer, { "cache-control": "no-store" });
|
|
4482
4595
|
}
|
|
4483
4596
|
case "createRunComputerViewer": {
|
|
@@ -4627,6 +4740,12 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4627
4740
|
// The workflow run's graph from its journal over the store (run-reads-over-store): an agentic run has none (404),
|
|
4628
4741
|
// a run whose output is withheld is refused (403), as the route refused it.
|
|
4629
4742
|
return send(res, 200, await runGraphView(store, id, runReadsDeps));
|
|
4743
|
+
case "getRunUsage":
|
|
4744
|
+
await needRun(id);
|
|
4745
|
+
// The run's lines from its booking (run-usage.ts), the figures its cost.usd joins: none, with why, while it is at work
|
|
4746
|
+
// or where its figure is not its booking's.
|
|
4747
|
+
// Names through the run's cut, and a withheld run refused (403), as its trace is.
|
|
4748
|
+
return send(res, 200, await servedRunUsage({ serverSecrets, signIns }, store, id));
|
|
4630
4749
|
case "getRunTrace":
|
|
4631
4750
|
await needRun(id);
|
|
4632
4751
|
// The run's spans over its served Timeline rows and its journal (run-trace.ts): cut by the run's one cut, as its
|
|
@@ -5264,6 +5383,25 @@ async function startHolding(options, data, checked, stops) {
|
|
|
5264
5383
|
res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store", "x-content-type-options": "nosniff", ...headers });
|
|
5265
5384
|
res.end(text);
|
|
5266
5385
|
}
|
|
5386
|
+
/**
|
|
5387
|
+
* Whether an API-only server lets this request into run `runId`'s live view, its page and files or (socket) its
|
|
5388
|
+
* WebSocket: from the public address alone (a page navigation may send no Origin; a socket always sends one), with the
|
|
5389
|
+
* viewer credential its backend minted for this run (viewer-credential.ts), not expired, its run not ended (read from
|
|
5390
|
+
* the store each time: its revocation). The credential, or the refusal and its authFailed reason.
|
|
5391
|
+
*/
|
|
5392
|
+
async function liveAdmits(req, runId, { socket }) {
|
|
5393
|
+
const sent = req.headers.origin?.toLowerCase();
|
|
5394
|
+
if (sent === undefined ? socket : sent !== publicOrigin) {
|
|
5395
|
+
return { reason: "live_view_origin", error: new ApiError("forbidden", "a run's live view here is opened on this server's public address (AGENTRUN_PUBLIC_URL) alone") };
|
|
5396
|
+
}
|
|
5397
|
+
const credential = viewerCredentialOf(req);
|
|
5398
|
+
if (credential === undefined)
|
|
5399
|
+
return { reason: "no_credential", error: new ApiError("unauthenticated", "a run's live view here takes the viewer link its backend minted (POST /v2/runs/{run_id}/computer/viewer)") };
|
|
5400
|
+
if (!viewerCredentialFor(viewerKey, runId, credential, Date.now()) || (await runOver(store, runId))) {
|
|
5401
|
+
return { reason: "viewer_credential", error: new ApiError("forbidden", "this viewer link is expired, for another run, or its run has ended: ask for a new one") };
|
|
5402
|
+
}
|
|
5403
|
+
return { credential };
|
|
5404
|
+
}
|
|
5267
5405
|
/** A run's live viewer's page and files (browser-live.ts, /v2/runs/{id}/computer/live/*): the owner's signed-in page
|
|
5268
5406
|
* alone, GET or HEAD, for a viewer the run's live process has handed over. The bytes are this server's own copy of pi-browser's viewer, never the run's port's:
|
|
5269
5407
|
* only the viewer's WebSocket reaches the run. */
|
|
@@ -5271,27 +5409,16 @@ async function startHolding(options, data, checked, stops) {
|
|
|
5271
5409
|
if (req.method !== "GET" && req.method !== "HEAD")
|
|
5272
5410
|
throw new ApiError("method_not_allowed", `${req.method} is not a method of a run's live view`, {}, { allow: "GET, HEAD" });
|
|
5273
5411
|
if (options.apiOnly) {
|
|
5274
|
-
// API-only: no owner here. The
|
|
5275
|
-
|
|
5276
|
-
|
|
5277
|
-
|
|
5278
|
-
|
|
5279
|
-
authFailed(`/v2/runs/${runId}/${family}/live`, "live_view_origin");
|
|
5280
|
-
throw new ApiError("forbidden", "a run's live view here is opened on this server's public address (AGENTRUN_PUBLIC_URL) alone");
|
|
5281
|
-
}
|
|
5282
|
-
const credential = viewerCredentialOf(req);
|
|
5283
|
-
if (credential === undefined) {
|
|
5284
|
-
authFailed(`/v2/runs/${runId}/${family}/live`, "no_credential");
|
|
5285
|
-
throw new ApiError("unauthenticated", "a run's live view here takes the viewer link its backend minted (POST /v2/runs/{run_id}/computer/viewer)");
|
|
5286
|
-
}
|
|
5287
|
-
if (!(await viewerHolds(credential, runId))) {
|
|
5288
|
-
authFailed(`/v2/runs/${runId}/${family}/live`, "viewer_credential");
|
|
5289
|
-
throw new ApiError("forbidden", "this viewer link is expired, for another run, or its run has ended: ask for a new one");
|
|
5412
|
+
// API-only: no owner here (liveAdmits). The page's answer sets the credential as the cookie its files and socket carry.
|
|
5413
|
+
const admitted = await liveAdmits(req, runId, { socket: false });
|
|
5414
|
+
if ("error" in admitted) {
|
|
5415
|
+
authFailed(`/v2/runs/${runId}/${family}/live`, admitted.reason);
|
|
5416
|
+
throw admitted.error;
|
|
5290
5417
|
}
|
|
5291
5418
|
const handover = await liveViewerFor(store, sealKey, runId, rest);
|
|
5292
5419
|
if (handover === undefined)
|
|
5293
5420
|
throw new ApiError("not_found", `this run's ${family} has no live view at that address`);
|
|
5294
|
-
res.setHeader("set-cookie", viewerCookie(req, runId, credential
|
|
5421
|
+
res.setHeader("set-cookie", viewerCookie(req, runId, admitted.credential));
|
|
5295
5422
|
return serveViewerFile(req, res, rest, (handover.kind ?? "browser") === "browser" ? "browser" : "computer");
|
|
5296
5423
|
}
|
|
5297
5424
|
if (!byOwnerSession(req)) {
|
|
@@ -5442,17 +5569,10 @@ async function startHolding(options, data, checked, stops) {
|
|
|
5442
5569
|
return deny("404 Not Found");
|
|
5443
5570
|
// A browser always sends its page's origin on a WebSocket, which no other page's script can forge: this server's own
|
|
5444
5571
|
// (as this request reaches it, or its public address, which a TLS proxy that rewrites Host or drops
|
|
5445
|
-
// X-Forwarded-Proto leaves as the only one the owner's page has), and the owner signed in, or nothing. API-only:
|
|
5446
|
-
//
|
|
5447
|
-
|
|
5448
|
-
|
|
5449
|
-
if (options.apiOnly) {
|
|
5450
|
-
if (sent === "" || sent !== publicOrigin)
|
|
5451
|
-
return (authFailed(raw, "live_view_origin"), deny("403 Forbidden"));
|
|
5452
|
-
if (credential === undefined)
|
|
5453
|
-
return (authFailed(raw, "no_credential"), deny("401 Unauthorized"));
|
|
5454
|
-
}
|
|
5455
|
-
else {
|
|
5572
|
+
// X-Forwarded-Proto leaves as the only one the owner's page has), and the owner signed in, or nothing. API-only:
|
|
5573
|
+
// liveAdmits, below.
|
|
5574
|
+
if (!options.apiOnly) {
|
|
5575
|
+
const sent = String(req.headers.origin ?? "").toLowerCase();
|
|
5456
5576
|
if (sent === "" || (sent !== ownOrigin(req) && sent !== publicOrigin))
|
|
5457
5577
|
return (authFailed(raw, "live_view_origin"), deny("403 Forbidden"));
|
|
5458
5578
|
if (!owner || !signedIn(req, owner))
|
|
@@ -5461,8 +5581,11 @@ async function startHolding(options, data, checked, stops) {
|
|
|
5461
5581
|
// Once the run's WebSocket is piped to this socket, a failure here only ends it: an HTTP line would land mid-stream.
|
|
5462
5582
|
let piping = false;
|
|
5463
5583
|
void (async () => {
|
|
5464
|
-
if (options.apiOnly
|
|
5465
|
-
|
|
5584
|
+
if (options.apiOnly) {
|
|
5585
|
+
const admitted = await liveAdmits(req, viewing[1], { socket: true });
|
|
5586
|
+
if ("error" in admitted)
|
|
5587
|
+
return (authFailed(raw, admitted.reason), deny(admitted.error.code === "unauthenticated" ? "401 Unauthorized" : "403 Forbidden"));
|
|
5588
|
+
}
|
|
5466
5589
|
const run = ID.test(viewing[1]) ? await momentOverStore(store, viewing[1], viewDepsFor(ownOriginOf())) : undefined;
|
|
5467
5590
|
// The run's live viewer from the store (the runner's browser/computer tool wrote it under its claim): none for a run no
|
|
5468
5591
|
// runner holds. A /computer/live socket reaches a viewer of every kind, a
|