@parcha/agentrun-serve 0.1.0-beta.29 → 0.1.0-beta.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/CHANGELOG.md +188 -0
  2. package/README.md +564 -97
  3. package/dist/adapters.d.ts +35 -6
  4. package/dist/adapters.js +152 -26
  5. package/dist/agents.d.ts +11 -5
  6. package/dist/agents.js +16 -10
  7. package/dist/app.js +80 -20
  8. package/dist/background.d.ts +28 -0
  9. package/dist/background.js +376 -0
  10. package/dist/box-egress.d.ts +98 -0
  11. package/dist/box-egress.js +259 -0
  12. package/dist/box-image.d.ts +1 -1
  13. package/dist/box-image.js +9 -7
  14. package/dist/box-relay-vm.d.ts +80 -0
  15. package/dist/box-relay-vm.js +389 -0
  16. package/dist/box-relay.d.ts +8 -5
  17. package/dist/box-relay.js +14 -9
  18. package/dist/boxes.d.ts +21 -3
  19. package/dist/boxes.js +14 -7
  20. package/dist/browser-cost.d.ts +41 -0
  21. package/dist/browser-cost.js +158 -0
  22. package/dist/cap.d.ts +129 -21
  23. package/dist/cap.js +338 -67
  24. package/dist/coding-tools.d.ts +7 -3
  25. package/dist/coding-tools.js +16 -10
  26. package/dist/console/THIRD-PARTY-NOTICES.txt +580 -0
  27. package/dist/console/assets/index-34jfpIbQ.js +481 -0
  28. package/dist/console/assets/index-DUHbWcIP.css +1 -0
  29. package/dist/console/index.html +2 -2
  30. package/dist/content-filter.d.ts +7 -0
  31. package/dist/content-filter.js +23 -0
  32. package/dist/decision-rows.d.ts +11 -3
  33. package/dist/decision-rows.js +18 -11
  34. package/dist/errors.d.ts +2 -0
  35. package/dist/errors.js +5 -2
  36. package/dist/files.d.ts +6 -1
  37. package/dist/files.js +7 -2
  38. package/dist/grade.d.ts +7 -10
  39. package/dist/grade.js +31 -51
  40. package/dist/graph-served.d.ts +23 -0
  41. package/dist/graph-served.js +75 -0
  42. package/dist/graph-view.d.ts +7 -5
  43. package/dist/graph-view.js +10 -3
  44. package/dist/harness-app.d.ts +4 -2
  45. package/dist/harness-app.js +101 -19
  46. package/dist/harness-opencode/adapter.d.ts +45 -0
  47. package/dist/harness-opencode/adapter.js +272 -0
  48. package/dist/harness-opencode/binary.d.ts +18 -0
  49. package/dist/harness-opencode/binary.js +87 -0
  50. package/dist/harness-opencode/config.d.ts +24 -0
  51. package/dist/harness-opencode/config.js +61 -0
  52. package/dist/harness-opencode/harness.d.ts +77 -0
  53. package/dist/harness-opencode/harness.js +620 -0
  54. package/dist/harness-opencode/host/mcp.d.ts +40 -0
  55. package/dist/harness-opencode/host/mcp.js +208 -0
  56. package/dist/harness-opencode/host/policy.d.ts +71 -0
  57. package/dist/harness-opencode/host/policy.js +419 -0
  58. package/dist/harness-opencode/host/server.d.ts +55 -0
  59. package/dist/harness-opencode/host/server.js +165 -0
  60. package/dist/harness-opencode/index.d.ts +9 -0
  61. package/dist/harness-opencode/index.js +6 -0
  62. package/dist/harness-opencode/verify.d.ts +32 -0
  63. package/dist/harness-opencode/verify.js +75 -0
  64. package/dist/harness-opencode/versions.d.ts +33 -0
  65. package/dist/harness-opencode/versions.js +64 -0
  66. package/dist/harness.d.ts +4 -1
  67. package/dist/harness.js +5 -2
  68. package/dist/host-tools.d.ts +12 -2
  69. package/dist/host-tools.js +26 -12
  70. package/dist/host.js +6 -2
  71. package/dist/hosted-search.js +5 -1
  72. package/dist/import.d.ts +2 -2
  73. package/dist/import.js +4 -3
  74. package/dist/key-check.d.ts +3 -2
  75. package/dist/key-check.js +7 -3
  76. package/dist/key-refusal.js +8 -4
  77. package/dist/learn/check.d.ts +10 -1
  78. package/dist/learn/check.js +19 -1
  79. package/dist/learn/grade.d.ts +3 -2
  80. package/dist/learn/grade.js +25 -13
  81. package/dist/learn/index.d.ts +2 -2
  82. package/dist/learn/index.js +2 -2
  83. package/dist/learn/notes.js +2 -1
  84. package/dist/learn/reflect.d.ts +2 -2
  85. package/dist/learn/reflect.js +51 -5
  86. package/dist/learn/secrets.js +28 -8
  87. package/dist/learn/skills.d.ts +17 -4
  88. package/dist/learn/skills.js +79 -6
  89. package/dist/learned-workflow.d.ts +59 -0
  90. package/dist/learned-workflow.js +191 -0
  91. package/dist/learning-run.d.ts +7 -5
  92. package/dist/learning-run.js +45 -23
  93. package/dist/learning-words.d.ts +6 -3
  94. package/dist/learning-words.js +8 -5
  95. package/dist/learning.d.ts +44 -3
  96. package/dist/learning.js +148 -3
  97. package/dist/mcp-servers.d.ts +7 -4
  98. package/dist/mcp-servers.js +5 -0
  99. package/dist/mcp.js +5 -5
  100. package/dist/model.d.ts +13 -11
  101. package/dist/model.js +11 -10
  102. package/dist/openapi/agentrun-v2.openapi.json +1 -0
  103. package/dist/openapi.js +358 -48
  104. package/dist/paid-calls.d.ts +5 -1
  105. package/dist/paid-calls.js +1 -1
  106. package/dist/pause.d.ts +2 -0
  107. package/dist/place.d.ts +27 -4
  108. package/dist/place.js +42 -10
  109. package/dist/propose.d.ts +2 -0
  110. package/dist/propose.js +38 -8
  111. package/dist/request-start.d.ts +12 -4
  112. package/dist/request-start.js +139 -15
  113. package/dist/run-box.d.ts +56 -4
  114. package/dist/run-box.js +173 -23
  115. package/dist/runnable.d.ts +5 -2
  116. package/dist/runnable.js +12 -4
  117. package/dist/runs.d.ts +258 -36
  118. package/dist/runs.js +830 -89
  119. package/dist/secrets.d.ts +12 -0
  120. package/dist/secrets.js +18 -0
  121. package/dist/server.d.ts +131 -35
  122. package/dist/server.js +467 -105
  123. package/dist/sign-ins.d.ts +99 -0
  124. package/dist/sign-ins.js +288 -0
  125. package/dist/skills.d.ts +16 -4
  126. package/dist/skills.js +35 -7
  127. package/dist/stats.d.ts +7 -2
  128. package/dist/stats.js +28 -7
  129. package/dist/tool-gate.d.ts +266 -0
  130. package/dist/tool-gate.js +554 -0
  131. package/dist/tool-keys.d.ts +46 -10
  132. package/dist/tool-keys.js +44 -2
  133. package/dist/tool-plane.d.ts +112 -27
  134. package/dist/tool-plane.js +205 -47
  135. package/dist/tools.d.ts +69 -14
  136. package/dist/tools.js +143 -24
  137. package/dist/trigger-secrets.d.ts +32 -0
  138. package/dist/trigger-secrets.js +143 -0
  139. package/dist/triggers.d.ts +439 -0
  140. package/dist/triggers.js +863 -0
  141. package/dist/turn-end.d.ts +3 -2
  142. package/dist/turn-end.js +3 -2
  143. package/dist/usage-lines.d.ts +26 -0
  144. package/dist/usage-lines.js +28 -0
  145. package/dist/validate.d.ts +2 -0
  146. package/dist/validate.js +11 -2
  147. package/dist/webhooks.d.ts +11 -4
  148. package/dist/webhooks.js +17 -1
  149. package/launcher/agentrun-serve +1 -1
  150. package/package.json +19 -13
  151. package/dist/console/assets/index-BN7oVcO4.js +0 -445
  152. package/dist/console/assets/index-By-jkqki.css +0 -1
