@parcha/agentrun-serve 0.1.0-beta.32 → 0.1.0-beta.33

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.
Files changed (163) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +78 -46
  3. package/dist/adapters.d.ts +0 -3
  4. package/dist/adapters.js +0 -7
  5. package/dist/agents.d.ts +1 -1
  6. package/dist/api-only.d.ts +14 -0
  7. package/dist/api-only.js +33 -0
  8. package/dist/archil-routes.d.ts +1 -1
  9. package/dist/box-egress-vm.d.ts +0 -8
  10. package/dist/box-egress-vm.js +0 -10
  11. package/dist/box-egress.d.ts +0 -4
  12. package/dist/box-egress.js +1 -16
  13. package/dist/box-paths.d.ts +25 -2
  14. package/dist/box-paths.js +79 -11
  15. package/dist/box-relay.d.ts +0 -11
  16. package/dist/box-relay.js +0 -20
  17. package/dist/box-settings.d.ts +46 -0
  18. package/dist/box-settings.js +107 -0
  19. package/dist/boxes.d.ts +4 -1
  20. package/dist/browser-cost.js +2 -1
  21. package/dist/browser-person.d.ts +0 -2
  22. package/dist/browser-person.js +0 -2
  23. package/dist/budget.d.ts +0 -4
  24. package/dist/budget.js +0 -7
  25. package/dist/cap.d.ts +0 -7
  26. package/dist/cap.js +0 -22
  27. package/dist/cli.js +23 -8
  28. package/dist/computers.d.ts +1 -1
  29. package/dist/console/assets/index-Dn0ngwG9.js +535 -0
  30. package/dist/console/assets/index-DvW6Aled.css +1 -0
  31. package/dist/console/index.html +2 -2
  32. package/dist/daytona-api.d.ts +0 -11
  33. package/dist/daytona-api.js +1 -82
  34. package/dist/docker-host-addresses.d.ts +37 -0
  35. package/dist/docker-host-addresses.js +110 -0
  36. package/dist/files.d.ts +0 -8
  37. package/dist/files.js +0 -17
  38. package/dist/github-connection.d.ts +1 -1
  39. package/dist/github-connection.js +1 -1
  40. package/dist/harness-install.d.ts +23 -0
  41. package/dist/harness-install.js +99 -4
  42. package/dist/harness.d.ts +4 -3
  43. package/dist/harness.js +16 -1
  44. package/dist/import.js +52 -13
  45. package/dist/learn/secrets.d.ts +2 -1
  46. package/dist/learn/secrets.js +19 -6
  47. package/dist/learned-workflow.d.ts +5 -4
  48. package/dist/learned-workflow.js +6 -3
  49. package/dist/learning-routes.d.ts +9 -46
  50. package/dist/learning-routes.js +25 -29
  51. package/dist/learning-run.d.ts +4 -231
  52. package/dist/learning-run.js +7 -651
  53. package/dist/live/translate.js +1 -1
  54. package/dist/mcp-gateway.d.ts +0 -3
  55. package/dist/mcp-gateway.js +0 -13
  56. package/dist/mcp-probe.d.ts +2 -2
  57. package/dist/mcp-probe.js +2 -2
  58. package/dist/mcp-servers-store.js +1 -1
  59. package/dist/openapi.js +3 -3
  60. package/dist/page.js +3 -1
  61. package/dist/paid-calls.js +3 -2
  62. package/dist/pause.d.ts +0 -2
  63. package/dist/pause.js +1 -8
  64. package/dist/place.d.ts +0 -5
  65. package/dist/place.js +0 -10
  66. package/dist/print.d.ts +2 -1
  67. package/dist/print.js +4 -2
  68. package/dist/run-db.d.ts +0 -2
  69. package/dist/run-db.js +0 -4
  70. package/dist/run-learning-served.d.ts +38 -0
  71. package/dist/run-learning-served.js +9 -0
  72. package/dist/run-secrets.d.ts +33 -0
  73. package/dist/run-secrets.js +53 -0
  74. package/dist/run-timeline-served.js +5 -2
  75. package/dist/run-view.d.ts +5 -9
  76. package/dist/run-view.js +4 -22
  77. package/dist/runner/adapter-loop.d.ts +8 -2
  78. package/dist/runner/adapter-loop.js +44 -12
  79. package/dist/runner/adapter-run-spec.d.ts +8 -0
  80. package/dist/runner/adapter-run-spec.js +6 -5
  81. package/dist/runner/adapters/pi.d.ts +4 -0
  82. package/dist/runner/adapters/pi.js +4 -1
  83. package/dist/runner/beside.js +19 -8
  84. package/dist/runner/claim-secrets.js +1 -1
  85. package/dist/runner/cli-run-spec.js +15 -1
  86. package/dist/runner/journal-kinds.d.ts +6 -0
  87. package/dist/runner/live-ticker.d.ts +1 -1
  88. package/dist/runner/live-ticker.js +28 -4
  89. package/dist/runner/loop-contract.d.ts +3 -2
  90. package/dist/runner/main.d.ts +11 -4
  91. package/dist/runner/main.js +39 -10
  92. package/dist/runner/mcp-claim.d.ts +1 -1
  93. package/dist/runner/mcp-claim.js +1 -1
  94. package/dist/runner/model-route.js +21 -2
  95. package/dist/runner/redact.d.ts +8 -2
  96. package/dist/runner/redact.js +11 -2
  97. package/dist/runner/workflow-spec.js +5 -9
  98. package/dist/runs-over-store.d.ts +1 -1
  99. package/dist/runs-over-store.js +16 -5
  100. package/dist/seal-key.d.ts +54 -15
  101. package/dist/seal-key.js +272 -84
  102. package/dist/sealed-settings.d.ts +2 -2
  103. package/dist/sealed-settings.js +3 -10
  104. package/dist/secrets.d.ts +2 -10
  105. package/dist/secrets.js +21 -17
  106. package/dist/server-secrets-store.js +1 -1
  107. package/dist/server-secrets.js +3 -0
  108. package/dist/server.d.ts +10 -6
  109. package/dist/server.js +89 -41
  110. package/dist/store/index.d.ts +1 -1
  111. package/dist/store/index.js +1 -1
  112. package/dist/store/open.d.ts +12 -2
  113. package/dist/store/open.js +23 -3
  114. package/dist/store/postgres/migrate.js +18 -1
  115. package/dist/store/sqlite/store.js +23 -8
  116. package/dist/store/store.d.ts +3 -0
  117. package/dist/store-reads/journal.d.ts +16 -0
  118. package/dist/store-reads/journal.js +82 -6
  119. package/dist/store-view.js +38 -5
  120. package/dist/tool-keys.d.ts +4 -3
  121. package/dist/tool-keys.js +7 -4
  122. package/dist/tools.d.ts +1 -1
  123. package/dist/tools.js +4 -1
  124. package/dist/trigger-schedule.js +2 -1
  125. package/dist/trigger-secrets-shown.js +5 -1
  126. package/dist/workspace/computer-deps.d.ts +29 -0
  127. package/dist/workspace/computer-deps.js +48 -1
  128. package/dist/workspace/computer-for-claim.d.ts +7 -3
  129. package/dist/workspace/computer-for-claim.js +1 -1
  130. package/dist/workspace/computer-providers.d.ts +6 -2
  131. package/dist/workspace/computer-providers.js +1 -1
  132. package/dist/workspace/index.d.ts +1 -1
  133. package/dist/workspace/index.js +1 -1
  134. package/dist/workspace.d.ts +0 -3
  135. package/dist/workspace.js +0 -3
  136. package/launcher/agentrun-serve +6 -33
  137. package/package.json +14 -14
  138. package/templates/inbound-lead/agent.md +1 -1
  139. package/templates/kyb/agent.md +1 -1
  140. package/dist/app.d.ts +0 -5
  141. package/dist/app.js +0 -514
  142. package/dist/bounds.d.ts +0 -26
  143. package/dist/bounds.js +0 -137
  144. package/dist/console/assets/index-35-7aeIZ.js +0 -519
  145. package/dist/console/assets/index-Cejbov-Y.css +0 -1
  146. package/dist/content-filter.d.ts +0 -7
  147. package/dist/content-filter.js +0 -23
  148. package/dist/disk.d.ts +0 -33
  149. package/dist/disk.js +0 -85
  150. package/dist/door-line.d.ts +0 -23
  151. package/dist/door-line.js +0 -83
  152. package/dist/harness-app.d.ts +0 -69
  153. package/dist/harness-app.js +0 -1162
  154. package/dist/request-start.d.ts +0 -27
  155. package/dist/request-start.js +0 -381
  156. package/dist/run-box.d.ts +0 -205
  157. package/dist/run-box.js +0 -661
  158. package/dist/run-holder.d.ts +0 -52
  159. package/dist/run-holder.js +0 -139
  160. package/dist/runs.d.ts +0 -1200
  161. package/dist/runs.js +0 -4103
  162. package/dist/served-only.d.ts +0 -5
  163. package/dist/served-only.js +0 -12
