@parcha/agentrun-serve 0.1.0-beta.34 → 0.1.0-beta.35

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 (227) hide show
  1. package/CHANGELOG.md +135 -0
  2. package/README.md +84 -16
  3. package/dist/adapters.d.ts +3 -0
  4. package/dist/adapters.js +7 -0
  5. package/dist/agent-rows.d.ts +1 -0
  6. package/dist/agents-store.js +17 -2
  7. package/dist/archil-settings.d.ts +11 -1
  8. package/dist/archil-settings.js +10 -0
  9. package/dist/bash-read-only.d.ts +13 -0
  10. package/dist/bash-read-only.js +77 -0
  11. package/dist/browser-cost.d.ts +2 -2
  12. package/dist/browser-cost.js +6 -4
  13. package/dist/budget.d.ts +0 -5
  14. package/dist/budget.js +0 -5
  15. package/dist/cap.d.ts +6 -3
  16. package/dist/cap.js +7 -4
  17. package/dist/cli.js +32 -5
  18. package/dist/computer-keys.d.ts +20 -10
  19. package/dist/computer-keys.js +36 -57
  20. package/dist/computer-setting.d.ts +6 -5
  21. package/dist/computer-setting.js +54 -26
  22. package/dist/computers.d.ts +9 -4
  23. package/dist/computers.js +4 -2
  24. package/dist/console/assets/index-B7NKTU8E.css +1 -0
  25. package/dist/console/assets/index-CXZMgJE7.js +550 -0
  26. package/dist/console/index.html +2 -2
  27. package/dist/content-filter.d.ts +7 -0
  28. package/dist/content-filter.js +23 -0
  29. package/dist/decision-cap.d.ts +7 -29
  30. package/dist/decision-cap.js +3 -94
  31. package/dist/errors.d.ts +1 -0
  32. package/dist/errors.js +3 -0
  33. package/dist/explain.js +3 -1
  34. package/dist/github-connection.js +25 -7
  35. package/dist/github-faux.d.ts +26 -0
  36. package/dist/github-faux.js +76 -0
  37. package/dist/github.d.ts +6 -2
  38. package/dist/github.js +5 -3
  39. package/dist/graph-served.d.ts +5 -3
  40. package/dist/graph-served.js +14 -6
  41. package/dist/graph-view.js +5 -2
  42. package/dist/harness-opencode/harness.js +0 -1
  43. package/dist/harness-opencode/host/policy.js +2 -2
  44. package/dist/index.d.ts +1 -0
  45. package/dist/index.js +1 -0
  46. package/dist/learn/check.d.ts +3 -1
  47. package/dist/learn/check.js +3 -3
  48. package/dist/learn/folder.d.ts +6 -3
  49. package/dist/learn/folder.js +7 -16
  50. package/dist/learn/grade.d.ts +4 -1
  51. package/dist/learn/grade.js +43 -5
  52. package/dist/learn/index.d.ts +2 -2
  53. package/dist/learn/index.js +2 -2
  54. package/dist/learn/learning.sh +1 -14
  55. package/dist/learn/notes.d.ts +14 -3
  56. package/dist/learn/notes.js +16 -6
  57. package/dist/learn/reflect.js +5 -3
  58. package/dist/learn/skills.d.ts +48 -5
  59. package/dist/learn/skills.js +97 -21
  60. package/dist/learned-nodes.d.ts +14 -0
  61. package/dist/learned-nodes.js +8 -0
  62. package/dist/learned-workflow.d.ts +9 -5
  63. package/dist/learned-workflow.js +53 -9
  64. package/dist/learning-routes.d.ts +41 -0
  65. package/dist/learning-routes.js +94 -26
  66. package/dist/learning-run.d.ts +7 -5
  67. package/dist/learning-run.js +9 -6
  68. package/dist/learning.d.ts +0 -22
  69. package/dist/learning.js +0 -16
  70. package/dist/llm.d.ts +4 -1
  71. package/dist/llm.js +4 -2
  72. package/dist/mcp-gateway.d.ts +6 -0
  73. package/dist/mcp-gateway.js +11 -1
  74. package/dist/mcp-servers-store.d.ts +12 -12
  75. package/dist/model.d.ts +3 -0
  76. package/dist/model.js +8 -0
  77. package/dist/openapi.js +37 -13
  78. package/dist/paid-calls.js +1 -1
  79. package/dist/pause.d.ts +2 -19
  80. package/dist/pause.js +5 -74
  81. package/dist/port-models.d.ts +10 -3
  82. package/dist/port-models.js +26 -6
  83. package/dist/propose.d.ts +2 -0
  84. package/dist/propose.js +1 -10
  85. package/dist/run-launch.d.ts +5 -3
  86. package/dist/run-launch.js +6 -5
  87. package/dist/run-learning-served.d.ts +11 -0
  88. package/dist/run-reads-over-store.d.ts +4 -2
  89. package/dist/run-reads-over-store.js +10 -8
  90. package/dist/run-timeline-served.js +12 -2
  91. package/dist/run-view.d.ts +30 -14
  92. package/dist/run-view.js +60 -32
  93. package/dist/runnable.d.ts +4 -1
  94. package/dist/runnable.js +14 -2
  95. package/dist/runner/adapter-loop.d.ts +30 -4
  96. package/dist/runner/adapter-loop.js +253 -29
  97. package/dist/runner/adapter-run-spec.d.ts +21 -0
  98. package/dist/runner/adapter-run-spec.js +104 -28
  99. package/dist/runner/adapters/pi.d.ts +29 -1
  100. package/dist/runner/adapters/pi.js +95 -23
  101. package/dist/runner/beside.d.ts +8 -0
  102. package/dist/runner/beside.js +18 -0
  103. package/dist/runner/claim-secrets.d.ts +6 -0
  104. package/dist/runner/claim-secrets.js +15 -1
  105. package/dist/runner/cli-run-spec.d.ts +3 -0
  106. package/dist/runner/cli-run-spec.js +123 -34
  107. package/dist/runner/conformance/harness.d.ts +1 -0
  108. package/dist/runner/conformance/harness.js +5 -5
  109. package/dist/runner/github-app.d.ts +7 -2
  110. package/dist/runner/github-app.js +46 -15
  111. package/dist/runner/harness-loops.d.ts +6 -1
  112. package/dist/runner/harness-loops.js +23 -0
  113. package/dist/runner/journal-kinds.d.ts +38 -2
  114. package/dist/runner/journal-kinds.js +23 -0
  115. package/dist/runner/learning-end.js +88 -16
  116. package/dist/runner/learning-loop.d.ts +2 -0
  117. package/dist/runner/learning-loop.js +13 -5
  118. package/dist/runner/learning-seed.d.ts +6 -0
  119. package/dist/runner/learning-seed.js +6 -0
  120. package/dist/runner/loop-contract.d.ts +4 -0
  121. package/dist/runner/main.d.ts +9 -4
  122. package/dist/runner/main.js +26 -11
  123. package/dist/runner/mcp-claim.d.ts +3 -0
  124. package/dist/runner/mcp-claim.js +6 -1
  125. package/dist/runner/mcp-github.d.ts +11 -2
  126. package/dist/runner/mcp-github.js +55 -4
  127. package/dist/runner/mcp-run.js +1 -0
  128. package/dist/runner/metrics.d.ts +14 -1
  129. package/dist/runner/metrics.js +72 -1
  130. package/dist/runner/model-route.d.ts +3 -0
  131. package/dist/runner/model-route.js +1 -1
  132. package/dist/runner/runner.js +90 -8
  133. package/dist/runner/spec-holds.d.ts +7 -2
  134. package/dist/runner/spec-holds.js +4 -3
  135. package/dist/runner/workflow-host.d.ts +7 -2
  136. package/dist/runner/workflow-host.js +3 -1
  137. package/dist/runner/workflow-loop.d.ts +4 -1
  138. package/dist/runner/workflow-loop.js +8 -2
  139. package/dist/runner/workflow-spec.d.ts +3 -0
  140. package/dist/runner/workflow-spec.js +156 -78
  141. package/dist/runs-over-store.d.ts +7 -1
  142. package/dist/runs-over-store.js +42 -11
  143. package/dist/seal-key.d.ts +0 -2
  144. package/dist/seal-key.js +0 -2
  145. package/dist/server-lock.js +4 -5
  146. package/dist/server.d.ts +21 -18
  147. package/dist/server.js +183 -34
  148. package/dist/stop-signals.d.ts +4 -2
  149. package/dist/stop-signals.js +5 -3
  150. package/dist/store/agent-body.d.ts +5 -1
  151. package/dist/store/agent-body.js +11 -5
  152. package/dist/store/deadline.d.ts +18 -0
  153. package/dist/store/deadline.js +45 -0
  154. package/dist/store/postgres/connection.d.ts +4 -0
  155. package/dist/store/postgres/connection.js +55 -9
  156. package/dist/store/sqlite/connection.js +3 -38
  157. package/dist/store-reads/journal.js +39 -4
  158. package/dist/store-reads/learning.d.ts +58 -2
  159. package/dist/store-reads/learning.js +172 -7
  160. package/dist/store-view.d.ts +15 -1
  161. package/dist/store-view.js +45 -12
  162. package/dist/templates.d.ts +9 -4
  163. package/dist/templates.js +14 -9
  164. package/dist/timeline/timeline.d.ts +8 -0
  165. package/dist/tool-budget.d.ts +18 -0
  166. package/dist/tool-budget.js +50 -0
  167. package/dist/tool-gate.d.ts +6 -2
  168. package/dist/tool-gate.js +8 -5
  169. package/dist/tool-plane.d.ts +9 -10
  170. package/dist/tools.d.ts +37 -7
  171. package/dist/tools.js +73 -12
  172. package/dist/uploads.d.ts +28 -5
  173. package/dist/uploads.js +82 -9
  174. package/dist/usage.d.ts +1 -47
  175. package/dist/usage.js +3 -82
  176. package/dist/validate.d.ts +2 -0
  177. package/dist/validate.js +11 -1
  178. package/dist/workspace/archil-claim.d.ts +2 -2
  179. package/dist/workspace/archil-claim.js +4 -3
  180. package/dist/workspace/archil-disk.d.ts +10 -1
  181. package/dist/workspace/archil-disk.js +4 -0
  182. package/dist/workspace/archil-exec.d.ts +12 -2
  183. package/dist/workspace/archil-exec.js +16 -0
  184. package/dist/workspace/archil.d.ts +2 -2
  185. package/dist/workspace/archil.js +25 -5
  186. package/dist/workspace/attach.js +2 -0
  187. package/dist/workspace/computer-deps.d.ts +9 -10
  188. package/dist/workspace/computer-deps.js +53 -40
  189. package/dist/workspace/computer-for-claim.d.ts +5 -3
  190. package/dist/workspace/computer-for-claim.js +28 -16
  191. package/dist/workspace/computer-ledger.d.ts +1 -8
  192. package/dist/workspace/computer-ledger.js +0 -3
  193. package/dist/workspace/computer-providers.d.ts +5 -3
  194. package/dist/workspace/computer-providers.js +11 -9
  195. package/dist/workspace/hands.d.ts +5 -2
  196. package/dist/workspace/hands.js +4 -3
  197. package/dist/workspace/index.d.ts +3 -3
  198. package/dist/workspace/index.js +1 -1
  199. package/dist/workspace/local.d.ts +3 -0
  200. package/dist/workspace/local.js +9 -0
  201. package/dist/workspace/paths.js +3 -2
  202. package/dist/workspace/pi-env.d.ts +4 -0
  203. package/dist/workspace/pi-env.js +3 -2
  204. package/dist/workspace/resolve-computer.d.ts +8 -3
  205. package/dist/workspace/resolve-computer.js +28 -11
  206. package/dist/workspace/run-tools.d.ts +2 -0
  207. package/dist/workspace/run-tools.js +9 -3
  208. package/dist/workspace/workspace.d.ts +5 -0
  209. package/dist/workspace.d.ts +0 -3
  210. package/dist/workspace.js +1 -14
  211. package/package.json +14 -14
  212. package/skills/agentrun-serve/SKILL.md +1 -1
  213. package/templates/README.md +2 -2
  214. package/templates/code-review/evals/mentions-defused/case.yaml +15 -0
  215. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +254 -0
  216. package/templates/code-review/evals/mentions-defused/graders/no-pings.md +16 -0
  217. package/templates/code-review/evals/mentions-defused/graders/posted-a-review.md +5 -0
  218. package/templates/code-review/evals/mentions-defused/graders/schema.md +5 -0
  219. package/templates/code-review/evals/mentions-defused/prompt.md +10 -0
  220. package/templates/kyb/evals/clean-public-company/graders/no-opensanctions.md +5 -0
  221. package/templates/kyb/evals/opensanctions-on/case.yaml +5 -0
  222. package/templates/kyb/evals/opensanctions-on/graders/licence-and-evidence.md +18 -0
  223. package/templates/kyb/evals/opensanctions-on/graders/schema.md +5 -0
  224. package/templates/kyb/evals/opensanctions-on/prompt.md +11 -0
  225. package/templates/release-notes/agent.md +11 -0
  226. package/dist/console/assets/index-RPHGlXmM.js +0 -540
  227. package/dist/console/assets/index-opTN5Naq.css +0 -1
