@parcha/agentrun-serve 0.1.0-beta.42 → 0.1.0-beta.44

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 (181) hide show
  1. package/CHANGELOG.md +126 -0
  2. package/README.md +221 -31
  3. package/dist/cli.js +42 -8
  4. package/dist/composio-preset.d.ts +4 -3
  5. package/dist/composio-preset.js +12 -4
  6. package/dist/composio-triggers.d.ts +20 -2
  7. package/dist/composio-triggers.js +183 -17
  8. package/dist/computer-lost.d.ts +11 -0
  9. package/dist/computer-lost.js +19 -0
  10. package/dist/computer-record.d.ts +10 -2
  11. package/dist/computer-record.js +50 -18
  12. package/dist/computer-setting.d.ts +1 -0
  13. package/dist/computer-setting.js +2 -2
  14. package/dist/console/assets/index-BUktRvS-.css +1 -0
  15. package/dist/console/assets/index-nB9kTfIN.js +711 -0
  16. package/dist/console/index.html +2 -2
  17. package/dist/decisions.js +0 -4
  18. package/dist/errors.d.ts +1 -0
  19. package/dist/errors.js +3 -0
  20. package/dist/harness-table.d.ts +51 -3
  21. package/dist/harness-table.js +101 -13
  22. package/dist/harness.d.ts +18 -1
  23. package/dist/harness.js +21 -9
  24. package/dist/host.d.ts +12 -10
  25. package/dist/host.js +18 -16
  26. package/dist/import-sources.js +25 -5
  27. package/dist/import-worker.d.ts +3 -0
  28. package/dist/import-worker.js +7 -5
  29. package/dist/import.d.ts +22 -1
  30. package/dist/import.js +141 -28
  31. package/dist/learn/audit.d.ts +123 -0
  32. package/dist/learn/audit.js +159 -0
  33. package/dist/learn/check.d.ts +3 -0
  34. package/dist/learn/check.js +1 -1
  35. package/dist/learn/compile.d.ts +50 -74
  36. package/dist/learn/compile.js +90 -124
  37. package/dist/learn/delete.d.ts +17 -0
  38. package/dist/learn/delete.js +44 -0
  39. package/dist/learn/folder.d.ts +9 -0
  40. package/dist/learn/folder.js +13 -2
  41. package/dist/learn/promote.d.ts +92 -200
  42. package/dist/learn/promote.js +65 -187
  43. package/dist/learn/replay-calls.d.ts +5 -0
  44. package/dist/learn/replay-calls.js +12 -1
  45. package/dist/learn/secrets.d.ts +8 -0
  46. package/dist/learn/secrets.js +12 -0
  47. package/dist/learn/skills.d.ts +4 -0
  48. package/dist/learn/skills.js +19 -5
  49. package/dist/learn/workflow-nodes.d.ts +23 -3
  50. package/dist/learn/workflow-nodes.js +30 -12
  51. package/dist/learned-nodes.d.ts +9 -34
  52. package/dist/learned-nodes.js +11 -23
  53. package/dist/learned-workflow.d.ts +6 -8
  54. package/dist/learned-workflow.js +18 -57
  55. package/dist/learning-batch.d.ts +13 -5
  56. package/dist/learning-batch.js +34 -8
  57. package/dist/learning-cost.d.ts +111 -4
  58. package/dist/learning-cost.js +120 -3
  59. package/dist/learning-evals.d.ts +2 -0
  60. package/dist/learning-evals.js +4 -3
  61. package/dist/learning-routes.d.ts +8 -0
  62. package/dist/learning-routes.js +18 -1
  63. package/dist/learning-setting.d.ts +16 -1
  64. package/dist/learning-setting.js +34 -2
  65. package/dist/learning.d.ts +1 -1
  66. package/dist/listen-first.d.ts +30 -0
  67. package/dist/listen-first.js +115 -0
  68. package/dist/llms.txt +2 -1
  69. package/dist/mcp-servers-store.d.ts +12 -12
  70. package/dist/model.d.ts +8 -4
  71. package/dist/model.js +16 -8
  72. package/dist/openapi.js +203 -87
  73. package/dist/owner.d.ts +8 -0
  74. package/dist/owner.js +11 -0
  75. package/dist/paid-calls.d.ts +6 -0
  76. package/dist/paid-calls.js +11 -1
  77. package/dist/place.d.ts +8 -3
  78. package/dist/place.js +13 -9
  79. package/dist/provider.js +15 -1
  80. package/dist/run-launch.d.ts +6 -3
  81. package/dist/run-launch.js +2 -0
  82. package/dist/run-learning-served.d.ts +1 -1
  83. package/dist/run-model-key.d.ts +64 -0
  84. package/dist/run-model-key.js +147 -0
  85. package/dist/runner/adapter-loop.d.ts +10 -0
  86. package/dist/runner/adapter-loop.js +26 -4
  87. package/dist/runner/adapter-run-spec.d.ts +6 -3
  88. package/dist/runner/adapter-run-spec.js +83 -25
  89. package/dist/runner/adapters/index.d.ts +4 -2
  90. package/dist/runner/adapters/index.js +13 -4
  91. package/dist/runner/audit.d.ts +68 -0
  92. package/dist/runner/audit.js +349 -0
  93. package/dist/runner/beside.d.ts +2 -1
  94. package/dist/runner/beside.js +6 -3
  95. package/dist/runner/claim-secrets.d.ts +49 -0
  96. package/dist/runner/claim-secrets.js +110 -1
  97. package/dist/runner/cli-run-spec.d.ts +2 -1
  98. package/dist/runner/cli-run-spec.js +44 -15
  99. package/dist/runner/commands.d.ts +3 -6
  100. package/dist/runner/feedback-round.d.ts +3 -2
  101. package/dist/runner/feedback-round.js +8 -7
  102. package/dist/runner/harness-loops.js +31 -23
  103. package/dist/runner/journal-kinds.d.ts +5 -7
  104. package/dist/runner/journal-kinds.js +0 -7
  105. package/dist/runner/learning-dispatch.d.ts +0 -16
  106. package/dist/runner/learning-dispatch.js +4 -47
  107. package/dist/runner/learning-end.d.ts +55 -13
  108. package/dist/runner/learning-end.js +128 -44
  109. package/dist/runner/learning-factory.d.ts +1 -1
  110. package/dist/runner/learning-factory.js +1 -4
  111. package/dist/runner/learning-loop.d.ts +2 -38
  112. package/dist/runner/learning-loop.js +8 -116
  113. package/dist/runner/loop-contract.d.ts +6 -0
  114. package/dist/runner/loop-contract.js +4 -0
  115. package/dist/runner/loop.js +6 -2
  116. package/dist/runner/main.d.ts +1 -0
  117. package/dist/runner/main.js +25 -8
  118. package/dist/runner/memory-claim.d.ts +9 -6
  119. package/dist/runner/memory-claim.js +12 -9
  120. package/dist/runner/promotion.d.ts +55 -54
  121. package/dist/runner/promotion.js +232 -585
  122. package/dist/runner/reflect-hook.d.ts +14 -0
  123. package/dist/runner/reflect-hook.js +28 -3
  124. package/dist/runner/runner.js +57 -4
  125. package/dist/runner/store-secrets.js +9 -5
  126. package/dist/runner/workflow-first.d.ts +6 -5
  127. package/dist/runner/workflow-first.js +17 -12
  128. package/dist/runner/workflow-spec.js +10 -2
  129. package/dist/runs-over-store.d.ts +5 -4
  130. package/dist/runs-over-store.js +13 -3
  131. package/dist/sdk/workflows.d.ts +1 -1
  132. package/dist/server.d.ts +64 -50
  133. package/dist/server.js +516 -134
  134. package/dist/store/index.d.ts +2 -2
  135. package/dist/store/index.js +1 -1
  136. package/dist/store/seal.d.ts +20 -2
  137. package/dist/store/seal.js +24 -8
  138. package/dist/store/sqlite/run-launch.d.ts +4 -1
  139. package/dist/store/sqlite/run-launch.js +12 -0
  140. package/dist/store/sqlite/store.d.ts +3 -2
  141. package/dist/store/sqlite/store.js +119 -16
  142. package/dist/store/store.d.ts +41 -3
  143. package/dist/store-reads/analytics.js +11 -1
  144. package/dist/store-reads/learning.d.ts +57 -7
  145. package/dist/store-reads/learning.js +194 -28
  146. package/dist/store-reads/loop.d.ts +4 -39
  147. package/dist/store-reads/loop.js +10 -79
  148. package/dist/store-reads/stats.js +13 -3
  149. package/dist/store-view.d.ts +5 -1
  150. package/dist/store-view.js +12 -1
  151. package/dist/telemetry.d.ts +59 -0
  152. package/dist/telemetry.js +153 -0
  153. package/dist/tool-keys-store.d.ts +1 -1
  154. package/dist/tool-keys.d.ts +2 -2
  155. package/dist/tool-plane.d.ts +12 -12
  156. package/dist/tools.d.ts +11 -11
  157. package/dist/tools.js +18 -5
  158. package/dist/trigger-adapter.d.ts +3 -0
  159. package/dist/trigger-adapters.d.ts +4 -0
  160. package/dist/trigger-adapters.js +13 -0
  161. package/dist/trigger-composio.d.ts +58 -1
  162. package/dist/trigger-composio.js +160 -6
  163. package/dist/triggers.d.ts +4 -0
  164. package/dist/triggers.js +22 -3
  165. package/dist/validate.d.ts +11 -7
  166. package/dist/validate.js +8 -7
  167. package/dist/workspace/computer-for-claim.d.ts +15 -5
  168. package/dist/workspace/computer-for-claim.js +228 -32
  169. package/dist/workspace/resolve-computer.d.ts +8 -2
  170. package/dist/workspace/resolve-computer.js +1 -1
  171. package/dist/workspace/run-tools.d.ts +1 -1
  172. package/dist/workspace/run-tools.js +14 -3
  173. package/package.json +10 -9
  174. package/dist/console/assets/index-C3gNPz58.css +0 -1
  175. package/dist/console/assets/index-DYJ_wj27.js +0 -711
  176. package/dist/learn/general.d.ts +0 -69
  177. package/dist/learn/general.js +0 -75
  178. package/dist/learn/refit.d.ts +0 -48
  179. package/dist/learn/refit.js +0 -264
  180. package/dist/runner/step-guard.d.ts +0 -62
  181. package/dist/runner/step-guard.js +0 -93
