@parcha/agentrun-serve 0.0.0-bootstrap.0 → 0.1.0-beta.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (229) hide show
  1. package/CHANGELOG.md +560 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +1724 -0
  5. package/dist/adapters.d.ts +205 -0
  6. package/dist/adapters.js +459 -0
  7. package/dist/agents.d.ts +124 -0
  8. package/dist/agents.js +302 -0
  9. package/dist/app.d.ts +7 -0
  10. package/dist/app.js +324 -0
  11. package/dist/bound-files.d.ts +4 -0
  12. package/dist/bound-files.js +164 -0
  13. package/dist/box/record.d.ts +6 -0
  14. package/dist/box/record.js +41 -0
  15. package/dist/box/sweep.d.ts +53 -0
  16. package/dist/box/sweep.js +193 -0
  17. package/dist/box-image.d.ts +98 -0
  18. package/dist/box-image.js +283 -0
  19. package/dist/box-relay.d.ts +42 -0
  20. package/dist/box-relay.js +222 -0
  21. package/dist/boxes.d.ts +54 -0
  22. package/dist/boxes.js +182 -0
  23. package/dist/cap.d.ts +224 -0
  24. package/dist/cap.js +721 -0
  25. package/dist/catalog.d.ts +20 -0
  26. package/dist/catalog.js +53 -0
  27. package/dist/cli.d.ts +2 -0
  28. package/dist/cli.js +167 -0
  29. package/dist/coding-tools.d.ts +31 -0
  30. package/dist/coding-tools.js +81 -0
  31. package/dist/console/THIRD-PARTY-NOTICES.txt +1141 -0
  32. package/dist/console/assets/index-BN7oVcO4.js +445 -0
  33. package/dist/console/assets/index-By-jkqki.css +1 -0
  34. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  35. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
  36. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
  37. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
  38. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
  39. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
  40. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
  41. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
  42. package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  43. package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
  44. package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
  45. package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
  46. package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
  47. package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  48. package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  49. package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
  50. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  51. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
  52. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
  53. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
  54. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
  55. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
  56. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
  57. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
  58. package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
  59. package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
  60. package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
  61. package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
  62. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
  63. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
  64. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
  65. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
  66. package/dist/console/index.html +15 -0
  67. package/dist/daytona-api.d.ts +21 -0
  68. package/dist/daytona-api.js +101 -0
  69. package/dist/decision-rows.d.ts +11 -0
  70. package/dist/decision-rows.js +116 -0
  71. package/dist/decisions.d.ts +94 -0
  72. package/dist/decisions.js +184 -0
  73. package/dist/effort-guidance.d.ts +5 -0
  74. package/dist/effort-guidance.js +14 -0
  75. package/dist/environment.d.ts +5 -0
  76. package/dist/environment.js +11 -0
  77. package/dist/errors.d.ts +72 -0
  78. package/dist/errors.js +66 -0
  79. package/dist/exa-keyless.d.ts +35 -0
  80. package/dist/exa-keyless.js +202 -0
  81. package/dist/fetch-page.d.ts +114 -0
  82. package/dist/fetch-page.js +182 -0
  83. package/dist/files.d.ts +60 -0
  84. package/dist/files.js +153 -0
  85. package/dist/grade.d.ts +96 -0
  86. package/dist/grade.js +348 -0
  87. package/dist/graph-view.d.ts +100 -0
  88. package/dist/graph-view.js +212 -0
  89. package/dist/harness-app.d.ts +38 -0
  90. package/dist/harness-app.js +626 -0
  91. package/dist/harness.d.ts +53 -0
  92. package/dist/harness.js +74 -0
  93. package/dist/home-path.d.ts +27 -0
  94. package/dist/home-path.js +78 -0
  95. package/dist/host-tools.d.ts +20 -0
  96. package/dist/host-tools.js +140 -0
  97. package/dist/host.d.ts +39 -0
  98. package/dist/host.js +81 -0
  99. package/dist/hosted-search.d.ts +27 -0
  100. package/dist/hosted-search.js +129 -0
  101. package/dist/import-sources.d.ts +104 -0
  102. package/dist/import-sources.js +629 -0
  103. package/dist/import-summary.d.ts +25 -0
  104. package/dist/import-summary.js +75 -0
  105. package/dist/import-worker.d.ts +26 -0
  106. package/dist/import-worker.js +41 -0
  107. package/dist/import.d.ts +145 -0
  108. package/dist/import.js +1221 -0
  109. package/dist/index.d.ts +7 -0
  110. package/dist/index.js +6 -0
  111. package/dist/key-check.d.ts +36 -0
  112. package/dist/key-check.js +108 -0
  113. package/dist/key-refusal.d.ts +51 -0
  114. package/dist/key-refusal.js +187 -0
  115. package/dist/learn/check.d.ts +99 -0
  116. package/dist/learn/check.js +259 -0
  117. package/dist/learn/grade.d.ts +79 -0
  118. package/dist/learn/grade.js +433 -0
  119. package/dist/learn/index.d.ts +7 -0
  120. package/dist/learn/index.js +11 -0
  121. package/dist/learn/invisible.d.ts +5 -0
  122. package/dist/learn/invisible.js +42 -0
  123. package/dist/learn/notes.d.ts +59 -0
  124. package/dist/learn/notes.js +146 -0
  125. package/dist/learn/reflect.d.ts +49 -0
  126. package/dist/learn/reflect.js +167 -0
  127. package/dist/learn/secrets.d.ts +18 -0
  128. package/dist/learn/secrets.js +111 -0
  129. package/dist/learn/skills.d.ts +84 -0
  130. package/dist/learn/skills.js +198 -0
  131. package/dist/learning-routes.d.ts +196 -0
  132. package/dist/learning-routes.js +609 -0
  133. package/dist/learning-run.d.ts +304 -0
  134. package/dist/learning-run.js +797 -0
  135. package/dist/learning-words.d.ts +73 -0
  136. package/dist/learning-words.js +171 -0
  137. package/dist/learning.d.ts +377 -0
  138. package/dist/learning.js +801 -0
  139. package/dist/llm.d.ts +40 -0
  140. package/dist/llm.js +37 -0
  141. package/dist/llms.txt +37 -0
  142. package/dist/mcp-servers.d.ts +115 -0
  143. package/dist/mcp-servers.js +445 -0
  144. package/dist/mcp.d.ts +51 -0
  145. package/dist/mcp.js +392 -0
  146. package/dist/model.d.ts +184 -0
  147. package/dist/model.js +484 -0
  148. package/dist/monid.d.ts +74 -0
  149. package/dist/monid.js +277 -0
  150. package/dist/openapi/agentrun-v2.openapi.json +4805 -0
  151. package/dist/openapi.d.ts +10 -0
  152. package/dist/openapi.js +1417 -0
  153. package/dist/owner.d.ts +55 -0
  154. package/dist/owner.js +222 -0
  155. package/dist/packs.d.ts +71 -0
  156. package/dist/packs.js +180 -0
  157. package/dist/page.d.ts +32 -0
  158. package/dist/page.js +133 -0
  159. package/dist/paid-calls.d.ts +46 -0
  160. package/dist/paid-calls.js +110 -0
  161. package/dist/pause.d.ts +68 -0
  162. package/dist/pause.js +97 -0
  163. package/dist/pdf-pages.d.ts +44 -0
  164. package/dist/pdf-pages.js +147 -0
  165. package/dist/place.d.ts +46 -0
  166. package/dist/place.js +105 -0
  167. package/dist/print.d.ts +20 -0
  168. package/dist/print.js +29 -0
  169. package/dist/propose.d.ts +38 -0
  170. package/dist/propose.js +82 -0
  171. package/dist/quiet-sqlite-warning.d.ts +1 -0
  172. package/dist/quiet-sqlite-warning.js +14 -0
  173. package/dist/request-start.d.ts +14 -0
  174. package/dist/request-start.js +226 -0
  175. package/dist/result.d.ts +3 -0
  176. package/dist/result.js +5 -0
  177. package/dist/rows.d.ts +46 -0
  178. package/dist/rows.js +121 -0
  179. package/dist/run-box.d.ts +134 -0
  180. package/dist/run-box.js +440 -0
  181. package/dist/run-manifest.d.ts +27 -0
  182. package/dist/run-manifest.js +60 -0
  183. package/dist/runnable.d.ts +80 -0
  184. package/dist/runnable.js +162 -0
  185. package/dist/runs.d.ts +840 -0
  186. package/dist/runs.js +2279 -0
  187. package/dist/secret-cut.d.ts +27 -0
  188. package/dist/secret-cut.js +109 -0
  189. package/dist/secrets.d.ts +50 -0
  190. package/dist/secrets.js +140 -0
  191. package/dist/server-lock.d.ts +44 -0
  192. package/dist/server-lock.js +140 -0
  193. package/dist/server.d.ts +626 -0
  194. package/dist/server.js +1756 -0
  195. package/dist/sessions.d.ts +4 -0
  196. package/dist/sessions.js +105 -0
  197. package/dist/skills.d.ts +31 -0
  198. package/dist/skills.js +68 -0
  199. package/dist/stats.d.ts +101 -0
  200. package/dist/stats.js +82 -0
  201. package/dist/tool-keys.d.ts +151 -0
  202. package/dist/tool-keys.js +273 -0
  203. package/dist/tool-plane.d.ts +143 -0
  204. package/dist/tool-plane.js +242 -0
  205. package/dist/tools.d.ts +147 -0
  206. package/dist/tools.js +253 -0
  207. package/dist/turn-end.d.ts +23 -0
  208. package/dist/turn-end.js +14 -0
  209. package/dist/turns.d.ts +34 -0
  210. package/dist/turns.js +202 -0
  211. package/dist/uploads.d.ts +104 -0
  212. package/dist/uploads.js +474 -0
  213. package/dist/usage.d.ts +29 -0
  214. package/dist/usage.js +58 -0
  215. package/dist/validate.d.ts +55 -0
  216. package/dist/validate.js +175 -0
  217. package/dist/web-fetch.d.ts +64 -0
  218. package/dist/web-fetch.js +262 -0
  219. package/dist/web-search.d.ts +54 -0
  220. package/dist/web-search.js +136 -0
  221. package/dist/webhooks.d.ts +182 -0
  222. package/dist/webhooks.js +487 -0
  223. package/dist/workspace-paths.d.ts +33 -0
  224. package/dist/workspace-paths.js +104 -0
  225. package/dist/workspace.d.ts +88 -0
  226. package/dist/workspace.js +369 -0
  227. package/launcher/agentrun-serve +109 -0
  228. package/package.json +96 -1
  229. package/skills/agentrun-serve/SKILL.md +128 -0