@@ -5,13 +5,15 @@
5
5
  // a person's words, the verdict, what it merged, learned, held for the owner's OK and lost, what the checks left out,
6
6
  // and what the grade spent. What the server keeps on a run before its end (what it was given and read, its seed's
7
7
  // notes, its answer's time and costs) is the run's, not this.
8
+ import { posix } from "node:path";
8
9
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
9
10
  import { currentLearning, holdsForOk, LEARNING_REASONS } from "../learning.js";
10
11
  import { runLearningBody } from "../learning-routes.js";
11
12
  import { learningStartOf, readLaunchBody } from "../run-launch.js";
12
13
  import { learningImpact, noteRuns, notesRead } from "../learning-run.js";
14
+ import { reflects } from "../reflect-range.js";
13
15
  import { notesOf } from "../usage.js";
14
- import { runReflect, runTimeline } from "./journal.js";
16
+ import { runEntries, runReflect, runTimeline } from "./journal.js";
15
17
  import { FINAL_STATES } from "../store/store.js";
16
18
  import { journalEntries } from "../runner/journal-reader.js";
17
19
  import { KINDS } from "../runner/journal-kinds.js";
@@ -143,7 +145,14 @@ export async function agentLearningOverStore(store, agentId) {
143
145
  const final = FINAL_STATES.includes(run.state);
144
146
  const started = await learningStartOfRun(store, run.id);
145
147
  const end = await runLearningEnd(store, run.id);
146
- const read = final && started?.given.length ? notesReadOf(started.given, await runReflect(store, run.id, BACKGROUND_CONTEXT), await runTimeline(store, run.id, BACKGROUND_CONTEXT, { settled: true })) : [];
148
+ // What the run's journal says here (the notes its job opened, what its claims laid of the skills and workflows it was
149
+ // offered): read once for a settled run and kept by its epoch (settledJournalReads), else read now.
150
+ const offered = !!(started?.skills?.length || started?.workflows?.length);
151
+ const journal = async () => ({
152
+ read: final && started?.given.length ? notesReadOf(started.given, await runReflect(store, run.id, BACKGROUND_CONTEXT), await runTimeline(store, run.id, BACKGROUND_CONTEXT, { settled: true })) : [],
153
+ laid: offered ? laidOf(await runEntries(store, run.id, BACKGROUND_CONTEXT)) : undefined,
154
+ });
155
+ const { read, laid } = final ? await settledJournalReads(store, run.id, run.epoch, journal) : await journal();
147
156
  if (started || end)
148
157
  files.push(notesOf({ given: started?.given ?? [], read }));
149
158
  // The row learningImpact reads (the file path's RunRow): an ended run is a completed one.
@@ -152,18 +161,58 @@ export async function agentLearningOverStore(store, agentId) {
152
161
  startedAt: new Date(run.startedAt).toISOString(), endedAt: run.endedAt === null ? null : new Date(run.endedAt).toISOString(),
153
162
  costUsd: run.costUsd, importedFrom: run.importedFrom, archivedAt: run.archivedAt === null ? null : new Date(run.archivedAt).toISOString(),
154
163
  });