@@ -0,0 +1,75 @@
1
+ // What GET /runs/{id}/graph serves of each part of a run's graph (runs.ts servedGraph): redacted by a run's answer's rule
2
+ // (key-refusal.ts redactedOutput, over the values the server holds and handed the run), and only then cut. graph-view.ts
3
+ // makes the view whole, so a key saved after it was made, or kept for a busy store's read, is still found.
4
+ import { redactedOutput } from "./key-refusal.js";
5
+ /** The most of a map item's label and of an error (a call's, a decision's) the graph shows. */
6
+ export const LABEL_SHOWN = 200;
7
+ export const ERROR_SHOWN = 2000;
8
+ /** Where an error was cut when it was stored, before errors were stored whole: one this long may have been cut there. */
9
+ const ERROR_CUT_BEFORE = 2000;
10
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
11
+ /** `value`, a part of a graph view of `kind`, as the graph serves it with `values` held: each string and number by
12
+ * redactedOutput, then a map item's label cut at LABEL_SHOWN and an error at ERROR_SHOWN. A text stored cut (a
13
+ * decision's state past 64 KB, an error marked cut, or one of exactly ERROR_CUT_BEFORE characters from before) has its
14
+ * last 6 times the longest held value plus 16 characters held back, where a value the stored cut split would sit. */
15
+ export function servedPart(kind, value, values) {
16
+ const shown = redactedOutput(value, values);
17
+ if (!isRecord(shown))
18
+ return shown;
19
+ const hold = 6 * values.reduce((most, held) => Math.max(most, held.length), 0) + 16;
20
+ const heldBack = (text) => `${text.slice(0, Math.max(0, text.length - hold))}…`;
21
+ if (kind === "nodes") {
22
+ return Object.fromEntries(Object.entries(shown).map(([path, node]) => [path, isRecord(node) && Array.isArray(node.items) ? { ...node, items: node.items.map((item) => (isRecord(item) && typeof item.label === "string" ? { ...item, label: item.label.slice(0, LABEL_SHOWN) } : item)) } : node]));
23
+ }
24
+ const raw = isRecord(value) ? value : {};
25
+ const { error_cut: _cut, error_truncated: _truncated, ...rest } = shown;
26
+ const out = { ...rest };
27
+ if (kind === "decision" && out.state_truncated === true && typeof out.state === "string")
28
+ out.state = heldBack(out.state);
29
+ if (typeof out.error === "string") {
30
+ const cut = raw.error_cut === true || raw.error_truncated === true || (typeof raw.error === "string" && raw.error.length === ERROR_CUT_BEFORE);
31
+ out.error = (cut ? heldBack(out.error) : out.error).slice(0, ERROR_SHOWN);
32
+ }
33
+ return out;
34
+ }
35
+ /** What every run's graph keeps in serve's memory, in one cache: each part as served (servedPart), and each workflow
36
+ * run's last whole view, which a busy store's read answers from. */
37
+ export const GRAPH_CACHE_BYTES = 32 * 1024 * 1024;
38
+ /** A least recently used cache bounded by bytes: an entry read or set is the most recent, and past `maxBytes` the least
39
+ * recent go, one at a time, until it fits; never all at once. An entry bigger than the bound is not kept. */
40
+ export class PartCache {
41
+ maxBytes;
42
+ entries = new Map();
43
+ bytes = 0;
44
+ constructor(maxBytes) {
45
+ this.maxBytes = maxBytes;
46
+ }
47
+ get size() {
48
+ return this.entries.size;
49
+ }
50
+ get(key) {
51
+ const entry = this.entries.get(key);
52
+ if (!entry)
53
+ return undefined;
54
+ this.entries.delete(key);
55
+ this.entries.set(key, entry);
56
+ return entry.value;
57
+ }
58
+ set(key, value, bytes) {
59
+ const old = this.entries.get(key);
60
+ if (old) {
61
+ this.entries.delete(key);
62
+ this.bytes -= old.bytes;
63
+ }
64
+ if (bytes > this.maxBytes)
65
+ return;
66
+ this.entries.set(key, { value, bytes });
67
+ this.bytes += bytes;
68
+ for (const [oldest, entry] of this.entries) {
69
+ if (this.bytes <= this.maxBytes)
70
+ break;
71
+ this.entries.delete(oldest);
72
+ this.bytes -= entry.bytes;
73
+ }
74
+ }
75
+ }
@@ -53,6 +53,12 @@ export declare function runGraph(given: GraphInput): Promise<{
53
53
  graph: import("@parcha/agentrun-dsl/graph").WorkflowGraph;
54
54
  nodes: Record<string, NodeView>;
55
55
  decisions: {
56
+ images: {
57
+ token: {} | null;
58
+ ref: {} | null;
59
+ url: string | null;
60
+ }[];
61
+ error_cut?: boolean | undefined;
56
62
  id: {} | null;
57
63
  node: string | null;
58
64
  executionPath: {} | null;
@@ -72,11 +78,6 @@ export declare function runGraph(given: GraphInput): Promise<{
72
78
  state: {} | null;
73
79
  state_truncated: boolean;
74
80
  error: string | null;
75
- images: {
76
- token: {} | null;
77
- ref: {} | null;
78
- url: string | null;
79
- }[];
80
81
  }[];
81
82
  effects: {
82
83
  node: string | null;
@@ -87,6 +88,7 @@ export declare function runGraph(given: GraphInput): Promise<{
87
88
  input: unknown;
88
89
  output: unknown;
89
90
  error: string | null;
91
+ error_cut?: boolean;
90
92
  startedAt: string;
91
93
  endedAt: string | null;
92
94
  }[];
@@ -11,15 +11,17 @@ import { llmAnswers, readLiveView, readNodeLog } from "./pause.js";
11
11
  const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
12
12
  const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
13
13
  const at = (state, path) => path.split(".").reduce((value, key) => (isObject(value) ? value[key] : undefined), state);
14
+ /** A map item's label: the item, or its name, whole. The server redacts it, then cuts it (runs.ts servedGraph): a view kept
15
+ * for a busy store's read holds what was written, so a key saved after it is still found whole. */
14
16
  const labelOf = (item) => {
15
17
  if (typeof item === "string")
16
- return item.slice(0, 200);
18
+ return item;
17
19
  if (typeof item === "number")
18
20
  return String(item);
19
21
  if (!isObject(item))
20
22
  return undefined;
21
23
  const named = item.name ?? item.label ?? item.title ?? item.id ?? item.file ?? item.path ?? item.url;
22
- return typeof named === "string" || typeof named === "number" ? String(named).slice(0, 200) : undefined;
24
+ return typeof named === "string" || typeof named === "number" ? String(named) : undefined;
23
25
  };
24
26
  export async function runGraph(given) {
25
27
  const [{ graphNodeOf, nodeStatus, workflowGraph }, { readWorkflowRun }, { durableDecisions, readJournal }] = await Promise.all([
@@ -169,6 +171,8 @@ export async function runGraph(given) {
169
171
  questions: r.questions ?? null, answers: r.answers ?? null, evidence: r.evidence ?? [], rule: r.rule ?? null, action: r.action ?? null,
170
172
  cost_usd: typeof r.cost_usd === "number" ? r.cost_usd : null, cost_basis: r.cost_basis ?? null, latency_ms: r.latency_ms ?? null,
171
173
  state: r.state ?? null, state_truncated: r.state_truncated === true, error: typeof r.error === "string" ? r.error : null,
174
+ // Whole up to 64 KB (the DSL's receipt); `error_cut` marks one it kept cut, for the server to hold its tail back.
175
+ ...(r.error_truncated === true ? { error_cut: true } : {}),
172
176
  images: images.map((image) => ({ token: image.token ?? null, ref: image.ref ?? null, url: typeof image.ref === "string" ? runFile(image.ref) : null })),
173
177
  };
174
178
  });
@@ -188,7 +192,10 @@ export async function runGraph(given) {
188
192
  if (!start)
189
193
  continue;
190
194
  const effect = effects[placeOf.get(start)];
191
- Object.assign(effect, { status: line.status, output: line.output ?? null, error: line.error ?? null, endedAt: line.at });
195
+ // An error is stored whole up to 64 KB (app.ts), longer ones cut and marked; one of a log from before, cut at 2000.
196
+ // Whole, as logged (up to 64 KB, app.ts); `error_cut` marks one stored cut, for the server to hold its tail back
197
+ // (graph-served.ts, which also takes one of exactly 2000 characters, from a log made before, as cut).
198
+ Object.assign(effect, { status: line.status, output: line.output ?? null, error: line.error ?? null, ...(line.error_truncated === true ? { error_cut: true } : {}), endedAt: line.at });
192
199
  }
193
200
  }
194
201
  // The run's spend: its decisions', its llm calls' and its model nodes'; one unknown makes it unknown. An llm call's cost
@@ -3,6 +3,7 @@ import { type ToolRegistration } from "@earendil-works/pi-durable";
3
3
  import { type AgentAdapter, type SessionSpec } from "@parcha/agentrun-kernel";
4
4
  import type { DoorHook, DurableRun } from "@parcha/pi-durable-disk";
5
5
  import { type ConfineChild } from "./adapters.js";
6
+ import { type RunGate } from "./tool-gate.js";
6
7
  import { type CapGuard } from "./cap.js";
7
8
  /** The root's marker of a paid request already written as a pi.assistant entry. */
8
9
  export declare const BOOKED = "adapter.request";
@@ -34,5 +35,6 @@ export interface AdapterRun {
34
35
  * `budgetUsd`: the run's spend cap. `cancelled`: whether the run was cancelled (request-start.ts `cancelledIn`): once it
35
36
  * says so, no model request leaves, as on pi. `cwd`: the run's workspace, the directory its file tools confine to, where
36
37
  * the harness works too (the adapter's io.cwd), so a path the model builds from its working directory is one the tools
37
- * take (in a box, coding-tools.ts names it at the box's work dir). */
38
- export declare function adapterRun(make: (confine?: ConfineChild) => Promise<AgentAdapter>, harness: string, spec: Omit<SessionSpec, "tools">, context: Context, budgetUsd?: number, tools?: readonly string[], dir?: string, cap?: CapGuard, cancelled?: () => boolean, cwd?: string, coding?: readonly ToolRegistration[], stopRecord?: StopRecord): AdapterRun;
38
+ * take (in a box, coding-tools.ts names it at the box's work dir). `gate`: the run's tool gate, which each host tool
39
+ * call passes. */
40
+ export declare function adapterRun(make: (confine?: ConfineChild) => Promise<AgentAdapter>, harness: string, spec: Omit<SessionSpec, "tools">, context: Context, budgetUsd?: number, tools?: readonly string[], dir?: string, cap?: CapGuard, cancelled?: () => boolean, cwd?: string, coding?: readonly ToolRegistration[], stopRecord?: StopRecord, gate?: RunGate, extra?: readonly ToolRegistration[]): AdapterRun;
@@ -21,18 +21,25 @@
21
21
  // A message the door accepts is on the root before the door says so, and its end (sent to the session, or dropped by a
22
22
  // stop) after: one that waited for a turn's end when the process died is sent at the next open. Its end is written once
23
23
  // the session has it, so a process that dies between the two sends it again rather than never.
24
+ //
25
+ // A host tool call the tool gate parks for a person's approval (tool-gate.ts) ends its turn: no model request leaves
26
+ // after it, and the turn is interrupted once its result is in, then settled as a stopped one is, its end interrupted.
27
+ // The answer's resume is a message of its own, sent as a person's is; a turn the park ended is not resumed at the next
28
+ // open while the call still waits.
29
+ import { existsSync, writeFileSync } from "node:fs";
24
30
  import { randomUUID } from "node:crypto";
25
31
  import { AssistantEntry, ROOT_CONVERSATION_ID, ToolResultEntry, UserEntry } from "@earendil-works/pi-durable";
26
32
  import { modelPortFor, RUNNER_RECORDS } from "@parcha/agentrun-kernel";
27
33
  import { confineOf } from "./adapters.js";
28
34
  import { hostTools } from "./host-tools.js";
29
- import { CAP_REFUSED_FIELD, capToolSpend, holdsInFlight, useSpend } from "./cap.js";
35
+ import { endsTurn } from "./tool-gate.js";
36
+ import { CAP_REFUSAL_CODE, CAP_REFUSED_FIELD, capToolSpend, holdsInFlight, sideSpend, takePaidRefusal, useSpend } from "./cap.js";
30
37
  import { durableSessions } from "./sessions.js";
31
38
  import { handsParallel, planeOf } from "./tool-plane.js";
32
39
  import { parallelOf } from "./web-fetch.js";
33
40
  import { WEB_SEARCH_TOOL } from "./web-search.js";
34
41
  import { ADAPTER_API, MESSAGE, MESSAGE_END, TURN_END } from "./turn-end.js";
35
- import { REQUEST_CONTINUED, REQUEST_COST_LATE, REQUEST_COST_PENDING, REQUEST_STARTED, TOOL_COST, TOOL_STARTED } from "@parcha/pi-durable-agent/timeline";
42
+ import { originOf, REQUEST_CONTINUED, REQUEST_COST_LATE, REQUEST_COST_PENDING, REQUEST_STARTED, TOOL_COST, TOOL_STARTED } from "@parcha/pi-durable-agent/timeline";
36
43
  /** The root's marker of a paid request already written as a pi.assistant entry. */
37
44
  export const BOOKED = "adapter.request";
38
45
  /** The cost of a request whose answer was written at unknown cost, and its tokens, written once it came in: the timeline
@@ -95,8 +102,9 @@ function assistantMessage(harness, model, request, text, calls, error) {
95
102
  * `budgetUsd`: the run's spend cap. `cancelled`: whether the run was cancelled (request-start.ts `cancelledIn`): once it
96
103
  * says so, no model request leaves, as on pi. `cwd`: the run's workspace, the directory its file tools confine to, where
97
104
  * the harness works too (the adapter's io.cwd), so a path the model builds from its working directory is one the tools
98
- * take (in a box, coding-tools.ts names it at the box's work dir). */
99
- export function adapterRun(make, harness, spec, context, budgetUsd, tools = [], dir, cap, cancelled = () => false, cwd, coding, stopRecord) {
105
+ * take (in a box, coding-tools.ts names it at the box's work dir). `gate`: the run's tool gate, which each host tool
106
+ * call passes. */
107
+ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [], dir, cap, cancelled = () => false, cwd, coding, stopRecord, gate, extra = []) {
100
108
  const plane = planeOf(process.env);
101
109
  // The web tools' Parallel key, when one resolves to Parallel, read as the run's app loads, before its process starts
102
110
  // one of its own (web-fetch.ts).
@@ -111,18 +119,29 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
111
119
  // That `refused` is the cap's, not the cancel's: its error entry gets a start mark of its own first, as pi's does, so the
112
120
  // run's usage counts no request for it.
113
121
  let capRefused = false;
122
+ // A refusal for room's figures, for its start mark (cap.ts RefusalFigures).
123
+ let refusedFigures;
114
124
  const CANCELLED = "the run was cancelled: the model request was not sent";
115
125
  // What the run's paid tools charged, in earlier processes (read at the open) and this one: null once one is unknown.
116
126
  let charged = 0;
117
127
  // Each admitted request's worst case until its cost is booked: the booking's spend counts it only then.
118
128
  const inFlight = holdsInFlight();
129
+ // The run's spend as a paid tool's check reads it (useSpend, set at the open): a paid call refused under it pauses the
130
+ // run at this run's next request (guard).
131
+ let spend;
119
132
  const plus = (a, b) => (a === null || b === null ? null : a + b);
120
133
  const guard = (request) => {
121
134
  const byCancel = cancelled();
122
- const answer = byCancel ? { refuse: CANCELLED } : cap?.beforeRequest({ ...request, spentUsd: plus(request.spentUsd, charged) });
135
+ // What the run spent: the booking's, its paid tools' charges, and its own model requests' beside the harness's (a
136
+ // learned workflow's: cap.ts sideSpend); theirs in flight are held with the paid calls' (paidHolds, capBefore).
137
+ // A paid call the cap just refused for room (cap.ts takePaidRefusal): this request is refused in its words, so the
138
+ // turn ends there and the run waits on a raise, as at a model request's refusal. A refusal no cap fixes comes first.
139
+ const paid = byCancel || !cap || request.spentUsd === null ? undefined : takePaidRefusal(spend);
140
+ const answer = byCancel ? { refuse: CANCELLED } : paid ? { refuse: `${CAP_REFUSAL_CODE}${paid.words}`, spentUsd: paid.figures.spentUsd, needsUsd: paid.figures.needsUsd } : cap?.beforeRequest({ ...request, spentUsd: plus(plus(request.spentUsd, charged), sideSpend()) });
123
141
  if (answer && "refuse" in answer) {
124
142
  refused = answer.refuse;
125
143
  capRefused = !byCancel;
144
+ refusedFigures = !byCancel && "needsUsd" in answer && typeof answer.needsUsd === "number" && typeof answer.spentUsd === "number" ? { spentUsd: answer.spentUsd, needsUsd: answer.needsUsd } : undefined;
126
145
  return answer;
127
146
  }
128
147
  // Admitted, limited to the output what is left of the cap buys (which the runner hands the model proxy, and holds it
@@ -148,6 +167,12 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
148
167
  };
149
168
  // A paid request whose cost could not be written: the booking admits no request after it, and the turn stops on it.
150
169
  let halted;
170
+ // The call the gate parked, until the next message starts a turn: no request leaves meanwhile, and the turn is
171
+ // interrupted once the call's result is in. Not a failure: the turn ends as the person's answer will resume it.
172
+ let parked;
173
+ const PARKED = new Error("the turn ended: a tool call waits for a person's approval");
174
+ // Each call's arguments, by its id, for a park named by tool and arguments (endsTurn).
175
+ const argsOf = new Map();
151
176
  const results = new Map();
152
177
  let run;
153
178
  let session;
@@ -304,6 +329,7 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
304
329
  text += event.delta;
305
330
  else if (event.type === "tool_start") {
306
331
  const call = { type: "toolCall", id: event.callId, name: event.name, arguments: (event.args ?? {}) };
332
+ argsOf.set(event.callId, event.args ?? {});
307
333
  // A call of the current request's answer after that answer's entry was written (at its first call's end): written
308
334
  // now as the answer's continuation, so its result never comes before it and the next answer never holds it.
309
335
  const request = current;
@@ -324,6 +350,9 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
324
350
  data: { diagnostics: [] },
325
351
  });
326
352
  }).then(() => undefined));
353
+ // The parked call's result is in: its turn ends here, settled once the interrupt is done (runTurns).
354
+ if (endsTurn(parked, { callId: event.callId, tool: event.name, args: argsOf.get(event.callId) }) && !stopping)
355
+ stopping = session?.interrupt();
327
356
  }
328
357
  };
329
358
  /** The session's requests, from its runner records, by number: the model each asked for, and the usage of each it
@@ -349,11 +378,13 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
349
378
  };
350
379
  /** The person's message: the session's new turn, then its entry and its end on the root. */
351
380
  const sendOf = (message) => async () => {
381
+ parked = undefined;
382
+ argsOf.clear();
352
383
  await message.recorded;
353
384
  taking = message.id;
354
385
  await session.send(message.content);
355
386
  await later(() => commit(async (tx) => {
356
- await tx.appendEntry(UserEntry, ROOT_CONVERSATION_ID, { model: [{ role: "user", content: [{ type: "text", text: message.content }], timestamp: now() }] });
387
+ await tx.appendEntry(UserEntry, ROOT_CONVERSATION_ID, { model: [{ role: "user", content: [{ type: "text", text: message.content }], timestamp: now() }], ...(message.origin ? { data: { origin: message.origin } } : {}) });
357
388
  await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: MESSAGE_END, data: { key: spec.key, id: message.id, sent: true } });
358
389
  }).then(() => undefined));
359
390
  };
@@ -369,6 +400,10 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
369
400
  let failed;
370
401
  let status = "failed";
371
402
  answer = carry;
403
+ // A turn of its own: a paid call's refusal a stop left pending (its turn stopped before its next request) is
404
+ // let go, so this turn's first request is judged as any other, never paused for a call the person moved on from.
405
+ if (spend)
406
+ takePaidRefusal(spend);
372
407
  try {
373
408
  await start();
374
409
  const end = await session.turnEnd();
@@ -396,8 +431,21 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
396
431
  // its error and ends failed. The run's status is its last turn's end (turns.ts): with no message waiting, the run
397
432
  // fails on this error, as a pi run does; a message waiting behind it is still sent, and when that turn completes,
398
433
  // the run completes with its answer, this failure kept in the timeline.
399
- const why = refused ?? halted?.message ?? (failed === undefined ? undefined : `${harness}: ${failed}`);
434
+ // A turn the gate parked ends interrupted, never failed on the request its park refused.
435
+ const why = refused ?? halted?.message ?? (failed === undefined || parked !== undefined ? undefined : `${harness}: ${failed}`);
436
+ if (parked !== undefined && why === undefined)
437
+ status = "interrupted";
438
+ // A test's seam, unset in a server (AGENTRUN_SERVE_TEST_CRASH_AFTER_ANSWER, a file that marks it once): a parked
439
+ // turn holds its end until the answer's message is recorded, then the process goes by a signal, as a crash
440
+ // between the two would leave the run.
441
+ if (CRASH_SEAM && parked !== undefined && !existsSync(CRASH_SEAM)) {
442
+ await answerIn;
443
+ writeFileSync(CRASH_SEAM, "");
444
+ process.kill(process.pid, "SIGKILL");
445
+ }
400
446
  const unsent = refused !== undefined && capRefused;
447
+ const figures = unsent ? refusedFigures : undefined;
448
+ refusedFigures = undefined;
401
449
  refused = undefined;
402
450
  capRefused = false;
403
451
  const pending = open.size > 0;
@@ -409,7 +457,7 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
409
457
  if (why !== undefined) {
410
458
  // A refusal of the cap's: a start mark of its own first, as pi's is, so the run's usage counts no request for it.
411
459
  if (unsent)
412
- await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: REQUEST_STARTED, data: { [CAP_REFUSED_FIELD]: true } });
460
+ await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: REQUEST_STARTED, data: { [CAP_REFUSED_FIELD]: true, ...(figures ? { spentUsd: figures.spentUsd, needsUsd: figures.needsUsd } : {}) } });
413
461
  await tx.appendEntry(AssistantEntry, ROOT_CONVERSATION_ID, { model: [assistantMessage(harness, undefined, undefined, "", [], why)] });