@@ -38,6 +38,10 @@ export type Checked = {
38
38
  };
39
39
  /** What the hook reads of the run and the host. */
40
40
  export interface ReflectDeps {
41
+ /** Why no grade is queued for what the run proposes, asked when it would be (a grade runs after the run's turn, with no
42
+ * key to spend: learning-end spendOff): its proposal is dropped `grade_failed` in these words, nothing spent. Absent, or
43
+ * undefined: a grade is queued. */
44
+ readonly gradeOff?: () => string | undefined;
41
45
  /** Whether the run's job gave nothing new to look back on: its only tool work was its learned workflows, each of them
42
46
  * answering, with no error, no refused call, no approval and nothing said after its first message. Such a run is not
43
47
  * asked its end-of-run turn (no model request, nothing spent looking back), and its learning is dropped `empty` in
@@ -75,6 +79,16 @@ export interface ReflectDeps {
75
79
  outcome: "completed" | "failed";
76
80
  refuse: readonly string[];
77
81
  }) => Promise<CompileAsk | undefined>;
82
+ /** Compile once: a compile turn whose drafts all failed their checks (one answered, none passed) is the compile's
83
+ * attempt, kept on a promotion record (learning-end.ts recordDraftFailed) that compileFacts reads. Its `workflow` and
84
+ * `errors` come cut of `refuse`. Absent: none kept. */
85
+ readonly compileFailed?: (input: {
86
+ runId: string;
87
+ agentId: string;
88
+ compile: CompileAsk;
89
+ workflow: string;
90
+ errors: readonly string[];
91
+ }) => Promise<void>;
78
92
  /** The compile turn's deadline, every attempt in it. Default learn/compile.ts COMPILE_TIMEOUT_MS. */
79
93
  readonly compileDeadlineMs?: number;
80
94
  /** What the person said in the run, and a trigger's input, as the checks and the grader read them. */
@@ -57,11 +57,19 @@ export function createReflectHook(deps) {
57
57
  // its look-back's), unknown when any is.
58
58
  const earlier = deps.before;
59
59
  const followUp = () => (round === 1 ? {} : { follow_up_usd: job === null || typeof earlier?.job_cost_usd !== "number" || typeof earlier.look_back_usd !== "number" ? null : Math.max(0, Math.round((job - earlier.job_cost_usd - earlier.look_back_usd) * 1e9) / 1e9) });
60
+ /** Where the compile turn began, once one is asked: the run's spend as its first attempt was asked (an earlier claim's,
61
+ * kept with that ask, after a restart), unknown when unread; `alone` when the compile is the round's only ask (the
62
+ * whole look-back). Its turn's spend joins the revision it drafts (learning-cost.ts amortize), never the run's own. */
63
+ let compileFrom;
64
+ const cents = (usd) => Math.max(0, Math.round(usd * 1e9) / 1e9);
60
65
  // closeLearning: what looking back cost, the run's spend once the turn closed (its re-ask included) less the job's,
61
- // unknown when either is. Kept with every end the turn reaches from here, beside when the job answered and its cost.
66
+ // unknown when either is. Kept with every end the turn reaches from here, beside when the job answered and its cost;
67
+ // with a compile asked, what of it the compile turn spent (`compile_usd`), from its first ask to the close.
62
68
  const looked = async (rows) => {
63
69
  const total = (await deps.facts(input.runId)).costUsd;
64
- const answered = { answered_at: answeredAt, job_cost_usd: job, look_back_usd: total === null || job === null ? null : Math.max(0, Math.round((total - job) * 1e9) / 1e9), ...followUp() };
70
+ const lookBack = total === null || job === null ? null : cents(total - job);
71
+ const compileUsd = compileFrom === undefined ? {} : { compile_usd: compileFrom === "alone" ? lookBack : total === null || compileFrom.usd === null ? null : cents(total - compileFrom.usd) };
72
+ const answered = { answered_at: answeredAt, job_cost_usd: job, look_back_usd: lookBack, ...compileUsd, ...followUp() };
65
73
  return { also: rows.also.map((row) => (row.table === "learning_proposals" ? { ...row, row: { ...row.row, proposal: { ...row.row.proposal, ...answered } } } : row)) };
66
74
  };
67
75
  // A run cut or skipped here asks nothing: its drop alone, or with looked's figures when its look-back had started.
@@ -195,14 +203,21 @@ export function createReflectHook(deps) {
195
203
  let revised = compile.mode === "revise" && compile.base ? { workflow: compile.workflow, base: compile.base } : undefined;
196
204
  /** An attempt the cap refused, or whose spend took the run past it: the learning is dropped as the look-back's is. */
197
205
  let capped = false;
206
+ // Where the compile turn begins (the run's spend now), kept with each attempt as the job's figures are: a later claim
207
+ // answers with the earlier one's, so what it spent compiling stays the compile's.
208
+ compileFrom = alone ? "alone" : { usd: (await deps.facts(input.runId)).costUsd };
198
209
  const result = await compileTurn({
199
210
  ask: async (prompt, attempt, left) => {
200
- const keep = { ...(alone ? { answered_at: answeredAt, job_cost_usd: job } : {}), ...(revised ? { compile_base: revised.base } : {}) };
211
+ const from = compileFrom !== "alone" && compileFrom !== undefined ? { compile_from_usd: compileFrom.usd } : {};
212
+ const keep = { ...(alone ? { answered_at: answeredAt, job_cost_usd: job } : {}), ...from, ...(revised ? { compile_base: revised.base } : {}) };
201
213
  const said_ = await input.ask(prompt, { ...ask, deadlineMs: left, step: `compile-${attempt}`, ...(Object.keys(keep).length ? { keep } : {}) });
202
214
  if ("failed" in said_ && CAP_REFUSAL.test(said_.failed.message))
203
215
  capped = true;
204
216
  if (alone)
205
217
  firstAsk(said_.kept);
218
+ const keptFrom = said_.kept?.compile_from_usd;
219
+ if (!alone && (typeof keptFrom === "number" || keptFrom === null))
220
+ compileFrom = { usd: keptFrom };
206
221
  const base = said_.kept?.compile_base;
207
222
  if (revised && typeof base === "string")
208
223
  revised = { ...revised, base };
@@ -237,6 +252,12 @@ export function createReflectHook(deps) {
237
252
  : checked.reason === "checker" ? { ...checked, problems: [...checked.problems, ...problems] }
238
253
  : checked;
239
254
  compiled = { record: result.record, draft_errors: result.draftErrors };
255
+ // Compile once: its failed drafts are the compile's attempt, on record before the learning closes. The draft's
256
+ // name and errors are the model's words: cut of `refuse` as the proposal row is (cutRow) before they are saved
257
+ // on the promotion record or logged, whose reads cut only the server's secrets, never this run's.
258
+ const cut = (text) => redactSecrets(text, refuse, Number.POSITIVE_INFINITY);
259
+ if (result.drafted && deps.compileFailed)
260
+ await deps.compileFailed({ runId: input.runId, agentId: input.agentId, compile, workflow: cut(result.record.workflow), errors: result.draftErrors.map(cut) }).catch(() => undefined);
240
261
  }
241
262
  }
242
263
  const compiledFields = compiled ? { compiled: compiled.record, ...(compiled.draft_errors?.length ? { draft_errors: compiled.draft_errors } : {}) } : {};
@@ -247,6 +268,10 @@ export function createReflectHook(deps) {
247
268
  // The learning run's cap: what the run's cap leaves now its look-back is spent, read after the checks. A spend under
248
269
  // the cap that is unknown (or a read that fails, never no cap) queues no grade: none could be kept within the cap, and
249
270
  // the words say the spend is unknown, never that the cap has no room (learning-end.ts capSpendOf's rule).
271
+ // Asked here, at the end: a key a message handed during the run counts as one the run brought.
272
+ const gradeOff = deps.gradeOff?.();
273
+ if (gradeOff)
274
+ return close([droppedRow(turn, "grade_failed", gradeOff, compiledFields)]);
250
275
  const capUsd = deps.gradeCap ? await deps.gradeCap(input.runId).catch(() => null) : undefined;
251
276
  if (capUsd === null)
252
277
  return close([droppedRow(turn, "unknown_cost", said.gradeUnknownSpend)]);
@@ -11,6 +11,10 @@ import { randomUUID } from "node:crypto";
11
11
  import { hostname } from "node:os";
12
12
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
13
13
  import { COMMAND_KINDS, endedReason } from "./commands.js";
14
+ import { COMPUTER_CALL } from "../computer-channel.js";
15
+ import { COMPUTER_HAND_BACK, COMPUTER_TAKE_OVER } from "../computer-commands.js";
16
+ import { HELD_COMMANDS } from "../computer-held.js";
17
+ import { HAND_BACK } from "./hand-back.js";
14
18
  import { KINDS, withdrawnAnswers } from "./journal-kinds.js";
15
19
  import { journalEntries } from "./journal-reader.js";
16
20
  import { ClaimRefused, stopEnd } from "./loop-contract.js";
@@ -59,6 +63,9 @@ class EndNotWithdrawn extends Error {
59
63
  }
60
64
  /** The first wait after a stopped end that withdraws a call is refused; each later one doubles (RunnerOptions). */
61
65
  export const END_RETRY_BACKOFF_MS = 5_000;
66
+ /** The command rows a row that cannot be delivered yet does not hold back (runner.ts deliver), beside a stop and a cancel:
67
+ * those that act on the run's computer for its owner, so a stop that kept the computer can still let it go. */
68
+ const PASSES_A_BLOCKED_ROW = new Set([...HELD_COMMANDS, COMPUTER_CALL, HAND_BACK, COMPUTER_TAKE_OVER, COMPUTER_HAND_BACK]);
62
69
  /** The longest wait between those tries: 5 min. */
63
70
  export const END_RETRY_CAP_MS = 300_000;
64
71
  /** The tries at that cap before the run ends stopped on its row alone (about an hour of retries in all; endRefused). */
@@ -270,6 +277,11 @@ export function startRunner(options) {
270
277
  delivery = (async () => {
271
278
  try {
272
279
  const rows = given ?? (await store.commands(held.claim.runId, held.cursor));
280
+ // A row whose delivery threw (its loop could not take it yet: a message whose model key cannot be read, adapter-
281
+ // loop.ts command) blocks the rows after it, which wait in order behind it, but a stop or a cancel: those still
282
+ // reach the loop, so a run is never kept turning and spending behind a row it cannot take. The cursor stays before
283
+ // the blocked row, which the next poll delivers again; the error is said once the rows are read.
284
+ let blocked;
273
285
  for (const row of rows) {
274
286
  if (held.stopping || held.ending || held.fence.lost || killed)
275
287
  break;
@@ -279,16 +291,55 @@ export function startRunner(options) {
279
291
  // The cursor moves past a row only once its delivery went through (handed to the loop, and any refusal written):
280
292
  // a delivery that throws leaves the row for the next poll, never skipped for the rest of the claim.
281
293
  if (row.takenAt !== null) {
282
- held.cursor = Math.max(held.cursor, row.id);
294
+ if (!blocked)
295
+ held.cursor = Math.max(held.cursor, row.id);
296
+ continue;
297
+ }
298
+ // A row handed on past a blocked row earlier (PASSES_A_BLOCKED_ROW) is never handed on again.
299
+ if (held.passed.has(row.id)) {
300
+ if (!blocked)
301
+ held.cursor = Math.max(held.cursor, row.id);
283
302
  continue;
284
303
  }
285
304
  if (row.kind === "stop" || row.kind === "cancel") {
286
- held.cursor = Math.max(held.cursor, row.id);
305
+ if (!blocked)
306
+ held.cursor = Math.max(held.cursor, row.id);
287
307
  stopLoop(held, { kind: "command", commandId: row.id, ...(row.kind === "cancel" ? { cancel: true } : {}) });
288
308
  // A stop that keeps the run's computer leaves the rows after it to be handed on (the loop head ends the rest).
289
309
  continue;
290
310
  }
291
- const outcome = COMMAND_KINDS.has(row.kind) ? await held.loop.command(row) : { refused: `no command is of kind ${JSON.stringify(row.kind)}` };
311
+ // Past a blocked row, the commands that act on the run's computer for its owner go on too (a release, a start,
312
+ // a call, a take-over and a hand-back): a stop that kept the computer must still be able to let it go. Each is
313
+ // handed on once (held.passed), the cursor still before the blocked row; the message itself is never handed on.
314
+ if (blocked) {
315
+ if (!PASSES_A_BLOCKED_ROW.has(row.kind) || held.passed.has(row.id))
316
+ continue;
317
+ try {
318
+ const passed = await held.loop.command(row);
319
+ // Marked handed on only once its answer is kept: a refusal whose write fails is asked of the loop again at the
320
+ // next delivery, so its caller hears it once the store answers, never a silence.
321
+ if ("refused" in passed) {
322
+ await store.take(held.claim, row.id, "refused", passed.refused);
323
+ emit({ type: "refused", runId: held.claim.runId, commandId: row.id, reason: passed.refused });
324
+ }
325
+ held.passed.add(row.id);
326
+ }
327
+ catch (error) {
328
+ if (isFenced(error) || held.sealed || killed)
329
+ throw error;
330
+ }
331
+ continue;
332
+ }
333
+ let outcome;
334
+ try {
335
+ outcome = COMMAND_KINDS.has(row.kind) ? await held.loop.command(row) : { refused: `no command is of kind ${JSON.stringify(row.kind)}` };
336
+ }
337
+ catch (error) {
338
+ if (isFenced(error) || held.sealed || killed)
339
+ throw error;
340
+ blocked = { error };
341
+ continue;
342
+ }
292
343
  if (held.sealed || killed)
293
344
  return;
294
345
  // `taken`: the loop's commit took it. `later`: left untaken for the run's next claim. Only a refusal is written here.
@@ -298,6 +349,8 @@ export function startRunner(options) {
298
349
  }
299
350
  held.cursor = Math.max(held.cursor, row.id);
300
351
  }
352
+ if (blocked)
353
+ throw blocked.error;
301
354
  }
302
355
  catch (error) {
303
356
  if (held.sealed || killed)
@@ -631,7 +684,7 @@ export function startRunner(options) {
631
684
  },
632
685
  redact,
633
686
  });
634
- const held = { claim, loop, fence, abort, cursor: 0, stopping: false, ending: false, sealed: false, renewing: false, delivering: false, deliverAgain: false, mib };
687
+ const held = { passed: new Set(), claim, loop, fence, abort, cursor: 0, stopping: false, ending: false, sealed: false, renewing: false, delivering: false, deliverAgain: false, mib };
635
688
  heldNow = held;
636
689
  // The loop's own end landed: the run is ending from here, its teardown included (no renew, no lost claim).
637
690
  ending = () => {
@@ -7,7 +7,7 @@
7
7
  // flight (mcp_oauth_pending); each trigger source's settings, a webhook trigger's signing secret and the GitHub App's key
8
8
  // and webhook secret among them, and the outbound webhook's signing secret, each it held before too (trigger_settings),
9
9
  // but a field its source marks public; browser sign-in pointers, live and forgotten; live viewer tokens; a launch's sealed
10
- // part. Beside the store, what the data directory keeps where the runner shares it (server-secrets.ts besideTheStore: the
10
+ // part (a run's handed MCP credentials and its own model key). Beside the store, what the data directory keeps where the runner shares it (server-secrets.ts besideTheStore: the
11
11
  // owner's API token and the sign-in session secret). Each value in every spelling the server's list has
12
12
  // (standard-webhooks.ts secretForms), a PEM key whole and line by line. A value that does not open under the runner's key
13
13
  // is left out: the store never holds one in the clear, and nothing of this runner can be handed it.
@@ -55,20 +55,24 @@ function jsonSecrets(text) {
55
55
  walk(value);
56
56
  return out;
57
57
  }
58
- /** A launch's sealed JSON: its own listed values (jsonSecrets), and each handed MCP credential's headers (store/seal.ts
59
- * sealRunMcpAuth: `{"mcp": {"<server>": {"headers": {...}}}}`), as a saved server's are listed. */
58
+ /** A launch's sealed JSON: its own listed values (jsonSecrets), each handed MCP credential's headers (store/seal.ts
59
+ * sealRunLaunch: `{"mcp": {"<server>": {"headers": {...}}}}`), as a saved server's are listed, and the run's own model
60
+ * key (`{"model": {"key": "..."}}`). */
60
61
  function launchSecrets(text) {
61
62
  const out = jsonSecrets(text);
62
- let mcp;
63
+ let opened;
63
64
  try {
64
- mcp = JSON.parse(text)?.mcp;
65
+ opened = JSON.parse(text);
65
66
  }
66
67
  catch {
67
68
  return out;
68
69
  }
70
+ const mcp = opened?.mcp;
69
71
  if (mcp && typeof mcp === "object")
70
72
  for (const entry of Object.values(mcp))
71
73
  out.push(...jsonSecrets(JSON.stringify(entry)));
74
+ if (typeof opened?.model?.key === "string")
75
+ out.push(opened.model.key);
72
76
  return out;
73
77
  }
74
78
  /** The ChatGPT sign-in's sealed row (chatgpt-plan.ts): its access and refresh tokens, each alone, as a renewal in any
@@ -2,7 +2,7 @@ import { type LearnedWorkflow } from "../learning.js";
2
2
  import type { RunLaunch } from "../run-launch.js";
3
3
  import { COST_WINDOW, type RunPath } from "../learning-cost.js";
4
4
  export { COST_WINDOW };
5
- import { type GuardRow, type LoopRow } from "../learned-nodes.js";
5
+ import { type LoopRow } from "../learned-nodes.js";
6
6
  import type { Skipped } from "../learn/replay-calls.js";
7
7
  /** The root entry a run served workflow-first keeps, once the workflow's call ended: which workflow, at which learned
8
8
  * revision, under which call, and how it ended. A later claim that finds it never runs the workflow again. */
@@ -162,9 +162,9 @@ export declare function servedOf(entries: readonly {
162
162
  /** The run-record fields a learning run's metrics carry, from the run-end classifier's `classified` path
163
163
  * (runPathOverStore): the path it took, the learned revision it ran on, the learned workflow it ran (served first, or
164
164
  * called by its agent) and, for one served first, its digest and the promotion it served under (`workflow_promotion`,
165
- * which its grade keeps); and from its root `entries`, each step guard's check of its learned workflows' calls
166
- * (`guards`, learned-nodes.ts guardsOf) and each loop's exit (`loops`, loopsOf: a quote re-pick is a loop's second
167
- * pass), when one ran. learning-cost reads path and workflow from here. None for a run that does not learn. */
165
+ * which its grade keeps), and `not_auditable` when a trigger started it (never audited); and from its root `entries`,
166
+ * each loop's exit (`loops`, loopsOf: a quote re-pick is a loop's second pass), when one ran. learning-cost reads path
167
+ * and workflow from here. None for a run that does not learn. */
168
168
  export declare function pathMetrics(launch: RunLaunch, classified: {
169
169
  path: RunPath;
170
170
  workflow: string | null;
@@ -179,9 +179,10 @@ export declare function pathMetrics(launch: RunLaunch, classified: {
179
179
  workflow?: string;
180
180
  workflow_digest?: string;
181
181
  workflow_promotion?: number;
182
- guards?: GuardRow[];
182
+ not_auditable?: true;
183
183
  loops?: LoopRow[];
184
184
  replay?: ReplayMetrics;
185
+ audit?: NonNullable<RunLaunch["audit"]>;
185
186
  };
186
187
  /** A replay run's record (metrics.replay): the graded run it replayed and how its workflow ended there. */
187
188
  export type ReplayMetrics = {
@@ -1,12 +1,12 @@
1
1
  // workflow-first: a run of an agent whose learned revision holds one active workflow fitting the run's input starts on
2
2
  // that workflow, with no turn of the agent's model (a JIT's compiled path: the agent is the interpreter, the workflow is
3
- // the code it compiled, its escalate nodes are guards). The workflow answering is the run's answer; the workflow handing
3
+ // the code it compiled, its escalate nodes hand a case back). The workflow answering is the run's answer; the workflow handing
4
4
  // the job back (it escalated, a node failed, its output failed its schema) is a deopt: the same run goes on as an
5
5
  // agentic run, the agent handed the workflow's trace, and the handback feeds the agent's next revision.
6
6
  //
7
7
  // The choice here is structural, never semantic: a workflow fits when its input schema has at least one required field
8
8
  // and the run's input passes it at the top level (validate.ts inputIssues, the check a run's input gets at start). Whether
9
- // the workflow can do the job is its own guards' call, never the engine's. Exactly one fitting active workflow serves;
9
+ // the workflow can do the job is its own escalate nodes' call, never the engine's. Exactly one fitting active workflow serves;
10
10
  // none, or more than one (said in one log line), leaves the run to the agent. A launch's `workflowFirst: false` (RunCreate
11
11
  // `workflow_first`) forces the agent path. A handback is an escalation, never a failure: it asks for no revision (one run
12
12
  // is one sample; a revision is asked only of a workflow its promotion holds), and never keeps the workflow from serving.
@@ -26,11 +26,12 @@
26
26
  // the first input), through the run's own learned_workflow tool, gate, record and ledger.
27
27
  import { createHash } from "node:crypto";
28
28
  import { LEARNING_LABEL } from "../learning.js";
29
- import { COST_WINDOW } from "../learning-cost.js";
29
+ import { COST_WINDOW, SERVED_PATHS } from "../learning-cost.js";
30
+ import { auditableLaunch } from "../learn/audit.js";
30
31
  export { COST_WINDOW };
31
32
  import { KINDS } from "./journal-kinds.js";
32
33
  import { inputIssues, isObject } from "../validate.js";
33
- import { endedIn, guardsOf, loopsOf, replaySkippedIn } from "../learned-nodes.js";
34
+ import { endedIn, loopsOf, replaySkippedIn } from "../learned-nodes.js";
34
35
  import { sameAnswer } from "../learn/promote.js";
35
36
  /** The root entry a run served workflow-first keeps, once the workflow's call ended: which workflow, at which learned
36
37
  * revision, under which call, and how it ended. A later claim that finds it never runs the workflow again. */
@@ -65,7 +66,7 @@ export function costLineOf(past, name, digest) {
65
66
  }
66
67
  const agent = newest.filter((run) => pathFields(run.metrics).path === "agent");
67
68
  const first = Math.min(...newest.filter(ran).map((run) => run.startedAt));
68
- const hand = agent.some(known) ? agent : newest.filter((run) => run.startedAt < first && !SERVED.includes(pathFields(run.metrics).path) && pathFields(run.metrics).path !== "replay");
69
+ const hand = agent.some(known) ? agent : newest.filter((run) => run.startedAt < first && !SERVED.includes(pathFields(run.metrics).path) && pathFields(run.metrics).path !== "replay" && pathFields(run.metrics).path !== "audit");
69
70
  const byHand = hand.filter(known).map((run) => run.allInUsd);
70
71
  return { served: meanOf(served) ?? { runs: 0, mean_usd: null }, by_hand: meanOf(byHand), unknown_runs: servedUnknown + hand.length - byHand.length };
71
72
  }
@@ -222,21 +223,23 @@ export function servedOf(entries) {
222
223
  /** The run-record fields a learning run's metrics carry, from the run-end classifier's `classified` path
223
224
  * (runPathOverStore): the path it took, the learned revision it ran on, the learned workflow it ran (served first, or
224
225
  * called by its agent) and, for one served first, its digest and the promotion it served under (`workflow_promotion`,
225
- * which its grade keeps); and from its root `entries`, each step guard's check of its learned workflows' calls
226
- * (`guards`, learned-nodes.ts guardsOf) and each loop's exit (`loops`, loopsOf: a quote re-pick is a loop's second
227
- * pass), when one ran. learning-cost reads path and workflow from here. None for a run that does not learn. */
226
+ * which its grade keeps), and `not_auditable` when a trigger started it (never audited); and from its root `entries`,
227
+ * each loop's exit (`loops`, loopsOf: a quote re-pick is a loop's second pass), when one ran. learning-cost reads path
228
+ * and workflow from here. None for a run that does not learn. */
228
229
  export function pathMetrics(launch, classified, entries = []) {
230
+ // A shadow run (runner/audit.ts): path `audit` and the run it audits, whatever it did: no learning, no money rule.
231
+ if (launch.audit)
232
+ return { path: "audit", audit: { of: launch.audit.of, workflow: launch.audit.workflow, digest: launch.audit.digest } };
229
233
  if (!launch.learning)
230
234
  return {};
231
235
  const { path, workflow, digest, promotion } = classified ?? { path: "agent", workflow: null };
232
- const guards = guardsOf(entries);
233
236
  const loops = loopsOf(entries);
234
- const rows = { ...(guards.length ? { guards } : {}), ...(loops.length ? { loops } : {}) };
237
+ const rows = loops.length ? { loops } : {};
235
238
  if (launch.replay) {
236
239
  // A replay run (runner/promotion.ts): path `replay`, whatever its workflow did, so the money rule and the agent's
237
240
  // by-hand cost never read it; how its workflow ended, for the replay's score (learn/promote.ts ReplayRow).
238
241
  const { of, workflow: name, digest: at } = launch.replay;
239
- // Handed back when the workflow ended escalated (an escalate node or a guard: the workflow knowing its limits), however
242
+ // Handed back when the workflow ended escalated (an escalate node: the workflow knowing its limits), however
240
243
  // many of its nodes failed on the way and were recovered (a map's collected item); a workflow that itself ended failed
241
244
  // (a credential or tool the replay ran without, a step's output off its schema), or was refused, is failed: no
242
245
  // evidence. Skipped when a write it needed is not in the graded run's recording (learn/replay-calls.ts): never run.
@@ -244,7 +247,9 @@ export function pathMetrics(launch, classified, entries = []) {
244
247
  const outcome = skipped ? "skipped_write" : path === "workflow" && workflow === name ? "answered" : path === "handed_back" && workflow === name && endedIn(entries, name) === "escalated" ? "handed_back" : "failed";
245
248
  return { path: "replay", ...(launch.learning.seed ? { learned_revision: launch.learning.seed } : {}), workflow: name, workflow_digest: at, ...rows, replay: { of, outcome, ...(skipped ? { skipped } : {}) } };
246
249
  }
247
- return { path, ...(launch.learning.seed ? { learned_revision: launch.learning.seed } : {}), ...(workflow ? { workflow } : {}), ...(digest ? { workflow_digest: digest } : {}), ...(promotion !== undefined ? { workflow_promotion: promotion } : {}), ...rows };
250
+ // A served run a trigger started (learn/audit.ts auditableLaunch) is never audited: counted on the promotions read.
251
+ const notAuditable = SERVED_PATHS.includes(path) && !auditableLaunch(launch);
252
+ return { path, ...(launch.learning.seed ? { learned_revision: launch.learning.seed } : {}), ...(workflow ? { workflow } : {}), ...(digest ? { workflow_digest: digest } : {}), ...(promotion !== undefined ? { workflow_promotion: promotion } : {}), ...(notAuditable ? { not_auditable: true } : {}), ...rows };
248
253
  }
249
254
  /** What run `entries` (its root's) say its learned workflow answered alone: the workflow and its answer (the model's
250
255
  * message written just before the WORKFLOW_FIRST entry, in its commit); undefined for a run it did not answer. A follow-up that opens such a
@@ -33,7 +33,7 @@ import { AsyncLocalStorage } from "node:async_hooks";
33
33
  import { bookedIn, parallelExtractFee, parallelSearchFee } from "../paid-calls.js";
34
34
  import { searchArgs, WEB_SEARCH_TOOL } from "../web-search.js";
35
35
  import { money, pricingOf, requestPrice, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
36
- import { claimSecrets, withModelKeys } from "./claim-secrets.js";
36
+ import { claimModelEnv, claimModelKey, claimSecrets, holdRunKey, keyedAtClaim, withoutModelKeys } from "./claim-secrets.js";
37
37
  import { routeOf } from "./model-route.js";
38
38
  import { capModelOf, PI_WIRES, storeSettings } from "./adapter-run-spec.js";
39
39
  import { policyFor } from "./adapters/pi.js";
@@ -163,7 +163,15 @@ export function workflowSpecOf(deps) {
163
163
  // The run's models resolve the one way the runner resolves any (routeProviderOf over routeOf), unless a test gives its
164
164
  // own: each tier's key from the runner's environment, else the one the claim opened (a key saved in
165
165
  // Settings → Model keys runs the next run with no restart).
166
- const providerOf = deps.providerOf ?? routeProviderOf(withModelKeys(deps.env ?? process.env, claimedEnv));
166
+ // A run with its own model key (model_key, sealed in its launch): every model node carries that key alone, and no model
167
+ // key is on the env its decisions and call nodes run under. A workflow run takes no message, so its key is the one
168
+ // its start handed, for the run's life.
169
+ const runKey = await claimModelKey({ store: deps.store, sealKey: deps.sealKey, env: deps.env ?? process.env }, claim.runId);
170
+ if (keyedAtClaim(runKey))
171
+ withoutModelKeys(claimedEnv);
172
+ if (runKey && run?.redact)
173
+ holdRunKey(heldRedactor(run.redact), runKey);
174
+ const providerOf = deps.providerOf ?? routeProviderOf(claimModelEnv(deps.env ?? process.env, claimedEnv, runKey));
167
175
  // Each tier's provider and cap model, resolved once; the proxies start here (before the Harness opens, since the models
168
176
  // catalog the Harness takes points at them), their hooks deferred to the booking wired at harnessReady.
169
177
  const providers = new Map();
@@ -7,7 +7,7 @@ import { type Place } from "./place.js";
7
7
  import { type RepoBinding } from "./run-repo.js";
8
8
  import { type LaunchDisk, type RunLaunch, type SeedFailed } from "./run-launch.js";
9
9
  import { type ApprovalDecision, type RunMoment } from "./run-view.js";
10
- import { type NewRevision, type RevisionRow, type RunOrigin, type RunRow, type Store } from "./store/index.js";
10
+ import { type LaunchSealed, type NewRevision, type RevisionRow, type RunOrigin, type RunRow, type Store } from "./store/index.js";
11
11
  import { type ToolSettingsMap } from "./tool-plane.js";
12
12
  import type { RunTrigger } from "./triggers.js";
13
13
  import { type Json } from "./validate.js";
@@ -59,7 +59,7 @@ export declare function message(store: RunsStore, moment: RunMoment, content: st
59
59
  queue?: (command: SteerCommand) => Promise<{
60
60
  skipped: string;
61
61
  } | void>;
62
- launchSealed?: Uint8Array;
62
+ launchSealed?: LaunchSealed;
63
63
  beforeSubmit?: (runId: string, content: string) => Promise<void> | void;
64
64
  }): Promise<{
65
65
  mode: MessageMode;
@@ -190,8 +190,9 @@ export interface StartDeps {
190
190
  * it must have a cap (a trigger's), and who its first message is from when the person did not write it. */
191
191
  export interface StartOptions {
192
192
  readonly trigger?: RunTrigger;
193
- /** The run's launch secrets, sealed for its id once it has one (the create body's mcp_auth, server.ts). */
194
- readonly sealed?: (runId: string) => Uint8Array;
193
+ /** The run's launch secrets, sealed for its id once it has one (the create body's mcp_auth and model_key, server.ts),
194
+ * given the launch the start prepared, which the sealer may refuse (a model key where the run's model takes none). */
195
+ readonly sealed?: (runId: string, launch: RunLaunch, kind: Revision["kind"]) => Uint8Array | null;
195
196
  /** The run's title when its starter names one (a trigger's: "<Source> <name>"), else it is made from its input. */
196
197
  readonly title?: string;
197
198
  readonly origin?: RunOrigin;
@@ -26,6 +26,7 @@ import { resolvePlace } from "./place.js";
26
26
  import { githubTargetOf } from "./github.js";
27
27
  import { repoOf } from "./run-repo.js";
28
28
  import { launchBody } from "./run-launch.js";
29
+ import { modelKeyRequired, serverKeyMissing } from "./run-model-key.js";
29
30
  import { raiseFollowUpId } from "./run-view.js";
30
31
  import { sendCommand } from "./runner/commands.js";
31
32
  import { AnswerTaken, ExternalBodyConflict, RunFinal, StoreConstraint, StoreLaunchMissing } from "./store/index.js";
@@ -215,7 +216,7 @@ export async function message(store, moment, content, { requestId, answers = tru
215
216
  * (reopenableWhere: an agentic run that completed, or that a person stopped, as the console offers a follow-up to both).
216
217
  * Any other (cancelled, failed, a workflow's, an imported or a learning run) answers 409 finished, nothing written. */
217
218
  async function steerOrReopen(store, moment, command, launchSealed) {
218
- // The message's launch secrets (its mcp_auth, sealed) ride in the same write as its steer, whichever door takes it.
219
+ // The message's launch secrets (its mcp_auth and model_key, sealed) ride in the same write as its steer, whichever door takes it.
219
220
  const sealed = launchSealed ? { launchSealed } : undefined;
220
221
  try {
221
222
  await sendCommand(store, moment.id, command, sealed);
@@ -446,10 +447,11 @@ export async function startRun(store, deps, entry, body, { trigger, origin, capp
446
447
  if (entry.revision?.body?.sdk)
447
448
  throw new ApiError("agent_not_runnable", "This agent runs in your backend SDK. Start it through its SDK learning wrapper; AgentRun does not launch its tools or credentials.");
448
449
  const { launch, revision } = await prepareLaunch(deps, entry, body, { ...(trigger ? { trigger } : {}), capped, ...(from ? { from } : {}), ...(title !== undefined ? { title } : {}) });
450
+ keyedOrRefused(deps, launch, revision.kind, sealed);
449
451
  const runId = (deps.newRunId ?? uuidv7)();
450
452
  try {
451
453
  const labels = labelsOf(body.labels);
452
- return await withHeldFiles(deps, runId, launch, () => store.runs.create({ id: runId, agentId: entry.agent.id, revisionId: revision.id, ...(origin ? { origin } : {}), ...(labels ? { labels } : {}) }, { body: launchBody(launch), ...(sealed ? { sealed: sealed(runId) } : {}) }));
454
+ return await withHeldFiles(deps, runId, launch, () => store.runs.create({ id: runId, agentId: entry.agent.id, revisionId: revision.id, ...(origin ? { origin } : {}), ...(labels ? { labels } : {}) }, { body: launchBody(launch), ...(sealed ? { sealed: sealed(runId, launch, revision.kind) } : {}) }));
453
455
  }
454
456
  catch (error) {
455
457
  // Only another writer of the store got here first under the same origin key: its run is the one asked for.
@@ -462,6 +464,13 @@ export async function startRun(store, deps, entry, body, { trigger, origin, capp
462
464
  throw error;
463
465
  }
464
466
  }
467
+ /** A start with no launch secrets (`sealed`: a trigger's firing, a learning batch's row) whose route goes to the model
468
+ * gateway, on a server that holds no key for it (run-model-key.ts serverKeyMissing): 422 model_key_required, nothing
469
+ * written, never a failure at its first model call. A start with them (the API's) is the sealer's to check. */
470
+ function keyedOrRefused(deps, launch, kind, sealed) {
471
+ if (!sealed && serverKeyMissing(deps.planeEnv(), { kind, model: launch.model, native: Boolean(launch.native) }))
472
+ throw modelKeyRequired(false);
473
+ }
465
474
  /** Writes run `runId` with `write`, its files (launch.files) held for it first (StartDeps.files): a hold that fails part
466
475
  * way, a write that fails, or one that answers another run (an origin key's run started before), lets go of the hold. */
467
476
  async function withHeldFiles(deps, runId, launch, write) {
@@ -509,6 +518,7 @@ export async function startInline(store, deps, inline, body, { origin, sealed }
509
518
  // A store revision is the revision the run path reads as a pi Revision (its body is the revision body), as pinnedOf hands
510
519
  // one across.
511
520
  const { launch } = await prepareLaunch(deps, entry, body, { revision: (storedRevision ?? revision) });
521
+ keyedOrRefused(deps, launch, (storedRevision ?? revision).kind, sealed);
512
522
  const runId = (deps.newRunId ?? uuidv7)();
513
523
  const labels = labelsOf(body.labels);
514
524
  try {
@@ -516,7 +526,7 @@ export async function startInline(store, deps, inline, body, { origin, sealed }
516
526
  agent: { id: entry.agent.id, name: inline.name, description: inline.description, ref },
517
527
  revision: { id: revision.id, version: external.version, kind: revision.kind, body: revision.body, skills: revision.skills, ...(revision.note !== undefined ? { note: revision.note } : {}), ...(revision.mcpPin !== undefined ? { mcpPin: revision.mcpPin } : {}), ...(revision.monidPin !== undefined ? { monidPin: revision.monidPin } : {}) },
518
528
  run: { id: runId, ...(origin ? { origin } : {}), ...(labels ? { labels } : {}) },
519
- launch: { body: launchBody(launch), ...(sealed ? { sealed: sealed(runId) } : {}) },
529
+ launch: { body: launchBody(launch), ...(sealed ? { sealed: sealed(runId, launch, (storedRevision ?? revision).kind) } : {}) },
520
530
  }));
521
531
  }
522
532
  catch (error) {
@@ -14,7 +14,7 @@ export declare function sdkWorkflowManifest(tools: unknown, adapters: unknown):
14
14
  export declare function sdkDraftTools(manifest: readonly SdkWorkflowTool[]): {
15
15
  tools: string[];
16
16
  gated: {
17
- [k: string]: "allow" | "ask" | "deny";
17
+ [k: string]: "ask" | "allow" | "deny";
18
18
  };
19
19
  deniedBy: {
20
20
  [k: string]: "agent";