@parcha/agentrun-serve 0.0.0-stage → 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 (273) hide show
  1. package/CHANGELOG.md +748 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +2190 -2
  5. package/dist/adapters.d.ts +234 -0
  6. package/dist/adapters.js +585 -0
  7. package/dist/agents.d.ts +130 -0
  8. package/dist/agents.js +308 -0
  9. package/dist/app.d.ts +7 -0
  10. package/dist/app.js +384 -0
  11. package/dist/background.d.ts +28 -0
  12. package/dist/background.js +376 -0
  13. package/dist/bound-files.d.ts +4 -0
  14. package/dist/bound-files.js +164 -0
  15. package/dist/box/record.d.ts +6 -0
  16. package/dist/box/record.js +41 -0
  17. package/dist/box/sweep.d.ts +53 -0
  18. package/dist/box/sweep.js +193 -0
  19. package/dist/box-egress.d.ts +98 -0
  20. package/dist/box-egress.js +259 -0
  21. package/dist/box-image.d.ts +98 -0
  22. package/dist/box-image.js +285 -0
  23. package/dist/box-relay-vm.d.ts +80 -0
  24. package/dist/box-relay-vm.js +389 -0
  25. package/dist/box-relay.d.ts +45 -0
  26. package/dist/box-relay.js +227 -0
  27. package/dist/boxes.d.ts +72 -0
  28. package/dist/boxes.js +189 -0
  29. package/dist/browser-cost.d.ts +41 -0
  30. package/dist/browser-cost.js +158 -0
  31. package/dist/cap.d.ts +332 -0
  32. package/dist/cap.js +992 -0
  33. package/dist/catalog.d.ts +20 -0
  34. package/dist/catalog.js +53 -0
  35. package/dist/cli.d.ts +2 -0
  36. package/dist/cli.js +167 -0
  37. package/dist/coding-tools.d.ts +35 -0
  38. package/dist/coding-tools.js +87 -0
  39. package/dist/console/THIRD-PARTY-NOTICES.txt +1721 -0
  40. package/dist/console/assets/index-34jfpIbQ.js +481 -0
  41. package/dist/console/assets/index-DUHbWcIP.css +1 -0
  42. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  43. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
  44. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
  45. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
  46. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
  47. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
  48. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
  49. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
  50. package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  51. package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
  52. package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
  53. package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
  54. package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
  55. package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  56. package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  57. package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
  58. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  59. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
  60. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
  61. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
  62. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
  63. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
  64. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
  65. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
  66. package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
  67. package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
  68. package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
  69. package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
  70. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
  71. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
  72. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
  73. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
  74. package/dist/console/index.html +15 -0
  75. package/dist/content-filter.d.ts +7 -0
  76. package/dist/content-filter.js +23 -0
  77. package/dist/daytona-api.d.ts +21 -0
  78. package/dist/daytona-api.js +101 -0
  79. package/dist/decision-rows.d.ts +19 -0
  80. package/dist/decision-rows.js +123 -0
  81. package/dist/decisions.d.ts +94 -0
  82. package/dist/decisions.js +184 -0
  83. package/dist/effort-guidance.d.ts +5 -0
  84. package/dist/effort-guidance.js +14 -0
  85. package/dist/environment.d.ts +5 -0
  86. package/dist/environment.js +11 -0
  87. package/dist/errors.d.ts +74 -0
  88. package/dist/errors.js +69 -0
  89. package/dist/exa-keyless.d.ts +35 -0
  90. package/dist/exa-keyless.js +202 -0
  91. package/dist/fetch-page.d.ts +114 -0
  92. package/dist/fetch-page.js +182 -0
  93. package/dist/files.d.ts +65 -0
  94. package/dist/files.js +158 -0
  95. package/dist/grade.d.ts +93 -0
  96. package/dist/grade.js +328 -0
  97. package/dist/graph-served.d.ts +23 -0
  98. package/dist/graph-served.js +75 -0
  99. package/dist/graph-view.d.ts +102 -0
  100. package/dist/graph-view.js +219 -0
  101. package/dist/harness-app.d.ts +40 -0
  102. package/dist/harness-app.js +708 -0
  103. package/dist/harness-opencode/adapter.d.ts +45 -0
  104. package/dist/harness-opencode/adapter.js +272 -0
  105. package/dist/harness-opencode/binary.d.ts +18 -0
  106. package/dist/harness-opencode/binary.js +87 -0
  107. package/dist/harness-opencode/config.d.ts +24 -0
  108. package/dist/harness-opencode/config.js +61 -0
  109. package/dist/harness-opencode/harness.d.ts +77 -0
  110. package/dist/harness-opencode/harness.js +620 -0
  111. package/dist/harness-opencode/host/mcp.d.ts +40 -0
  112. package/dist/harness-opencode/host/mcp.js +208 -0
  113. package/dist/harness-opencode/host/policy.d.ts +71 -0
  114. package/dist/harness-opencode/host/policy.js +419 -0
  115. package/dist/harness-opencode/host/server.d.ts +55 -0
  116. package/dist/harness-opencode/host/server.js +165 -0
  117. package/dist/harness-opencode/index.d.ts +9 -0
  118. package/dist/harness-opencode/index.js +6 -0
  119. package/dist/harness-opencode/verify.d.ts +32 -0
  120. package/dist/harness-opencode/verify.js +75 -0
  121. package/dist/harness-opencode/versions.d.ts +33 -0
  122. package/dist/harness-opencode/versions.js +64 -0
  123. package/dist/harness.d.ts +56 -0
  124. package/dist/harness.js +77 -0
  125. package/dist/home-path.d.ts +27 -0
  126. package/dist/home-path.js +78 -0
  127. package/dist/host-tools.d.ts +30 -0
  128. package/dist/host-tools.js +154 -0
  129. package/dist/host.d.ts +39 -0
  130. package/dist/host.js +85 -0
  131. package/dist/hosted-search.d.ts +27 -0
  132. package/dist/hosted-search.js +133 -0
  133. package/dist/import-sources.d.ts +104 -0
  134. package/dist/import-sources.js +629 -0
  135. package/dist/import-summary.d.ts +25 -0
  136. package/dist/import-summary.js +75 -0
  137. package/dist/import-worker.d.ts +26 -0
  138. package/dist/import-worker.js +41 -0
  139. package/dist/import.d.ts +145 -0
  140. package/dist/import.js +1222 -0
  141. package/dist/index.d.ts +7 -0
  142. package/dist/index.js +6 -0
  143. package/dist/key-check.d.ts +37 -0
  144. package/dist/key-check.js +112 -0
  145. package/dist/key-refusal.d.ts +51 -0
  146. package/dist/key-refusal.js +191 -0
  147. package/dist/learn/check.d.ts +108 -0
  148. package/dist/learn/check.js +277 -0
  149. package/dist/learn/grade.d.ts +80 -0
  150. package/dist/learn/grade.js +445 -0
  151. package/dist/learn/index.d.ts +7 -0
  152. package/dist/learn/index.js +11 -0
  153. package/dist/learn/invisible.d.ts +5 -0
  154. package/dist/learn/invisible.js +42 -0
  155. package/dist/learn/notes.d.ts +59 -0
  156. package/dist/learn/notes.js +147 -0
  157. package/dist/learn/reflect.d.ts +49 -0
  158. package/dist/learn/reflect.js +213 -0
  159. package/dist/learn/secrets.d.ts +18 -0
  160. package/dist/learn/secrets.js +131 -0
  161. package/dist/learn/skills.d.ts +97 -0
  162. package/dist/learn/skills.js +271 -0
  163. package/dist/learned-workflow.d.ts +59 -0
  164. package/dist/learned-workflow.js +191 -0
  165. package/dist/learning-routes.d.ts +196 -0
  166. package/dist/learning-routes.js +609 -0
  167. package/dist/learning-run.d.ts +306 -0
  168. package/dist/learning-run.js +819 -0
  169. package/dist/learning-words.d.ts +76 -0
  170. package/dist/learning-words.js +174 -0
  171. package/dist/learning.d.ts +418 -0
  172. package/dist/learning.js +946 -0
  173. package/dist/llm.d.ts +40 -0
  174. package/dist/llm.js +37 -0
  175. package/dist/llms.txt +37 -0
  176. package/dist/mcp-servers.d.ts +118 -0
  177. package/dist/mcp-servers.js +450 -0
  178. package/dist/mcp.d.ts +51 -0
  179. package/dist/mcp.js +392 -0
  180. package/dist/model.d.ts +186 -0
  181. package/dist/model.js +485 -0
  182. package/dist/monid.d.ts +74 -0
  183. package/dist/monid.js +277 -0
  184. package/dist/openapi/agentrun-v2.openapi.json +4806 -0
  185. package/dist/openapi.d.ts +10 -0
  186. package/dist/openapi.js +1727 -0
  187. package/dist/owner.d.ts +55 -0
  188. package/dist/owner.js +222 -0
  189. package/dist/packs.d.ts +71 -0
  190. package/dist/packs.js +180 -0
  191. package/dist/page.d.ts +32 -0
  192. package/dist/page.js +133 -0
  193. package/dist/paid-calls.d.ts +50 -0
  194. package/dist/paid-calls.js +110 -0
  195. package/dist/pause.d.ts +70 -0
  196. package/dist/pause.js +97 -0
  197. package/dist/pdf-pages.d.ts +44 -0
  198. package/dist/pdf-pages.js +147 -0
  199. package/dist/place.d.ts +69 -0
  200. package/dist/place.js +137 -0
  201. package/dist/print.d.ts +20 -0
  202. package/dist/print.js +29 -0
  203. package/dist/propose.d.ts +40 -0
  204. package/dist/propose.js +112 -0
  205. package/dist/quiet-sqlite-warning.d.ts +1 -0
  206. package/dist/quiet-sqlite-warning.js +14 -0
  207. package/dist/request-start.d.ts +22 -0
  208. package/dist/request-start.js +350 -0
  209. package/dist/result.d.ts +3 -0
  210. package/dist/result.js +5 -0
  211. package/dist/rows.d.ts +46 -0
  212. package/dist/rows.js +121 -0
  213. package/dist/run-box.d.ts +186 -0
  214. package/dist/run-box.js +590 -0
  215. package/dist/run-manifest.d.ts +27 -0
  216. package/dist/run-manifest.js +60 -0
  217. package/dist/runnable.d.ts +83 -0
  218. package/dist/runnable.js +170 -0
  219. package/dist/runs.d.ts +1062 -0
  220. package/dist/runs.js +3020 -0
  221. package/dist/secret-cut.d.ts +27 -0
  222. package/dist/secret-cut.js +109 -0
  223. package/dist/secrets.d.ts +62 -0
  224. package/dist/secrets.js +158 -0
  225. package/dist/server-lock.d.ts +44 -0
  226. package/dist/server-lock.js +140 -0
  227. package/dist/server.d.ts +722 -0
  228. package/dist/server.js +2118 -0
  229. package/dist/sessions.d.ts +4 -0
  230. package/dist/sessions.js +105 -0
  231. package/dist/sign-ins.d.ts +99 -0
  232. package/dist/sign-ins.js +288 -0
  233. package/dist/skills.d.ts +43 -0
  234. package/dist/skills.js +96 -0
  235. package/dist/stats.d.ts +106 -0
  236. package/dist/stats.js +103 -0
  237. package/dist/tool-gate.d.ts +266 -0
  238. package/dist/tool-gate.js +554 -0
  239. package/dist/tool-keys.d.ts +187 -0
  240. package/dist/tool-keys.js +315 -0
  241. package/dist/tool-plane.d.ts +228 -0
  242. package/dist/tool-plane.js +400 -0
  243. package/dist/tools.d.ts +202 -0
  244. package/dist/tools.js +372 -0
  245. package/dist/trigger-secrets.d.ts +32 -0
  246. package/dist/trigger-secrets.js +143 -0
  247. package/dist/triggers.d.ts +439 -0
  248. package/dist/triggers.js +863 -0
  249. package/dist/turn-end.d.ts +24 -0
  250. package/dist/turn-end.js +15 -0
  251. package/dist/turns.d.ts +34 -0
  252. package/dist/turns.js +202 -0
  253. package/dist/uploads.d.ts +104 -0
  254. package/dist/uploads.js +474 -0
  255. package/dist/usage-lines.d.ts +26 -0
  256. package/dist/usage-lines.js +28 -0
  257. package/dist/usage.d.ts +29 -0
  258. package/dist/usage.js +58 -0
  259. package/dist/validate.d.ts +57 -0
  260. package/dist/validate.js +184 -0
  261. package/dist/web-fetch.d.ts +64 -0
  262. package/dist/web-fetch.js +262 -0
  263. package/dist/web-search.d.ts +54 -0
  264. package/dist/web-search.js +136 -0
  265. package/dist/webhooks.d.ts +189 -0
  266. package/dist/webhooks.js +503 -0
  267. package/dist/workspace-paths.d.ts +33 -0
  268. package/dist/workspace-paths.js +104 -0
  269. package/dist/workspace.d.ts +88 -0
  270. package/dist/workspace.js +369 -0
  271. package/launcher/agentrun-serve +109 -0
  272. package/package.json +100 -4
  273. package/skills/agentrun-serve/SKILL.md +128 -0
