@parcha/agentrun-serve 0.0.0-bootstrap.0 → 0.1.0-beta.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +560 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +1724 -0
- package/dist/adapters.d.ts +205 -0
- package/dist/adapters.js +459 -0
- package/dist/agents.d.ts +124 -0
- package/dist/agents.js +302 -0
- package/dist/app.d.ts +7 -0
- package/dist/app.js +324 -0
- package/dist/bound-files.d.ts +4 -0
- package/dist/bound-files.js +164 -0
- package/dist/box/record.d.ts +6 -0
- package/dist/box/record.js +41 -0
- package/dist/box/sweep.d.ts +53 -0
- package/dist/box/sweep.js +193 -0
- package/dist/box-image.d.ts +98 -0
- package/dist/box-image.js +283 -0
- package/dist/box-relay.d.ts +42 -0
- package/dist/box-relay.js +222 -0
- package/dist/boxes.d.ts +54 -0
- package/dist/boxes.js +182 -0
- package/dist/cap.d.ts +224 -0
- package/dist/cap.js +721 -0
- package/dist/catalog.d.ts +20 -0
- package/dist/catalog.js +53 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +167 -0
- package/dist/coding-tools.d.ts +31 -0
- package/dist/coding-tools.js +81 -0
- package/dist/console/THIRD-PARTY-NOTICES.txt +1141 -0
- package/dist/console/assets/index-BN7oVcO4.js +445 -0
- package/dist/console/assets/index-By-jkqki.css +1 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
- package/dist/console/index.html +15 -0
- package/dist/daytona-api.d.ts +21 -0
- package/dist/daytona-api.js +101 -0
- package/dist/decision-rows.d.ts +11 -0
- package/dist/decision-rows.js +116 -0
- package/dist/decisions.d.ts +94 -0
- package/dist/decisions.js +184 -0
- package/dist/effort-guidance.d.ts +5 -0
- package/dist/effort-guidance.js +14 -0
- package/dist/environment.d.ts +5 -0
- package/dist/environment.js +11 -0
- package/dist/errors.d.ts +72 -0
- package/dist/errors.js +66 -0
- package/dist/exa-keyless.d.ts +35 -0
- package/dist/exa-keyless.js +202 -0
- package/dist/fetch-page.d.ts +114 -0
- package/dist/fetch-page.js +182 -0
- package/dist/files.d.ts +60 -0
- package/dist/files.js +153 -0
- package/dist/grade.d.ts +96 -0
- package/dist/grade.js +348 -0
- package/dist/graph-view.d.ts +100 -0
- package/dist/graph-view.js +212 -0
- package/dist/harness-app.d.ts +38 -0
- package/dist/harness-app.js +626 -0
- package/dist/harness.d.ts +53 -0
- package/dist/harness.js +74 -0
- package/dist/home-path.d.ts +27 -0
- package/dist/home-path.js +78 -0
- package/dist/host-tools.d.ts +20 -0
- package/dist/host-tools.js +140 -0
- package/dist/host.d.ts +39 -0
- package/dist/host.js +81 -0
- package/dist/hosted-search.d.ts +27 -0
- package/dist/hosted-search.js +129 -0
- package/dist/import-sources.d.ts +104 -0
- package/dist/import-sources.js +629 -0
- package/dist/import-summary.d.ts +25 -0
- package/dist/import-summary.js +75 -0
- package/dist/import-worker.d.ts +26 -0
- package/dist/import-worker.js +41 -0
- package/dist/import.d.ts +145 -0
- package/dist/import.js +1221 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +6 -0
- package/dist/key-check.d.ts +36 -0
- package/dist/key-check.js +108 -0
- package/dist/key-refusal.d.ts +51 -0
- package/dist/key-refusal.js +187 -0
- package/dist/learn/check.d.ts +99 -0
- package/dist/learn/check.js +259 -0
- package/dist/learn/grade.d.ts +79 -0
- package/dist/learn/grade.js +433 -0
- package/dist/learn/index.d.ts +7 -0
- package/dist/learn/index.js +11 -0
- package/dist/learn/invisible.d.ts +5 -0
- package/dist/learn/invisible.js +42 -0
- package/dist/learn/notes.d.ts +59 -0
- package/dist/learn/notes.js +146 -0
- package/dist/learn/reflect.d.ts +49 -0
- package/dist/learn/reflect.js +167 -0
- package/dist/learn/secrets.d.ts +18 -0
- package/dist/learn/secrets.js +111 -0
- package/dist/learn/skills.d.ts +84 -0
- package/dist/learn/skills.js +198 -0
- package/dist/learning-routes.d.ts +196 -0
- package/dist/learning-routes.js +609 -0
- package/dist/learning-run.d.ts +304 -0
- package/dist/learning-run.js +797 -0
- package/dist/learning-words.d.ts +73 -0
- package/dist/learning-words.js +171 -0
- package/dist/learning.d.ts +377 -0
- package/dist/learning.js +801 -0
- package/dist/llm.d.ts +40 -0
- package/dist/llm.js +37 -0
- package/dist/llms.txt +37 -0
- package/dist/mcp-servers.d.ts +115 -0
- package/dist/mcp-servers.js +445 -0
- package/dist/mcp.d.ts +51 -0
- package/dist/mcp.js +392 -0
- package/dist/model.d.ts +184 -0
- package/dist/model.js +484 -0
- package/dist/monid.d.ts +74 -0
- package/dist/monid.js +277 -0
- package/dist/openapi/agentrun-v2.openapi.json +4805 -0
- package/dist/openapi.d.ts +10 -0
- package/dist/openapi.js +1417 -0
- package/dist/owner.d.ts +55 -0
- package/dist/owner.js +222 -0
- package/dist/packs.d.ts +71 -0
- package/dist/packs.js +180 -0
- package/dist/page.d.ts +32 -0
- package/dist/page.js +133 -0
- package/dist/paid-calls.d.ts +46 -0
- package/dist/paid-calls.js +110 -0
- package/dist/pause.d.ts +68 -0
- package/dist/pause.js +97 -0
- package/dist/pdf-pages.d.ts +44 -0
- package/dist/pdf-pages.js +147 -0
- package/dist/place.d.ts +46 -0
- package/dist/place.js +105 -0
- package/dist/print.d.ts +20 -0
- package/dist/print.js +29 -0
- package/dist/propose.d.ts +38 -0
- package/dist/propose.js +82 -0
- package/dist/quiet-sqlite-warning.d.ts +1 -0
- package/dist/quiet-sqlite-warning.js +14 -0
- package/dist/request-start.d.ts +14 -0
- package/dist/request-start.js +226 -0
- package/dist/result.d.ts +3 -0
- package/dist/result.js +5 -0
- package/dist/rows.d.ts +46 -0
- package/dist/rows.js +121 -0
- package/dist/run-box.d.ts +134 -0
- package/dist/run-box.js +440 -0
- package/dist/run-manifest.d.ts +27 -0
- package/dist/run-manifest.js +60 -0
- package/dist/runnable.d.ts +80 -0
- package/dist/runnable.js +162 -0
- package/dist/runs.d.ts +840 -0
- package/dist/runs.js +2279 -0
- package/dist/secret-cut.d.ts +27 -0
- package/dist/secret-cut.js +109 -0
- package/dist/secrets.d.ts +50 -0
- package/dist/secrets.js +140 -0
- package/dist/server-lock.d.ts +44 -0
- package/dist/server-lock.js +140 -0
- package/dist/server.d.ts +626 -0
- package/dist/server.js +1756 -0
- package/dist/sessions.d.ts +4 -0
- package/dist/sessions.js +105 -0
- package/dist/skills.d.ts +31 -0
- package/dist/skills.js +68 -0
- package/dist/stats.d.ts +101 -0
- package/dist/stats.js +82 -0
- package/dist/tool-keys.d.ts +151 -0
- package/dist/tool-keys.js +273 -0
- package/dist/tool-plane.d.ts +143 -0
- package/dist/tool-plane.js +242 -0
- package/dist/tools.d.ts +147 -0
- package/dist/tools.js +253 -0
- package/dist/turn-end.d.ts +23 -0
- package/dist/turn-end.js +14 -0
- package/dist/turns.d.ts +34 -0
- package/dist/turns.js +202 -0
- package/dist/uploads.d.ts +104 -0
- package/dist/uploads.js +474 -0
- package/dist/usage.d.ts +29 -0
- package/dist/usage.js +58 -0
- package/dist/validate.d.ts +55 -0
- package/dist/validate.js +175 -0
- package/dist/web-fetch.d.ts +64 -0
- package/dist/web-fetch.js +262 -0
- package/dist/web-search.d.ts +54 -0
- package/dist/web-search.js +136 -0
- package/dist/webhooks.d.ts +182 -0
- package/dist/webhooks.js +487 -0
- package/dist/workspace-paths.d.ts +33 -0
- package/dist/workspace-paths.js +104 -0
- package/dist/workspace.d.ts +88 -0
- package/dist/workspace.js +369 -0
- package/launcher/agentrun-serve +109 -0
- package/package.json +96 -1
- package/skills/agentrun-serve/SKILL.md +128 -0
package/dist/agents.js
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
// The agents this server holds: one agent store of @parcha/pi-durable-agent in the data directory (`store.sqlite`), many
|
|
2
|
+
// agents in it, each with revisions written once. A definition is one revision; an edit commits the next, its parent
|
|
3
|
+
// the current one, and makes it current.
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { DatabaseSync } from "node:sqlite";
|
|
7
|
+
import { AgentHomeError, openStore, STORE_FILE } from "@parcha/pi-durable-agent";
|
|
8
|
+
import { ApiError, invalid } from "./errors.js";
|
|
9
|
+
import { DEFAULT_HARNESS, harnessOfBody } from "./harness.js";
|
|
10
|
+
import { isObject, skillIssues, skillNames, stable } from "./validate.js";
|
|
11
|
+
/** SQLITE_BUSY or SQLITE_LOCKED: another connection holds the database. */
|
|
12
|
+
export const sqliteBusy = (error) => isObject(error) && error.code === "ERR_SQLITE_ERROR" && typeof error.errcode === "number" && [5, 6].includes(error.errcode & 0xff);
|
|
13
|
+
/** How long a request waits for a busy agent store, step by step: short first, so a reader's overlap costs
|
|
14
|
+
* milliseconds; about 2 s in all, then the request answers home_busy. */
|
|
15
|
+
export const REQUEST_BUSY_MS = [10, 20, 50, 100, 200, 400, 600, 600];
|
|
16
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
17
|
+
/** `act` again while another connection holds the store: after busy `attempt`, `onBusy` hears of it and the next of
|
|
18
|
+
* `delaysMs` is waited out without blocking the event loop. Past the last, the busy error is thrown. */
|
|
19
|
+
export async function whenFree(act, delaysMs, onBusy) {
|
|
20
|
+
for (let attempt = 0;; attempt++) {
|
|
21
|
+
try {
|
|
22
|
+
return await act();
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
if (!sqliteBusy(error))
|
|
26
|
+
throw error;
|
|
27
|
+
const delay = delaysMs[attempt];
|
|
28
|
+
onBusy?.(attempt, delay);
|
|
29
|
+
if (delay === undefined)
|
|
30
|
+
throw error;
|
|
31
|
+
await sleep(delay);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/** A store another writer holds: SQLite's busy or locked, or the agent home's own `busy` (a home held past its deadline, or a
|
|
36
|
+
* store a stopped writer left mid-write). Every answer of the server maps it the same way: home_busy. */
|
|
37
|
+
export const storeBusy = (error) => sqliteBusy(error) || (error instanceof AgentHomeError && error.code === "busy");
|
|
38
|
+
/** The answer to a request the agent store stayed busy for. */
|
|
39
|
+
export const homeBusy = () => new ApiError("home_busy", "the agent store is busy with another write; try again", { retry_after_ms: 500 });
|
|
40
|
+
/** A store error as the request's answer: a busy store is retryable, a refusal names the field it refused. */
|
|
41
|
+
export function storeError(error, field = "definition") {
|
|
42
|
+
if (storeBusy(error))
|
|
43
|
+
throw homeBusy();
|
|
44
|
+
if (error instanceof AgentHomeError && error.code === "invalid") {
|
|
45
|
+
// A workflow's refusal carries every issue, each at its path under the field.
|
|
46
|
+
const issues = error.issues;
|
|
47
|
+
if (issues?.length)
|
|
48
|
+
throw invalid(issues.map((issue) => ({ field: `${field}${issue.path}`, reason: "invalid", code: issue.code, message: issue.message })), error.message);
|
|
49
|
+
throw invalid([{ field, reason: "invalid", message: error.message }]);
|
|
50
|
+
}
|
|
51
|
+
if (error instanceof AgentHomeError && error.code === "missing")
|
|
52
|
+
throw new ApiError("not_found", error.message);
|
|
53
|
+
if (error instanceof AgentHomeError && error.code === "stale")
|
|
54
|
+
throw new ApiError("precondition_failed", "the agent's current revision moved since the If-Match it was read at: read the agent again");
|
|
55
|
+
throw error;
|
|
56
|
+
}
|
|
57
|
+
export class Agents {
|
|
58
|
+
dir;
|
|
59
|
+
/** Never waits for another connection synchronously: what touches it goes through `request` or `whenFree`. */
|
|
60
|
+
store;
|
|
61
|
+
/** Read-only, for the store's skill texts, which its reads do not return. */
|
|
62
|
+
skills;
|
|
63
|
+
constructor(dir) {
|
|
64
|
+
this.dir = dir;
|
|
65
|
+
this.store = openStore(dir, { busyTimeoutMs: 0 });
|
|
66
|
+
this.skills = new DatabaseSync(join(dir, STORE_FILE), { readOnly: true, timeout: 0 });
|
|
67
|
+
}
|
|
68
|
+
/** A read or write of the store for a request: a busy store is waited for about 2 s (REQUEST_BUSY_MS). */
|
|
69
|
+
request(act) {
|
|
70
|
+
return whenFree(act, REQUEST_BUSY_MS);
|
|
71
|
+
}
|
|
72
|
+
closed = false;
|
|
73
|
+
close() {
|
|
74
|
+
if (this.closed)
|
|
75
|
+
return;
|
|
76
|
+
this.closed = true;
|
|
77
|
+
this.skills.close();
|
|
78
|
+
this.store.close();
|
|
79
|
+
}
|
|
80
|
+
/** Skill texts by their SHA-256. */
|
|
81
|
+
texts(shas) {
|
|
82
|
+
const out = new Map();
|
|
83
|
+
const read = this.skills.prepare("SELECT content FROM skills WHERE sha256 = ?");
|
|
84
|
+
for (const sha of shas) {
|
|
85
|
+
const row = read.get(sha);
|
|
86
|
+
if (typeof row?.content === "string")
|
|
87
|
+
out.set(sha, row.content);
|
|
88
|
+
}
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
/** The revision a checked definition makes; `files` are its skill files by path. */
|
|
92
|
+
revisionOf(definition, files, note) {
|
|
93
|
+
const issues = skillIssues(definition.skills, Object.keys(files));
|
|
94
|
+
if (issues.length)
|
|
95
|
+
throw invalid(issues);
|
|
96
|
+
// The default harness is never stored: naming pi and naming none are one revision.
|
|
97
|
+
const harness = typeof definition.harness === "string" && definition.harness !== DEFAULT_HARNESS ? { harness: definition.harness } : {};
|
|
98
|
+
// Unlike the harness, a place is kept when it is runner: the default is the host's, so naming runner says something.
|
|
99
|
+
const place = isObject(definition.place) ? { place: definition.place } : {};
|
|
100
|
+
// A capability with nothing set is none: `{web_search: {}}` and no settings are one revision.
|
|
101
|
+
const kept = Object.entries(isObject(definition.tool_settings) ? definition.tool_settings : {}).filter(([, setting]) => isObject(setting) && Object.keys(setting).length);
|
|
102
|
+
const set = kept.length ? { toolSettings: Object.fromEntries(kept) } : {};
|
|
103
|
+
const common = { skills: files, tools: definition.tools ?? [], ...harness, ...place, ...set, ...(note !== undefined ? { note } : {}) };
|
|
104
|
+
if (isObject(definition.workflow))
|
|
105
|
+
return { kind: "workflow", workflow: definition.workflow, ...common };
|
|
106
|
+
// The learning switch is kept whenever a definition sets it, false included; a definition that leaves it out keeps
|
|
107
|
+
// none, and its revision id is the one it had before the switch.
|
|
108
|
+
const learning = typeof definition.learning === "boolean" ? { learning: definition.learning } : {};
|
|
109
|
+
return { kind: "agentic", instructions: definition.instructions, ...(typeof definition.model === "string" ? { model: definition.model } : {}), ...(typeof definition.thinking === "string" ? { thinking: definition.thinking } : {}), ...common, ...learning };
|
|
110
|
+
}
|
|
111
|
+
/** `definition.version`, when given, is the number of the revision the request leaves current. */
|
|
112
|
+
checkVersion(definition, version) {
|
|
113
|
+
if (definition.version !== undefined && definition.version !== version)
|
|
114
|
+
throw invalid([{ field: "definition.version", reason: "not_an_option", message: `definition.version is ${version} here: the number of the revision this definition leaves current` }]);
|
|
115
|
+
}
|
|
116
|
+
/** A workflow revision is checked before anything is written, so a refusal makes no agent. */
|
|
117
|
+
async checked(revision) {
|
|
118
|
+
if (revision.kind !== "workflow")
|
|
119
|
+
return;
|
|
120
|
+
const { checkWorkflowBody } = await import("@parcha/pi-durable-agent/workflow");
|
|
121
|
+
await checkWorkflowBody({ workflow: revision.workflow, tools: revision.tools ?? [] }).catch((error) => storeError(error, "definition.workflow"));
|
|
122
|
+
}
|
|
123
|
+
/** A new agent and its first revision, current. A definition id already here is `409 agent_exists`. `check` sees the
|
|
124
|
+
* revision before anything is written, and may refuse it. */
|
|
125
|
+
async create({ definition, skills = {}, note }, check) {
|
|
126
|
+
const given = typeof definition.id === "string" ? definition.id : undefined;
|
|
127
|
+
if (given !== undefined && (await this.request(() => this.store.readAgent(given))))
|
|
128
|
+
throw new ApiError("agent_exists", `an agent ${given} exists here`);
|
|
129
|
+
const revision = this.revisionOf(definition, skills, note);
|
|
130
|
+
this.checkVersion(definition, 1);
|
|
131
|
+
await this.checked(revision);
|
|
132
|
+
await check?.(revision);
|
|
133
|
+
let agent;
|
|
134
|
+
try {
|
|
135
|
+
agent = await this.request(() => this.store.createAgent({ name: definition.name, ...(typeof definition.description === "string" ? { description: definition.description } : {}), ...(given !== undefined ? { id: given } : {}) }));
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
if (error instanceof AgentHomeError && error.code === "exists")
|
|
139
|
+
throw new ApiError("agent_exists", `an agent ${given} exists here`);
|
|
140
|
+
storeError(error);
|
|
141
|
+
}
|
|
142
|
+
await this.request(() => this.store.commitRevision(agent.id, revision, { setCurrent: true })).catch((error) => storeError(error));
|
|
143
|
+
return (await this.get(agent.id));
|
|
144
|
+
}
|
|
145
|
+
/** An edit: a new revision of the agent, its parent the current one, made current. Without `skills` the current
|
|
146
|
+
* revision's skill files carry over. An edit that is the current revision writes nothing, so a PUT sent twice makes
|
|
147
|
+
* one revision. The store keeps an agent's id, name and description from its creation. `ifCurrent` (from If-Match)
|
|
148
|
+
* is the current revision the caller read, null for none: the store compares it in the commit's own transaction.
|
|
149
|
+
* `check` sees the revision, the current one's included, before anything is written, and may refuse it. */
|
|
150
|
+
/** `contract`: the contract's edit, whose version the caller has checked is past the current one. It always makes a new
|
|
151
|
+
* revision, the same definition included, numbered as this store numbers them (the next), whatever version it named. */
|
|
152
|
+
async commit(read, { definition, skills, note }, { ifCurrent, check, contract = false } = {}) {
|
|
153
|
+
const held = (now) => {
|
|
154
|
+
if (ifCurrent !== undefined && (now.revision?.id ?? null) !== ifCurrent)
|
|
155
|
+
storeError(new AgentHomeError("stale", "the agent's current revision is not the one the commit expects"));
|
|
156
|
+
return now;
|
|
157
|
+
};
|
|
158
|
+
let entry = held((await this.get(read.agent.id)) ?? read);
|
|
159
|
+
const { agent } = entry;
|
|
160
|
+
const kept = [
|
|
161
|
+
...(definition.id !== undefined && definition.id !== agent.id ? [{ field: "definition.id", reason: "not_an_option", message: `definition.id is ${agent.id}, the agent's id` }] : []),
|
|
162
|
+
...["name", "description"]
|
|
163
|
+
.filter((key) => definition[key] !== undefined && definition[key] !== agent[key])
|
|
164
|
+
.map((key) => ({ field: `definition.${key}`, reason: "not_allowed", message: `The agent store keeps an agent's ${key} from its creation; an edit does not change it.`, fix: `Remove definition.${key}.` })),
|
|
165
|
+
];
|
|
166
|
+
if (kept.length)
|
|
167
|
+
throw invalid(kept);
|
|
168
|
+
// Each try builds the revision on the current one, checks it and commits it on that one: a current revision another
|
|
169
|
+
// writer moved since the build is sent back as stale, and the next try builds and checks again on the new one, so
|
|
170
|
+
// what an edit leaves out (skill files, harness, place, learning) is never carried over from a revision it does not
|
|
171
|
+
// follow.
|
|
172
|
+
for (let tries = 1;; tries++) {
|
|
173
|
+
if (tries > 1)
|
|
174
|
+
entry = held((await this.get(agent.id)) ?? entry);
|
|
175
|
+
let files = skills;
|
|
176
|
+
if (files === undefined) {
|
|
177
|
+
const held = Object.entries(entry.revision?.body.skills ?? {});
|
|
178
|
+
const texts = await this.request(() => this.texts(held.map(([, sha]) => sha)));
|
|
179
|
+
files = Object.fromEntries(held.map(([path, sha]) => [path, texts.get(sha) ?? ""]));
|
|
180
|
+
}
|
|
181
|
+
// An edit that names no harness, place or learning switch keeps the agent's, as it keeps its skill files: absent
|
|
182
|
+
// here is unchanged, not the default.
|
|
183
|
+
const harness = entry.revision?.body.harness;
|
|
184
|
+
const place = entry.revision?.body.place;
|
|
185
|
+
const learning = entry.revision?.kind === "agentic" && !isObject(definition.workflow) ? entry.revision.body.learning : undefined;
|
|
186
|
+
const revision = this.revisionOf({ ...definition, ...(definition.harness === undefined && harness ? { harness } : {}), ...(definition.place === undefined && place ? { place } : {}), ...(definition.learning === undefined && learning !== undefined ? { learning } : {}) }, files, note);
|
|
187
|
+
await this.checked(revision);
|
|
188
|
+
await check?.(revision);
|
|
189
|
+
const base = entry.revision?.id ?? null;
|
|
190
|
+
const attempt = async () => {
|
|
191
|
+
const now = held(this.entry(agent.id) ?? entry);
|
|
192
|
+
if ((now.revision?.id ?? null) !== base)
|
|
193
|
+
throw new AgentHomeError("stale", "the agent's current revision moved while the edit was checked");
|
|
194
|
+
if (!contract && now.revision && sameRevision(now.revision, revision)) {
|
|
195
|
+
this.checkVersion(definition, now.version);
|
|
196
|
+
return now;
|
|
197
|
+
}
|
|
198
|
+
if (!contract)
|
|
199
|
+
this.checkVersion(definition, now.revisions + 1);
|
|
200
|
+
await this.store.commitRevision(agent.id, revision, { setCurrent: true, ifCurrent: base });
|
|
201
|
+
return undefined;
|
|
202
|
+
};
|
|
203
|
+
try {
|
|
204
|
+
return (await this.request(attempt)) ?? (await this.get(agent.id));
|
|
205
|
+
}
|
|
206
|
+
catch (error) {
|
|
207
|
+
// Without If-Match an edit goes on the revision current when it commits: one moved under it is read again.
|
|
208
|
+
if (ifCurrent === undefined && tries < 5 && error instanceof AgentHomeError && error.code === "stale")
|
|
209
|
+
continue;
|
|
210
|
+
storeError(error);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
/** Makes `revision`, one of the agent's own, its current one. */
|
|
215
|
+
async setCurrent(entry, revision) {
|
|
216
|
+
await this.request(() => this.store.setCurrent(entry.agent.id, revision)).catch((error) => storeError(error, "revision"));
|
|
217
|
+
return (await this.get(entry.agent.id));
|
|
218
|
+
}
|
|
219
|
+
/** Archives or unarchives an agent or a run. */
|
|
220
|
+
async setArchived(kind, id, archived) {
|
|
221
|
+
await this.request(() => this.store.setArchived(kind, id, archived)).catch((error) => storeError(error));
|
|
222
|
+
}
|
|
223
|
+
/** The agent's revisions, newest first, each with its number. */
|
|
224
|
+
revisions(id) {
|
|
225
|
+
return this.request(() => {
|
|
226
|
+
const rows = this.store.listRevisions(id);
|
|
227
|
+
return rows.map((row, index) => ({ ...row, version: rows.length - index }));
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
/** Revision `id` and its number, or null when it is not one of `agent`'s. */
|
|
231
|
+
async revision(agent, id) {
|
|
232
|
+
const row = (await this.revisions(agent)).find((r) => r.id === id);
|
|
233
|
+
return row ? { revision: await this.request(() => this.store.readRevision(id)), version: row.version } : null;
|
|
234
|
+
}
|
|
235
|
+
/** The agent `id`, or null. `runs` saves a read when the caller holds every run already. */
|
|
236
|
+
get(id) {
|
|
237
|
+
return this.request(() => this.entry(id));
|
|
238
|
+
}
|
|
239
|
+
entry(id, runs) {
|
|
240
|
+
const found = this.store.readAgent(id);
|
|
241
|
+
if (!found)
|
|
242
|
+
return null;
|
|
243
|
+
const at = found.revisions.findIndex((revision) => revision.current);
|
|
244
|
+
const revision = at < 0 ? null : (({ current: _, ...rest }) => rest)(found.revisions[at]);
|
|
245
|
+
const own = (runs ?? this.store.listRuns({ agent: id })).filter((run) => run.agent === id);
|
|
246
|
+
const sizes = new Map();
|
|
247
|
+
if (revision)
|
|
248
|
+
for (const [sha, text] of this.texts(Object.values(revision.body.skills)))
|
|
249
|
+
sizes.set(sha, Buffer.byteLength(text, "utf8"));
|
|
250
|
+
const live = own.filter((run) => run.state === "running").length;
|
|
251
|
+
return { agent: found.agent, revision, version: at < 0 ? 0 : found.revisions.length - at, revisions: found.revisions.length, runs: { count: own.length, live }, sizes };
|
|
252
|
+
}
|
|
253
|
+
/** Every agent here, newest first. */
|
|
254
|
+
list() {
|
|
255
|
+
return this.request(() => {
|
|
256
|
+
const runs = this.store.listRuns();
|
|
257
|
+
return this.store
|
|
258
|
+
.listAgents()
|
|
259
|
+
.map((row) => this.entry(row.id, runs))
|
|
260
|
+
.sort((a, b) => b.agent.createdAt.localeCompare(a.agent.createdAt) || a.agent.id.localeCompare(b.agent.id));
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
/** Whether `next` would be `current` again: the same kind and body, skills by their SHA-256. */
|
|
265
|
+
function sameRevision(current, next) {
|
|
266
|
+
const { kind, note: _, skills = {}, ...rest } = next;
|
|
267
|
+
const body = { ...rest, skills: Object.fromEntries(Object.entries(skills).map(([path, text]) => [path, createHash("sha256").update(text).digest("hex")])), tools: next.tools ?? [] };
|
|
268
|
+
return current.kind === kind && stable(current.body) === stable(body);
|
|
269
|
+
}
|
|
270
|
+
/** The agent's ETag: its current revision, which only an edit or `POST .../current` moves. */
|
|
271
|
+
export const etagOf = (entry) => `"${entry.revision?.id ?? "none"}"`;
|
|
272
|
+
/** A revision as a definition, as `POST /agents` takes one, numbered. */
|
|
273
|
+
export function definitionOf(agent, revision, version) {
|
|
274
|
+
const body = revision.kind === "agentic"
|
|
275
|
+
? { instructions: revision.body.instructions, ...(revision.body.model ? { model: revision.body.model } : {}), ...(revision.body.thinking ? { thinking: revision.body.thinking } : {}), ...(revision.body.learning !== undefined ? { learning: revision.body.learning } : {}) }
|
|
276
|
+
: { workflow: revision.body.workflow };
|
|
277
|
+
return { id: agent.id, version, name: agent.name, ...(agent.description !== undefined ? { description: agent.description } : {}), ...body, harness: harnessOfBody(revision.body), ...(revision.body.place ? { place: revision.body.place } : {}), skills: skillNames(Object.keys(revision.body.skills)), tools: revision.body.tools, ...(revision.body.toolSettings ? { tool_settings: revision.body.toolSettings } : {}) };
|
|
278
|
+
}
|
|
279
|
+
/** `Agent` as the contract shows it, with its current revision. */
|
|
280
|
+
export function agentView(entry) {
|
|
281
|
+
const { agent, revision } = entry;
|
|
282
|
+
return {
|
|
283
|
+
agent_id: agent.id,
|
|
284
|
+
definition: revision ? definitionOf(agent, revision, entry.version) : null,
|
|
285
|
+
kind: revision?.kind ?? null,
|
|
286
|
+
revision: revision?.id ?? null,
|
|
287
|
+
revisions: entry.revisions,
|
|
288
|
+
source: null,
|
|
289
|
+
skills: Object.entries(revision?.body.skills ?? {}).map(([path, sha]) => ({ path, sha256: sha, size_bytes: entry.sizes.get(sha) ?? null })),
|
|
290
|
+
sign_ins: [],
|
|
291
|
+
runs: entry.runs,
|
|
292
|
+
region: "local",
|
|
293
|
+
home_etag: etagOf(entry),
|
|
294
|
+
archived_at: agent.archivedAt ?? null,
|
|
295
|
+
created_at: agent.createdAt,
|
|
296
|
+
updated_at: revision && revision.createdAt > agent.createdAt ? revision.createdAt : agent.createdAt,
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
/** One revision as `GET .../revisions` lists it. */
|
|
300
|
+
export function revisionView(agent, row, revision) {
|
|
301
|
+
return { revision: row.id, version: row.version, parent: row.parent, kind: row.kind, current: row.current, note: row.note ?? null, created_at: row.createdAt, definition: definitionOf(agent, revision, row.version) };
|
|
302
|
+
}
|
package/dist/app.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { AppContext, AppOptions } from "@parcha/pi-durable-disk";
|
|
2
|
+
import { promptOf } from "./skills.js";
|
|
3
|
+
/** The workflow adapters this host gives every run: model nodes, and calls `via: "tool"` to the table's tools. Typed
|
|
4
|
+
* questions (`runJudge`) run too where the host sets a decision provider's key (decisions.ts). */
|
|
5
|
+
export declare const WORKFLOW_ADAPTERS: readonly ["runNode", "runEffect"];
|
|
6
|
+
export { promptOf };
|
|
7
|
+
export default function app(where: AppContext): Promise<AppOptions>;
|
package/dist/app.js
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
// The app `pi-durable-disk run --app` loads for each run serve starts. It reads the run's revision from the agent store
|
|
2
|
+
// (`<data>/store.sqlite`, the run being `<data>/runs/<id>`) and runs it on the model model.ts chooses:
|
|
3
|
+
// - agentic: the root agent with the revision's instructions and skills, and the tools it names, bound from the
|
|
4
|
+
// closed table in tools.ts;
|
|
5
|
+
// - workflow: the revision's workflow, started with startWorkflowRevision of @parcha/pi-durable-agent/workflow on
|
|
6
|
+
// agentrun-pi's durable workflow task, each model node on the host's model of its tier with the tools it names of the
|
|
7
|
+
// table's node tools, and its typed questions on Jev or Parallel when the server hands this process the provider's key. When the
|
|
8
|
+
// workflow ends the app writes the run's final status, with the outcome, and releases the run. The server carries
|
|
9
|
+
// it back once this process has exited: this process holds the run's store until then.
|
|
10
|
+
// First: the secrets serve hands this process over a pipe, read and the pipe closed before anything else runs.
|
|
11
|
+
import { authContextOf, withSecrets } from "./secrets.js";
|
|
12
|
+
import { mkdir } from "node:fs/promises";
|
|
13
|
+
import { BACKGROUND_CONTEXT as BACKGROUND } from "@earendil-works/chord/context";
|
|
14
|
+
import { basename, join, resolve } from "node:path";
|
|
15
|
+
import { createRegistry, ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
|
|
16
|
+
import { openStoreReader, RUN_STORE_FILE } from "@parcha/pi-durable-agent";
|
|
17
|
+
import { RUN_RESUMED } from "@parcha/pi-durable-agent/timeline";
|
|
18
|
+
import { settleIn } from "./paid-calls.js";
|
|
19
|
+
import { capBefore, capModels, capOf, spentIn } from "./cap.js";
|
|
20
|
+
import { codingSource } from "./coding-tools.js";
|
|
21
|
+
import { cancelledIn, markRequests } from "./request-start.js";
|
|
22
|
+
import { decisionProvidersOf } from "./decisions.js";
|
|
23
|
+
import { FOLLOW_UP_OPEN_ENV, readJson, RUN_META } from "./files.js";
|
|
24
|
+
import { adapterFor, claudeModel, claudePriceModel, claudeSkillCheck, codexModel, openRouterOnly, thinkingFor } from "./adapters.js";
|
|
25
|
+
import { DEFAULT_HARNESS, FAUX_HARNESS_ENV } from "./harness.js";
|
|
26
|
+
import { adapterRun } from "./harness-app.js";
|
|
27
|
+
import { withLearned } from "./learning.js";
|
|
28
|
+
import { completer } from "./llm.js";
|
|
29
|
+
import { searchOn } from "./hosted-search.js";
|
|
30
|
+
import { imageLoader } from "./pdf-pages.js";
|
|
31
|
+
import { EFFORT_ENV, llmTiers, nodeTiers, runModels, thinkingOf, workflowNodes } from "./model.js";
|
|
32
|
+
import { gated, liveView, nodeLog, readLiveView } from "./pause.js";
|
|
33
|
+
import { remotePlace, storedPlace } from "./place.js";
|
|
34
|
+
import { runBox, runBoxProvider } from "./run-box.js";
|
|
35
|
+
import { ASK_TOOL, toolOf, workflowTools } from "./tools.js";
|
|
36
|
+
import { promptOf, systemOf } from "./skills.js";
|
|
37
|
+
import { EnvironmentLine, environmentLine } from "./environment.js";
|
|
38
|
+
import { effortGuidance } from "./effort-guidance.js";
|
|
39
|
+
import { isObject } from "./validate.js";
|
|
40
|
+
import { mirrorWrites } from "./workspace.js";
|
|
41
|
+
/** The workflow adapters this host gives every run: model nodes, and calls `via: "tool"` to the table's tools. Typed
|
|
42
|
+
* questions (`runJudge`) run too where the host sets a decision provider's key (decisions.ts). */
|
|
43
|
+
export const WORKFLOW_ADAPTERS = ["runNode", "runEffect"];
|
|
44
|
+
/** A call node's tool failure, as the value its effect completed with (runEffect below). */
|
|
45
|
+
const TOOL_FAILED = "agentrun_serve_tool_failed";
|
|
46
|
+
/** A run's own commit of `kind` to its root, outside any one call's turn: a workflow call node's ledger, and every
|
|
47
|
+
* request's settle (paid-calls.ts settleIn). */
|
|
48
|
+
const rootRecordOf = (harness) => (kind, data) => harness.commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind, data })), BACKGROUND);
|
|
49
|
+
export { promptOf };
|
|
50
|
+
/** A run's process that opens to go on with a run its last process left unfinished writes that on the root
|
|
51
|
+
* (RUN_RESUMED), so the run's timeline shows it from the store, which the settle's read keeps: after a crash (that
|
|
52
|
+
* process died holding the run, and left it `running`) or after the server stopped (it drained, `sleeping`). A first
|
|
53
|
+
* open, a follow-up's and a wake from a park get none. A run whose root conversation was never made writes nothing
|
|
54
|
+
* and opens as before: the root comes with a workflow run's task (its start) and with an agentic run's first message,
|
|
55
|
+
* so a process that died or drained before then left none. */
|
|
56
|
+
async function markResumed({ harness, context, generation, previous }) {
|
|
57
|
+
const drained = previous?.status === "sleeping" && isObject(previous.detail) && previous.detail.reason === "drained";
|
|
58
|
+
const after = previous?.status === "running" ? "crash" : drained ? "server_stop" : undefined;
|
|
59
|
+
// A follow-up's open, which the server names (FOLLOW_UP_OPEN_ENV): the run's turn had ended, and the record its last
|
|
60
|
+
// process left is its server letting it go once it answered (a drain, as a server stop writes one), not cut work.
|
|
61
|
+
if (process.env[FOLLOW_UP_OPEN_ENV] === "1")
|
|
62
|
+
return;
|
|
63
|
+
if (!after || !(await harness.conversation(ROOT_CONVERSATION_ID, context)))
|
|
64
|
+
return;
|
|
65
|
+
await harness.commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: RUN_RESUMED, data: { after, generation, at: Date.now() } })), context);
|
|
66
|
+
}
|
|
67
|
+
/** claude-agent's model and pi-ai's catalog that prices it: its own settings, never the gateway's (adapters.ts). */
|
|
68
|
+
async function claudeModels(env, ref) {
|
|
69
|
+
const choice = claudeModel(env, ref);
|
|
70
|
+
if ("why" in choice)
|
|
71
|
+
throw new Error(choice.why);
|
|
72
|
+
const { builtinModels } = await import("@earendil-works/pi-ai/providers/all");
|
|
73
|
+
return { models: builtinModels({ authContext: authContextOf(env) }), model: choice.model, byTier: new Map([["default", choice.model]]), unpriced: new Set() };
|
|
74
|
+
}
|
|
75
|
+
/** codex's model and pi-ai's catalog that prices it, where codex reaches OpenAI only through OpenRouter (codexModel: no
|
|
76
|
+
* OpenAI key needed); anywhere else, the run's usual models (runModels). */
|
|
77
|
+
async function codexModels(env, ref) {
|
|
78
|
+
if (env[FAUX_HARNESS_ENV] || !openRouterOnly("codex", env))
|
|
79
|
+
return runModels(env, ref, ["default"], "codex");
|
|
80
|
+
const choice = await codexModel(env, ref);
|
|
81
|
+
if ("why" in choice)
|
|
82
|
+
throw new Error(choice.why);
|
|
83
|
+
const { builtinModels } = await import("@earendil-works/pi-ai/providers/all");
|
|
84
|
+
return { models: builtinModels({ authContext: authContextOf(env) }), model: choice.model, byTier: new Map([["default", choice.model]]), unpriced: new Set() };
|
|
85
|
+
}
|
|
86
|
+
/** The run's row and its pinned revision, read from the store the run's directory sits in. */
|
|
87
|
+
function revisionOf(where) {
|
|
88
|
+
const reader = openStoreReader(resolve(where.root, "..", ".."));
|
|
89
|
+
try {
|
|
90
|
+
const id = basename(resolve(where.root));
|
|
91
|
+
const run = reader.readRun(id);
|
|
92
|
+
if (!run)
|
|
93
|
+
throw new Error(`the agent store has no run ${id}`);
|
|
94
|
+
return { run, revision: reader.readRevision(run.revision) };
|
|
95
|
+
}
|
|
96
|
+
finally {
|
|
97
|
+
reader.close();
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
export default async function app(where) {
|
|
101
|
+
const { run, revision } = revisionOf(where);
|
|
102
|
+
// This process's reading of its environment, with its secrets: never a child's (secrets.ts).
|
|
103
|
+
const env = withSecrets(process.env);
|
|
104
|
+
const workflowNodeList = revision.kind === "workflow" ? workflowNodes(revision.body.workflow, (await import("@parcha/agentrun-dsl")).inspectWorkflow(revision.body.workflow)) : [];
|
|
105
|
+
// codex's model as a save resolves it (codexModel): an OpenAI model it reaches through OpenRouter alone needs no OpenAI key.
|
|
106
|
+
const chosen = revision.kind === "agentic" && revision.body.harness === "claude-agent" && !env[FAUX_HARNESS_ENV] ? await claudeModels(env, revision.body.model) : revision.kind === "agentic" && revision.body.harness === "codex" ? await codexModels(env, revision.body.model) : revision.kind === "agentic" ? await runModels(env, revision.body.model, ["default"], revision.body.harness) : await runModels(env, undefined, llmTiers(workflowNodeList, nodeTiers(workflowNodeList)));
|
|
107
|
+
const { model, byTier } = chosen;
|
|
108
|
+
// Read before the run opens its store: what it spent in earlier processes counts against its cap.
|
|
109
|
+
const cap = capOf(process.env);
|
|
110
|
+
// Each request is marked as it leaves (request-start.ts), inside the cap: a request the cap refuses never leaves, and
|
|
111
|
+
// gets a start mark of its own, which its error entry answers.
|
|
112
|
+
const marked = await markRequests(chosen.models, cancelledIn(where.root));
|
|
113
|
+
const models = cap === undefined ? marked.models : await capModels(marked.models, cap, spentIn(join(where.store, RUN_STORE_FILE)), { unpriced: chosen.unpriced, refused: marked.refused });
|
|
114
|
+
const thinkingLevel = thinkingOf(process.env, revision.kind === "agentic" ? revision.body.thinking : undefined);
|
|
115
|
+
// The run's place, as its start resolved and kept it (serve.json): in a box, its coding tools run there (run-box.ts).
|
|
116
|
+
const meta = await readJson(join(where.root, RUN_META));
|
|
117
|
+
const place = storedPlace(meta?.place);
|
|
118
|
+
const root = resolve(where.root, "..", "..");
|
|
119
|
+
// A remote box (Daytona) is the server's to make and seed, reached through its relay; Docker's is made here.
|
|
120
|
+
const box = place.mode === "sandbox" ? runBox(remotePlace(place) ? { relay: root } : { provider: () => runBoxProvider(place, env, root) }, { id: run.id, root, dir: where.root, place }) : undefined;
|
|
121
|
+
// What the run's host tools file in work/ is copied into a remote box too, which does not share this machine's work/.
|
|
122
|
+
if (box?.mirror)
|
|
123
|
+
mirrorWrites(where.work, box.mirror);
|
|
124
|
+
const coding = codingSource(place, box);
|
|
125
|
+
const registry = createRegistry();
|
|
126
|
+
// An agentic run's system prompt starts with the date and the workspace (environment.ts). On pi it is a section,
|
|
127
|
+
// installed first so it comes before every other extension's and the instructions.
|
|
128
|
+
if (revision.kind === "agentic")
|
|
129
|
+
registry.install(EnvironmentLine);
|
|
130
|
+
registry.install(coding.extension);
|
|
131
|
+
// What the run's agent learned goes into its instructions, and the skills it wrote join the revision's, the one path for
|
|
132
|
+
// every harness (learning.ts).
|
|
133
|
+
const learned = revision.kind === "agentic" ? await withLearned(where.root, where.work, revision.body.instructions, Object.keys(revision.body.skills)) : { instructions: "", skills: [] };
|
|
134
|
+
// The run's effort, as its thinking level reads it: its note on how to work follows the instructions on every harness
|
|
135
|
+
// (effort-guidance.ts). None without an effort.
|
|
136
|
+
const guidance = effortGuidance(process.env[EFFORT_ENV]);
|
|
137
|
+
if (revision.kind === "agentic" && revision.body.harness && revision.body.harness !== DEFAULT_HARNESS) {
|
|
138
|
+
const harness = revision.body.harness;
|
|
139
|
+
// claude-agent loads the skills its adapter takes itself (its Skill tool), and its prompt keeps only the ones it would
|
|
140
|
+
// refuse; codex's prompt, and a faux harness's, keep every skill (skills.ts).
|
|
141
|
+
const check = harness === "claude-agent" && !env[FAUX_HARNESS_ENV] ? await claudeSkillCheck() : undefined;
|
|
142
|
+
const { system: instructions, native } = await systemOf(learned.instructions, learned.skills, where.work, check);
|
|
143
|
+
// The session's system prompt starts with the line, made as this process opens it: a run resumed on a later day is
|
|
144
|
+
// opened with that day.
|
|
145
|
+
const spec = { key: `run:${run.id}`, label: run.agent, system: [environmentLine(), instructions, guidance].filter((text) => Boolean(text)), context: "fresh", thinking: thinkingFor(harness, thinkingLevel) };
|
|
146
|
+
// ask_person stays pi's (runnable.ts refuses a run that names it here); the file tools are pi's own.
|
|
147
|
+
const named = revision.body.tools.filter((name) => name !== ASK_TOOL);
|
|
148
|
+
// The harness's own files (its homes, its state) go in a private directory beside the workspace, never in it. It works
|
|
149
|
+
// in the workspace itself (where.work), the directory the run's file tools confine to: a path the model builds from
|
|
150
|
+
// its working directory is then one they take.
|
|
151
|
+
const dir = join(where.root, "harness");
|
|
152
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
153
|
+
// Built at the open: the harness's own process runs under the run's confinement, the prefix pi's commands get there.
|
|
154
|
+
const make = (confine) => adapterFor(harness, env, { model: model, models: chosen.models, ...(confine ? { confine } : {}), ...(native.length ? { skills: native } : {}) });
|
|
155
|
+
// The run's cap, checked before each of the harness's requests: the same ceiling rule as pi's (cap.ts).
|
|
156
|
+
// claude-agent's run is capped at the price of whoever bills it (claudeProvider's priceModel), as its adapter prices it.
|
|
157
|
+
const priced = harness === "claude-agent" && !env[FAUX_HARNESS_ENV] ? claudePriceModel(env, model) : model;
|
|
158
|
+
const guard = await capBefore(cap, chosen.models.getModel(priced.provider, priced.modelId), { listed: !chosen.unpriced.has(priced.modelId) });
|
|
159
|
+
// The cancel mark serve writes is read here too, as pi's model wrapper reads it (request-start.ts).
|
|
160
|
+
// The run's stop record (serve.json, as serve saved it before a stop's abort): a turn it names is not resumed.
|
|
161
|
+
const stopRecord = { ...(typeof meta?.stopped_at === "string" ? { stopped_at: meta.stopped_at } : {}), ...(typeof meta?.stopped_after === "number" ? { stopped_after: meta.stopped_after } : {}) };
|
|
162
|
+
const { door, onOpen } = adapterRun(make, harness, spec, BACKGROUND, cap, named, dir, guard, cancelledIn(where.root), where.work, coding.tools, stopRecord);
|
|
163
|
+
// A paid host tool's settle goes to the run's root, as on pi (paid-calls.ts settleIn).
|
|
164
|
+
return { models: {}, registry: createRegistry(), door, onOpen: async (durable) => (settleIn(rootRecordOf(durable.harness)), onOpen(durable)), beforeResume: markResumed };
|
|
165
|
+
}
|
|
166
|
+
// web_search's own request to the model provider, when it resolves native, goes through the run's models (hosted-search.ts).
|
|
167
|
+
searchOn(models);
|
|
168
|
+
// Each tool the revision names is bound once, from the table: its extensions installed here, its documents written in
|
|
169
|
+
// each conversation's creating commit, what it settles done before anything resumes, and what it lets go done before
|
|
170
|
+
// the run is released.
|
|
171
|
+
const writes = [];
|
|
172
|
+
const settles = [];
|
|
173
|
+
const stops = [];
|
|
174
|
+
const host = {
|
|
175
|
+
where, env, coding, install: (extension) => registry.install(extension),
|
|
176
|
+
onConversation: (write) => void writes.push(write), beforeResume: (settle) => void settles.push(settle), beforeRelease: (stop) => void stops.push(stop),
|
|
177
|
+
};
|
|
178
|
+
const letGo = async (harness) => { for (const stop of stops)
|
|
179
|
+
await stop(harness); };
|
|
180
|
+
const bound = new Map();
|
|
181
|
+
const bind = (name, nodes = false) => {
|
|
182
|
+
const entry = toolOf(name);
|
|
183
|
+
if (!entry || (nodes && !entry.nodes))
|
|
184
|
+
throw new Error(`the revision names the tool ${name}, which agentrun-serve does not bind${nodes ? " for a workflow's model node" : ""}`);
|
|
185
|
+
let tools = bound.get(name);
|
|
186
|
+
if (!tools)
|
|
187
|
+
bound.set(name, (tools = entry.bind(host)));
|
|
188
|
+
return tools;
|
|
189
|
+
};
|
|
190
|
+
const hooks = {
|
|
191
|
+
conversationCreated: async (tx, conversation) => { for (const write of writes)
|
|
192
|
+
await write(tx, conversation.id); },
|
|
193
|
+
beforeResume: async (run) => { await markResumed(run); for (const settle of settles)
|
|
194
|
+
await settle(run.harness); },
|
|
195
|
+
};
|
|
196
|
+
// A SIGTERM lets the run go: what a tool holds is let go there, then the wake is recorded as pi-durable-disk records it
|
|
197
|
+
// by default (sleeping, due at `at`).
|
|
198
|
+
const wake = async (durable, at) => {
|
|
199
|
+
await letGo(durable.harness);
|
|
200
|
+
await durable.setStatus("sleeping", { reason: "drained" }, { wakeAt: at === null ? null : new Date(at).toISOString() });
|
|
201
|
+
};
|
|
202
|
+
if (revision.kind === "agentic") {
|
|
203
|
+
const tools = (await Promise.all(revision.body.tools.map((name) => bind(name)))).flatMap((binding) => binding.tools);
|
|
204
|
+
const instructions = [await promptOf(learned.instructions, learned.skills, where.work), guidance].filter(Boolean).join("\n\n");
|
|
205
|
+
return { models, registry, ...hooks, ...(stops.length ? { wake } : {}), root: { agent: { model, thinkingLevel, instructions, tools } }, onOpen: async (durable) => (settleIn(rootRecordOf(durable.harness)), marked.open(durable)) };
|
|
206
|
+
}
|
|
207
|
+
const input = isObject(meta?.input) ? meta.input : {};
|
|
208
|
+
const [{ BACKGROUND_CONTEXT }, { createWorkflowExtension, decisionRecovery, durableDecisions, nodeRunner, taskScope }, { EffectFailure, inspectWorkflow, judgeFromProviders }, { withRecovery, workspaceFiles }, { startWorkflowRevision }, decisionProviders] = await Promise.all([
|
|
209
|
+
import("@earendil-works/chord/context"),
|
|
210
|
+
import("@parcha/agentrun-pi/durable"),
|
|
211
|
+
import("@parcha/agentrun-dsl"),
|
|
212
|
+
import("@parcha/agentrun-dsl/recovery"),
|
|
213
|
+
import("@parcha/pi-durable-agent/workflow"),
|
|
214
|
+
// The decision providers, holding the decision keys the server handed this process: in no environment a tool reads.
|
|
215
|
+
decisionProvidersOf(process.env),
|
|
216
|
+
]);
|
|
217
|
+
const nodeTools = new Map();
|
|
218
|
+
for (const name of workflowTools(workflowNodeList).nodes)
|
|
219
|
+
nodeTools.set(name, await bind(name, true));
|
|
220
|
+
// A decision node's images are files of the run's work directory (pdf_pages draws them there).
|
|
221
|
+
const loadImage = imageLoader(where.work);
|
|
222
|
+
const log = nodeLog(where.root);
|
|
223
|
+
// The receipts earlier processes recorded, read before this one opens the store, which then holds it exclusively.
|
|
224
|
+
const earlier = await (async () => {
|
|
225
|
+
try {
|
|
226
|
+
return durableDecisions(join(where.store, RUN_STORE_FILE));
|
|
227
|
+
}
|
|
228
|
+
catch {
|
|
229
|
+
return (await readLiveView(where.root))?.receipts ?? [];
|
|
230
|
+
}
|
|
231
|
+
})();
|
|
232
|
+
const live = liveView(where.root, [...earlier]);
|
|
233
|
+
// The `llm` tool's one completion: on the run's models (capped and marked as a model node's), its tier's model.
|
|
234
|
+
const complete = completer(models, (tier) => byTier.get(tier ?? "default"), thinkingLevel);
|
|
235
|
+
/** The run, once it opens: a call node's paid requests are booked in its store (paid-calls.ts). */
|
|
236
|
+
let opened;
|
|
237
|
+
/** A call node `via: "tool"`: the table's tool by name, its interpolated args in, what its `out` schema checks out. Its
|
|
238
|
+
* input and output go to the node log, and its paid requests are booked under the node's own call (its execution
|
|
239
|
+
* path, and its item in a map). */
|
|
240
|
+
const runEffect = async ({ node, input, signal, executionPath, item }) => {
|
|
241
|
+
const effect = node.via === "tool" && node.tool ? toolOf(node.tool)?.effect : undefined;
|
|
242
|
+
if (!effect)
|
|
243
|
+
throw new Error(`call node "${node.label}": agentrun-serve runs no tool ${node.tool ?? `via ${node.via}`}`);
|
|
244
|
+
const at = { path: executionPath ?? null, item: item?.index ?? null, tool: node.tool, label: node.label };
|
|
245
|
+
log({ t: "effect.start", ...at, input, at: new Date().toISOString() });
|
|
246
|
+
try {
|
|
247
|
+
const durable = opened;
|
|
248
|
+
const ledger = durable ? { call: `${node.label}@${executionPath ?? ""}${item ? `#${item.index}` : ""}`, record: rootRecordOf(durable.harness) } : undefined;
|
|
249
|
+
const output = await effect(input, { signal, env, work: where.work, complete, ...(ledger ? { ledger } : {}) });
|
|
250
|
+
log({ t: "effect.end", ...at, status: "done", output, at: new Date().toISOString() });
|
|
251
|
+
return output;
|
|
252
|
+
}
|
|
253
|
+
catch (error) {
|
|
254
|
+
const message = String(error?.message ?? error);
|
|
255
|
+
log({ t: "effect.end", ...at, status: "failed", error: message.slice(0, 2000), at: new Date().toISOString() });
|
|
256
|
+
// An abort (a cancel, the node's deadline) stays a throw: the driver keeps its effect unknown. A tool that failed on
|
|
257
|
+
// its own (an unreadable PDF, a model's refusal) answered: its failure is the effect's outcome, completed, and is
|
|
258
|
+
// thrown past the driver as the call node's typed failure (`failing`), which a collecting map ends that item on.
|
|
259
|
+
if (signal.aborted || error?.name === "AbortError")
|
|
260
|
+
throw error;
|
|
261
|
+
return { [TOOL_FAILED]: `call node "${node.label}": ${node.tool} failed: ${message.slice(0, 500)}` };
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
/** `runEffect` past the driver: a tool's failure the driver recorded as its effect's outcome is thrown here, on the
|
|
265
|
+
* first run and on a resume that answers it from the receipt alike. */
|
|
266
|
+
const failing = (run) => async (params) => {
|
|
267
|
+
const value = await run(params);
|
|
268
|
+
if (isObject(value) && typeof value[TOOL_FAILED] === "string")
|
|
269
|
+
throw new EffectFailure(value[TOOL_FAILED], null, { code: null });
|
|
270
|
+
return value;
|
|
271
|
+
};
|
|
272
|
+
/** A model node's agent: its tier's model, the tools it names, and the extensions they come from. */
|
|
273
|
+
const nodeAgent = (node) => {
|
|
274
|
+
const bindings = (node.tools ?? []).flatMap((name) => nodeTools.get(name) ?? []);
|
|
275
|
+
return { model: byTier.get(node.tier ?? "default"), thinkingLevel, extensions: [...new Set([coding.extension, ...bindings.flatMap((b) => b.extensions)])], tools: bindings.flatMap((b) => b.tools) };
|
|
276
|
+
};
|
|
277
|
+
const nodes = nodeRunner({ agent: (node) => nodeAgent(node) });
|
|
278
|
+
/** The node log's starts and ends, from the workflow's events: what a graph shows of a node's timing. */
|
|
279
|
+
const onEvent = (event) => {
|
|
280
|
+
if ((event.type !== "node.start" && event.type !== "node.end") || typeof event.executionPath !== "string")
|
|
281
|
+
return;
|
|
282
|
+
const detail = (event.detail ?? {});
|
|
283
|
+
log({ t: event.type, path: event.executionPath, kind: String(detail.kind ?? ""), at: new Date().toISOString(), ...(detail.status ? { status: detail.status } : {}), ...(typeof detail.duration_ms === "number" ? { duration_ms: detail.duration_ms } : {}), ...(detail.error !== undefined ? { error: String(detail.error?.message ?? detail.error).slice(0, 500) } : {}) });
|
|
284
|
+
};
|
|
285
|
+
const workflows = createWorkflowExtension({
|
|
286
|
+
options: () => ({ files: workspaceFiles(where.work) }),
|
|
287
|
+
run: ({ key, runtime, context, driver }) => {
|
|
288
|
+
// Each typed question's receipt is a row of the run's store before its answer acts, and a resumed run takes an
|
|
289
|
+
// answered one instead of asking again.
|
|
290
|
+
const decisions = decisionRecovery({ key, runtime, context });
|
|
291
|
+
live.driver(driver);
|
|
292
|
+
const deps = withRecovery(driver, {
|
|
293
|
+
runNode: nodes.on(taskScope(runtime), context).runNode, runEffect: runEffect, ...(decisionProviders ? { runJudge: judgeFromProviders({ ...decisionProviders, loadImage }), decisionProviders } : {}),
|
|
294
|
+
recordDecision: async (receipt, exchange) => {
|
|
295
|
+
await decisions.recordDecision(receipt, exchange);
|
|
296
|
+
live.receipt(receipt);
|
|
297
|
+
},
|
|
298
|
+
}, { durableNodes: true });
|
|
299
|
+
const { recovery } = deps;
|
|
300
|
+
if (!recovery)
|
|
301
|
+
throw new Error("the workflow's recovery gave the run no recovery hooks");
|
|
302
|
+
// The pause gate: each node's resume, which the interpreter awaits before it starts the node (before a call's deadline
|
|
303
|
+
// is armed), and each model call and decision, outside the recovery: one waiting at it was never admitted, so a kill
|
|
304
|
+
// while paused leaves nothing half asked.
|
|
305
|
+
const gate = (fn) => (fn ? gated(where.root, fn) : fn);
|
|
306
|
+
const resume = gated(where.root, (args) => recovery.resume(...args));
|
|
307
|
+
return { deps: { ...deps, runEffect: deps.runEffect && failing(deps.runEffect), runNode: gate(deps.runNode), runJudge: gate(deps.runJudge), onEvent, recovery: { ...recovery, resume: (...args) => resume(args), decision: decisions.decision } } };
|
|
308
|
+
},
|
|
309
|
+
});
|
|
310
|
+
registry.install(nodes.extension);
|
|
311
|
+
registry.install(workflows.extension);
|
|
312
|
+
const onOpen = async (durable) => {
|
|
313
|
+
opened = durable;
|
|
314
|
+
settleIn(rootRecordOf(durable.harness));
|
|
315
|
+
marked.open(durable);
|
|
316
|
+
const started = { runId: run.id, storePath: join(where.store, RUN_STORE_FILE), agentId: run.agent, revision: revision };
|
|
317
|
+
const outcome = await startWorkflowRevision({ harness: durable.harness, workflows, context: BACKGROUND_CONTEXT, run: started, input, tools: inspectWorkflow(revision.body.workflow).requires.tools });
|
|
318
|
+
live.stop();
|
|
319
|
+
await letGo(durable.harness);
|
|
320
|
+
await durable.setStatus(outcome.status === "complete" ? "done" : "failed", { workflow: outcome.status, ...(outcome.status === "refused" ? { code: outcome.code, message: outcome.message.slice(0, 500) } : {}) });
|
|
321
|
+
await durable.release();
|
|
322
|
+
};
|
|
323
|
+
return { models, registry, ...hooks, ...(stops.length ? { wake } : {}), onOpen };
|
|
324
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { type ExecutionEnv } from "@earendil-works/pi-durable/env";
|
|
2
|
+
/** A box run's read, write and edit environment on this machine's `hostWork` (canonical: the bind's source), naming the
|
|
3
|
+
* box's paths. Its shell runs nothing, and only the operations those tools make are offered. */
|
|
4
|
+
export declare function boundFiles(hostWork: string): ExecutionEnv;
|