414
462
  }
415
463
  const data = {
@@ -436,6 +484,24 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
436
484
  emit?.({ type: "run_end" });
437
485
  })();
438
486
  };
487
+ /** The gate's resume (tool-gate.ts): the answer as a message of its own, recorded with the gate's mark in one commit,
488
+ * then sent as a person's is. */
489
+ const CRASH_SEAM = process.env.AGENTRUN_SERVE_TEST_CRASH_AFTER_ANSWER;
490
+ let answerRecorded;
491
+ const answerIn = new Promise((resolve) => (answerRecorded = resolve));
492
+ const resume = async (id, content, mark) => {
493
+ await opened;
494
+ const message = { id: `approval-${id}`, content, recorded: commit(async (tx) => {
495
+ await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: MESSAGE, data: { key: spec.key, id: `approval-${id}`, content } });
496
+ await mark(tx);
497
+ }) };
498
+ await message.recorded;
499
+ answerRecorded?.();
500
+ if (turn)
501
+ queue.push(message);
502
+ else
503
+ runTurns(sendOf(message));
504
+ };
439
505
  const door = {
440
506
  attach(given) {
441
507
  emit = given;
@@ -449,7 +515,8 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
449
515
  return { accepted: false, reason: "busy" };
450
516
  const id = randomUUID();
451
517
  const content = textOf(input.content);
452
- const message = { id, content, recorded: commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: MESSAGE, data: { key: spec.key, id, content } }))) };
518
+ const origin = input.origin;
519
+ const message = { id, content, ...(origin ? { origin } : {}), recorded: commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: MESSAGE, data: { key: spec.key, id, content, ...(origin ? { origin } : {}) } }))) };
453
520
  if (turn)