155
- learnings.set(run.id, end ? impactLearningOf(end, started) : null);
164
+ // What its claims laid of the skills and workflows it was offered (every learningLaid entry, laidOf): the run started
165
+ // from those alone.
166
+ learnings.set(run.id, end ? impactLearningOf(end, started, laid) : null);
156
167
  }
157
168
  return { counts, impact: learningImpact(rows, (row) => learnings.get(row.id) ?? null), notes: noteRuns(files) };
158
169
  }
170
+ /** What a settled run's journal tells the agent's learning view, kept by store and run id with the run's epoch: a claim
171
+ * and a run's end each move the epoch, and only a claim writes to its journal, so a settled run's reads hold until the
172
+ * next claim of it. At most SETTLED_READS_MAX runs a store, the oldest read dropped first. */
173
+ const settledReads = new WeakMap();
174
+ const SETTLED_READS_MAX = 4096;
175
+ async function settledJournalReads(store, runId, epoch, read) {
176
+ let runs = settledReads.get(store);
177
+ if (!runs)
178
+ settledReads.set(store, (runs = new Map()));
179
+ const kept = runs.get(runId);
180
+ if (kept && kept.epoch === epoch)
181
+ return kept.value;
182
+ const value = await read();
183
+ runs.delete(runId);
184
+ runs.set(runId, { epoch, value });
185
+ if (runs.size > SETTLED_READS_MAX)
186
+ runs.delete(runs.keys().next().value);
187
+ return value;
188
+ }
189
+ /** What every claim of a run laid, from its learningLaid entries, each name once: a resumed claim finds an earlier
190
+ * claim's skill folders there already and lays none of them again, though the run still has them. None laid when it has
191
+ * no entry. */
192
+ export function laidOf(entries) {
193
+ const names = (list) => (Array.isArray(list) ? list.filter((name) => typeof name === "string") : []);
194
+ const skills = new Set();
195
+ const workflows = new Set();
196
+ for (const entry of entries) {
197
+ if (entry.kind !== KINDS.learningLaid)
198
+ continue;
199
+ const data = (entry.data ?? {});
200
+ for (const name of names(data.skills))
201
+ skills.add(name);
202
+ for (const name of names(data.workflows))
203
+ workflows.add(name);
204
+ }
205
+ return { skills: [...skills], workflows: [...workflows] };
206
+ }
159
207
  /** What a run's learning end tells its impact, as ofAgent's learningOf read a held run: how it ended and when, the notes
160
208
  * it started from; when its job answered and its costs once it looked back (a look-back of 0 for an ended one that did
161
209
  * not); its grade's cost once it ended (0 when nothing was graded). */