package/dist/grade.js ADDED
@@ -0,0 +1,348 @@
1
+ // Learning, its grade and its merge: once a run's proposal passed the checks (propose.ts), one grader decides whether its
2
+ // new notes, and its skill and workflow draft, join the agent's main, and the host merges them.
3
+ // - The grader is learn/grade.ts' gradePrompt, asked as one bounded completion against main as it is now: each active
4
+ // note's index line, the whole text only of the notes the proposal supersedes, and what the user said in the run, so
5
+ // the prompt is bounded whatever the folder holds (GRADE_CAPS). It runs on the model the server names for grading
6
+ // (learning.ts gradeModelOf: `--grade-model`, else its strong tier), else on the agent's own. Its answer is read by parseVerdict,
7
+ // which fails closed. A
8
+ // call cut off at its bound spent what nobody knows: the grade's cost is then unknown, never $0. Before it, and only
9
+ // when this server has an independent judge (Jev), each new note goes through the injection screen: pi-browser's page
10
+ // classifier with its own INJECTION_THRESHOLD. A score at or over it refuses the proposal, and no score refuses it too.
11
+ // - The merge is one host commit on main, made with plumbing on a temporary index: the new notes added, each note one of
12
+ // them supersedes marked, the skill's and draft's files added or changed (one the grader held, marked pending), and
13
+ // MEMORY.md rebuilt (buildIndex). Its message is `learning: <run id>: merged`, the verdict's
14
+ // reason and a `Run-Id` trailer, and main moves only from the commit it was made on (compare and swap), once more on a
15
+ // main that moved meanwhile. A run a commit on main already names is merged, never twice. The merge's own questions
16
+ // (learn/check.ts mergeProblems) are asked again of main as it is then, and each note superseded must still be the
17
+ // blob the grade read: one a person changed since is theirs, and nothing merges. The checked-out files are brought in
18
+ // line.
19
+ // The merge runs in the agent's queue; the screen and the grader never do, so no run's seed waits on a model.
20
+ import { rm } from "node:fs/promises";
21
+ import { join } from "node:path";
22
+ import { buildIndex, gradedItems, held, INDEX_FILE, learnedPlace, mergedNote, mergeProblems, parseNoteFile, supersede, supersededBy } from "./learn/index.js";
23
+ import { claudeModel, claudeProvider, codexModel, codexProvider } from "./adapters.js";
24
+ import { FAUX_JEV_ENV, fauxFetch, jevKey } from "./decisions.js";
25
+ import { homeOf } from "./files.js";
26
+ import { FAUX_HARNESS_ENV } from "./harness.js";
27
+ import { agentFolder, checkOut, git, line, mainOf, NO_TOKENS, readBlobs, withAgentRepo } from "./learning.js";
28
+ import { completer } from "./llm.js";
29
+ import { openRouterOnly, runModels, thinkingOf } from "./model.js";
30
+ /** How long one note's screen and the grader may take (the grader's unless the server names another), and the most the
31
+ * grader may write. */
32
+ const SCREEN_TIMEOUT_MS = 60_000;
33
+ const GRADE_TIMEOUT_MS = 180_000;
34
+ const GRADE_MAX_TOKENS = 16_000;
35
+ const utf8 = new TextDecoder("utf-8", { fatal: true });
36
+ /** The newest commit on main whose Run-Id trailer names the run, as git reads trailers. */
37
+ async function mergeOf(home, repo, main, runId) {
38
+ const out = (await git(home, repo, ["log", "--first-parent", "--format=%H %(trailers:key=Run-Id,valueonly,separator=%x2C)", main])).toString("utf8");
39
+ return out.split("\n").find((entry) => entry.slice(entry.indexOf(" ") + 1).split(",").includes(runId))?.split(" ")[0];
40
+ }
41
+ /** Main's top: every entry, and the text of each `.md` blob, read with plumbing. A blob that is not UTF-8 is left out. */
42
+ async function readMain(home, repo, sha) {
43
+ const listed = (await git(home, repo, ["ls-tree", "-z", sha])).toString("utf8").split("\0").filter(Boolean).map((entry) => {
44
+ const [mode, type, oid] = entry.slice(0, entry.indexOf("\t")).split(" ");
45
+ return { mode, type, oid: oid, path: entry.slice(entry.indexOf("\t") + 1) };
46
+ });
47
+ const blobs = listed.filter((entry) => entry.type === "blob" && entry.mode === "100644" && entry.path.endsWith(".md"));
48
+ const read = await readBlobs(home, repo, blobs.map((entry) => entry.oid));
49
+ const texts = new Map();
50
+ blobs.forEach((entry, i) => {
51
+ try {
52
+ texts.set(entry.path, utf8.decode(read[i]));
53
+ }
54
+ catch {
55
+ // Not UTF-8: no note of the folder's, and never read as one.
56
+ }
57
+ });
58
+ return { sha, files: listed.map((entry) => entry.path), texts, oids: new Map(listed.map((entry) => [entry.path, entry.oid])) };
59
+ }
60
+ /** Main's notes, parsed: the ones out of shape left out, as a run's seed leaves them. */
61
+ const notesOf = (main) => [...main.texts].flatMap(([file, text]) => {
62
+ const note = file === INDEX_FILE ? [] : parseNoteFile(file, text);
63
+ return Array.isArray(note) ? [] : [note];
64
+ });
65
+ /** The proposal's notes, parsed: each passed the checks, so one that does not parse is an error. */
66
+ const proposedOf = (proposal) => proposal.notes.map(({ file, text }) => {
67
+ const note = parseNoteFile(file, text);
68
+ if (Array.isArray(note))
69
+ throw new Error(`the proposal's ${file} is not a note`);
70
+ return note;
71
+ });
72
+ /** What stops the proposal joining `main` as it is now (learn/check.ts mergeProblems). */
73
+ const problemsOf = (main, notes) => mergeProblems({ files: main.files, active: notesOf(main).filter((note) => note.status === "active") }, notes);
74
+ /** Main now, for run `runId`'s grade, in the agent's queue: merged already (a commit names the run), what stops its
75
+ * proposal joining main as it is now, or its active notes' index lines and the notes the proposal supersedes in full. */
76
+ export function readForGrade(data, agentId, runId, proposal) {
77
+ const home = homeOf(data, agentId);
78
+ return withAgentRepo(data, agentId, async () => {
79
+ const repo = await agentFolder(data, agentId);
80
+ const sha = (await mainOf(home, repo));
81
+ const merged = await mergeOf(home, repo, sha, runId);
82
+ if (merged)
83
+ return { merged };
84
+ const main = await readMain(home, repo, sha);
85
+ const added = proposedOf(proposal);
86
+ const problems = problemsOf(main, added);
87
+ if (problems.length)
88
+ return { problems };
89
+ const active = notesOf(main).filter((note) => note.status === "active").map(({ file, name, description }) => ({ file, name, description }));
90
+ // mergeProblems passed: each note superseded is active on main, and named once.
91
+ const superseded = added.flatMap((note) => note.supersedes).map((file) => ({ file, text: main.texts.get(file) }));
92
+ return { active, superseded, graded: Object.fromEntries(superseded.map(({ file }) => [file, main.oids.get(file)])) };
93
+ });
94
+ }
95
+ /** Counts one call in `cost`: its dollars and tokens, each null when unknown (a call that failed, or reported none). */
96
+ const counter = (cost) => (usd, tokens) => {
97
+ cost.usd = usd !== null && Number.isFinite(usd) && cost.usd !== null ? cost.usd + usd : null;
98
+ cost.tokens = tokens && cost.tokens ? { input: cost.tokens.input + tokens.input, cache_read: cost.tokens.cache_read + tokens.cache_read, cache_write: cost.tokens.cache_write + tokens.cache_write, output: cost.tokens.output + tokens.output } : null;
99
+ };
100
+ /** `work`, given a signal that aborts at `ms` or with `outer`, and rejected then whether or not it listens. A call cut
101
+ * off so, before it settled, spent what nobody knows: `cost` turns unknown (null dollars and tokens), never the zeros
102
+ * it started from, and a late answer leaves it unknown. */
103
+ function bounded(ms, outer, cost, work) {
104
+ if (outer.aborted)
105
+ return Promise.reject(outer.reason);
106
+ const signal = AbortSignal.any([outer, AbortSignal.timeout(ms)]);
107
+ let settled = false;
108
+ const doing = work(signal).finally(() => (settled = true));
109
+ doing.catch(() => undefined);
110
+ const cut = new Promise((_, reject) => {
111
+ const stop = () => {
112
+ if (settled)
113
+ return;
114
+ counter(cost)(null, null);
115
+ reject(signal.reason);
116
+ };
117
+ if (signal.aborted)
118
+ stop();
119
+ else
120
+ signal.addEventListener("abort", stop, { once: true });
121
+ });
122
+ return Promise.race([doing, cut]);
123
+ }
124
+ /** That usage by the platform's names; null when there is none, or a count is not a whole number. */
125
+ const tokensOf = (usage) => usage && [usage.input, usage.output, usage.cacheRead ?? 0, usage.cacheWrite ?? 0].every((n) => Number.isSafeInteger(n) && n >= 0) ? { input: usage.input, cache_read: usage.cacheRead ?? 0, cache_write: usage.cacheWrite ?? 0, output: usage.output } : null;
126
+ /** The variable pi-ai's anthropic provider reads for each auth mode: it sends the first as `authorization: Bearer`, the
127
+ * second as `x-api-key`. */
128
+ const BEARER_VARIABLE = "ANTHROPIC_AUTH_TOKEN";
129
+ const X_API_KEY_VARIABLE = "ANTHROPIC_API_KEY";
130
+ /** pi-ai's auth context for a grade on `provider`, the run's: its credential under the one variable pi-ai reads for its
131
+ * auth mode, and no other variable of serve's env. */
132
+ export function graderAuth(provider) {
133
+ const name = provider.auth === "bearer" ? BEARER_VARIABLE : X_API_KEY_VARIABLE;
134
+ return { env: async (asked) => (asked === name ? (await provider.credential()) || undefined : undefined), fileExists: async () => false };
135
+ }
136
+ /** One completion for the grader: on the model the server names for grading (`named`), picked as a workflow's strong
137
+ * tier is (runModels: the gateway, pi-ai's providers, or the faux module); else on the agent's own model, as its run's
138
+ * process picks it (app.ts): claude-agent's from pi-ai's catalog, sent where and as the run's own requests go
139
+ * (claudeProvider), any other harness's by runModels. At its revision's thinking; counted in `cost` (a call that fails
140
+ * has an unknown cost). */
141
+ async function graderModel(env, agent, cost, named) {
142
+ let chosen;
143
+ if (named) {
144
+ // The strong tier named over `env` itself, never a copy of it: the server's keys are properties that do not list
145
+ // (secrets.ts withSecrets), so a spread would leave every one out. runModels and pi-ai's auth read each by name.
146
+ const tiered = Object.create(env, { AGENT_MODEL_STRONG: { value: named, enumerable: true } });
147
+ const picked = await runModels(tiered, undefined, ["strong"]);
148
+ chosen = { models: picked.models, model: picked.byTier.get("strong") };
149
+ }
150
+ else if (agent.harness === "claude-agent" && !env[FAUX_HARNESS_ENV]) {
151
+ const choice = claudeModel(env, agent.model);
152
+ if ("why" in choice)
153
+ throw new Error(choice.why);
154
+ const { builtinModels } = await import("@earendil-works/pi-ai/providers/all");
155
+ // The grader asks where the run's requests go, with the run's credential and auth mode: one claudeProvider call for
156
+ // both. It sends the id the run sends (claudeProvider's modelId), on pi-ai's anthropic provider. The catalog only
157
+ // prices the model.
158
+ const sent = claudeProvider(env, choice.model);
159
+ const catalog = builtinModels({ authContext: graderAuth(sent) });
160
+ const at = (found) => (found && typeof found === "object" ? { ...found, baseUrl: sent.origin } : found);
161
+ chosen = { models: { getModel: (provider, id) => at(catalog.getModel(provider, id)), completeSimple: (...call) => catalog.completeSimple(...call) }, model: { provider: "anthropic", modelId: sent.modelId } };
162
+ }
163
+ else if (agent.harness === "codex" && !env[FAUX_HARNESS_ENV] && openRouterOnly("codex", env)) {
164
+ // codex on OpenRouter alone: the grade goes where the run's requests go, OpenRouter with its key, on the model the run
165
+ // runs (codexModel, then the id codexProvider sends), through pi-ai's openrouter provider. The revision's own name
166
+ // (openai/<model>) would ask for an OpenAI key, which this route never needs.
167
+ const choice = await codexModel(env, agent.model);
168
+ if ("why" in choice)
169
+ throw new Error(choice.why);
170
+ chosen = await runModels(env, `openrouter/${codexProvider(env, choice.model).modelId}`);
171
+ }
172
+ else
173
+ chosen = await runModels(env, agent.model);
174
+ const models = chosen.models;
175
+ const { model } = chosen;
176
+ const add = counter(cost);
177
+ return async (args, signal) => {
178
+ // The call's tokens from pi-ai's own usage, which keeps the cache's reads and writes apart.
179
+ let usage;
180
+ const tapped = {
181
+ getModel: (provider, id) => models.getModel(provider, id),
182
+ completeSimple: async (...call) => {
183
+ const message = await models.completeSimple(...call);
184
+ usage = message.usage;
185
+ return message;
186
+ },
187
+ };
188
+ const answer = await completer(tapped, () => model, thinkingOf(env, agent.thinking))(args, signal).catch((error) => (add(null, null), Promise.reject(error)));
189
+ add(answer.cost_usd, tokensOf(usage));
190
+ return answer;
191
+ };
192
+ }
193
+ /** The injection screen's judge: Jev, by TypeSafe's API or OpenRouter, when this server has its key; else none, and no
194
+ * screen runs. Each call is counted in `cost` (one that fails, or reports no price, is unknown unless its error carries
195
+ * a cost). */
196
+ async function independentJudge(env, cost) {
197
+ const key = jevKey(env);
198
+ if (!key)
199
+ return undefined;
200
+ const [{ jevProvider }, { judgeFromProvider }, fetch] = await Promise.all([import("@parcha/agentrun-jev"), import("@parcha/agentrun-dsl"), fauxFetch(env, FAUX_JEV_ENV)]);
201
+ const judge = judgeFromProvider(jevProvider({ apiKey: key.key, ...(key.route === "openrouter" ? { provider: "openrouter" } : {}), ...(fetch ? { fetch } : {}) }));
202
+ const add = counter(cost);
203
+ return async (request) => {
204
+ const result = await judge(request).catch((error) => (add(typeof error?.costUsd === "number" ? error.costUsd : null, null), Promise.reject(error)));
205
+ // A decision provider counts `{input_tokens, output_tokens}`, with no cache of its own.
206
+ const used = (result.usage ?? null);
207
+ add(typeof result.cost_usd === "number" ? result.cost_usd : null, typeof used?.input_tokens === "number" && typeof used.output_tokens === "number" ? { ...NO_TOKENS, input: used.input_tokens, output: used.output_tokens } : null);
208
+ return result;
209
+ };
210
+ }
211
+ /** The screen (only with an independent judge), then the grader, on `gradeModel` when the server names one (gradeModelOf),
212
+ * given `asked`, what the user said in the run: the first note the screen refuses or cannot judge, the grader's verdict,
213
+ * or why the grader gave none; with what it spent. Rejects only when `signal` (the server closing) aborts it: nothing
214
+ * is decided then. */
215
+ export async function judgeProposal(input) {
216
+ const { runId, agent, main, proposed, env, signal } = input;
217
+ const files = input.files ?? [];
218
+ const cost = { usd: 0, tokens: { ...NO_TOKENS } };
219
+ const judge = await independentJudge(env, cost);
220
+ if (judge) {
221
+ const { createPageClassifier, INJECTION_THRESHOLD } = await import("@parcha/pi-browser");
222
+ const screened = [...proposed, ...files];
223
+ const classify = createPageClassifier({ judge: () => judge, maxPages: screened.length });
224
+ for (const { file, text } of screened) {
225
+ const verdict = await bounded(SCREEN_TIMEOUT_MS, signal, cost, (screen) => classify({ url: file, status: null, contentType: null, text }, screen)).catch(() => undefined);
226
+ signal.throwIfAborted();
227
+ // The injection score alone decides: the classifier's wall question is about pages, not notes.
228
+ const score = verdict?.injection;
229
+ if (typeof score !== "number" || !Number.isFinite(score))
230
+ return { reason: "screen_down", file, cost };
231
+ if (score >= INJECTION_THRESHOLD)
232
+ return { reason: "screen", file, cost };
233
+ }
234
+ }
235
+ try {
236
+ const { gradePrompt, parseVerdict } = await import("./learn/index.js");
237
+ const prompt = gradePrompt({ run: runId, instructions: agent.instructions, active: main.active, superseded: main.superseded, proposed, ...(files.length ? { files } : {}), ...(input.asked ? { asked: input.asked } : {}) });
238
+ const grader = await graderModel(env, agent, cost, input.gradeModel);
239
+ const answer = await bounded(input.gradeTimeoutMs ?? GRADE_TIMEOUT_MS, signal, cost, (grade) => grader({ prompt, maxTokens: GRADE_MAX_TOKENS }, grade));
240
+ // The items with their texts: a note the run marked risky waits whatever the grader says (parseVerdict).
241
+ return { verdict: parseVerdict(answer.text, gradedItems(proposed, files)), cost };
242
+ }
243
+ catch (error) {
244
+ signal.throwIfAborted();
245
+ return { reason: "grade_failed", error: error, cost };
246
+ }
247
+ }
248
+ /** Each skill and draft file as main keeps it: as the run gave it, or, for one the grader held for its owner's OK, with
249
+ * `status: pending` in its SKILL.md or its README.md (learn/skills.ts held). A held workflow.json is as given: its
250
+ * README holds it. */
251
+ export function heldFiles(files, verdict) {
252
+ const waiting = new Set((verdict?.items ?? []).filter((item) => item.pending).map((item) => item.file));
253
+ return files.map(({ file, text }) => {
254
+ const place = learnedPlace(file);
255
+ const judged = place?.kind === "readme" ? `workflows/${place.name}/workflow.json` : file;
256
+ return { file, text: waiting.has(judged) && place?.kind !== "workflow" ? held(text) : text };
257
+ });
258
+ }
259
+ /** The blob `file` is at commit `sha` of the agent's folder, or undefined when the commit holds no such file. */
260
+ async function blobAt(home, repo, sha, file) {
261
+ try {
262
+ return line(await git(home, repo, ["rev-parse", "--verify", "--quiet", `${sha}:${file}`])) || undefined;
263
+ }
264
+ catch {
265
+ return undefined;
266
+ }
267
+ }
268
+ /** Merges run `runId`'s proposal into main as main is now, in the agent's queue, as `verdict` judged its notes: one commit
269
+ * on main (its parent main) that adds the new notes, each with its `origin` and a pending one with `status: pending`
270
+ * (in no index, so no run reads it, until a person approves it), marks each note a kept one supersedes (a pending
271
+ * note's wait for its approval), adds or changes the skill's and draft's files (heldFiles: a held one pending) and
272
+ * rebuilds MEMORY.md, its message `learning: <run>: merged`,
273
+ * `reason` and the run's Run-Id; moved onto main only from the commit it was made on, once more on a main that moved
274
+ * meanwhile. Then the checked-out files are main's. A run a commit on main already names is that commit. `problems`
275
+ * when main, as it is now, takes the notes no more (mergeProblems), or when a note the merge marks superseded is not
276
+ * the blob the grade read (`graded`, readForGrade's): a person changed it since, and their text stands. A note held for
277
+ * its owner's OK marks nothing (supersededBy), so what it names is not checked. `checkout` is why the files could not
278
+ * be brought in line, when they could not: main is merged all the same. */
279
+ export function mergeProposal(data, agentId, runId, proposal, reason, graded, verdict) {
280
+ const home = homeOf(data, agentId);
281
+ // Each note as main keeps it: its origin, the grader's (a run's when it names none), and a pending one waiting.
282
+ const judged = new Map((verdict?.items ?? []).map((item) => [item.file, item]));
283
+ const texts = proposal.notes.map(({ file, text }) => ({ file, text: mergedNote(text, { origin: judged.get(file)?.origin ?? "run", pending: judged.get(file)?.pending === true }) }));
284
+ const added = proposedOf({ ...proposal, notes: texts });
285
+ return withAgentRepo(data, agentId, async () => {
286
+ const repo = await agentFolder(data, agentId);
287
+ const checkout = (sha) => checkOut(repo, sha);
288
+ for (let tries = 0;; tries++) {
289
+ const sha = (await mainOf(home, repo));
290
+ const known = await mergeOf(home, repo, sha, runId);
291
+ if (known)
292
+ return { merged: known, checkout: await checkout(sha) };
293
+ const main = await readMain(home, repo, sha);
294
+ const problems = problemsOf(main, added);
295
+ if (problems.length)
296
+ return { problems };
297
+ // What the merge marks superseded (a note held for its owner's OK marks nothing).
298
+ const replaced = supersededBy(added);
299
+ // The verdict was on the text the grade read: a note this merge marks that is another blob now is never marked on
300
+ // it.
301
+ const changed = [...replaced].filter(([old]) => main.oids.get(old) !== graded[old]).map(([old, by]) => ({ rule: "supersedes", path: by, detail: `${old} changed after the grade read it` }));
302
+ if (changed.length)
303
+ return { problems: changed };
304
+ // A skill's or a draft's file is written whole over main's: one that changed on main after the run started (a
305
+ // person retired or approved it, or another run's merge changed it) is never written over on this run's copy.
306
+ const moved = [];
307
+ for (const { file } of proposal.files ?? []) {
308
+ if ((await blobAt(home, repo, proposal.seed, file)) !== (await blobAt(home, repo, sha, file)))
309
+ moved.push({ rule: "supersedes", path: file, detail: `${file} changed on main after the run started` });
310
+ }
311
+ if (moved.length)
312
+ return { problems: moved };
313
+ const notes = notesOf(main);
314
+ // The new tree: main's, with the new notes, the ones the kept notes supersede marked, and the index rebuilt from
315
+ // what is active then (a pending note is not).
316
+ const files = new Map([...texts, ...heldFiles(proposal.files ?? [], verdict)].map(({ file, text }) => [file, text]));
317
+ for (const [old, by] of replaced)
318
+ files.set(old, supersede(main.texts.get(old), by));
319
+ const after = [...notes.filter((note) => !replaced.has(note.file)), ...added];
320
+ files.set(INDEX_FILE, buildIndex(after));
321
+ const env = { GIT_INDEX_FILE: join(repo, ".git", `merge-${runId}.index`) };
322
+ let commit;
323
+ try {
324
+ await rm(env.GIT_INDEX_FILE, { force: true });
325
+ await git(home, repo, ["read-tree", sha], "", env);
326
+ const entries = [];
327
+ for (const [file, text] of files)
328
+ entries.push(`100644 ${line(await git(home, repo, ["hash-object", "-w", "--no-filters", "--stdin"], text))}\t${file}\0`);
329
+ await git(home, repo, ["update-index", "-z", "--index-info"], entries.join(""), env);
330
+ const tree = line(await git(home, repo, ["write-tree"], "", env));
331
+ commit = line(await git(home, repo, ["commit-tree", tree, "-p", sha, "-m", `learning: ${runId}: merged`, "-m", reason, "-m", `Run-Id: ${runId}`]));
332
+ }
333
+ finally {
334
+ await rm(env.GIT_INDEX_FILE, { force: true });
335
+ }
336
+ try {
337
+ await git(home, repo, ["update-ref", "-m", `learning: merge ${runId}`, "refs/heads/main", commit, sha]);
338
+ }
339
+ catch (error) {
340
+ // Lost to a write since main was read: merged again onto the main that won, never forced over it.
341
+ if (tries === 0 && (await mainOf(home, repo)) !== sha)
342
+ continue;
343
+ throw error;
344
+ }
345
+ return { merged: commit, checkout: await checkout(commit) };
346
+ }
347
+ });
348
+ }
@@ -0,0 +1,100 @@
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
+ id: {} | null;
57
+ node: string | null;
58
+ executionPath: {} | null;
59
+ item: {} | null;
60
+ kind: {} | null;
61
+ provider: {} | null;
62
+ model: {} | null;
63
+ status: {} | null;
64
+ questions: {} | null;
65
+ answers: {} | null;
66
+ evidence: {};
67
+ rule: {} | null;
68
+ action: {} | null;
69
+ cost_usd: number | null;
70
+ cost_basis: {} | null;
71
+ latency_ms: {} | null;
72
+ state: {} | null;
73
+ state_truncated: boolean;
74
+ error: string | null;
75
+ images: {
76
+ token: {} | null;
77
+ ref: {} | null;
78
+ url: string | null;
79
+ }[];
80
+ }[];
81
+ effects: {
82
+ node: string | null;
83
+ executionPath: string | null;
84
+ item: number | null;
85
+ tool: string;
86
+ status: string;
87
+ input: unknown;
88
+ output: unknown;
89
+ error: string | null;
90
+ startedAt: string;
91
+ endedAt: string | null;
92
+ }[];
93
+ totals: {
94
+ cost_usd: number | null;
95
+ decisions: number;
96
+ effects: number;
97
+ elapsed_ms: number | null;
98
+ };
99
+ }>;
100
+ export {};