454
521
  queue.push(message);
455
522
  else
@@ -525,7 +592,7 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
525
592
  else if (entry.kind === PRICED_LATE && typeof data.request === "number")
526
593
  priced.add(data.request);
527
594
  else if (entry.kind === MESSAGE && typeof data.id === "string")
528
- accepted.set(data.id, { id: data.id, content: String(data.content ?? ""), recorded: Promise.resolve() });
595
+ accepted.set(data.id, { id: data.id, content: String(data.content ?? ""), ...(originOf(data.origin) ? { origin: data.origin } : {}), recorded: Promise.resolve() });
529
596
  else if (entry.kind === MESSAGE_END && typeof data.id === "string") {
530
597
  accepted.delete(data.id);
531
598
  if (data.sent === true)
@@ -556,7 +623,7 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
556
623
  ...(budgetUsd !== undefined ? { budgetUsd } : {}),
557
624
  beforeRequest: guard,
558
625
  onEvent: onModel,
559
- stopped: () => halted ?? cancelStop(),
626
+ stopped: () => halted ?? cancelStop() ?? (parked === undefined ? undefined : PARKED),
560
627
  stop: (reason, message) => {
561
628
  const error = new Error(message ?? reason);
562
629
  if (reason === "model_error" && !halted) {
@@ -570,13 +637,18 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
570
637
  await booking.bookCut();
571
638
  // A paid tool's check before it spends: the session's requests, each booked once the proxy has answered (waited
572
639
  // for, as at a turn's end), one still in flight at the worst case the cap held for it (as pi's spend counts it),
573
- // with the run's charges; its charge joins them.
640
+ // with the run's charges and its own model requests' (sideSpend); its charge joins them. The run's own model
641
+ // requests read the same total at once (`now`: capModels' `joined`), a request in flight held, never less.
574
642
  if (budgetUsd !== undefined) {
575
- useSpend({
643
+ const now = () => plus(plus(plus(booking.spentUsd(), charged), sideSpend()), inFlight.total());
644
+ spend = {
576
645
  cap: budgetUsd,
577
- spent: async () => (await bookings(BOOKING_WAIT_MS), plus(plus(booking.spentUsd(), charged), inFlight.total())),
646
+ spent: async () => (await bookings(BOOKING_WAIT_MS), plus(plus(booking.spentUsd(), charged), sideSpend())),
647
+ held: () => inFlight.total(),
578
648
  add: (usd) => void (charged = plus(charged, usd)),
579
- });
649
+ now,
650
+ };
651
+ useSpend(spend);
580
652
  }
581
653
  // Each request the session booked and the root has no entry for: its cost, with no content.
582
654
  // Each request the session booked and the root does not have, or has at unknown cost only: written now, once.
@@ -584,14 +656,22 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
584
656
  if (!written.has(request) || (unpriced.has(request) && !priced.has(request)))
585
657
  costed.push({ request, usage });
586
658
  await flush();
587
- session = await adapter.open({ ...spec, tools: hostTools(durable, tools, context, results, coding) }, { writer, models: booking.models, signal: stop.signal, onEvent, ...(dir ? { dir } : {}), ...(cwd ? { cwd } : {}) });
659
+ // The calls that wait for a person's approval, read before any turn goes on.
660
+ await gate?.load(durable, context, coding, extra);
661
+ // The park every gated call of the run's takes, built once: the host tools' here, and the MCP gateway's, which takes
662
+ // the same object beside them (`{ gate, park }`). A call parked by its id or by its tool and arguments ends its turn.
663
+ const park = { commit: (change) => commit(change), parked: (callId) => void (parked = { callId }), parkedBy: (match) => void (parked = match), turn: () => taking };
664
+ session = await adapter.open({ ...spec, tools: hostTools(durable, tools, context, results, coding, gate ? { gate, park } : undefined, extra) }, { writer, models: booking.models, signal: stop.signal, onEvent, ...(dir ? { dir } : {}), ...(cwd ? { cwd } : {}) });
588
665
  // A turn the person stopped is still open in the session (an interrupt writes no end there), and it is not resumed.
589
666
  // The run's stop record names the person's newest message when they stopped: with no message on the root newer than
590
667
  // it, the open turn is the stopped one. The session settles it, ended interrupted, and the next message is a turn of
591
668
  // its own. A turn a crash or a drain cut has no stop record newer than the newest message, and is resumed as before.
592
- const stopped = stopRecord?.stopped_at !== undefined
669
+ // A turn the gate parked is settled as a stopped one: its call waits for its answer, which resumes the run. So is
670
+ // one whose parked call was answered before a process went: its request names the turn (gate.parkedIn), so the
671
+ // answer's message, queued, follows it, and the turn is never run again.
672
+ const stopped = (stopRecord?.stopped_at !== undefined
593
673
  ? lastUser !== undefined && lastUser <= placeOf(stopRecord.stopped_at)
594
- : stopRecord?.stopped_after !== undefined && stopRecord.stopped_after === users;
674
+ : stopRecord?.stopped_after !== undefined && stopRecord.stopped_after === users) || gate?.waiting() === true || gate?.parkedIn(unended?.message) === true;
595
675
  // An adapter written before settleOpenTurn has none: its stopped turn is recovered, as before.
596
676
  if (session.state === "open_turn" && stopped && typeof session.settleOpenTurn === "function")
597
677
  await session.settleOpenTurn();
@@ -615,12 +695,14 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
615
695
  await restore(restored);
616
696
  openedDone();
617
697
  // Its answer so far is the root's, which a recovery that streams no new text keeps as the turn's.
618
- if (session.state === "open_turn")
698
+ if (session.state === "open_turn" && !gate?.waiting())
619
699
  runTurns(() => session.recover(), unended?.answer ?? undefined);
620
700
  else if (queue.length) {
621
701
  const next = sendOf(queue.shift());
622
702
  runTurns(restored ? async () => (await restore(restored), await next()) : next);
623
703
  }
704
+ // The answers from now on: each resumes the session with one message of its own.
705
+ gate?.start(resume);
624
706
  },
625
707
  };
626
708
  }