package/dist/app.js DELETED
@@ -1,514 +0,0 @@
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 { mcpCredentials, withSecrets } from "./secrets.js";
12
- import { mkdir } from "node:fs/promises";
13
- import { BACKGROUND_CONTEXT as BACKGROUND } from "@earendil-works/chord/context";
14
- import { createModels } from "@earendil-works/pi-ai/models";
15
- import { basename, join, resolve } from "node:path";
16
- import { createRegistry, defineExtension, ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
17
- import { openStoreReader, RUN_STORE_FILE } from "@parcha/pi-durable-agent";
18
- import { RUN_RESUMED } from "@parcha/pi-durable-agent/timeline";
19
- import { settleIn } from "./paid-calls.js";
20
- import { BARRIER, syncNow } from "@parcha/pi-durable-disk";
21
- import { AsyncLocalStorage } from "node:async_hooks";
22
- import { BUDGET_HOLD_ENV, BUDGET_HOLD_MS, budgetWaits } from "./budget.js";
23
- import { capBefore, capModels, capModeOf, capOf, costsIn, capRefusals, DECISION_COST, DECISION_HOLD, decisionSpentIn, runSpendNow, spentIn, wrapUpSentIn } from "./cap.js";
24
- import { askedBefore, cappedDecisions } from "./decision-cap.js";
25
- import { codingSource } from "./coding-tools.js";
26
- import { cancelledIn, markRequests } from "./request-start.js";
27
- import { decisionProvidersOf } from "./decisions.js";
28
- import { dataOfRun, FOLLOW_UP_OPEN_ENV, readJson, RUN_META } from "./files.js";
29
- import { adapterFor, thinkingFor } from "./adapters.js";
30
- import { PORT_PROVIDER, portModels } from "./port-models.js";
31
- import { harnessOf } from "./harness-table.js";
32
- import { adapterRun } from "./harness-app.js";
33
- import { MCP_PIN, mcpGateway, mcpNameOf, mcpRegistrations } from "./mcp-gateway.js";
34
- import { pinnedWorkflows, readPin, withLearned } from "./learning.js";
35
- import { LEARNED_WORKFLOW_TOOL, learnedWorkflowTool } from "./learned-workflow.js";
36
- import { completer } from "./llm.js";
37
- import { searchOn } from "./hosted-search.js";
38
- import { imageLoader } from "./pdf-pages.js";
39
- import { EFFORT_ENV, llmTiers, nodeTiers, runModels, thinkingOf, wireModels, workflowNodes } from "./model.js";
40
- import { gated, liveView, nodeLog, readLiveView } from "./pause.js";
41
- import { remotePlace, storedPlace } from "./place.js";
42
- import { runBox, runBoxProvider } from "./run-box.js";
43
- import { RUN_EPOCH_ENV } from "./run-holder.js";
44
- import { planeOf } from "./tool-plane.js";
45
- import { ASK_TOOL, toolOf, workflowTools } from "./tools.js";
46
- import { promptOf, readsFiles, systemOf } from "./skills.js";
47
- import { EnvironmentLine, environmentLine } from "./environment.js";
48
- import { effortGuidance } from "./effort-guidance.js";
49
- import { isObject } from "./validate.js";
50
- import { mirrorWrites } from "./workspace.js";
51
- import { deniedText, runGate } from "./tool-gate.js";
52
- import { callNodeAskText } from "./refusal-words.js";
53
- // The workflow adapters this host gives every run moved to the runner side (runner/workflow-adapters.ts); re-exported
54
- // here so readers that still take it from this module are unchanged.
55
- export { WORKFLOW_ADAPTERS } from "./runner/workflow-adapters.js";
56
- /** A call node's tool failure, as the value its effect completed with (runEffect below). */
57
- const TOOL_FAILED = "agentrun_serve_tool_failed";
58
- /** A call node's effect its cap refused (cap.ts capRefusals): completed as held, with the refusal, sending nothing. The
59
- * call waits for a raise past the driver (`failing`) and goes again as a new effect, never as the tool's own failure. */
60
- const CAP_HELD = "agentrun_serve_cap_held";
61
- /** A run's own commit of `kind` to its root, outside any one call's turn: a workflow call node's ledger, and every
62
- * request's settle (paid-calls.ts settleIn). */
63
- const rootRecordOf = (harness) => (kind, data) => harness.commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind, data })), BACKGROUND);
64
- export { promptOf };
65
- /** A run's process that opens to go on with a run its last process left unfinished writes that on the root
66
- * (RUN_RESUMED), so the run's timeline shows it from the store, which the settle's read keeps: after a crash (that
67
- * process died holding the run, and left it `running`) or after the server stopped (it drained, `sleeping`). A first
68
- * open, a follow-up's and a wake from a park get none. A run whose root conversation was never made writes nothing
69
- * and opens as before: the root comes with a workflow run's task (its start) and with an agentic run's first message,
70
- * so a process that died or drained before then left none. */
71
- async function markResumed({ harness, context, generation, previous }) {
72
- const drained = previous?.status === "sleeping" && isObject(previous.detail) && previous.detail.reason === "drained";
73
- const after = previous?.status === "running" ? "crash" : drained ? "server_stop" : undefined;
74
- // A follow-up's open, which the server names (FOLLOW_UP_OPEN_ENV): the run's turn had ended, and the record its last
75
- // process left is its server letting it go once it answered (a drain, as a server stop writes one), not cut work.
76
- if (process.env[FOLLOW_UP_OPEN_ENV] === "1")
77
- return;
78
- if (!after || !(await harness.conversation(ROOT_CONVERSATION_ID, context)))
79
- return;
80
- await harness.commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: RUN_RESUMED, data: { after, generation, at: Date.now() } })), context);
81
- }
82
- /** The run's row and its pinned revision, read from the store the run's directory sits in. */
83
- function revisionOf(where) {
84
- const reader = openStoreReader(dataOfRun(where.root));
85
- try {
86
- const id = basename(resolve(where.root));
87
- const run = reader.readRun(id);
88
- if (!run)
89
- throw new Error(`the agent store has no run ${id}`);
90
- return { run, revision: reader.readRevision(run.revision) };
91
- }
92
- finally {
93
- reader.close();
94
- }
95
- }
96
- export default async function app(where) {
97
- const { run, revision } = revisionOf(where);
98
- // This process's reading of its environment, with its secrets: never a child's (secrets.ts).
99
- const env = withSecrets(process.env);
100
- const workflowNodeList = revision.kind === "workflow" ? workflowNodes(revision.body.workflow, (await import("@parcha/agentrun-dsl")).inspectWorkflow(revision.body.workflow)) : [];
101
- // The run's harness, resolved once (harness-table.ts): its model as a save resolves it (runnable.ts harnessModel).
102
- const entry = revision.kind === "agentic" ? harnessOf(env, revision.body.harness) : undefined;
103
- const chosen = revision.kind !== "agentic" ? await runModels(env, undefined, llmTiers(workflowNodeList, nodeTiers(workflowNodeList))) : entry?.onWire(env) ? await wireModels(entry, env, revision.body.model) : await runModels(env, revision.body.model, ["default"], revision.body.harness);
104
- const { model, byTier } = chosen;
105
- // Read before the run opens its store: what it spent in earlier processes counts against its cap.
106
- const cap = capOf(process.env);
107
- const mode = capModeOf(process.env);
108
- // A run on another harness has one model route, its session's proxy: every model request of the run goes through it,
109
- // the harness's own and the run's beside them (a learned workflow's nodes, its `llm` call nodes, a call node's native
110
- // search), on the session's booking under the run's one cap (port-models.ts, harness-app.ts). The run's models are the
111
- // session's port then; on pi they are the run's own, each request marked as it leaves (request-start.ts) inside the cap:
112
- // a request the cap refuses never leaves, and gets a start mark of its own, which its error entry answers.
113
- const onHarness = entry?.facts !== undefined;
114
- // A run on an adapter is capped at the price of whoever bills it (its entry's priceModel: providerFor's), as its adapter
115
- // prices it.
116
- const priced = onHarness && model ? entry.priceModel(env, model) : model;
117
- /** The session's port, once the harness's run is made (adapterRun): read at each request. */
118
- let sessionPort;
119
- const marked = onHarness ? undefined : await markRequests(chosen.models, cancelledIn(where.root));
120
- // The wrap-up on pi (cap.ts WrapUp): near its cap the run's own model is told once, under this cap, to finish. Not on
121
- // another harness: its guard tells the harness's model (harness-app.ts). Nor on a workflow run, whose model nodes each
122
- // deliver a record their node's instructions ask for: a step its cap has no room for waits for a raise instead (budget.ts).
123
- const storeFile = join(where.store, RUN_STORE_FILE);
124
- const wrapUp = cap === undefined || onHarness || !model || revision.kind === "workflow" ? undefined : { model: model.modelId, costs: costsIn(storeFile, model.modelId), sent: wrapUpSentIn(storeFile, cap), record: marked.wrapUp };
125
- // A workflow's decisions are its spend too, as the cap counted each in an earlier process (decision-cap.ts).
126
- const spentBefore = (() => {
127
- const spent = spentIn(storeFile);
128
- return spent === null || revision.kind !== "workflow" ? spent : spent + decisionSpentIn(storeFile);
129
- })();
130
- const models = onHarness
131
- ? await portModels(() => sessionPort?.(LEARNED_WORKFLOW_TOOL), priced ? chosen.models.getModel(priced.provider, priced.modelId) : undefined)
132
- : cap === undefined ? marked.models : await capModels(marked.models, cap, spentBefore, { unpriced: chosen.unpriced, refused: marked.refused, mode, ...(wrapUp ? { wrapUp } : {}) });
133
- // web_search's own request to the model provider, when it resolves native, goes through the run's models (hosted-search.ts):
134
- // on another harness, the session's port, for a learned workflow's call node.
135
- searchOn(models);
136
- const thinkingLevel = thinkingOf(process.env, revision.kind === "agentic" ? revision.body.thinking : undefined);
137
- // The run's place, as its start resolved and kept it (serve.json): in a box, its coding tools run there (run-box.ts).
138
- const meta = await readJson(join(where.root, RUN_META));
139
- const place = storedPlace(meta?.place);
140
- const root = dataOfRun(where.root);
141
- // A remote box (Daytona) is the server's to make and seed, reached through its relay; Docker's is made here.
142
- // Its box carries the epoch of the claim this process was launched under (runs.ts launch): a box of an earlier one is
143
- // an earlier process's, destroyed before this one makes its own (run-box.ts fenceRunBoxes).
144
- const epoch = Number(process.env[RUN_EPOCH_ENV] ?? "0");
145
- const box = place.mode === "sandbox" ? runBox(remotePlace(place) ? { relay: root } : { provider: () => runBoxProvider(place, env, root) }, { id: run.id, root, dir: where.root, place, epoch: Number.isSafeInteger(epoch) ? epoch : 0 }) : undefined;
146
- // What the run's host tools file in work/ is copied into a remote box too, which does not share this machine's work/.
147
- if (box?.mirror)
148
- mirrorWrites(where.work, box.mirror);
149
- const coding = codingSource(place, box);
150
- // Every tool call the run's model makes passes the run's tool gate (tool-gate.ts): pi's tools wrapped by name where the
151
- // registry composes each agent's, another harness's host tools in their call. An approved call runs on this coding
152
- // source, as the run's own would.
153
- const toolGate = runGate(where, run.id, revision);
154
- // Its remote MCP servers, as its first launch pinned them, with the credentials this launch handed it (mcp-gateway.ts).
155
- const pinned = (await readJson(join(where.root, MCP_PIN)));
156
- // Its records (a held ask, a priced call's mark and charge, an unpriced call's "not metered") go on the run's root, once
157
- // the run is open.
158
- let runHarness;
159
- const commit = () => runHarness && ((change) => runHarness.commit(change, BACKGROUND));
160
- const gateway = pinned && Object.keys(pinned).length ? mcpGateway({ pin: pinned, credentials: mcpCredentials(), work: () => where.work, commit, gate: toolGate }) : undefined;
161
- const registry = createRegistry();
162
- // An agentic run's system prompt starts with the date and the workspace (environment.ts). On pi it is a section,
163
- // installed first so it comes before every other extension's and the instructions.
164
- if (revision.kind === "agentic")
165
- registry.install(EnvironmentLine);
166
- registry.install(coding.extension);
167
- // What the run's agent learned goes into its instructions, and the skills it wrote join the revision's, the one path for
168
- // every harness (learning.ts).
169
- const learned = revision.kind === "agentic" ? await withLearned(where.root, where.work, revision.body.instructions, Object.keys(revision.body.skills)) : { instructions: "", skills: [] };
170
- // The workflows the agent learned that its run may run, as one tool (learned-workflow.ts), when its pin names any: on
171
- // the run's models, as the run's own requests under its cap, each model node and `llm` call on the run's model of its
172
- // tier, else the run's own (the only one the run was made with, and handed the key of); on another harness, the
173
- // session's one model, through its proxy; the `llm` tool's completion for a call node that names it; its call nodes on
174
- // the agent's tools its run's plane resolves (the plane its harness and its tools read).
175
- const flows = revision.kind === "agentic" ? await pinnedWorkflows(where.root, await readPin(where.root)) : [];
176
- const learnedModel = (tier) => (onHarness ? { provider: PORT_PROVIDER, modelId: "session" } : (byTier.get(tier ?? "default") ?? byTier.get("default")));
177
- const learnedTool = flows.length && revision.kind === "agentic"
178
- ? learnedWorkflowTool({ workflows: flows, granted: revision.body.tools, plane: planeOf(process.env), policy: toolGate.policy, denyFrom: toolGate.denyFrom, env, work: where.work, models: models, modelOf: learnedModel, complete: completer(models, learnedModel, thinkingLevel) })
179
- : undefined;
180
- // The run's effort, as its thinking level reads it: its note on how to work follows the instructions on every harness
181
- // (effort-guidance.ts). None without an effort.
182
- const guidance = effortGuidance(process.env[EFFORT_ENV]);
183
- if (revision.kind === "agentic" && revision.body.harness && entry?.facts) {
184
- const harness = revision.body.harness;
185
- const facts = entry.facts;
186
- // A harness that loads the skills its adapter takes itself (its entry's skillCheck: claude-agent's Skill tool, codex's
187
- // and opencode's skill lists) keeps in its prompt only the ones it would refuse; any other's prompt (a test's stand-in)
188
- // names each skill and its file when the run reads its files (it reads the SKILL.md when it fits), else keeps every
189
- // skill whole (skills.ts).
190
- const check = await entry.skillCheck?.();
191
- const { system: instructions, native } = await systemOf(learned.instructions, learned.skills, where.work, check, { onDemand: readsFiles(revision.body.tools) });
192
- // The session's system prompt starts with the line, made as this process opens it: a run resumed on a later day is
193
- // opened with that day.
194
- const spec = { key: `run:${run.id}`, label: run.agent, system: [environmentLine(), instructions, guidance].filter((text) => Boolean(text)), context: "fresh", thinking: thinkingFor(facts, thinkingLevel), ...(gateway ? { mcp: gateway } : {}) };
195
- // ask_person stays pi's (runnable.ts refuses a run that names it here); the file tools are pi's own; the MCP tools
196
- // are the harness's own client's, at the session's proxy.
197
- const named = revision.body.tools.filter((name) => name !== ASK_TOOL && !mcpNameOf(name));
198
- // The harness's own files (its homes, its state) go in a private directory beside the workspace, never in it. It works
199
- // in the workspace itself (where.work), the directory the run's file tools confine to: a path the model builds from
200
- // its working directory is then one they take.
201
- const dir = join(where.root, "harness");
202
- await mkdir(dir, { recursive: true, mode: 0o700 });
203
- // Built at the open: the harness's own process runs under the run's confinement, the prefix pi's commands get there.
204
- const make = (confine) => adapterFor(harness, env, { model: model, models: chosen.models, unpriced: chosen.unpriced, ...(confine ? { confine } : {}), ...(native.length ? { skills: native } : {}) });
205
- // The run's cap, checked before each of the session's requests (the harness's and the run's own beside them): the
206
- // same ceiling rule as pi's (cap.ts), at the price `priced` names (above).
207
- const guard = await capBefore(cap, chosen.models.getModel(priced.provider, priced.modelId), { listed: !chosen.unpriced.has(priced.modelId), mode });
208
- // The cancel mark serve writes is read here too, as pi's model wrapper reads it (request-start.ts).
209
- // The run's stop record (serve.json, as serve saved it before a stop's abort): a turn it names is not resumed.
210
- const stopRecord = { ...(typeof meta?.stopped_at === "string" ? { stopped_at: meta.stopped_at } : {}), ...(typeof meta?.stopped_after === "number" ? { stopped_after: meta.stopped_after } : {}) };
211
- const { door, onOpen, port } = adapterRun(make, harness, spec, BACKGROUND, cap, learnedTool ? [...named, LEARNED_WORKFLOW_TOOL] : named, dir, guard, cancelledIn(where.root), where.work, coding.tools, stopRecord, toolGate, learnedTool ? [learnedTool] : []);
212
- // The run's own model requests beside the harness's go through the session's proxy, booked on its records (port-models.ts).
213
- sessionPort = port;
214
- // A paid host tool's settle goes to the run's root, as on pi (paid-calls.ts settleIn).
215
- // The store's own Harness makes no model request here (the adapter's harness does), so it gets an empty catalog, never
216
- // the run's models: a non-pi run must not get a pi model catalog by accident. A real Models all the same, since pi
217
- // 1.5's Harness.open wraps it at the open (it binds models.getAuth).
218
- return { models: createModels(), registry: createRegistry(), door, onOpen: async (durable) => ((runHarness = durable.harness), settleIn(rootRecordOf(durable.harness), durable.store), onOpen(durable)), beforeResume: markResumed };
219
- }
220
- // Each tool the revision names is bound once, from the table: its extensions installed here, its documents written in
221
- // each conversation's creating commit, what it settles done before anything resumes, and what it lets go done before
222
- // the run is released.
223
- const writes = [];
224
- const settles = [];
225
- const stops = [];
226
- const host = {
227
- where, env, coding, install: (extension) => registry.install(extension),
228
- onConversation: (write) => void writes.push(write), beforeResume: (settle) => void settles.push(settle), beforeRelease: (stop) => void stops.push(stop),
229
- };
230
- const letGo = async (harness) => { for (const stop of stops)
231
- await stop(harness); };
232
- const bound = new Map();
233
- const bind = (name, nodes = false) => {
234
- const entry = toolOf(name);
235
- if (!entry || (nodes && !entry.nodes))
236
- throw new Error(`the revision names the tool ${name}, which agentrun-serve does not bind${nodes ? " for a workflow's model node" : ""}`);
237
- let tools = bound.get(name);
238
- if (!tools)
239
- bound.set(name, (tools = entry.bind(host)));
240
- return tools;
241
- };
242
- // The gate reads its store before the run resumes (an agentic run's and a workflow's alike): the resume dispatches the
243
- // calls a crash cut, and a rerun of one it let through must find its mark (tool-gate.ts prime).
244
- // The run's store as a barrier takes it, and its harness, from the open's beforeResume: a task the open resumes (a turn or
245
- // a workflow a crash cut) runs before onOpen, and what it sends needs both. A workflow effect's admission is synced on
246
- // the store (workflowAdmit, below); a paid call's hold is synced on it and booked on the run's root (settleIn), a call
247
- // node's under its call (runEffect's ledger), and a priced MCP call's records go through the harness's commit.
248
- let journal;
249
- const hooks = {
250
- conversationCreated: async (tx, conversation) => { for (const write of writes)
251
- await write(tx, conversation.id); },
252
- beforeResume: async (run) => { journal = run.syncTarget; runHarness = run.harness; settleIn(rootRecordOf(run.harness), run.syncTarget); await toolGate.prime(run.harness, run.context, run.syncTarget); await markResumed(run); for (const settle of settles)
253
- await settle(run.harness); },
254
- };
255
- // 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
256
- // by default (sleeping, due at `at`).
257
- const wake = async (durable, at) => {
258
- await letGo(durable.harness);
259
- await durable.setStatus("sleeping", { reason: "drained" }, { wakeAt: at === null ? null : new Date(at).toISOString() });
260
- };
261
- if (revision.kind === "agentic") {
262
- const tools = (await Promise.all(revision.body.tools.filter((name) => !mcpNameOf(name)).map((name) => bind(name)))).flatMap((binding) => binding.tools);
263
- // The MCP tools pass the gate in the gateway (mcp-gateway.ts) and carry its mark (GATED_BY_GATEWAY), so the gate's
264
- // extension leaves exactly those; every other tool, any mcp__ name included, it wraps.
265
- const mcp = gateway ? mcpRegistrations(gateway) : [];
266
- if (mcp.length)
267
- registry.install(defineExtension({ name: "mcp", tools: mcp }));
268
- tools.push(...mcp);
269
- if (learnedTool) {
270
- registry.install(defineExtension({ name: "learned-workflow", tools: [learnedTool] }));
271
- tools.push(learnedTool);
272
- }
273
- registry.install(toolGate.extension(tools));
274
- // Each skill named with its file when the run reads its files (it reads the SKILL.md when it fits), else whole.
275
- const instructions = [await promptOf(learned.instructions, learned.skills, where.work, { onDemand: readsFiles(revision.body.tools) }), guidance].filter(Boolean).join("\n\n");
276
- // The calls that wait for a person's approval are read as the run opens, and their answers acted on from then.
277
- const onOpen = async (durable) => {
278
- runHarness = durable.harness;
279
- settleIn(rootRecordOf(durable.harness), durable.store);
280
- marked.open(durable);
281
- await toolGate.load(durable, BACKGROUND, coding.tools, learnedTool ? [learnedTool] : []);
282
- toolGate.start();
283
- };
284
- return { models, registry, ...hooks, ...(stops.length ? { wake } : {}), root: { agent: { model, thinkingLevel, instructions, tools } }, onOpen };
285
- }
286
- const input = isObject(meta?.input) ? meta.input : {};
287
- const [{ BACKGROUND_CONTEXT }, { createWorkflowExtension, decisionRecovery, durableDecisions, nodeRunner, taskScope }, { EffectFailure, inspectWorkflow, judgeFromProviders }, { withRecovery, workspaceFiles }, { startWorkflowRevision }, decisionProviders] = await Promise.all([
288
- import("@earendil-works/chord/context"),
289
- import("@parcha/agentrun-pi/durable"),
290
- import("@parcha/agentrun-dsl"),
291
- import("@parcha/agentrun-dsl/recovery"),
292
- import("@parcha/pi-durable-agent/workflow"),
293
- // The decision providers, holding the decision keys the server handed this process: in no environment a tool reads.
294
- decisionProvidersOf(process.env),
295
- ]);
296
- const nodeTools = new Map();
297
- for (const name of workflowTools(workflowNodeList).nodes)
298
- nodeTools.set(name, await bind(name, true));
299
- // A model node's tools pass the gate too; one set to ask is refused there, as no node can wait for a person. A call
300
- // node is the author's own step, which cannot wait for an approval: runnable.ts refuses a run whose call node calls a tool
301
- // set to deny or ask, and a tool set to either since is refused as its call node runs (runEffect).
302
- const gatedTools = toolGate.extension([...nodeTools.values()].flatMap((binding) => binding.tools));
303
- registry.install(gatedTools);
304
- // A decision node's images are files of the run's work directory (pdf_pages draws them there).
305
- const loadImage = imageLoader(where.work);
306
- const log = nodeLog(where.root);
307
- // The receipts earlier processes recorded, read before this one opens the store, which then holds it exclusively.
308
- // Lock-free, as the server reads it: nothing made beside the store (a plain read leaves a -shm there).
309
- const earlier = await (async () => {
310
- try {
311
- return durableDecisions(join(where.store, RUN_STORE_FILE), { unlocked: true });
312
- }
313
- catch {
314
- return (await readLiveView(where.root))?.receipts ?? [];
315
- }
316
- })();
317
- const live = liveView(where.root, [...earlier]);
318
- // The `llm` tool's one completion: on the run's models (capped and marked as a model node's), its tier's model.
319
- const complete = completer(models, (tier) => byTier.get(tier ?? "default"), thinkingLevel);
320
- // Under a cap: where a step the cap refuses for room waits for a raise (budget.ts), and the step each wait is for (a
321
- // model node's request knows no node of its own: it waits inside the node's step, `steps`).
322
- const spend = runSpendNow();
323
- const steps = new AsyncLocalStorage();
324
- /** The model nodes running: a model request whose step its async context lost waits as the one running, when one is. */
325
- const running = new Set();
326
- const stepNow = () => steps.getStore() ?? (running.size === 1 ? [...running][0] : undefined);
327
- const holdMs = Number(process.env[BUDGET_HOLD_ENV]);
328
- const waits = spend ? budgetWaits(where.root, spend, { holdMs: Number.isFinite(holdMs) && holdMs > 0 ? holdMs : BUDGET_HOLD_MS, letGo: () => void process.kill(process.pid, "SIGTERM") }) : undefined;
329
- if (spend && waits) {
330
- spend.wait = (refusal, signal) => waits.wait(refusal, signal, stepNow());
331
- spend.stopped = (refusal) => waits.record(refusal, stepNow());
332
- }
333
- /** `fn`, a step of the run (a node, a call, a decision) named by its params, counted in flight for the pause's let-go. */
334
- const stepped = (fn, model = false) => {
335
- if (!fn)
336
- return fn;
337
- const counted = waits ? waits.step(fn) : fn;
338
- return (async (params) => {
339
- const at = { label: String(params?.label ?? params?.node?.label ?? ""), path: params?.executionPath ?? null };
340
- if (model)
341
- running.add(at);
342
- try {
343
- return await steps.run(at, () => counted(params));
344
- }
345
- finally {
346
- running.delete(at);
347
- }
348
- });
349
- };
350
- /** A model node that failed on a refusal no raise fixes (its model with no price, a spend no one knows: capModels
351
- * recorded it, spend.stopped) fails as CapStop, as a call or a decision does, never as the node's own failure, which a
352
- * collecting map would take for an item's and go on. */
353
- const capStopped = (fn) => (fn && waits ? (async (params) => {
354
- try {
355
- return await fn(params);
356
- }
357
- catch (error) {
358
- // A refusal kept with no path of its own is this node's only while it runs alone (stepped counts it running).
359
- throw waits.stopped(params?.executionPath, running.size === 1) ?? error;
360
- }
361
- }) : fn);
362
- // Each decision's hold under the cap, before its request is admitted, and its charge once it answers (decision-cap.ts).
363
- const capped = waits && decisionProviders ? cappedDecisions({
364
- providers: decisionProviders, waits, mode,
365
- book: async (data) => void (runHarness && (await rootRecordOf(runHarness)(DECISION_COST, data))),
366
- keep: async (data) => {
367
- if (!runHarness)
368
- throw new Error("the run's store is not open");
369
- await rootRecordOf(runHarness)(DECISION_HOLD, data);
370
- },
371
- }) : undefined;
372
- /** A call node `via: "tool"`: the table's tool by name, its interpolated args in, what its `out` schema checks out. Its
373
- * input and output go to the node log, and its paid requests are booked under the node's own call (its execution
374
- * path, and its item in a map). */
375
- const runEffect = async ({ node, input, signal, executionPath, item }) => {
376
- const effect = node.via === "tool" && node.tool ? toolOf(node.tool)?.effect : undefined;
377
- if (!effect)
378
- throw new Error(`call node "${node.label}": agentrun-serve runs no tool ${node.tool ?? `via ${node.via}`}`);
379
- const at = { path: executionPath ?? null, item: item?.index ?? null, tool: node.tool, label: node.label };
380
- log({ t: "effect.start", ...at, input, at: new Date().toISOString() });
381
- try {
382
- // Its tool's permission now, the gate's one rule read as each call node runs (tool-gate.ts policy): a tool set to
383
- // deny since the run started is refused in the gate's words, and one set to ask too, since a call node cannot wait
384
- // for an approval. Neither runs.
385
- const permission = toolGate.policy(node.tool);
386
- if (permission === "deny")
387
- throw new Error(deniedText(node.tool, undefined, toolGate.denyFrom(node.tool)));
388
- if (permission === "ask")
389
- throw new Error(callNodeAskText(node.tool));
390
- // Booked in the run's store, through the harness beforeResume took: a call node a resumed workflow runs before onOpen
391
- // is booked as on a first run.
392
- const harness = runHarness;
393
- const ledger = harness ? { call: `${node.label}@${executionPath ?? ""}${item ? `#${item.index}` : ""}`, record: rootRecordOf(harness) } : undefined;
394
- // A refusal of the cap inside the effect (a paid request's, the `llm` call's) is the call's: it sent nothing, and
395
- // whatever the tool made of it, the effect completes as held (CAP_HELD), never as the tool's answer or failure.
396
- let refused;
397
- const output = await capRefusals.run((refusal) => void (refused ??= refusal), () => effect(input, { signal, env, work: where.work, complete, ...(ledger ? { ledger } : {}) }))
398
- .catch((error) => { if (refused && !signal.aborted)
399
- return undefined; throw error; });
400
- if (refused) {
401
- log({ t: "effect.end", ...at, status: "failed", error: `spend cap: ${refused.words}`.slice(0, 65_536), at: new Date().toISOString() });
402
- return { [CAP_HELD]: { ...refused, heldAt: Date.now() } };
403
- }
404
- log({ t: "effect.end", ...at, status: "done", output, at: new Date().toISOString() });
405
- return output;
406
- }
407
- catch (error) {
408
- const message = String(error?.message ?? error);
409
- // Whole up to 64 KB, so the server redacts it before it cuts it for the graph (graph-view.ts); a longer one is marked cut.
410
- log({ t: "effect.end", ...at, status: "failed", error: message.slice(0, 65_536), ...(message.length > 65_536 ? { error_truncated: true } : {}), at: new Date().toISOString() });
411
- // An abort (a cancel, the node's deadline) stays a throw: the driver keeps its effect unknown. A tool that failed on
412
- // its own (an unreadable PDF, a model's refusal) answered: its failure is the effect's outcome, completed, and is
413
- // thrown past the driver as the call node's typed failure (`failing`), which a collecting map ends that item on.
414
- if (signal.aborted || error?.name === "AbortError")
415
- throw error;
416
- return { [TOOL_FAILED]: `call node "${node.label}": ${node.tool} failed: ${message.slice(0, 500)}` };
417
- }
418
- };
419
- /** `runEffect` past the driver: a tool's failure the driver recorded as its effect's outcome is thrown here, on the
420
- * first run and on a resume that answers it from the receipt alike. A call its cap held (CAP_HELD) waits here, past
421
- * the driver's admission, for a raise, and goes again as the driver's next effect at its path; held by a refusal no
422
- * raise fixes, the run stops (CapStop). A resume answers each held effect from its receipt the same way, and a cap
423
- * raised since sends the call at once. */
424
- const failing = (run, holdPoll) => async (params) => {
425
- for (;;) {
426
- const value = await run(params);
427
- if (isObject(value) && typeof value[TOOL_FAILED] === "string")
428
- throw new EffectFailure(value[TOOL_FAILED], null, { code: null });
429
- if (!(isObject(value) && isObject(value[CAP_HELD])))
430
- return value;
431
- const refusal = value[CAP_HELD];
432
- const { node, executionPath, signal } = params;
433
- const at = { label: node.label, path: executionPath ?? null };
434
- if (!waits)
435
- throw new Error(`call node "${node.label}": ${refusal.words}`);
436
- if (!refusal.room)
437
- waits.stop(refusal, at);
438
- if (!(await waits.wait(refusal, signal, at)))
439
- throw signal?.reason ?? new Error(`call node "${node.label}" was not sent: its wait for a raise ended`);
440
- // What it waited, from its refusal (a resume's included), is the call's own no more: its poll window moves back by
441
- // it (the driver's durable clock, once per hold), as its attempt's deadline does (deps.held).
442
- const heldAt = value[CAP_HELD].heldAt;
443
- if (typeof heldAt === "number" && executionPath)
444
- holdPoll?.(executionPath, Date.now() - heldAt, String(heldAt));
445
- }
446
- };
447
- /** A model node's agent: its tier's model, the tools it names, and the extensions they come from. */
448
- const nodeAgent = (node) => {
449
- const bindings = (node.tools ?? []).flatMap((name) => nodeTools.get(name) ?? []);
450
- return { model: byTier.get(node.tier ?? "default"), thinkingLevel, extensions: [...new Set([coding.extension, ...bindings.flatMap((b) => b.extensions), gatedTools])], tools: bindings.flatMap((b) => b.tools) };
451
- };
452
- const nodes = nodeRunner({ agent: (node) => nodeAgent(node) });
453
- /** The node log's starts and ends, from the workflow's events: what a graph shows of a node's timing. */
454
- const onEvent = (event) => {
455
- if ((event.type !== "node.start" && event.type !== "node.end") || typeof event.executionPath !== "string")
456
- return;
457
- const detail = (event.detail ?? {});
458
- 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) } : {}) });
459
- };
460
- const workflows = createWorkflowExtension({
461
- // Each workflow effect's admission is synced before it is dispatched (pi-durable-disk barriers.ts, workflowAdmit): the
462
- // driver's journal is the run's store, taken in beforeResume, so a workflow the open resumes, before onOpen, has it.
463
- options: () => ({ files: workspaceFiles(where.work), afterAdmit: async () => {
464
- if (!journal)
465
- throw new Error("the run's store is not open, so a workflow effect's admission cannot be made durable: it is not sent");
466
- await syncNow(journal, BARRIER.workflowAdmit);
467
- } }),
468
- run: ({ key, runtime, context, driver }) => {
469
- // Each typed question's receipt is a row of the run's store before its answer acts, and a resumed run takes an
470
- // answered one instead of asking again.
471
- const decisions = decisionRecovery({ key, runtime, context });
472
- live.driver(driver);
473
- const deps = withRecovery(driver, {
474
- runNode: nodes.on(taskScope(runtime), context).runNode, runEffect: runEffect,
475
- ...(decisionProviders ? { runJudge: (capped ? capped.settling(judgeFromProviders({ ...decisionProviders, loadImage })) : judgeFromProviders({ ...decisionProviders, loadImage })), decisionProviders } : {}),
476
- recordDecision: async (receipt, exchange) => {
477
- await decisions.recordDecision(receipt, exchange);
478
- live.receipt(receipt);
479
- },
480
- }, { durableNodes: true });
481
- const { recovery } = deps;
482
- if (!recovery)
483
- throw new Error("the workflow's recovery gave the run no recovery hooks");
484
- // The pause gate: each node's resume, which the interpreter awaits before it starts the node (before a call's deadline
485
- // is armed), and each model call and decision, outside the recovery: one waiting at it was never admitted, so a kill
486
- // while paused leaves nothing half asked.
487
- const gate = (fn) => (fn ? gated(where.root, fn) : fn);
488
- const resume = gated(where.root, (args) => recovery.resume(...args));
489
- // Under a cap, each decision is held before the driver admits it (a route the driver answers from what it decided
490
- // sends nothing), each step counts in flight, and a call node's deadline leaves out what it waited for a raise.
491
- // A request the driver answers from what an earlier process did (a route it decided, a request it admitted and that
492
- // did not fail, which escalates unsent) holds nothing and never waits for a raise (askedBefore).
493
- const judge = capped && deps.runJudge ? capped.before(deps.runJudge, (params) => askedBefore(driver, params)) : deps.runJudge;
494
- return { deps: {
495
- ...deps, runEffect: stepped(deps.runEffect && failing(deps.runEffect, (path, ms, hold) => driver.holdPoll(path, ms, hold))), runNode: stepped(gate(capStopped(deps.runNode)), true), runJudge: stepped(gate(judge)), onEvent,
496
- ...(waits ? { held: (path) => waits.held(path) } : {}),
497
- recovery: { ...recovery, resume: (...args) => resume(args), decision: decisions.decision },
498
- } };
499
- },
500
- });
501
- registry.install(nodes.extension);
502
- registry.install(workflows.extension);
503
- const onOpen = async (durable) => {
504
- settleIn(rootRecordOf(durable.harness), durable.store);
505
- marked.open(durable);
506
- const started = { runId: run.id, storePath: join(where.store, RUN_STORE_FILE), agentId: run.agent, revision: revision };
507
- const outcome = await startWorkflowRevision({ harness: durable.harness, workflows, context: BACKGROUND_CONTEXT, run: started, input, tools: inspectWorkflow(revision.body.workflow).requires.tools });
508
- live.stop();
509
- await letGo(durable.harness);
510
- await durable.setStatus(outcome.status === "complete" ? "done" : "failed", { workflow: outcome.status, ...(outcome.status === "refused" ? { code: outcome.code, message: outcome.message.slice(0, 500) } : {}) });
511
- await durable.release();
512
- };
513
- return { models, registry, ...hooks, ...(stops.length ? { wake } : {}), onOpen };
514
- }
package/dist/bounds.d.ts DELETED
@@ -1,26 +0,0 @@
1
- export declare class RequestBounds {
2
- /** The newest entry read, by id: an entry at or before it is read again, and changes nothing. */
3
- private seen;
4
- /** Each request in flight that names itself: a harness request, by `<key>:<request>`, and a pi side request, by
5
- * `side:<requestId>`; its bound. */
6
- private harness;
7
- /** Each harness request booked before its cost, by `<key>:<request>`: its bound, served as in flight until its late
8
- * cost comes, and never holding the ended bounds back. */
9
- private awaiting;
10
- /** pi's one generation request in flight: its bound. */
11
- private pi;
12
- /** The bounds of the requests that ended since the run's cost last fit its cap, together. */
13
- private since;
14
- /** What the run has spent by the entries read, as the cap reads each entry's cost. */
15
- private spent;
16
- /** Reads `entries` of the run's root, each once, against the run's `cap` (none: no overshoot to explain). */
17
- note(entries: readonly unknown[], cap?: number): void;
18
- private noteOne;
19
- private closeHarness;
20
- private closePi;
21
- /** The bounds of the requests in flight, together: those whose cost may still be a miss. */
22
- inFlight(): number;
23
- /** The bounds of the requests that ended since the run's cost last fit its cap, together: how far a cache miss among
24
- * them may have taken the run past its cap. */
25
- ended(): number;
26
- }