@@ -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
+ }
@@ -0,0 +1,102 @@
1
+ export type GraphNodeStatus = "pending" | "working" | "done" | "failed" | "stopped" | "escalated" | "not_run" | "needs_review";
2
+ type Item = {
3
+ index: number;
4
+ status: GraphNodeStatus;
5
+ executionPath: string;
6
+ label?: string;
7
+ branches?: Record<string, string>;
8
+ };
9
+ type NodeView = {
10
+ status: GraphNodeStatus;
11
+ startedAt?: string;
12
+ endedAt?: string;
13
+ branch?: string;
14
+ items?: Item[];
15
+ };
16
+ export type GraphInput = {
17
+ run: {
18
+ id: string;
19
+ agent: string;
20
+ revision: string;
21
+ status: string;
22
+ paused: boolean;
23
+ startedAt: string;
24
+ endedAt: string | null;
25
+ };
26
+ /** The run has ended: a node it never reached is `not_run`, not `pending`, and its store is read. */
27
+ ended: boolean;
28
+ /** Read the live view even though the run ended: its store was busy. */
29
+ liveOnly?: boolean;
30
+ workflow: unknown;
31
+ storeFile: string;
32
+ /** The run's directory: its node log is there. */
33
+ root: string;
34
+ /** The run's input: what a map's items are read from before its state has them. */
35
+ input: unknown;
36
+ /** The model nodes' cost from the run's rows (read once it ended; 0 before), null when unknown. */
37
+ modelCost: number | null;
38
+ /** How many of its llm calls' answers its node log held when its rows were last read: their cost is in `modelCost`. */
39
+ llmRead?: number;
40
+ };
41
+ export declare function runGraph(given: GraphInput): Promise<{
42
+ read_at: string;
43
+ run: {
44
+ id: string;
45
+ agent: string;
46
+ revision: string;
47
+ status: string;
48
+ paused: boolean;
49
+ startedAt: string;
50
+ endedAt: string | null;
51
+ };
52
+ workflow: unknown;
53
+ graph: import("@parcha/agentrun-dsl/graph").WorkflowGraph;
54
+ nodes: Record<string, NodeView>;
55
+ decisions: {
56
+ images: {
57
+ token: {} | null;
58
+ ref: {} | null;
59
+ url: string | null;
60
+ }[];
61
+ error_cut?: boolean | undefined;
62
+ id: {} | null;
63
+ node: string | null;
64
+ executionPath: {} | null;
65
+ item: {} | null;
66
+ kind: {} | null;
67
+ provider: {} | null;
68
+ model: {} | null;
69
+ status: {} | null;
70
+ questions: {} | null;
71
+ answers: {} | null;
72
+ evidence: {};
73
+ rule: {} | null;
74
+ action: {} | null;
75
+ cost_usd: number | null;
76
+ cost_basis: {} | null;
77
+ latency_ms: {} | null;
78
+ state: {} | null;
79
+ state_truncated: boolean;
80
+ error: string | null;
81
+ }[];
82
+ effects: {
83
+ node: string | null;
84
+ executionPath: string | null;
85
+ item: number | null;
86
+ tool: string;
87
+ status: string;
88
+ input: unknown;
89
+ output: unknown;
90
+ error: string | null;
91
+ error_cut?: boolean;
92
+ startedAt: string;
93
+ endedAt: string | null;
94
+ }[];
95
+ totals: {
96
+ cost_usd: number | null;
97
+ decisions: number;
98
+ effects: number;
99
+ elapsed_ms: number | null;
100
+ };
101
+ }>;
102
+ export {};
@@ -0,0 +1,219 @@
1
+ // GET /v2/runs/{id}/graph: a workflow run drawn from what it has written so far. The graph is the DSL's `workflowGraph`
2
+ // of the revision's workflow; each node's state is `nodeStatus` over the journal's frame (and, once the run ended,
3
+ // `readWorkflowRun`'s, with the task's end); a map's items, a route's branch taken and the interrupted decisions come
4
+ // from the frame; the decisions are the receipts, each joined to its graph node by its execution path (`graphNodeOf`);
5
+ // the calls and the nodes' times are the run process's node log (pause.ts).
6
+ //
7
+ // Where the frame and the receipts come from: while the run goes its process holds its store exclusively, so they are
8
+ // the process's live view (pause.ts `live.json`), and the store is never opened (an open racing the process's own would
9
+ // fail it). Once the run ended, the store.
10
+ import { llmAnswers, readLiveView, readNodeLog } from "./pause.js";
11
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
12
+ const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
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. */
16
+ const labelOf = (item) => {
17
+ if (typeof item === "string")
18
+ return item;
19
+ if (typeof item === "number")
20
+ return String(item);
21
+ if (!isObject(item))
22
+ return undefined;
23
+ const named = item.name ?? item.label ?? item.title ?? item.id ?? item.file ?? item.path ?? item.url;
24
+ return typeof named === "string" || typeof named === "number" ? String(named) : undefined;
25
+ };
26
+ export async function runGraph(given) {
27
+ const [{ graphNodeOf, nodeStatus, workflowGraph }, { readWorkflowRun }, { durableDecisions, readJournal }] = await Promise.all([
28
+ import("@parcha/agentrun-dsl/graph"),
29
+ import("@parcha/pi-durable-agent/workflow"),
30
+ import("@parcha/agentrun-pi/durable"),
31
+ ]);
32
+ const { id } = given.run;
33
+ const graph = workflowGraph(given.workflow);
34
+ let view;
35
+ let pin;
36
+ let receipts;
37
+ let readAt = new Date().toISOString();
38
+ if (given.ended && !given.liveOnly) {
39
+ view = await readWorkflowRun({ runId: id, storePath: given.storeFile, revision: { body: { workflow: given.workflow } } });
40
+ pin = (readJournal(given.storeFile, id)?.state?.pin) ?? {};
41
+ receipts = durableDecisions(given.storeFile);
42
+ }
43
+ else {
44
+ const live = await readLiveView(given.root);
45
+ pin = live?.pin ?? {};
46
+ receipts = live?.receipts ?? [];
47
+ if (live?.at)
48
+ readAt = live.at;
49
+ view = { status: nodeStatus(graph, { pin: pin, result: null }) };
50
+ }
51
+ const lines = await readNodeLog(given.root);
52
+ const nodeAt = (path) => (typeof path === "string" ? (graphNodeOf(graph, path)?.path ?? (graph.nodes.some((n) => n.path === path) ? path : undefined)) : undefined);
53
+ const kinds = new Map(graph.nodes.map((node) => [node.path, node.kind]));
54
+ // Each node's state, `not-run` read as pending until the run ends.
55
+ const nodes = {};
56
+ for (const node of graph.nodes) {
57
+ const state = view.status[node.path] ?? "not-run";
58
+ nodes[node.path] = { status: state === "not-run" ? (given.ended ? "not_run" : "pending") : state };
59
+ }
60
+ // A decision a later process found asked and never answered goes to review, never asked again.
61
+ const interrupted = new Set();
62
+ for (const [where, requests] of Object.entries(pin.decisions ?? {})) {
63
+ if (isObject(requests) && Object.values(requests).some((r) => isObject(r) && r.status === "interrupted"))
64
+ interrupted.add(where);
65
+ }
66
+ for (const where of interrupted) {
67
+ const path = nodeAt(where);
68
+ if (path && nodes[path])
69
+ nodes[path].status = "needs_review";
70
+ }
71
+ if (view.escalation?.kind === "decision_interrupted" && view.escalatedAt && nodes[view.escalatedAt.path])
72
+ nodes[view.escalatedAt.path].status = "needs_review";
73
+ // Times: a node's first start and, once it ended, its last end, over all its instances; a container's from what is in it.
74
+ const starts = new Map();
75
+ const ends = new Map();
76
+ for (const line of lines) {
77
+ if (line.t !== "node.start" && line.t !== "node.end")
78
+ continue;
79
+ const path = nodeAt(line.path);
80
+ if (!path)
81
+ continue;
82
+ if (line.t === "node.start" && (!starts.has(path) || line.at < starts.get(path)))
83
+ starts.set(path, line.at);
84
+ if (line.t === "node.end" && (!ends.has(path) || line.at > ends.get(path)))
85
+ ends.set(path, line.at);
86
+ }
87
+ for (const node of graph.nodes) {
88
+ const own = nodes[node.path];
89
+ const inside = [...starts.keys()].filter((path) => path === node.path || path.startsWith(`${node.path}/`));
90
+ const first = inside.map((path) => starts.get(path)).sort()[0];
91
+ const last = [...ends.entries()].filter(([path]) => path === node.path || path.startsWith(`${node.path}/`)).map(([, when]) => when).sort().at(-1);
92
+ if (first)
93
+ own.startedAt = first;
94
+ if (last && ["done", "failed", "escalated", "stopped", "needs_review"].includes(own.status))
95
+ own.endedAt = last;
96
+ }
97
+ // A route's branch taken: its committed decision, else the branch whose body ran (a route by value).
98
+ for (const node of graph.nodes.filter((n) => n.kind === "route")) {
99
+ const decided = Object.entries(pin.routes ?? {}).filter(([where]) => nodeAt(where) === node.path);
100
+ const top = decided.find(([where]) => where === node.path) ?? decided.at(-1);
101
+ if (top?.[1]?.branch)
102
+ nodes[node.path].branch = top[1].branch;
103
+ else {
104
+ const prefix = `${node.path}/branches/`;
105
+ const ran = graph.nodes.find((n) => n.path.startsWith(prefix) && n.path.endsWith("/body") && n.path.split("/").length === prefix.split("/").length + 1 && !["pending", "not_run"].includes(nodes[n.path].status));
106
+ if (ran)
107
+ nodes[node.path].branch = ran.path.slice(prefix.length, -"/body".length).replace(/~1/g, "/").replace(/~0/g, "~");
108
+ }
109
+ }
110
+ // A map's items, for a map that runs once (not inside another map or loop): one cell per item of its list.
111
+ const workflow = given.workflow;
112
+ const definition = (path) => path.split("/").slice(1).reduce((value, part) => (typeof value === "object" && value !== null ? value[part.replace(/~1/g, "/").replace(/~0/g, "~")] : undefined), workflow);
113
+ const keys = [...(pin.done ?? []), ...Object.keys(pin.states ?? {}), ...Object.keys(pin.inputs ?? {}), ...Object.keys(pin.steps ?? {}), ...Object.keys(pin.failures ?? {}), ...Object.keys(pin.decisions ?? {}), ...Object.keys(pin.routes ?? {}),
114
+ ...lines.flatMap((line) => (typeof line.path === "string" ? [line.path] : [])), ...receipts.map((r) => String(r.execution_path ?? ""))];
115
+ const done = new Set(pin.done ?? []);
116
+ // The run's real input first: a map over an input list has its whole list, in order, from the start.
117
+ const candidates = [given.input, ...Object.values(pin.states ?? {})];
118
+ for (const node of graph.nodes.filter((n) => n.kind === "map" && graphNodeOf(graph, n.path)?.at.length === 0)) {
119
+ const map = node.path;
120
+ const own = nodes[map];
121
+ const def = definition(map);
122
+ const list = typeof def?.itemsPath === "string" ? candidates.map((state) => at(state, def.itemsPath)).find(Array.isArray) : undefined;
123
+ const seen = new Set();
124
+ const pattern = new RegExp(`^${escape(map)}/items/(\\d+)(?:/|$)`);
125
+ for (const key of keys) {
126
+ const index = pattern.exec(key)?.[1];
127
+ if (index !== undefined)
128
+ seen.add(Number(index));
129
+ }
130
+ const count = Math.max(list?.length ?? 0, seen.size ? Math.max(...seen) + 1 : 0);
131
+ const body = `${map}/body`;
132
+ const steps = kinds.get(body) === "chain" ? graph.nodes.filter((n) => n.path.startsWith(`${body}/steps/`) && /^\d+$/.test(n.path.slice(`${body}/steps/`.length))).map((n) => n.path.slice(body.length)) : [""];
133
+ const items = [];
134
+ const routesIn = graph.nodes.filter((n) => n.kind === "route" && n.path.startsWith(`${body}/`) || n.kind === "route" && n.path === body).map((n) => n.path);
135
+ for (let index = 0; index < count; index++) {
136
+ const exec = `${map}/items/${index}`;
137
+ const inside = (key) => key === exec || key.startsWith(`${exec}/`);
138
+ let status;
139
+ if (pin.failures && Object.hasOwn(pin.failures, exec))
140
+ status = "failed";
141
+ else if ([...interrupted].some(inside))
142
+ status = "needs_review";
143
+ else if (own.status === "done" || steps.every((step) => done.has(`${exec}/body${step}`)) || isObject(pin.states) && (Object.hasOwn(pin.states, exec) || Object.hasOwn(pin.states, `${exec}/body`)))
144
+ status = "done";
145
+ else if (Object.values(pin.steps ?? {}).some((step, i) => isObject(step) && step.status === "failed" && inside(Object.keys(pin.steps)[i])))
146
+ status = "failed";
147
+ else if (seen.has(index))
148
+ status = given.ended ? (own.status === "failed" ? "failed" : own.status === "escalated" ? "escalated" : "stopped") : "working";
149
+ else
150
+ status = given.ended ? "not_run" : "pending";
151
+ const label = labelOf(list?.[index]);
152
+ // Each route in the body that ran for this item, and its branch: the committed decision, else the branch that ran.
153
+ const branches = {};
154
+ for (const route of routesIn) {
155
+ const at = `${exec}/body${route.slice(body.length)}`;
156
+ const decided = pin.routes?.[at]?.branch;
157
+ const ran = decided ?? keys.map((key) => (key.startsWith(`${at}/branches/`) ? key.slice(at.length + "/branches/".length).split("/")[0] : undefined)).find((name) => name !== undefined);
158
+ if (ran)
159
+ branches[route] = ran.replace(/~1/g, "/").replace(/~0/g, "~");
160
+ }
161
+ items.push({ index, status, executionPath: exec, ...(label !== undefined ? { label } : {}), ...(Object.keys(branches).length ? { branches } : {}) });
162
+ }
163
+ own.items = items;
164
+ }
165
+ const runFile = (ref) => `/v2/runs/${encodeURIComponent(id)}/files/${ref.split("/").map(encodeURIComponent).join("/")}`;
166
+ const decisions = receipts.map((r) => {
167
+ const images = Array.isArray(r.images) ? r.images : [];
168
+ return {
169
+ id: r.decision_id ?? r.id ?? null, node: nodeAt(r.execution_path) ?? null, executionPath: r.execution_path ?? null, item: r.item ?? null, kind: r.kind ?? null,
170
+ provider: r.provider ?? null, model: r.model ?? null, status: r.status ?? null,
171
+ questions: r.questions ?? null, answers: r.answers ?? null, evidence: r.evidence ?? [], rule: r.rule ?? null, action: r.action ?? null,
172
+ cost_usd: typeof r.cost_usd === "number" ? r.cost_usd : null, cost_basis: r.cost_basis ?? null, latency_ms: r.latency_ms ?? null,
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 } : {}),
176
+ images: images.map((image) => ({ token: image.token ?? null, ref: image.ref ?? null, url: typeof image.ref === "string" ? runFile(image.ref) : null })),
177
+ };
178
+ });
179
+ // The calls, each start paired with its end in order.
180
+ const open = new Map();
181
+ const effects = [];
182
+ const placeOf = new Map();
183
+ for (const line of lines) {
184
+ if (line.t === "effect.start") {
185
+ const key = `${line.path}\n${line.tool}\n${line.label}`;
186
+ (open.get(key) ?? open.set(key, []).get(key)).push(line);
187
+ placeOf.set(line, effects.length);
188
+ effects.push({ node: nodeAt(line.path) ?? null, executionPath: line.path, item: line.item, tool: line.tool, status: given.ended ? "stopped" : "working", input: line.input, output: null, error: null, startedAt: line.at, endedAt: null });
189
+ }
190
+ else if (line.t === "effect.end") {
191
+ const start = open.get(`${line.path}\n${line.tool}\n${line.label}`)?.shift();
192
+ if (!start)
193
+ continue;
194
+ const effect = effects[placeOf.get(start)];
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 });
199
+ }
200
+ }
201
+ // The run's spend: its decisions', its llm calls' and its model nodes'; one unknown makes it unknown. An llm call's cost
202
+ // is a REQUEST_COST entry, in `modelCost` once the run's rows hold it: the first `llmRead` answers of the node log (an
203
+ // answer is logged after its cost is committed). Only the later ones are counted from the node log.
204
+ const calls = llmAnswers(lines).slice(given.llmRead ?? 0).map((line) => (isObject(line.output) && typeof line.output.cost_usd === "number" ? line.output.cost_usd : null));
205
+ const costs = [...decisions.map((d) => d.cost_usd), ...calls, given.modelCost];
206
+ const cost = costs.some((c) => c === null) ? null : Math.round(costs.reduce((a, b) => a + b, 0) * 1e8) / 1e8;
207
+ const startedMs = Date.parse(given.run.startedAt);
208
+ const endMs = given.run.endedAt ? Date.parse(given.run.endedAt) : Date.now();
209
+ return {
210
+ read_at: readAt,
211
+ run: given.run,
212
+ workflow: given.workflow,
213
+ graph,
214
+ nodes,
215
+ decisions,
216
+ effects,
217
+ totals: { cost_usd: cost, decisions: decisions.length, effects: effects.length, elapsed_ms: Number.isFinite(startedMs) ? Math.max(0, endMs - startedMs) : null },
218
+ };
219
+ }
@@ -0,0 +1,40 @@
1
+ import type { Context } from "@earendil-works/chord";
2
+ import { type ToolRegistration } from "@earendil-works/pi-durable";
3
+ import { type AgentAdapter, type SessionSpec } from "@parcha/agentrun-kernel";
4
+ import type { DoorHook, DurableRun } from "@parcha/pi-durable-disk";
5
+ import { type ConfineChild } from "./adapters.js";
6
+ import { type RunGate } from "./tool-gate.js";
7
+ import { type CapGuard } from "./cap.js";
8
+ /** The root's marker of a paid request already written as a pi.assistant entry. */
9
+ export declare const BOOKED = "adapter.request";
10
+ /** The cost of a request whose answer was written at unknown cost, and its tokens, written once it came in: the timeline
11
+ * adds it to the run's cost without counting a request, and a later open reads it as that request's cost being in. */
12
+ export declare const PRICED_LATE = "agentrun.request_cost_late";
13
+ /** How long a turn's end waits for its requests' costs, booked once the proxy has answered the harness. */
14
+ export declare const BOOKING_WAIT_MS = 2000;
15
+ /** The root's record of a message the door accepted, and of its end: `sent` to the session, or dropped by a stop. */
16
+ export { MESSAGE, MESSAGE_END } from "./turn-end.js";
17
+ /** A turn's end on the root (turn-end.ts): the message it took, the session's own outcome (`completed`, `interrupted`,
18
+ * `failed`) and the turn's answer, in the commit of the turn's last entries (its answer, its costs, any error). The only
19
+ * record that a turn which took the person's message is over: a request without content is written alike whether it
20
+ * ended the turn or not. */
21
+ export { TURN_END } from "./turn-end.js";
22
+ /** The run's stop record as serve keeps it (serve.json, runs.ts stopTurn, saved before the stop's abort): the person's
23
+ * newest message when they stopped the turn, by its row id (`<conversation>:<entry>`), or, from an older server, how many
24
+ * messages they had sent then. */
25
+ export type StopRecord = {
26
+ stopped_at?: string;
27
+ stopped_after?: number;
28
+ };
29
+ export interface AdapterRun {
30
+ readonly door: DoorHook;
31
+ onOpen(run: DurableRun): Promise<void>;
32
+ }
33
+ /** The door and the open of a run whose session is `spec` on `adapter`, with the host tools `tools` names (built at the
34
+ * open, over the run's environment; its coding tools from `coding`, the run's coding source, host-tools.ts).
35
+ * `budgetUsd`: the run's spend cap. `cancelled`: whether the run was cancelled (request-start.ts `cancelledIn`): once it
36
+ * says so, no model request leaves, as on pi. `cwd`: the run's workspace, the directory its file tools confine to, where
37
+ * the harness works too (the adapter's io.cwd), so a path the model builds from its working directory is one the tools
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;