@@ -0,0 +1,45 @@
1
+ import { type HostSkill } from "@parcha/agentrun-kernel";
2
+ import type { AgentAdapter } from "@parcha/agentrun-kernel";
3
+ import { type ModelProxyOptions } from "@parcha/agentrun-kernel/host";
4
+ import type { ConfineChild } from "./host/server.js";
5
+ export interface OpenCodeProvider {
6
+ /** The provider's origin (`https://api.openai.com`, or a gateway's base): the proxy forwards to its `/v1/responses` only. */
7
+ origin: string;
8
+ /** The provider key, read per request in this process. It never reaches OpenCode's process. */
9
+ credential: () => Promise<string> | string;
10
+ }
11
+ export interface OpenCodeAdapterOptions {
12
+ /** The provider's model id, or one per tier (`default` when a node names none). */
13
+ model: string | {
14
+ default: string;
15
+ fast?: string;
16
+ strong?: string;
17
+ };
18
+ provider: OpenCodeProvider;
19
+ /** Start OpenCode under the host's confinement (a `setpriv --no-new-privs` prefix, say). It may only add in front of
20
+ * the pinned binary and its arguments, and never touches its environment. */
21
+ confine?: ConfineChild;
22
+ /** The price of a response; null (or no function) records its cost as unknown. */
23
+ price?: ModelProxyOptions["price"];
24
+ /** The most output tokens one request may ask for. Default 32 000. */
25
+ maxOutputTokens?: number;
26
+ /** The model's context window. Default 272 000. */
27
+ contextWindow?: number;
28
+ /** Where sessions keep their private directories when the host lends none (`io.dir`): one per session key. */
29
+ sessionsDir?: string;
30
+ /** The host's skills, listed to the model by name and description and read with `read_skill_file`, and no others. */
31
+ skills?: readonly HostSkill[];
32
+ /** How long a drive waits for OpenCode's event stream to open, on each of its three tries. Default 10 s. */
33
+ eventConnectMs?: number;
34
+ log?: (message: string, fields?: Record<string, unknown>) => void;
35
+ /** For tests: a command that speaks `opencode serve`'s protocol instead of OpenCode (needs AGENTRUN_OPENCODE_STANDIN=1
36
+ * under a test runner). */
37
+ standIn?: {
38
+ command: string;
39
+ args?: string[];
40
+ env?: Record<string, string>;
41
+ };
42
+ /** For tests: the fetch the model proxy forwards with. */
43
+ fetch?: typeof fetch;
44
+ }
45
+ export declare function openCodeAdapter(options: OpenCodeAdapterOptions): AgentAdapter;