162
- function impactLearningOf(end, started) {
210
+ function impactLearningOf(end, started, laid) {
163
211
  const over = end.state === "merged" || end.state === "dropped";
164
212
  const looked = end.answered_at !== undefined ? { answered_at: end.answered_at, job_cost_usd: end.job_cost_usd ?? null, look_back_usd: end.look_back_usd ?? null } : over ? { look_back_usd: 0 } : {};
165
213
  return {
166
- state: end.state, reason: end.reason, at: end.at, ...(started?.seedNotes !== undefined ? { seed_notes: started.seedNotes } : {}), ...looked,
214
+ state: end.state, reason: end.reason, at: end.at, ...(started?.seedNotes !== undefined ? { seed_notes: started.seedNotes } : {}),
215
+ ...(laid?.skills.length ? { seed_skills: laid.skills.length } : {}), ...(laid?.workflows.length ? { seed_workflows: laid.workflows.length } : {}), ...looked,
167
216
  ...(over ? { grade_usd: end.cost_usd ? end.cost_usd.grade : 0 } : {}),
168
217
  };
169
218
  }
@@ -176,6 +225,120 @@ export function notesReadOf(given, reflect, rows) {
176
225
  const names = new Map(given.map((note) => [note.file, note.name]));
177
226
  return notesRead(reflect, rows).flatMap((file) => (names.has(file) ? [{ file, name: names.get(file) }] : []));
178
227
  }
228
+ /** learned_workflow by every name a harness calls it (runner/learning-end.ts LEARNED_NAMES). */
229
+ const WORKFLOW_CALLS = new Set(["learned_workflow", "mcp__hands__learned_workflow"]);
230
+ /** Each tool call of a run's journal, by its call's id: its tool and the arguments it was called with, as recorded (pi's
231
+ * call in its assistant entry, a CLI harness's in its record's call start). A timeline row's input preview is cut and
232
+ * for some tools absent, so what a call read or ran is read from these. */
233
+ export function callArgsOf(entries) {
234
+ const out = new Map();
235
+ const argsOf = (value) => (value && typeof value === "object" && !Array.isArray(value) ? value : {});
236
+ for (const entry of entries) {
237
+ if (entry.kind === "pi.assistant") {
238
+ for (const part of (entry.model?.[0]?.content ?? [])) {
239
+ if (part?.type === "toolCall" && typeof part.id === "string" && typeof part.name === "string")
240
+ out.set(part.id, { tool: part.name, args: argsOf(part.arguments) });
241
+ }
242
+ }
243
+ else if (entry.kind === KINDS.callStart) {
244
+ const data = (entry.data ?? {});
245
+ if (typeof data.callId === "string" && typeof data.tool === "string")
246
+ out.set(data.callId, { tool: data.tool, args: argsOf(data.input) });
247
+ }
248
+ }
249
+ return out;
250
+ }
251
+ /** The plugin claude-agent serves a run's skills from (@parcha/agentrun-harness-claude CLAUDE_AGENT_SKILLS_PLUGIN): the
252
+ * model loads each as `agentrun:<name>`, or by its bare name. */
253
+ const CLAUDE_SKILLS_PLUGIN = "agentrun";
254
+ /** The id ranges of a run's end-of-run turns, each from its prompt (an endOfRunTurn entry, `role: "person"`) to its
255
+ * answer (`role: "model"`); one with no answer runs to the person's next message (a reopened run's follow-up), else to
256
+ * the end. A reopened run has one per time it looked back. */
257
+ function endOfRunTurns(entries) {
258
+ const turns = [];
259
+ let open;
260
+ for (const entry of [...entries].filter((one) => one.id !== undefined).sort((a, b) => a.id - b.id)) {
261
+ const role = entry.data?.role;
262
+ if (entry.kind === KINDS.endOfRunTurn && role === "person")
263
+ open ??= entry.id;
264
+ else if (open !== undefined && ((entry.kind === KINDS.endOfRunTurn && role === "model") || (entry.kind === KINDS.message && role === "person"))) {
265
+ turns.push([open, entry.id]);
266
+ open = undefined;
267
+ }
268
+ }
269
+ if (open !== undefined)
270
+ turns.push([open, Number.POSITIVE_INFINITY]);
271
+ return turns;
272
+ }
273
+ /** The skills a run's job loaded with a harness's own Skill tool (claude-agent's): a native call, which the CLI's session
274
+ * records as a kernel step of its own (`kernel.start` named `tool.Skill`, keyed `tool:<call id>`, then its `kernel.end`)
275
+ * and never as a host tool's call record, so no timeline row or callArgsOf entry has it. Each by the name the model
276
+ * gave (`agentrun:<name>` or the bare one), only when its step completed, and only outside every end-of-run turn (a
277
+ * reopened run's follow-up's loads are the job's). */
278
+ export function nativeSkillLoads(entries) {
279
+ const turns = endOfRunTurns(entries);
280
+ const inTurn = (id) => id !== undefined && turns.some(([from, to]) => id >= from && id <= to);
281
+ const asked = new Map();
282
+ const loaded = [];
283
+ for (const entry of entries) {
284
+ if (inTurn(entry.id))
285
+ continue;
286
+ const data = (entry.data ?? {});
287
+ if (entry.kind === "kernel.start" && data.name === "tool.Skill" && typeof data.stepId === "string") {
288
+ const skill = data.input?.skill;
289
+ if (typeof skill === "string")
290
+ asked.set(data.stepId, skill);
291
+ }
292
+ else if (entry.kind === "kernel.end" && typeof data.stepId === "string" && data.status === "completed" && asked.has(data.stepId)) {
293
+ loaded.push(asked.get(data.stepId));
294
+ }
295
+ }
296
+ return loaded;
297
+ }
298
+ /** Whether a skill loaded by the name `asked` is skill `name`: by its plugin-qualified name or its bare one. */
299
+ const loadsSkill = (asked, name) => asked === name || asked === `${CLAUDE_SKILLS_PLUGIN}:${name}`;
300
+ /** Where a claim lays a learned skill's SKILL.md in the run's work (learning.ts RUN_SKILLS). */
301
+ const laidSkillPath = (name) => `.agents/skills/${name}/SKILL.md`;
302
+ /** Whether call `call` read skill `name`'s SKILL.md: the read hand on the path its claim laid it at (`.agents/skills/
303
+ * <name>/SKILL.md` in the run's work, relative or absolute under it, never another file whose path ends the same way), a
304
+ * CLI adapter's read_skill_file of the skill's SKILL.md, or a Skill tool call on the skill. */
305
+ function readsSkill(call, name) {
306
+ const text = (key) => (typeof call.args[key] === "string" ? call.args[key] : "");
307
+ if (call.tool === "read" || call.tool === "mcp__hands__read") {
308
+ const path = posix.normalize(text("path"));
309
+ return path === laidSkillPath(name) || (path.startsWith("/") && path.endsWith(`/${laidSkillPath(name)}`));
310
+ }
311
+ if (call.tool === "read_skill_file")
312
+ return text("skill") === name && posix.normalize(text("path")) === "SKILL.md";
313
+ if (call.tool === "Skill")
314
+ return [text("skill"), text("command"), text("name")].some((asked) => loadsSkill(asked, name));
315
+ return false;
316
+ }
317
+ /** `laid`: what the run's claims laid (laidOf): a skill its launch offered but no claim laid (over the budget, or a name
318
+ * the revision's own skill holds, whose copy is the one installed) is not the run's learned skill, whatever it read.
319
+ * `loads`: the skills its job loaded with a harness's own Skill tool (nativeSkillLoads), each a read of its SKILL.md. */
320
+ export function learnedUseOf(started, reflect, rows, args = new Map(), laid = { skills: [] }, loads = []) {
321
+ const job = rows.filter((row) => !reflects(reflect, row.id));
322
+ const results = new Map(job.flatMap((row) => (row.kind === "tool_result" && row.tool_use_id ? [[row.tool_use_id, row.tool_status]] : [])));
323
+ const calls = job.filter((row) => row.kind === "tool_use" && !row.parent_tool_use_id && row.tool_use_id).flatMap((row) => {
324
+ const call = args.get(row.tool_use_id);
325
+ return call ? [{ id: row.tool_use_id, ...call }] : [];
326
+ });
327
+ const installed = new Set(laid.skills);
328
+ const skills = (started?.skills ?? []).filter((name) => installed.has(name)).map((name) => ({ name, read: calls.some((call) => results.get(call.id) === "success" && readsSkill(call, name)) || loads.some((asked) => loadsSkill(asked, name)) }));
329
+ const workflows = new Map();
330
+ for (const call of calls) {
331
+ if (!WORKFLOW_CALLS.has(call.tool) || typeof call.args.name !== "string")
332
+ continue;
333
+ const seen = workflows.get(call.args.name) ?? { calls: 0, failed: 0 };
334
+ seen.calls += 1;
335
+ // Only a result that says so: a call with no result yet (one still running) is no failure.
336
+ if (results.get(call.id) === "failed")
337
+ seen.failed += 1;
338
+ workflows.set(call.args.name, seen);
339
+ }
340
+ return { skills, workflows: [...workflows].map(([name, seen]) => ({ name, ...seen })) };
341
+ }
179
342
  /** `end` with its run's given notes (from its launch's learning start) and the notes its job read. */
180
343
  export function withNotes(end, started, read) {
181
344
  return {
@@ -203,8 +366,10 @@ export async function runLearningOverStore(store, runId, shown, secrets, statuse
203
366
  const started = await learningStartOfRun(store, runId);
204
367
  const row = await store.runs.get(runId);
205
368
  const settled = row !== undefined && FINAL_STATES.includes(row.state);
206
- const read = started?.given.length ? notesReadOf(started.given, await runReflect(store, runId, BACKGROUND_CONTEXT), await runTimeline(store, runId, BACKGROUND_CONTEXT, { settled })) : [];
369
+ const used = started?.given.length || started?.skills?.length || started?.workflows?.length;
370
+ const [reflect, rows, entries] = used ? await Promise.all([runReflect(store, runId, BACKGROUND_CONTEXT), runTimeline(store, runId, BACKGROUND_CONTEXT, { settled }), runEntries(store, runId, BACKGROUND_CONTEXT)]) : [undefined, [], []];
371
+ const read = started?.given.length ? notesReadOf(started.given, reflect, rows) : [];
207
372
  const learning = withNotes(end, started, read);
208
373
  const current = holdsForOk(learning) && row && statuses ? currentLearning(learning, await statuses(row.agentId)) : learning;
209
- return runLearningBody({ id: runId, learning: current, seed: started?.seed ?? null, settled }, shown, secrets);
374
+ return runLearningBody({ id: runId, learning: current, seed: started?.seed ?? null, settled, used: learnedUseOf(started, reflect, rows, callArgsOf(entries), laidOf(entries), nativeSkillLoads(entries)) }, shown, secrets);
210
375
  }
@@ -1,4 +1,4 @@
1
- import type { TimelineEvent } from "./timeline/index.js";
1
+ import { type TimelineEvent } from "./timeline/index.js";
2
2
  import { type ItemStatus } from "./learning.js";
3
3
  import { type RunMoment, type SignInReader } from "./run-view.js";
4
4
  import { type Store } from "./store/store.js";
@@ -24,6 +24,20 @@ export interface ViewDeps {
24
24
  export declare function viewOverStore(store: Store, runId: string, deps: ViewDeps): Promise<Record<string, unknown> | undefined>;
25
25
  /** The run list's answer from the store, byte-identical to runs.ts's summary: the view's subset a list shows. */
26
26
  export declare function summaryOverStore(store: Store, runId: string, deps: ViewDeps): Promise<Record<string, unknown> | undefined>;
27
+ /** A run's facts as its view states them, and none of its words: its kind, revision, agent, status and times, and whether
28
+ * its output is withheld (`unshown`). What a read that serves its own parts (the graph) needs of the run: read off the
29
+ * run as viewOverStore reads it, with nothing of it served, so nothing is redacted here. Undefined for an unknown run. */
30
+ export declare function factsOverStore(store: Store, runId: string, deps: ViewDeps): Promise<RunStated | undefined>;
31
+ /** A run's facts as its view states them (factsOverStore): no word of it, so nothing in it is redacted. */
32
+ export type RunStated = {
33
+ readonly kind: string;
34
+ readonly revision: string;
35
+ readonly agentId: string;
36
+ readonly status: string;
37
+ readonly createdAt: string;
38
+ readonly endedAt: string | null;
39
+ readonly unshown: boolean;
40
+ };
27
41
  /** A run's live moment from the store (momentOf), for the one acceptance each act a run takes reads. A run no runner holds
28
42
  * (ended, or running with no live claim) reads live false. */
29
43
  export declare function momentOverStore(store: Store, runId: string, deps?: ViewDeps): Promise<RunMoment | undefined>;
@@ -4,19 +4,21 @@
4
4
  // model sees do not change. runs.ts still answers the API from files; this is the store-backed path the server cut switches
5
5
  // onto. viewOverStore answers the run read, summaryOverStore the run list, momentOverStore the one acceptance each act reads.
6
6
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
7
+ import { CAPS } from "./timeline/index.js";
7
8
  import { runLink } from "./console-links.js";
8
9
  import { redacted, redactedAnswer, redactedOutput, withoutLoopback } from "./key-refusal.js";
9
10
  import { structuredAnswer } from "./answer-json.js";
10
11
  import { currentLearning, holdsForOk, learningView, LEARNING_LABEL, secretsShown, shortOf } from "./learning.js";
11
12
  import { said } from "./learning-words.js";
13
+ import { CONTENT_FILTER_WORDS, contentFiltered, MODERATED } from "./content-filter.js";
12
14
  import { launchOf } from "./handed-values.js";
13
15
  import { learningStartOf, seedFailed } from "./run-launch.js";
14
- import { momentOf, pendingOf, approvalOf, asksOf, answersOf, budgetOf, browserPending, computerPending, redactorOf, servedRunErrorWith, servedReviewWith, statusOf, WITHHELD_SIGN_IN, WITHHELD_TITLE, costView, soFarOf, withAsks, withApprovalRows, } from "./run-view.js";
16
+ import { momentOf, pendingOf, approvalOf, asksOf, answersOf, activePauseOf, budgetOf, browserPending, computerPending, redactorOf, servedRunErrorWith, servedReviewWith, statusOf, WITHHELD_SIGN_IN, WITHHELD_TITLE, costView, soFarOf, withAsks, withApprovalRows, } from "./run-view.js";
15
17
  import { reflects } from "./reflect-range.js";
16
18
  import { overCapMessage, SPEND_CAP_REACHED } from "@parcha/agentrun-kernel/kernel/cap";
17
19
  import { bookedSpend } from "./runner/metrics.js";
18
20
  import { journalRecords, recordOf } from "./runner/journal-reader.js";
19
- import { KINDS } from "./runner/journal-kinds.js";
21
+ import { capNowOf, KINDS } from "./runner/journal-kinds.js";
20
22
  import { notesReadOf, runLearningEnd, withNotes } from "./store-reads/learning.js";
21
23
  import { runReflect, runTimeline, wholeAnswerFor, wholeAnswers } from "./store-reads/journal.js";
22
24
  import { readRun } from "./store-reads/runs.js";
@@ -62,14 +64,17 @@ function servedOnce(store, runId, input, values) {
62
64
  const answerOf = (rows) => rows.findLast((r) => r.kind === "final_answer" && r.agent_label !== LEARNING_LABEL)?.text ?? null;
63
65
  /** A failed run's error from its row (its own words are the summary; the store keeps no code or detail apart). A run
64
66
  * its cap ended once its cost passed it (the kernel's overCapEnd) is code spend_cap_reached, its message the words after
65
- * the code, as main served it; every other failure is run_failed. */
67
+ * the code, as main served it; a provider's content-filter stop is `moderated`, in words a person can act on
68
+ * (content-filter.ts); every other failure is run_failed. */
66
69
  const errorOfRow = (summary) => {
67
70
  const over = overCapMessage(summary);
68
71
  if (over !== undefined)
69
72
  return { code: SPEND_CAP_REACHED, message: over, retryable: false };
73
+ if (summary !== null && contentFiltered(summary))
74
+ return { code: MODERATED, message: CONTENT_FILTER_WORDS, retryable: false };
70
75
  return { code: "run_failed", message: summary ?? "The run failed.", retryable: false };
71
76
  };
72
- const reviewOfRow = (state, summary) => (state !== "escalated" ? null : { kind: null, node: null, reason: summary ?? "The workflow escalated." });
77
+ const reviewOfRow = (state, summary, kept) => (state !== "escalated" ? null : (kept ?? { kind: null, node: null, reason: summary ?? "The workflow escalated." }));
73
78
  const reviewAt = (review, endedAt) => (review ? { kind: review.kind, node: review.node, reason: review.reason, at: endedAt } : null);
74
79
  /** A run's facts as statusOf and momentOf read them, built from the run's journal: whether it stands parked at its cap
75
80
  * (an active agentrun.budget park), and the browser ask it waits on (wired next). A terminal run reaches none of them
@@ -165,14 +170,14 @@ async function storeRunOf(store, runId, deps) {
165
170
  // The rows a person reads: each call that waited for approval in order (held, your approval, what came of it), its
166
171
  // arguments and the person's notes through the run's redactor, as the file path's withApprovals served them.
167
172
  const rows = withApprovalRows(timeline, approvals, answers, redactorOf(values));
168
- // The run's cap as it stands: its newest raise's (the agentrun.raise entries the runner's loop holds it to, adapter-loop
169
- // capNow), else its launch's; a raise taken shows in the run's cost.cap_usd and its budget card, never the old cap.
170
- const raisedCapUsd = records.entries.findLast((entry) => entry.kind === KINDS.raise && typeof entry.data?.capUsd === "number" && entry.data.capUsd > 0)?.data;
171
- const capUsd = launch?.maxCostUsd === undefined ? undefined : Math.max(launch.maxCostUsd, raisedCapUsd?.capUsd ?? 0);
173
+ // The run's cap as it stands, through the one reader the runner's gate reads too (capNowOf): a raise taken shows in the
174
+ // run's cost.cap_usd and its budget card, never the old cap.
175
+ const capUsd = capNowOf(launch?.maxCostUsd, records.entries);
172
176
  const meta = { ...(capUsd !== undefined ? { max_cost_usd: capUsd } : {}), ...(Object.keys(answers).length ? { approvals: answers } : {}) };
173
177
  // The budget card the run shows while it stands parked at its cap, from its journal's agentrun.budget park (none once a
174
178
  // raise clears it). Read over the same meta cap and rows the card's figures and time come from.
175
179
  const budget = budgetOf(records.entries, { meta, rows, updatedAt: iso(updatedAtMs) });
180
+ const pause = activePauseOf(records.entries);
176
181
  // Whether a workflow run stands paused in its process now (its parked row with the pause's words, its newest pause not
177
182
  // resumed), the `paused` fact the status table reads for a paused workflow.
178
183
  const paused = pausedOf(runRow, records.entries);
@@ -218,15 +223,19 @@ async function storeRunOf(store, runId, deps) {
218
223
  // The cap pause's words, so the moment reads paused for a store budget park (the write half's raiseCap/sendMessage read
219
224
  // moment.paused/pausedWords); the file path's turns-based pausedAt gives nothing over the store.
220
225
  ...(budget?.kind === "budget" ? { pausedWords: budget.said } : {}),
226
+ // The park's own id: a raise's answer names the follow-up the runner sends for this pause (raiseFollowUpId).
227
+ ...(budget?.kind === "budget" && pause !== undefined ? { pause } : {}),
221
228
  meta,
222
229
  };
223
230
  // A completed workflow run's output, from its end (the workflow loop keeps it there, as main kept it on the run).
224
231
  const end = row.kind === "workflow" ? records.entries.findLast((entry) => entry.kind === KINDS.end) : undefined;
225
232
  const output = end?.data?.output ?? null;
233
+ // An escalated workflow run's review, as its end kept it (the escalate node's kind, label and summary).
234
+ const review = end?.data?.review;
226
235
  // What its decisions booked (their own session, never on the usage row, which counts its model requests and paid tools).
227
236
  const booked = bookedSpend(records.entries, "decisions");
228
237
  const decisions = booked.requests ? booked : undefined;
229
- return { row, runRow, launch, rows, version, harness, learningEnd, view, unshown, values, live, updatedAtMs, lastProgressAt, budget, paused, browserAsk, computerAsk, approvalsMode, output, structured, decisions };
238
+ return { row, runRow, launch, rows, version, harness, learningEnd, view, unshown, values, live, updatedAtMs, lastProgressAt, budget, paused, browserAsk, computerAsk, approvalsMode, output, ...(review ? { review } : {}), structured, decisions };
230
239
  }
231
240
  /** A run's learning as the view shows it: its end from the store (what it held for the owner's OK as it reads now), in a
232
241
  * person's words cut of the host's secrets now, and, for an ended run, the notes it read. */
@@ -263,7 +272,7 @@ export async function viewOverStore(store, runId, deps) {
263
272
  const run = await storeRunOf(store, runId, deps);
264
273
  if (!run)
265
274
  return undefined;
266
- const { row, runRow, launch, view, unshown, values, output, structured } = run;
275
+ const { row, runRow, launch, view, unshown, values, output, review: kept, structured } = run;
267
276
  const { status, state } = statusOf(view, factsOf(run));
268
277
  const terminal = TERMINAL.has(status);
269
278
  const endedAtMs = terminal ? (runRow.endedAt ?? runRow.startedAt) : null;
@@ -278,7 +287,20 @@ export async function viewOverStore(store, runId, deps) {
278
287
  // run's sign-in can't be read back.
279
288
  const ownOutput = row.kind === "workflow" ? output : status === "completed" && structured && "value" in structured ? structured.value : null;
280
289
  const servedOutput = !unshown && ownOutput !== null && ownOutput !== undefined ? redactedOutput(ownOutput, values) : null;
281
- const result = status === "completed" ? { output: servedOutput, final_answer: servedAnswer(finalAnswer) } : null;
290
+ // A run its cap ended once its cost passed it (spend_cap_reached) keeps the answer it paid for, as main kept it: the
291
+ // response that crossed the cap was answered and billed, so its text is the run's answer, cut as it came.
292
+ // Its answer is the newest answer row, else (a response cut at its length) the newest text it said; never the row's
293
+ // summary, which holds the cap's words.
294
+ const overCap = status === "failed" && overCapMessage(row.summary ?? null) !== undefined;
295
+ // A text the timeline cut at its cap is read whole from the journal and served as an answer row is (wholeAnswerFor).
296
+ const capRow = overCap && !unshown ? (run.rows.findLast((r) => r.kind === "final_answer" && r.agent_label !== LEARNING_LABEL) ?? run.rows.findLast((r) => r.kind === "text_block" && r.agent_label !== LEARNING_LABEL)) : undefined;
297
+ let capAnswer = capRow?.text ?? null;
298
+ if (capRow?.kind === "text_block" && capAnswer !== null && (capAnswer.length >= CAPS.text || capAnswer.endsWith("...") || capAnswer === "[redacted]")) {
299
+ const whole = (await runTimeline(store, runId, BACKGROUND_CONTEXT, { settled: true, caps: { text: Number.POSITIVE_INFINITY } })).find((r) => r.id === capRow.id)?.text;
300
+ if (typeof whole === "string")
301
+ capAnswer = wholeAnswerFor(values).serve(whole);
302
+ }
303
+ const result = status === "completed" ? { output: servedOutput, final_answer: servedAnswer(finalAnswer) } : overCap ? { output: null, final_answer: servedAnswer(capAnswer) } : null;
282
304
  // A failed run's reason in the model's own words when the store holds them: the last model-error row's text (a provider's
283
305
  // refusal, rendered from its pi.assistant error entry), else the run row's summary (the runner's generic "gave no answer").
284
306
  // It reads as the run's Timeline error row does (run-cut.ts runErrorWordsOf, main's errorWords): a refused key in plain
@@ -288,7 +310,7 @@ export async function viewOverStore(store, runId, deps) {
288
310
  const errorWords = status === "failed" && !unshown ? await runErrorWordsOf({ ...deps, keyEnv: deps.keyEnv ?? (() => process.env) }, store, runId, { workflow: row.kind === "workflow" }) : undefined;
289
311
  const withheld = unshown || errorWords === "unreadable";
290
312
  const error = status === "failed" ? (withheld ? { code: "run_failed", message: WITHHELD_SIGN_IN, retryable: false } : servedRunErrorWith(errorWords ?? shownWords, errorOfRow(failedReason))) : null;
291
- const review = endedAtMs === null ? null : servedReviewWith(shownWords, unshown, reviewAt(reviewOfRow(row.state, row.summary ?? null), iso(endedAtMs)));
313
+ const review = endedAtMs === null ? null : servedReviewWith(shownWords, unshown, reviewAt(reviewOfRow(row.state, row.summary ?? null, kept), iso(endedAtMs)));
292
314
  // The card the run shows while it waits, in the order the file-backed view (runs.ts) picks them: a tool call parked for a
293
315
  // person's approval (approvalOf, its arguments shown through the run's redactor), else a run parked at its cap (the budget
294
316
  // card), else its agent waiting on a person in its browser (browserPending), else the question its turn ended on (pendingOf).
@@ -348,6 +370,17 @@ export async function summaryOverStore(store, runId, deps) {
348
370
  learning: learning ? shortOf(learning) : null,
349
371
  };
350
372
  }
373
+ /** A run's facts as its view states them, and none of its words: its kind, revision, agent, status and times, and whether
374
+ * its output is withheld (`unshown`). What a read that serves its own parts (the graph) needs of the run: read off the
375
+ * run as viewOverStore reads it, with nothing of it served, so nothing is redacted here. Undefined for an unknown run. */
376
+ export async function factsOverStore(store, runId, deps) {
377
+ const run = await storeRunOf(store, runId, deps);
378
+ if (!run)
379
+ return undefined;
380
+ const { status } = statusOf(run.view, factsOf(run));
381
+ const endedAtMs = TERMINAL.has(status) ? (run.runRow.endedAt ?? run.runRow.startedAt) : null;
382
+ return { kind: run.row.kind, revision: run.row.revision, agentId: run.row.agent, status, createdAt: iso(run.runRow.startedAt), endedAt: endedAtMs === null ? null : iso(endedAtMs), unshown: run.unshown };
383
+ }
351
384
  /** A run's live moment from the store (momentOf), for the one acceptance each act a run takes reads. A run no runner holds
352
385
  * (ended, or running with no live claim) reads live false. */
353
386
  export async function momentOverStore(store, runId, deps = { origin: "", serverSecrets: () => [] }) {
@@ -77,8 +77,11 @@ export type Package = {
77
77
  };
78
78
  parameters: Record<string, Parameter>;
79
79
  secrets: string[];
80
+ /** Each run's limits: its spend cap (the agent's max_cost_usd) and the tool calls each of its conversations may make
81
+ * (the agent's max_tool_calls, tool-budget.ts). */
80
82
  budget?: {
81
- per_run_usd: number;
83
+ per_run_usd?: number;
84
+ tool_calls?: number;
82
85
  };
83
86
  learning?: boolean;
84
87
  /** Whether the agent asks its person before a tool runs (`ask`) or runs unattended (`never`): the package's default,
@@ -107,8 +110,9 @@ export declare class PackageError extends Error {
107
110
  * to acme/widgets." The package's name says what runs; the events are its accept's, the repositories its where
108
111
  * conditions on /repository/full_name, when every rule names some. */
109
112
  export declare function githubTriggerWords(packageName: string, source: Json): string;
110
- /** What an apply says of a github trigger it skipped because GitHub is not connected here. */
111
- export declare const GITHUB_TRIGGER_UNCONNECTED = "Connect GitHub in Settings, then apply again to review pull requests automatically.";
113
+ /** What an apply says of a github trigger it skipped because GitHub is not connected here: what to do, and what the
114
+ * trigger would then run on, in the package's own words ("Code review runs on each pull request to acme/widgets."). */
115
+ export declare const githubTriggerUnconnected: (packageName: string, source: Json) => string;
112
116
  /** Reads `dir` checked whole: a valid package, or PackageError with every problem found. */
113
117
  export declare function readPackage(dir: string): Package;
114
118
  /** What is wrong with the trigger bodies an apply makes (compiled's `triggers`), as POST /v2/triggers checks a body, all
@@ -154,7 +158,8 @@ export declare function packageView(p: Package): {
154
158
  parameters: Record<string, Parameter>;
155
159
  secrets: string[];
156
160
  budget: {
157
- per_run_usd: number;
161
+ per_run_usd?: number;
162
+ tool_calls?: number;
158
163
  } | null;
159
164
  learning: boolean;
160
165
  approvals_default: "ask" | "never";
package/dist/templates.js CHANGED
@@ -19,7 +19,7 @@ import { BASH_POLICIES } from "./bash-read-only.js";
19
19
  import { BOUND_TOOLS } from "./tools.js";
20
20
  import { TRIGGER_ADAPTERS } from "./trigger-adapters.js";
21
21
  import { triggerBodyIssues } from "./triggers.js";
22
- import { DEFAULT_INPUT_SCHEMA, definitionBodyIssues, inputIssues, isObject, MODEL_REF, unknownFields } from "./validate.js";
22
+ import { DEFAULT_INPUT_SCHEMA, definitionBodyIssues, inputIssues, isObject, MAX_TOOL_CALLS, MODEL_REF, unknownFields } from "./validate.js";
23
23
  import { APPROVALS } from "./approvals.js";
24
24
  export const TEMPLATES_DIR = fileURLToPath(new URL("../templates/", import.meta.url));
25
25
  export const MANIFEST = "agent.md";
@@ -98,9 +98,10 @@ export function githubTriggerWords(packageName, source) {
98
98
  const or = (words) => (words.length < 2 ? words.join("") : `${words.slice(0, -1).join(", ")} or ${words.at(-1)}`);
99
99
  return `${subject} runs on each ${or(events)} ${repos.length ? `to ${or(repos)}` : "to a repository the GitHub App is installed on"}.`;
100
100
  }
101
- const GITHUB_EVENT_WORDS = { pull_request: "pull request", pull_request_review: "pull request review", pull_request_review_comment: "review comment", issue_comment: "comment", issues: "issue" };
102
- /** What an apply says of a github trigger it skipped because GitHub is not connected here. */
103
- export const GITHUB_TRIGGER_UNCONNECTED = "Connect GitHub in Settings, then apply again to review pull requests automatically.";
101
+ const GITHUB_EVENT_WORDS = { pull_request: "pull request", pull_request_review: "pull request review", pull_request_review_comment: "review comment", issue_comment: "comment", issues: "issue", release: "release" };
102
+ /** What an apply says of a github trigger it skipped because GitHub is not connected here: what to do, and what the
103
+ * trigger would then run on, in the package's own words ("Code review runs on each pull request to acme/widgets."). */
104
+ export const githubTriggerUnconnected = (packageName, source) => `Connect GitHub in Settings, then apply again so it runs by itself: ${githubTriggerWords(packageName, source)}`;
104
105
  /** Every string in `value`, deep. */
105
106
  const strings = (value) => (typeof value === "string" ? [value] : Array.isArray(value) ? value.flatMap(strings) : isObject(value) ? Object.values(value).flatMap(strings) : []);
106
107
  /** `value` with each `${parameters.x}` in its strings replaced by the value given for x (its own: never an inherited
@@ -329,8 +330,12 @@ export function readPackage(dir) {
329
330
  const secrets = list(f.secrets, "secrets", (secret) => /^[A-Z][A-Z0-9_]{0,127}$/.test(secret));
330
331
  for (const secret of secrets.filter((name) => !PACKAGE_SECRETS.includes(name)))
331
332
  bad(MANIFEST, `secrets names ${secret}, a key this server cannot hold: a package needs the keys Settings saves and a run is handed (${PACKAGE_SECRETS.join(", ")})`);
332
- if (f.budget !== undefined && !(isObject(f.budget) && !unknownFields(f.budget, ["per_run_usd"]).length && typeof f.budget.per_run_usd === "number" && Number.isFinite(f.budget.per_run_usd) && f.budget.per_run_usd > 0))
333
- bad(MANIFEST, "budget is {per_run_usd: a number above 0}");
333
+ // Each run's limits: its spend cap (per_run_usd, the agent's max_cost_usd) and its tool-call budget (tool_calls, the
334
+ // agent's max_tool_calls: each conversation's calls), one of them at least.
335
+ const perRun = (value) => typeof value === "number" && Number.isFinite(value) && value > 0;
336
+ const toolCalls = (value) => Number.isSafeInteger(value) && value > 0 && value <= MAX_TOOL_CALLS;
337
+ if (f.budget !== undefined && !(isObject(f.budget) && Object.keys(f.budget).length && !unknownFields(f.budget, ["per_run_usd", "tool_calls"]).length && (f.budget.per_run_usd === undefined || perRun(f.budget.per_run_usd)) && (f.budget.tool_calls === undefined || toolCalls(f.budget.tool_calls))))
338
+ bad(MANIFEST, `budget is {per_run_usd?: a number above 0, tool_calls?: a whole number from 1 to ${MAX_TOOL_CALLS}}, one of them at least`);
334
339
  if (f.learning !== undefined && typeof f.learning !== "boolean")
335
340
  bad(MANIFEST, "learning is true or false");
336
341
  if (f.approvals !== undefined && f.approvals !== "ask" && f.approvals !== "never")
@@ -350,7 +355,7 @@ export function readPackage(dir) {
350
355
  if (!isObject(target) || target.kind !== "start_run" || target.agent_id !== undefined)
351
356
  bad(MANIFEST, `triggers[${i}].target is a start_run with no agent_id: the agent is the one the package makes`);
352
357
  });
353
- if (triggers.length && f.budget === undefined)
358
+ if (triggers.length && !(isObject(f.budget) && f.budget.per_run_usd !== undefined))
354
359
  bad(MANIFEST, "budget is required when the package has triggers: {per_run_usd}, each run's cap");
355
360
  let outputSchema;
356
361
  let schemaBounded = true;
@@ -496,7 +501,7 @@ export function readPackage(dir) {
496
501
  name, ...(typeof f.display_name === "string" ? { displayName: f.display_name } : {}), version: f.version, description: f.description,
497
502
  ...(typeof f.license === "string" ? { license: f.license } : {}), ...(isObject(f.author) ? { author: f.author } : {}), ...(typeof f.repository === "string" ? { repository: f.repository } : {}),
498
503
  ...(harness ? { harness } : {}), ...(isObject(f.model) ? { model: f.model } : {}), ...(typeof f.effort === "string" ? { effort: f.effort } : {}),
499
- ...(tools ? { tools } : {}), mcp, ...(toolPolicy ? { toolPolicy } : {}), parameters, secrets, ...(isObject(f.budget) ? { budget: { per_run_usd: f.budget.per_run_usd } } : {}), ...(typeof f.learning === "boolean" ? { learning: f.learning } : {}), ...(f.approvals === "ask" || f.approvals === "never" ? { approvals: f.approvals } : {}),
504
+ ...(tools ? { tools } : {}), mcp, ...(toolPolicy ? { toolPolicy } : {}), parameters, secrets, ...(isObject(f.budget) ? { budget: { ...(typeof f.budget.per_run_usd === "number" ? { per_run_usd: f.budget.per_run_usd } : {}), ...(typeof f.budget.tool_calls === "number" ? { tool_calls: f.budget.tool_calls } : {}) } } : {}), ...(typeof f.learning === "boolean" ? { learning: f.learning } : {}), ...(f.approvals === "ask" || f.approvals === "never" ? { approvals: f.approvals } : {}),
500
505
  triggers: triggers, ...(isObject(f.output) ? { output: { schema: f.output.schema } } : {}), ...(isObject(outputSchema) ? { outputSchema } : {}), checks, instructions, skills, evals,
501
506
  };
502
507
  // What an apply makes, made here with each parameter's default, else a sample of its type, and checked as POST
@@ -650,7 +655,7 @@ export function compiled(p, parameters, chosen, _deps) {
650
655
  name: p.displayName ? filled(p.displayName, parameters) : p.name, description: p.description, instructions: filled(p.instructions, parameters),
651
656
  ...(chosen.harness ? { harness: chosen.harness } : {}), ...(chosen.model ? { model: chosen.model } : {}), ...(p.effort ? { thinking: p.effort } : {}),
652
657
  ...(tools ? { tools } : {}), ...(Object.keys(settings).length ? { tool_settings: settings } : {}),
653
- ...(p.learning !== undefined ? { learning: p.learning } : {}), ...(p.budget ? { max_cost_usd: p.budget.per_run_usd } : {}), skills,
658
+ ...(p.learning !== undefined ? { learning: p.learning } : {}), ...(p.budget?.per_run_usd ? { max_cost_usd: p.budget.per_run_usd } : {}), ...(p.budget?.tool_calls ? { max_tool_calls: p.budget.tool_calls } : {}), skills,
654
659
  // The apply's choice: unattended only when it says never (none given: the agent asks).
655
660
  ...(chosen.approvals === "never" ? { approvals: "never" } : {}),
656
661
  // The package's answer schema (manifest `output`): each completed run's structured answer, checked, is its result.output.
@@ -63,6 +63,14 @@ export type TimelineEvent = {
63
63
  unpriced?: number;
64
64
  not_metered?: number;
65
65
  };
66
+ /** On a learned workflow call's `tool_result` row (learned_workflow): each of the workflow's nodes that ran, as the
67
+ * workflow DSL ended it, in order (store-reads/journal.ts withLearnedNodes). This projector writes none. */
68
+ learned_nodes?: {
69
+ label: string;
70
+ kind: string;
71
+ status: string;
72
+ duration_ms: number;
73
+ }[];
66
74
  };
67
75
  /** A pi conversation entry as stored: `pi.assistant`, `pi.tool-result`, a host's own kind. */
68
76
  export type EntryLike = {
@@ -0,0 +1,18 @@
1
+ import { type EntryRecord } from "@earendil-works/pi-durable";
2
+ /** What a call past the budget reads: the same words every time, never a count the model could argue with. */
3
+ export declare const TOOL_BUDGET_TEXT = "Tool budget spent: this conversation has made every tool call it may. Don't call another tool: answer now, from what you have.";
4
+ /** The tool calls before `callId` once one more page of a conversation's entries (`entries`, oldest first) is read, from
5
+ * `count`, the earlier pages': `done` once the call is reached or the count is `upTo`, where a reader stops. */
6
+ export declare function countCalls(entries: readonly EntryRecord[], callId: string, upTo: number, count?: number): {
7
+ count: number;
8
+ done: boolean;
9
+ };
10
+ /** What a call reads once its run's cap is nearly taken: the same words every time, as the tool-call budget's. */
11
+ export declare const WRAP_UP_TEXT = "Budget nearly spent: stop calling tools and answer now from what you have.";
12
+ /** The share of a run's cap at which it wraps up. Its spend and its holds together: a hold is a request's worst case,
13
+ * never its cost, so several requests out at once reach the line long before their spend does, and the quarter left
14
+ * above it is room for each conversation still working to answer. */
15
+ export declare const WRAP_UP_SHARE = 0.75;
16
+ /** Whether a run under `capUsd` that has taken `takenUsd` (its spend and what its steps still out hold, as the cap counts
17
+ * them; null: unknown) wraps up. No cap, or a figure no one knows (the cap refuses the next request for that), is no. */
18
+ export declare const wrappingUp: (capUsd: number | undefined, takenUsd: number | null) => boolean;
@@ -0,0 +1,50 @@
1
+ // A tool-call budget: an agent's `max_tool_calls`, held by the run's tool gate on pi. Each conversation of the run (the
2
+ // root, and any conversation a tool opens) may make that many tool calls; past it, every call is refused before its
3
+ // intent with one fixed text that tells the model to answer now from what it has. The refusal is not counted, and the
4
+ // run is never ended by it: the model's next answer is the turn's.
5
+ //
6
+ // The count is read from the conversation's committed entries, never kept in memory, so a restart or a moved claim counts
7
+ // the same calls: the tool calls of its assistant entries before this one, oldest first. The read stops at the budget: no
8
+ // refusal can come before the budget's last allowed call, so every call it counts is one that was let through, and a
9
+ // check never reads past them however long the run goes on. A call of the same round whose result has not landed yet
10
+ // counts as made: a round's calls are counted in the order the model gave them, so a round that crosses the line runs
11
+ // its first calls up to it and the rest are refused.
12
+ //
13
+ // The cap's wrap-up, the same refusal for money: a run with a cap whose spend, plus what its requests and paid steps
14
+ // still out hold at their worst case, reaches WRAP_UP_SHARE of the cap has every model-issued tool call refused before
15
+ // its intent, in WRAP_UP_TEXT, on every harness and in every conversation of the run (a `subagent` spawn is a call too).
16
+ // Nothing in flight is cut, and model requests are not touched: each conversation answers from what it has, under the
17
+ // cap, which stays the last line. The figure is read from the run's committed booking records at each call (the cap's
18
+ // own: a request still out counts at its hold and bound, one a lost claim cut the same), so a restart or a moved claim
19
+ // reads the same figure, and a raise of the cap ends the wrap-up from its next call.
20
+ import { AssistantEntry } from "@earendil-works/pi-durable";
21
+ /** What a call past the budget reads: the same words every time, never a count the model could argue with. */
22
+ export const TOOL_BUDGET_TEXT = "Tool budget spent: this conversation has made every tool call it may. Don't call another tool: answer now, from what you have.";
23
+ /** The tool calls before `callId` once one more page of a conversation's entries (`entries`, oldest first) is read, from
24
+ * `count`, the earlier pages': `done` once the call is reached or the count is `upTo`, where a reader stops. */
25
+ export function countCalls(entries, callId, upTo, count = 0) {
26
+ for (const entry of entries) {
27
+ if (!AssistantEntry.is(entry))
28
+ continue;
29
+ const content = entry.model?.[0]?.content;
30
+ if (!Array.isArray(content))
31
+ continue;
32
+ for (const part of content) {
33
+ if (part?.type !== "toolCall" || typeof part.id !== "string")
34
+ continue;
35
+ if (part.id === callId || count >= upTo)
36
+ return { count, done: true };
37
+ count++;
38
+ }
39
+ }
40
+ return { count, done: count >= upTo };
41
+ }
42
+ /** What a call reads once its run's cap is nearly taken: the same words every time, as the tool-call budget's. */
43
+ export const WRAP_UP_TEXT = "Budget nearly spent: stop calling tools and answer now from what you have.";
44
+ /** The share of a run's cap at which it wraps up. Its spend and its holds together: a hold is a request's worst case,
45
+ * never its cost, so several requests out at once reach the line long before their spend does, and the quarter left
46
+ * above it is room for each conversation still working to answer. */
47
+ export const WRAP_UP_SHARE = 0.75;
48
+ /** Whether a run under `capUsd` that has taken `takenUsd` (its spend and what its steps still out hold, as the cap counts
49
+ * them; null: unknown) wraps up. No cap, or a figure no one knows (the cap refuses the next request for that), is no. */
50
+ export const wrappingUp = (capUsd, takenUsd) => capUsd !== undefined && takenUsd !== null && Number.isFinite(takenUsd) && takenUsd >= WRAP_UP_SHARE * capUsd;
@@ -207,8 +207,12 @@ export declare class RunGate {
207
207
  * the deny (with where it was set, and that nothing was sent or charged), a pin, bash's policy (policyRefusal), then
208
208
  * the allow, then the ask, so an allow that approvals "never" made is decided
209
209
  * only after every refusal. Where no one can approve (accounts off: the store's approvers row a runner reads at each
210
- * claim, server-approvers.ts), the ask is refused at once in words, never parked, as `enter` refuses it. */
211
- decide(name: string, args: unknown): Promise<"allow" | "ask" | {
210
+ * claim, server-approvers.ts), the ask is refused at once in words, never parked, as `enter` refuses it. `replayed`:
211
+ * the call is run again after an earlier attempt that may have been sent (a replay-safe call rerun after a crash), so a
212
+ * refusal says whether it took effect is not known, never that nothing was sent. */
213
+ decide(name: string, args: unknown, options?: {
214
+ readonly replayed?: boolean;
215
+ }): Promise<"allow" | "ask" | {
212
216
  deny: string;
213
217
  }>;
214
218
  /** The name a call is asked about by, as main's request names it (enter's `tool`): its settings key, a shell tool its