@parcha/agentrun-serve 0.1.0-beta.39 → 0.1.0-beta.41

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 (173) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/README.md +129 -16
  3. package/dist/api-only.d.ts +3 -1
  4. package/dist/api-only.js +4 -2
  5. package/dist/api-token.d.ts +30 -0
  6. package/dist/api-token.js +89 -0
  7. package/dist/cli.js +19 -5
  8. package/dist/composio-made.d.ts +54 -0
  9. package/dist/composio-made.js +83 -0
  10. package/dist/composio-preset.d.ts +16 -8
  11. package/dist/composio-preset.js +106 -43
  12. package/dist/composio-triggers.d.ts +7 -2
  13. package/dist/composio-triggers.js +13 -7
  14. package/dist/computer-attach.d.ts +29 -11
  15. package/dist/computer-attach.js +141 -47
  16. package/dist/computer-keys.d.ts +4 -0
  17. package/dist/computer-keys.js +5 -0
  18. package/dist/computers.d.ts +11 -1
  19. package/dist/computers.js +21 -12
  20. package/dist/console/assets/index-C3gNPz58.css +1 -0
  21. package/dist/console/assets/index-COGhx_2Z.js +711 -0
  22. package/dist/console/index.html +2 -2
  23. package/dist/decisions.js +9 -2
  24. package/dist/email/account.d.ts +0 -1
  25. package/dist/email/account.js +3 -3
  26. package/dist/email/answer.d.ts +5 -0
  27. package/dist/email/answer.js +35 -0
  28. package/dist/email/mail.js +19 -26
  29. package/dist/email/names.d.ts +30 -0
  30. package/dist/email/names.js +34 -0
  31. package/dist/email/routes.d.ts +1 -0
  32. package/dist/email/routes.js +1 -1
  33. package/dist/email/tools.d.ts +11 -4
  34. package/dist/email/tools.js +91 -46
  35. package/dist/eval-feed.d.ts +26 -0
  36. package/dist/eval-feed.js +68 -0
  37. package/dist/eval-mailbox.d.ts +5 -2
  38. package/dist/eval-mailbox.js +14 -6
  39. package/dist/exa-keyless.d.ts +1 -1
  40. package/dist/exa-keyless.js +1 -1
  41. package/dist/feed/feed-faux.d.ts +62 -0
  42. package/dist/feed/feed-faux.js +123 -0
  43. package/dist/feed/fetch.d.ts +41 -0
  44. package/dist/feed/fetch.js +128 -0
  45. package/dist/feed/parse.d.ts +41 -0
  46. package/dist/feed/parse.js +300 -0
  47. package/dist/learn/check.d.ts +3 -1
  48. package/dist/learn/check.js +57 -2
  49. package/dist/learn/compile.d.ts +3 -2
  50. package/dist/learn/compile.js +7 -6
  51. package/dist/learn/promote.d.ts +25 -14
  52. package/dist/learn/promote.js +32 -14
  53. package/dist/learned-nodes.d.ts +21 -4
  54. package/dist/learned-nodes.js +21 -8
  55. package/dist/learned-workflow.d.ts +3 -3
  56. package/dist/learned-workflow.js +14 -5
  57. package/dist/learning-cost.d.ts +17 -8
  58. package/dist/learning-cost.js +12 -4
  59. package/dist/local-models.d.ts +7 -1
  60. package/dist/local-models.js +11 -5
  61. package/dist/mcp-oauth.d.ts +15 -1
  62. package/dist/mcp-oauth.js +39 -5
  63. package/dist/mcp-pin-first.d.ts +4 -2
  64. package/dist/mcp-pin-first.js +4 -3
  65. package/dist/mcp-servers-store.d.ts +58 -5
  66. package/dist/mcp-servers-store.js +136 -17
  67. package/dist/mcp.d.ts +2 -2
  68. package/dist/mcp.js +2 -2
  69. package/dist/observation/http.d.ts +4 -1
  70. package/dist/observation/http.js +5 -4
  71. package/dist/openapi.d.ts +1 -1
  72. package/dist/openapi.js +63 -27
  73. package/dist/port-models.d.ts +4 -1
  74. package/dist/port-models.js +1 -0
  75. package/dist/print.d.ts +6 -3
  76. package/dist/print.js +4 -2
  77. package/dist/refusal-words.d.ts +3 -0
  78. package/dist/refusal-words.js +3 -0
  79. package/dist/run-labels.d.ts +23 -0
  80. package/dist/run-labels.js +79 -0
  81. package/dist/run-launch.d.ts +2 -0
  82. package/dist/run-launch.js +2 -0
  83. package/dist/run-secrets.js +12 -4
  84. package/dist/run-view.d.ts +3 -4
  85. package/dist/run-view.js +26 -24
  86. package/dist/runner/adapter-loop.d.ts +6 -2
  87. package/dist/runner/adapter-loop.js +136 -22
  88. package/dist/runner/adapter-run-spec.d.ts +5 -0
  89. package/dist/runner/adapter-run-spec.js +75 -32
  90. package/dist/runner/beside.d.ts +6 -3
  91. package/dist/runner/beside.js +9 -7
  92. package/dist/runner/cli-run-spec.js +33 -26
  93. package/dist/runner/conformance/harness.js +69 -14
  94. package/dist/runner/conformance/subject.d.ts +4 -1
  95. package/dist/runner/journal-kinds.d.ts +22 -0
  96. package/dist/runner/journal-kinds.js +39 -0
  97. package/dist/runner/main.d.ts +1 -1
  98. package/dist/runner/main.js +2 -2
  99. package/dist/runner/mcp-claim.d.ts +3 -0
  100. package/dist/runner/mcp-claim.js +1 -1
  101. package/dist/runner/mcp-run.d.ts +4 -0
  102. package/dist/runner/mcp-run.js +5 -3
  103. package/dist/runner/model-route.d.ts +7 -3
  104. package/dist/runner/model-route.js +24 -9
  105. package/dist/runner/promotion.d.ts +16 -8
  106. package/dist/runner/promotion.js +178 -55
  107. package/dist/runner/workflow-first.d.ts +6 -5
  108. package/dist/runner/workflow-first.js +9 -7
  109. package/dist/runs-over-store.js +5 -2
  110. package/dist/sdk/runs.d.ts +7 -1
  111. package/dist/sdk/runs.js +19 -6
  112. package/dist/secret-cut.js +3 -1
  113. package/dist/secrets.js +3 -1
  114. package/dist/server.d.ts +27 -2
  115. package/dist/server.js +181 -56
  116. package/dist/store/dialect.d.ts +6 -0
  117. package/dist/store/dialect.js +2 -0
  118. package/dist/store/index.d.ts +1 -1
  119. package/dist/store/postgres/connection.d.ts +11 -5
  120. package/dist/store/postgres/connection.js +44 -17
  121. package/dist/store/postgres/dialect.js +6 -0
  122. package/dist/store/postgres/migrations/0015_run_labels.sql +5 -0
  123. package/dist/store/postgres/migrations/0016_minted_tokens.sql +21 -0
  124. package/dist/store/postgres/store.d.ts +7 -3
  125. package/dist/store/postgres/store.js +1 -0
  126. package/dist/store/schema.d.ts +9 -0
  127. package/dist/store/schema.js +26 -2
  128. package/dist/store/sqlite/connection.js +80 -8
  129. package/dist/store/sqlite/run-launch.d.ts +11 -0
  130. package/dist/store/sqlite/run-launch.js +8 -0
  131. package/dist/store/sqlite/run-patch.d.ts +2 -1
  132. package/dist/store/sqlite/run-patch.js +3 -2
  133. package/dist/store/sqlite/store.js +101 -26
  134. package/dist/store/sqlite/worker.d.ts +2 -0
  135. package/dist/store/sqlite/worker.js +13 -10
  136. package/dist/store/store.d.ts +53 -1
  137. package/dist/store-reads/journal.js +2 -1
  138. package/dist/store-reads/learning.d.ts +30 -13
  139. package/dist/store-reads/learning.js +130 -51
  140. package/dist/store-reads/runs.d.ts +4 -3
  141. package/dist/store-reads/runs.js +3 -2
  142. package/dist/store-view.js +4 -2
  143. package/dist/template-eval.d.ts +4 -0
  144. package/dist/template-eval.js +127 -50
  145. package/dist/templates.d.ts +24 -1
  146. package/dist/templates.js +129 -21
  147. package/dist/timeline/origin.d.ts +1 -1
  148. package/dist/timeline/origin.js +2 -2
  149. package/dist/tool-gate.d.ts +5 -3
  150. package/dist/tool-gate.js +5 -2
  151. package/dist/tools.d.ts +13 -0
  152. package/dist/tools.js +15 -10
  153. package/dist/trigger-adapter.d.ts +12 -36
  154. package/dist/trigger-adapters.js +2 -1
  155. package/dist/trigger-email.js +30 -77
  156. package/dist/trigger-feed.d.ts +12 -0
  157. package/dist/trigger-feed.js +371 -0
  158. package/dist/triggers.d.ts +27 -14
  159. package/dist/triggers.js +121 -80
  160. package/dist/webhooks.js +9 -5
  161. package/dist/workflow/decision-recovery.js +5 -2
  162. package/dist/workflow/decisions.d.ts +7 -0
  163. package/dist/workspace/computer-deps.d.ts +5 -1
  164. package/dist/workspace/computer-deps.js +2 -2
  165. package/dist/workspace/index.d.ts +1 -0
  166. package/dist/workspace/index.js +2 -0
  167. package/dist/workspace/resolve-computer.d.ts +32 -3
  168. package/dist/workspace/resolve-computer.js +47 -9
  169. package/launcher/agentrun-serve +6 -1
  170. package/package.json +10 -9
  171. package/templates/README.md +27 -2
  172. package/dist/console/assets/index-BNhZs-jp.css +0 -1
  173. package/dist/console/assets/index-BQv5aOGB.js +0 -700
@@ -6,12 +6,12 @@ import { openRunMcpAuth, sealRunMcpAuth } from "../store/seal.js";
6
6
  import { isCliRecord, piShaped, runEntries, runTimeline } from "../store-reads/journal.js";
7
7
  import { recordedCalls, replayCalls, SKIPPED_WRITE, toolClassOf, toolWord, unmarkedWords } from "../learn/replay-calls.js";
8
8
  import { isObject } from "../validate.js";
9
- import { answersAlone, championOf, clears, gradesOf, PROMOTE_BAR, promotionOf, promotionsOf, recordPromotion, REFIT_EVERY, REPLAY_INPUTS, REPLAY_MIN, replayingOf, scoreOf, skippedToolsOf, thresholdsOf, withinBar } from "../learn/promote.js";
9
+ import { answersAlone, championOf, clears, gradesOf, PROMOTE_BAR, PROMOTIONS_KEPT, promotionOf, promotionsOf, recordPromotion, REFIT_EVERY, REPLAY_INPUTS, REPLAY_MIN, replayingOf, scoreOf, skippedToolsOf, thresholdsOf, withinBar } from "../learn/promote.js";
10
10
  import { sendCommand } from "./commands.js";
11
11
  import { ClaimRefused } from "./loop-contract.js";
12
12
  import { readSnapshot } from "../learn/folder.js";
13
13
  import { refitGuards, refitRowsOf, scoreRows } from "../learn/refit.js";
14
- import { fits, servedOf, workflowDigest } from "./workflow-first.js";
14
+ import { fits, laidFor, servedOf, workflowDigest } from "./workflow-first.js";
15
15
  import { learningCommit } from "../learn/commit.js";
16
16
  import { recordOnly } from "../learn/promote.js";
17
17
  import { workflowsAt } from "./learning-seed.js";
@@ -60,7 +60,7 @@ export function claimPromotion(deps) {
60
60
  /** A replay run's claim (launch.replay) of run `runId`, once its first choice is made: refused (ClaimRefused: the run ends
61
61
  * failed, no agent turn, nothing sent) unless its revision's record still says replaying and names it among its runs (it
62
62
  * is reserved before its runs are created), or has none (trimmed), and the claim laid that revision to serve it. A
63
- * superseded, promoted or held revision's replay run never runs (a cancel that never reached it included), nor an older
63
+ * promoted or held revision's replay run never runs (a cancel that never reached it included), nor an older
64
64
  * replay's leftover once its revision replays again; one whose workflow is not laid at its digest (the seed could not be
65
65
  * read, the folder moved on) never falls to the agent's path. Any other run: nothing to check. */
66
66
  export async function replayClaimed(store, agentId, runId, launch, choice) {
@@ -69,7 +69,7 @@ export async function replayClaimed(store, agentId, runId, launch, choice) {
69
69
  const { workflow, digest } = launch.replay;
70
70
  const record = promotionOf(await promotionsOf(store.settings, agentId), workflow, digest);
71
71
  if (record && record.decided !== "replaying")
72
- throw new ClaimRefused(`This replay of ${workflow} at ${digest} did not run: that revision is ${record.decided === "superseded" ? `superseded by ${record.superseded_by ?? "a newer revision"}` : record.decided === "promote" ? "promoted already" : "held already"}.`);
72
+ throw new ClaimRefused(`This replay of ${workflow} at ${digest} did not run: that revision is ${record.decided === "skipped" ? `skipped for ${record.skipped_by ?? "a newer revision"}` : record.decided === "promote" ? "promoted already" : record.decided === "hold" ? "held already" : "queued, not replaying"}.`);
73
73
  if (record && !record.runs?.includes(runId))
74
74
  throw new ClaimRefused(`This replay of ${workflow} at ${digest} did not run: that revision replays again${record.replay_id ? ` (replay ${record.replay_id})` : ""}, and this run is not one of its runs.`);
75
75
  if (choice.serve?.replay !== true || choice.serve.name !== workflow)
@@ -85,6 +85,48 @@ export function replayLaid(launch, laid) {
85
85
  const { workflow, digest } = launch.replay;
86
86
  return laid.flatMap((one) => (one.name !== workflow ? [one] : workflowDigest(one) === digest ? [{ ...one, workflow: recordOnly(one.workflow) }] : []));
87
87
  }
88
+ /** The learned workflows a run's learned_workflow tool runs, once its first choice is made: what serves, never a
89
+ * revision its promotion has not promoted. The one its first choice served or the money rule stopped (laidFor: its
90
+ * champion in place of the laid revision) as chosen; any other the records name, its champion (championOf: the laid
91
+ * text when that is the champion, else its text at its record's commit), and none while nothing of it serves (none
92
+ * promoted yet, or the champion held): a revision replaying, queued, held or never decided is never handed to the
93
+ * agent to run in its place. One the records never named (no run's input fit it, so no claim asked) runs as laid. A
94
+ * replay run's as laid (replayLaid). The records unread: only the chosen one, as the gate leaves a run to its agent. */
95
+ export async function toolFlowsFor(deps, launch, laid, choice) {
96
+ const chosen = laidFor(laid, choice);
97
+ if (launch.replay || !chosen.length)
98
+ return chosen;
99
+ const name = choice.serve?.name ?? choice.revise?.workflow;
100
+ let records;
101
+ try {
102
+ records = await promotionsOf(deps.store.settings, deps.agentId);
103
+ }
104
+ catch (error) {
105
+ deps.log(`workflow-first: the promotions could not be read (${error?.message ?? error}); the learned_workflow tool runs only the workflow chosen first`);
106
+ return chosen.filter((one) => one.name === name);
107
+ }
108
+ const out = [];
109
+ for (const one of chosen) {
110
+ if (one.name === name || !records.some((record) => record.workflow === one.name)) {
111
+ out.push(one);
112
+ continue;
113
+ }
114
+ const digest = workflowDigest(one);
115
+ const champion = championOf(records, one.name);
116
+ if (champion?.digest === digest) {
117
+ out.push(one);
118
+ continue;
119
+ }
120
+ const text = champion?.commit && deps.champion ? await deps.champion(one.name, champion.commit).catch(() => undefined) : undefined;
121
+ if (text && workflowDigest(text) === champion.digest) {
122
+ deps.log(`workflow-first: the learned_workflow tool runs ${one.name}'s champion at ${champion.digest}, not ${digest}, which is not promoted`);
123
+ out.push(text);
124
+ }
125
+ else
126
+ deps.log(`workflow-first: the learned_workflow tool leaves out ${one.name}: ${digest} is not promoted, and ${champion ? `its champion at ${champion.digest} could not be read from its learning commit` : "no revision of it serves"}`);
127
+ }
128
+ return out;
129
+ }
88
130
  const iso = (ms) => new Date(ms).toISOString();
89
131
  /** The claim's seed as a record's `commit`: the learning commit the laid workflow's text was read from. */
90
132
  const seedOf = (deps) => (deps.launch.learning?.seed ? { commit: deps.launch.learning.seed } : {});
@@ -92,7 +134,7 @@ const plural = (n, one) => `${n} ${one}${n === 1 ? "" : "s"}`;
92
134
  /** The gate workflowFirstOf asks (its `promoted`), at every run's claim, a queued run's included: the workflow that serves
93
135
  * this run first. A run already executing keeps the revision an earlier claim of it served (keptFor). Else the laid
94
136
  * revision (`workflow` at `digest`, the folder's revision as the run's seed holds it) has its promotion moved on (decide:
95
- * a replay started, settled or superseded, a dry-run promote), and then servingNow alone says who serves: the champion
137
+ * a replay started, queued or settled, a dry-run promote), and then servingNow alone says who serves: the champion
96
138
  * (championOf), the laid text when it is the champion, its own text read from its record's commit when not; undefined
97
139
  * when none serves (the agent takes the run). A digest's own record never says it serves. */
98
140
  export const promotionGate = (deps) => {
@@ -179,8 +221,9 @@ async function keptFor(deps, workflow, digest) {
179
221
  deps.log(`workflow-first: ${workflow.name} at ${kept.digest} served this run on an earlier claim; it keeps that revision${kept.digest === digest ? "" : ` (its text could not be read: the laid ${digest} stands in, the kept outcome recovered as it is)`}`);
180
222
  return workflow;
181
223
  }
182
- /** Moves the laid revision's promotion on: a new digest is replayed (or promoted on its dry run), a replaying one
183
- * settled once its runs ended, a rival replay superseded. It decides nothing about who serves (servingNow does). */
224
+ /** Moves the laid revision's promotion on: a new digest is replayed (or promoted on its dry run), or queued while another
225
+ * replays; a replaying one settled once its runs ended; the replay ahead of a queued one settled, then the queued one
226
+ * started. It decides nothing about who serves (servingNow does). */
184
227
  async function decide(deps, workflow, digest) {
185
228
  const { store, agentId, log } = deps;
186
229
  const now = deps.now ?? Date.now;
@@ -191,8 +234,8 @@ async function decide(deps, workflow, digest) {
191
234
  log(`workflow-first: ${workflow.name} at ${digest} is held (${record.reason}); it does not serve this run`);
192
235
  return;
193
236
  }
194
- if (record?.decided === "superseded") {
195
- log(`workflow-first: ${workflow.name} at ${digest} was superseded by ${record.superseded_by ?? "a newer revision"} while it replayed; it does not serve this run`);
237
+ if (record?.decided === "skipped") {
238
+ log(`workflow-first: ${workflow.name} at ${digest} was skipped (${record.reason}); it does not serve this run`);
196
239
  return;
197
240
  }
198
241
  if (record?.decided === "replaying") {
@@ -202,48 +245,141 @@ async function decide(deps, workflow, digest) {
202
245
  log(`workflow-first: ${workflow.name} at ${digest} is replaying on ${plural(record.runs?.length ?? 0, "graded input")}; it does not serve this run`);
203
246
  return;
204
247
  }
205
- // A new revision. One challenger at a time: one still replaying is superseded by it when it is the newest revision (the
206
- // one the learning folder's main holds now); a run pinned to an older commit lays an older text, and starts nothing,
207
- // whenever it was launched.
208
- const records = await promotionsOf(store.settings, agentId);
209
- const rivals = replayingOf(records, workflow.name, digest);
210
- if (rivals.length) {
248
+ // A new revision, or a queued one. One replay at a time, and a running replay finishes: the laid one moves only when it
249
+ // is the newest revision (the one the learning folder's main holds now); a run pinned to an older commit lays an older
250
+ // text and starts nothing, whenever it was launched (a queued one it lays is skipped for the newest). With the records at
251
+ // the trim's cap a revision with none may be one whose record the trim dropped (a skipped or held one): it starts only
252
+ // when it is the newest too, so a skipped draft never replays once its record is gone. `seen`, the queue as read before
253
+ // the newest check: every queue change below (queued, skips, a start) is one guarded write kept only while the queue
254
+ // is still that (sameQueue), so a claim that read an older main never skips a newer revision a later claim queued
255
+ // meanwhile.
256
+ const seen = await promotionsOf(store.settings, agentId);
257
+ let records = seen;
258
+ const ahead = [...replayingOf(records, workflow.name, digest), ...replayingOf(records, workflow.name, digest, "queued")];
259
+ const trimmed = records.length >= PROMOTIONS_KEPT;
260
+ if (ahead.length || record || trimmed) {
211
261
  const newest = deps.newest ? await deps.newest(workflow.name) : undefined;
212
- if (newest !== digest) {
213
- log(`workflow-first: ${workflow.name} at ${digest} is not the learning folder's newest revision of it (${newest ?? "unknown"}), and ${rivals[0].digest} replays; it does not serve this run`);
262
+ if (newest !== digest && (ahead.length || record || newest !== undefined)) {
263
+ if (record && newest !== undefined)
264
+ await skip(deps, record, newest);
265
+ else
266
+ log(`workflow-first: ${workflow.name} at ${digest} is not the learning folder's newest revision of it (${newest ?? "unknown"})${ahead[0] ? `, and ${ahead[0].digest} ${ahead[0].decided === "replaying" ? "replays" : "is queued"}` : ""}; it does not serve this run`);
214
267
  return;
215
268
  }
216
- for (const rival of rivals)
217
- await supersede(deps, rival, digest);
269
+ // The replay at work finishes: decided here once its runs ended (its verdict stands), never cancelled. While it
270
+ // runs, the laid revision is queued behind it.
271
+ for (const rival of replayingOf(records, workflow.name, digest))
272
+ await settleRival(deps, workflow.name, rival);
273
+ records = await promotionsOf(store.settings, agentId);
274
+ const running = replayingOf(records, workflow.name, digest)[0];
275
+ if (running)
276
+ return enqueue(deps, workflow, digest, record, running, seen);
218
277
  }
219
- // A new revision: no record of it, nothing owed, so the agent's newest REPLAY_INPUTS (the one picker, inputsFor).
278
+ // Its replay starts now, and only the newest queued revision replays next: any queued before it is skipped in the same
279
+ // write, and says so. Kept while its record is still none (or still the queued one read here) and the queue is still seen.
280
+ const older = replayingOf(seen, workflow.name, digest, "queued");
281
+ const skips = older.map((one) => skippedFor(deps, one, digest));
282
+ const fresh = (was, items) => ownStill(record)(was) && sameQueue(items, seen, workflow.name, digest);
283
+ const after = record ? `, queued since ${record.at} behind another revision's replay` : "";
284
+ const skipped = () => { for (const one of older)
285
+ log(`workflow-first: ${one.workflow} at ${one.digest} skipped: ${skips[0].reason}`); };
286
+ // No replay of it yet, nothing owed, so the agent's newest REPLAY_INPUTS (the one picker, inputsFor).
220
287
  const { graded } = await inputsFor(deps, workflow, digest, records, "held");
221
288
  if (graded.length < REPLAY_MIN) {
222
289
  const reason = graded.length ? `${plural(graded.length, "graded input")} it fits, fewer than ${REPLAY_MIN}: promoted on its passing dry run` : `no graded input it fits: promoted on its passing dry run`;
223
- const kept = await recordPromotion(store.settings, agentId, { workflow: workflow.name, digest, at: iso(now()), decided: "promote", source: "dry_run", reason, ...seedOf(deps) }, (was) => was === undefined);
224
- if (kept.won)
290
+ const kept = await recordPromotion(store.settings, agentId, { workflow: workflow.name, digest, at: iso(now()), decided: "promote", source: "dry_run", reason, ...seedOf(deps) }, fresh, skips);
291
+ if (kept.won) {
292
+ skipped();
225
293
  log(`workflow-first: ${workflow.name} at ${digest}: ${reason}`);
294
+ }
226
295
  return;
227
296
  }
228
- const reserved = await reserve(deps, workflow, digest, graded, `replaying on the agent's last ${plural(graded.length, "graded input")} it fits`, (was) => was === undefined);
297
+ const reserved = await reserve(deps, workflow, digest, graded, `replaying on the agent's last ${plural(graded.length, "graded input")} it fits${after}`, fresh, [], skips);
229
298
  if (!reserved.won) {
230
- const rival = reserved.record ? undefined : replayingOf(await promotionsOf(store.settings, agentId), workflow.name, digest)[0];
231
- if (rival)
232
- log(`workflow-first: ${workflow.name} at ${digest}: ${rival.digest} began replaying first; it does not serve this run`);
299
+ const rival = replayingOf(await promotionsOf(store.settings, agentId), workflow.name, digest)[0];
300
+ log(`workflow-first: ${workflow.name} at ${digest}: ${rival ? `${rival.digest} began replaying first` : "the queue moved since this claim read it (a claim that read a newer revision acted first)"}; it does not serve this run`);
233
301
  return;
234
302
  }
235
- log(`workflow-first: ${workflow.name} at ${digest} is new: replaying it on the agent's last ${plural(graded.length, "graded input")} before it serves`);
303
+ skipped();
304
+ log(`workflow-first: ${workflow.name} at ${digest} is ${record ? "next" : "new"}: replaying it on the agent's last ${plural(graded.length, "graded input")} before it serves`);
305
+ }
306
+ /** Whether `was`, the laid revision's newest record now, is still `record`, the one its claim read: none, or the same
307
+ * queued record. */
308
+ const ownStill = (record) => (was) => (record ? was?.decided === "queued" && was.at === record.at : was === undefined);
309
+ /** The revisions of `name` other than `digest` queued in `records`, each by digest and when it was queued. */
310
+ const queueOf = (records, name, digest) => replayingOf(records, name, digest, "queued").map((one) => `${one.digest}@${one.at}`).sort().join(",");
311
+ /** Whether the queue in `items` (now, in the guarded write) is still the one in `seen` (read before the claim's newest
312
+ * check). Main only moves on, so a claim whose newest check read an older main read the records before any claim that
313
+ * read the newer main acted: when one did (queued its revision, skipped or started the one queued), the queue moved,
314
+ * and the stale claim's write is refused. A refused claim that was the newest after all (two read the same queue)
315
+ * changes nothing either; the next claim of the newest revision, which every new run lays, makes the change. */
316
+ const sameQueue = (items, seen, name, digest) => queueOf(items, name, digest) === queueOf(seen, name, digest);
317
+ /** Queues `workflow` at `digest`, the newest revision, behind `running`, the replay at work (a record of it already
318
+ * queued is left as it is), and skips each revision queued before it (only the newest queued one replays next), in one
319
+ * guarded write: kept only while its own record is still the one read and the queue is still `seen` (sameQueue). */
320
+ async function enqueue(deps, workflow, digest, record, running, seen) {
321
+ const { store, agentId, log } = deps;
322
+ const now = deps.now ?? Date.now;
323
+ const behind = `${running.digest}'s replay on ${plural(running.runs?.length ?? 0, "graded input")}`;
324
+ const reason = `queued behind ${behind}: a running replay finishes; the newest revision queued meanwhile replays next`;
325
+ const older = replayingOf(seen, workflow.name, digest, "queued");
326
+ const writes = [...(record ? [] : [{ workflow: workflow.name, digest, at: iso(now()), decided: "queued", source: "replay", reason, ...seedOf(deps) }]), ...older.map((one) => skippedFor(deps, one, digest))];
327
+ if (!writes.length) {
328
+ log(`workflow-first: ${workflow.name} at ${digest} is queued behind ${behind}; it does not serve this run`);
329
+ return;
330
+ }
331
+ const kept = await recordPromotion(store.settings, agentId, writes[0], (_, items) => ownStill(record)(promotionOf(items, workflow.name, digest)) && sameQueue(items, seen, workflow.name, digest), writes.slice(1));
332
+ if (!kept.won) {
333
+ log(`workflow-first: ${workflow.name} at ${digest}: the queue moved since this claim read it (a claim that read a newer revision acted first); this claim changes nothing, and it does not serve this run`);
334
+ return;
335
+ }
336
+ log(`workflow-first: ${workflow.name} at ${digest} is ${record ? "queued" : "new: queued"} behind ${behind}; it replays once that one is decided`);
337
+ for (const one of older)
338
+ log(`workflow-first: ${one.workflow} at ${one.digest} skipped: ${writes.at(-1).reason}`);
339
+ }
340
+ /** `record`, a revision queued behind another's replay, skipped for `by`, a newer revision that came before its replay
341
+ * could start: it never replays and never serves. Never silent: the record names `by` and says why. */
342
+ function skippedFor(deps, record, by) {
343
+ const now = deps.now ?? Date.now;
344
+ const reason = `a newer draft ${by} arrived before its replay could start: only the newest queued revision replays next`;
345
+ return { workflow: record.workflow, digest: record.digest, at: iso(now()), decided: "skipped", source: "replay", reason, skipped_by: by, ...(record.commit ? { commit: record.commit } : {}) };
346
+ }
347
+ /** Skips the laid revision's own queued `record` for `by`, the newest revision (its claim laid an older text): kept only
348
+ * while it is still that queued record. */
349
+ async function skip(deps, record, by) {
350
+ const one = skippedFor(deps, record, by);
351
+ const kept = await recordPromotion(deps.store.settings, deps.agentId, one, (was) => was?.decided === "queued" && was.at === record.at);
352
+ if (kept.won)
353
+ deps.log(`workflow-first: ${record.workflow} at ${record.digest} skipped: ${one.reason}`);
354
+ }
355
+ /** Decides `running`, the replay at work ahead of the laid (newest) revision, as a claim laying it would (relaunch, then
356
+ * settle) once its runs ended: its text read at its record's commit, its verdict standing (promote or hold) though a
357
+ * newer revision waits. No refit is written from it: the folder's main holds the newer revision, and a refit would land
358
+ * over it. Left replaying while a run of it is at work, or when its text cannot be read (its read, replayView, decides
359
+ * it then). */
360
+ async function settleRival(deps, name, running) {
361
+ const text = running.commit && deps.champion ? await deps.champion(name, running.commit).catch(() => undefined) : undefined;
362
+ if (!text || workflowDigest(text) !== running.digest) {
363
+ deps.log(`workflow-first: ${name} at ${running.digest} replays, and its text could not be read from its learning commit to decide it at this claim`);
364
+ return;
365
+ }
366
+ const ports = { ...deps, commit: undefined };
367
+ await relaunch(ports, text, running.digest, running);
368
+ const decided = await settle(ports, text, running.digest, running);
369
+ if (decided?.decided === "hold")
370
+ deps.log(`workflow-first: ${name} at ${running.digest} held with a newer revision waiting: no refit of it is written`);
236
371
  }
237
372
  /** Reserves a replay of `workflow` at `digest` on `graded`, then starts its runs: its replaying record names the replay
238
373
  * runs it will start (their ids, and the replay's own, minted here), kept only when `still` holds of the digest's record
239
374
  * now and no other revision of the workflow replays, in the one guarded write. Only the writer that kept it starts them:
240
375
  * a claim of the same digest, or of another revision, or a person's ask, at once, starts none. A claim's (decide) and a
241
- * person's (askReplay) are this one reservation. `owed`: the held runs among `graded` it must answer on (heldOn). */
242
- async function reserve(deps, workflow, digest, graded, reason, still, owed = []) {
376
+ * person's (askReplay) are this one reservation. `owed`: the held runs among `graded` it must answer on (heldOn). `also`:
377
+ * records kept in the same write (a claim's skips of the revisions queued before it). */
378
+ async function reserve(deps, workflow, digest, graded, reason, still, owed = [], also = []) {
243
379
  const now = deps.now ?? Date.now;
244
380
  const ids = graded.map(() => uuidv7());
245
381
  const launch = replayLaunchOf(deps);
246
- const reserved = await recordPromotion(deps.store.settings, deps.agentId, { workflow: workflow.name, digest, at: iso(now()), decided: "replaying", source: "replay", reason, runs: ids, inputs: graded.map((one) => one.grade.run), replay_id: uuidv7(), launch, ...seedOf(deps), ...(owed.length ? { held_on: owed } : {}) }, (was, items) => still(was) && replayingOf(items, workflow.name, digest).length === 0);
382
+ const reserved = await recordPromotion(deps.store.settings, deps.agentId, { workflow: workflow.name, digest, at: iso(now()), decided: "replaying", source: "replay", reason, runs: ids, inputs: graded.map((one) => one.grade.run), replay_id: uuidv7(), launch, ...seedOf(deps), ...(owed.length ? { held_on: owed } : {}) }, (was, items) => still(was, items) && replayingOf(items, workflow.name, digest).length === 0, also);
247
383
  if (reserved.won)
248
384
  for (const [i, one] of graded.entries())
249
385
  await startReplay(deps, workflow, digest, one.grade.run, one.launch, ids[i], launch);
@@ -274,28 +410,11 @@ function replayLaunchOf(deps) {
274
410
  return { revision: deps.revisionId, body: launchBody(base), ...(deps.sealKey && deps.runId ? { handed_from: deps.runId } : {}) };
275
411
  }
276
412
  /** Whether `was`, a digest's newest record now, is still the replay `record` reserved: replaying, under the same replay
277
- * id. A replay settled or superseded meanwhile, and a newer replay of the same revision its owner started since (a held
278
- * revision may be replayed again), are not: an older replay's late decision never lands over a newer one. */
413
+ * id. A replay settled meanwhile, and a newer replay of the same revision its owner started since (a held revision may
414
+ * be replayed again), are not: an older replay's late decision never lands over a newer one. */
279
415
  const sameReplay = (was, record) => was?.decided === "replaying" && was.replay_id === record.replay_id;
280
- /** Supersedes `record`, a revision still replaying, by the newer revision at `by`: its record decided superseded (kept only
281
- * while it is still that replay, sameReplay: a replay that settled first keeps its decision), then its replay runs not
282
- * ended are cancelled (cancelUnended) by the claim whose write kept it. */
283
- async function supersede(deps, record, by) {
284
- const { store, agentId, log } = deps;
285
- const now = deps.now ?? Date.now;
286
- const runs = record.runs ?? [];
287
- const reason = `superseded by ${by}, a newer revision, while it replayed: its replay runs were cancelled`;
288
- const kept = await recordPromotion(store.settings, agentId, {
289
- workflow: record.workflow, digest: record.digest, at: iso(now()), decided: "superseded", source: "replay", reason, superseded_by: by,
290
- ...(runs.length ? { runs } : {}), ...(record.commit ? { commit: record.commit } : {}), ...(record.replay_id ? { replay_id: record.replay_id } : {}),
291
- }, (was) => sameReplay(was, record));
292
- if (!kept.won)
293
- return;
294
- const cancelled = await cancelUnended(deps, record);
295
- log(`workflow-first: ${record.workflow} at ${record.digest} superseded by ${by} while it replayed; ${plural(cancelled, "replay run")} cancelled`);
296
- }
297
416
  /** Cancels each of `record`'s replay runs not ended, as a person's cancel is (an in-flight one stops, what it spent booked
298
- * on its row): once its revision is superseded, or decided with runs still at work. How many were sent their cancel. The
417
+ * on its row): once its replay is decided with runs still at work (past its deadline). How many were sent their cancel. The
299
418
  * record is the durable half: a cancel that is lost (a crash after the record, a write that fails) leaves a run whose
300
419
  * claim refuses it (replayClaimed: its revision no longer replays), so each cancel is tried and a failed one only logged. */
301
420
  async function cancelUnended(deps, record) {
@@ -703,7 +822,7 @@ async function revisionOf(ask, records, name, digest) {
703
822
  * held on (heldOn), which it promotes only once it answered on: the claim's picker (inputsFor). Its runs end as a claim's
704
823
  * do, and it is decided by the claim path's settle: at a claim that lays the revision, or at its read (replayView).
705
824
  * Refused (ReplayRefused): no such workflow or revision; one replaying already, or another revision of it replaying (one
706
- * at a time); a promoted one (it serves already); fewer than REPLAY_MIN graded inputs it fits (a replay on fewer could
825
+ * at a time, never queued by a person: a queued revision is one a run's claim found newest); a promoted one (it serves already); fewer than REPLAY_MIN graded inputs it fits (a replay on fewer could
707
826
  * only hold it: settle scores none of it), refused before anything is reserved; an agent that does not learn here. The
708
827
  * replay's id and its inputs. */
709
828
  export async function askReplay(ask, name, digest, inputs) {
@@ -718,7 +837,7 @@ export async function askReplay(ask, name, digest, inputs) {
718
837
  throw new ReplayRefused("conflict", `${name} at ${digest} is promoted: it serves already. A replay checks a revision that does not serve yet, or was held.`);
719
838
  const rival = replayingOf(records, name, digest)[0];
720
839
  if (rival)
721
- throw new ReplayRefused("conflict", `${name} at ${rival.digest} is replaying: one revision of a workflow replays at a time. Ask again once it ends.`);
840
+ throw new ReplayRefused("conflict", `${name} at ${rival.digest} is replaying: one revision of a workflow replays at a time, and a running replay finishes. ${own?.decided === "queued" ? `${digest} is queued behind it: the next run's claim once it ends replays it, unless a newer revision comes first.` : "Ask again once it ends."}`);
722
841
  const { graded, owed, named } = await inputsFor({ store: ask.store, agentId: ask.agentId }, found.workflow, digest, records, inputs);
723
842
  if (graded.length < REPLAY_MIN) {
724
843
  const among = typeof inputs === "number" ? `the agent's newest ${plural(inputs, "graded input")} it fits` : named ? `the ${plural(named, "graded input")} it was last decided or held on that are still graded and fit it` : "the agent's graded runs it fits";
@@ -755,6 +874,9 @@ export async function replayView(ask, name, digest, id) {
755
874
  let record = await find();
756
875
  if (!record)
757
876
  throw new ReplayRefused("missing", `${name} at ${digest} has no replay ${id}.`);
877
+ // A replay a newer draft cancelled (a beta.39 `superseded` record, read as skipped, promotionsOf): decided, never run to a verdict.
878
+ if (record.decided === "skipped")
879
+ return { replay: id, workflow: name, digest, status: "failed", inputs: record.runs?.length ?? 0, outcomes: NO_OUTCOMES, score: scoreRows([], new Map()), cost_usd: null, reason: record.reason };
758
880
  const textOf = async (one) => (one.commit ? (await workflowsAt(ask, one.commit).catch(() => [])).find((text) => text.name === name && workflowDigest(text) === digest) : undefined);
759
881
  let text = record.decided === "replaying" ? await textOf(record) : undefined;
760
882
  const ports = record.decided === "replaying" && text && record.launch ? readPorts(ask, record.launch) : undefined;
@@ -763,10 +885,11 @@ export async function replayView(ask, name, digest, id) {
763
885
  await settle(ports, text, digest, record);
764
886
  record = (await find()) ?? record;
765
887
  }
766
- const decided = record.decided === "replaying" ? undefined : record.decided;
888
+ // Only a replaying, promote or hold record carries a replay's id.
889
+ const decided = record.decided === "promote" || record.decided === "hold" ? record.decided : undefined;
767
890
  const inputs = record.runs?.length ?? 0;
768
891
  const said = decided ? { decided, reason: record.reason } : {};
769
- const kept = record.replay && decided && decided !== "superseded" ? record.replay : undefined;
892
+ const kept = record.replay && decided ? record.replay : undefined;
770
893
  if (kept) {
771
894
  // Decided: its record's numbers alone. With not one of its reserved runs ever created (none counted: a decided
772
895
  // replay counted every run there was, and none is created after), nothing was replayed (settle's reason says so).
@@ -777,7 +900,7 @@ export async function replayView(ask, name, digest, id) {
777
900
  const read = await replayRows(ask, record, true);
778
901
  text ??= await textOf(record);
779
902
  return {
780
- replay: id, workflow: name, digest, status: decided === undefined ? "running" : decided === "superseded" ? "failed" : "done", inputs,
903
+ replay: id, workflow: name, digest, status: decided === undefined ? "running" : "done", inputs,
781
904
  outcomes: read?.outcomes ?? NO_OUTCOMES,
782
905
  score: scoreRows(read?.scored ?? [], text ? thresholdsOf(text.workflow) : new Map()), cost_usd: read?.cost ?? null, ...said,
783
906
  };
@@ -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 } from "../learned-nodes.js";
5
+ import { type GuardRow, 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. */
@@ -101,8 +101,8 @@ export interface FirstChoice {
101
101
  * is not promoted yet or was held (runner/promotion.ts): the text the run's learned_workflow tool runs (laidFor). */
102
102
  readonly champion?: LearnedWorkflow;
103
103
  }
104
- /** The learned workflows a run's tool runs once its first choice is made: the laid ones, a champion (FirstChoice) in
105
- * place of its laid revision. */
104
+ /** The laid learned workflows with a first choice's champion (FirstChoice) in place of its laid revision: what
105
+ * runner/promotion.ts toolFlowsFor reads the rest of from the promotion records, so the run's tool runs only what serves. */
106
106
  export declare const laidFor: (laid: readonly LearnedWorkflow[], choice: FirstChoice) => LearnedWorkflow[];
107
107
  /** What serves a run in place of its laid workflow: the workflow (the laid one itself, or its champion's text), and the
108
108
  * promotion it serves under (WorkflowFirst.promotion). */
@@ -169,8 +169,8 @@ export declare function reviseOf(entries: readonly {
169
169
  * (runPathOverStore): the path it took, the learned revision it ran on, the learned workflow it ran (served first, or
170
170
  * called by its agent) and, for one served first, its digest and the promotion it served under (`workflow_promotion`,
171
171
  * which its grade keeps); and from its root `entries`, each step guard's check of its learned workflows' calls
172
- * (`guards`, learned-nodes.ts guardsOf), when one ran. learning-cost reads path and workflow from here. None for a run
173
- * that does not learn. */
172
+ * (`guards`, learned-nodes.ts guardsOf) and each loop's exit (`loops`, loopsOf: a quote re-pick is a loop's second
173
+ * pass), when one ran. learning-cost reads path and workflow from here. None for a run that does not learn. */
174
174
  export declare function pathMetrics(launch: RunLaunch, classified: {
175
175
  path: RunPath;
176
176
  workflow: string | null;
@@ -186,6 +186,7 @@ export declare function pathMetrics(launch: RunLaunch, classified: {
186
186
  workflow_digest?: string;
187
187
  workflow_promotion?: number;
188
188
  guards?: GuardRow[];
189
+ loops?: LoopRow[];
189
190
  replay?: ReplayMetrics;
190
191
  };
191
192
  /** A replay run's record (metrics.replay): the graded run it replayed and how its workflow ended there. */
@@ -28,7 +28,7 @@ import { COST_WINDOW } from "../learning-cost.js";
28
28
  export { COST_WINDOW };
29
29
  import { KINDS } from "./journal-kinds.js";
30
30
  import { inputIssues, isObject } from "../validate.js";
31
- import { endedIn, guardsOf, replaySkippedIn } from "../learned-nodes.js";
31
+ import { endedIn, guardsOf, loopsOf, replaySkippedIn } from "../learned-nodes.js";
32
32
  import { sameAnswer } from "../learn/promote.js";
33
33
  /** The root entry a run served workflow-first keeps, once the workflow's call ended: which workflow, at which learned
34
34
  * revision, under which call, and how it ended. A later claim that finds it never runs the workflow again. */
@@ -85,8 +85,8 @@ export function workflowCostsOf(past) {
85
85
  return { workflow, digest, state: overLine(line) ? "needs_revision" : "serving", served: line.served.runs ? line.served : null, by_hand: line.by_hand, unknown_cost_runs: line.unknown_runs };
86
86
  });
87
87
  }
88
- /** The learned workflows a run's tool runs once its first choice is made: the laid ones, a champion (FirstChoice) in
89
- * place of its laid revision. */
88
+ /** The laid learned workflows with a first choice's champion (FirstChoice) in place of its laid revision: what
89
+ * runner/promotion.ts toolFlowsFor reads the rest of from the promotion records, so the run's tool runs only what serves. */
90
90
  export const laidFor = (laid, choice) => choice.champion ? laid.map((one) => (one.name === choice.champion.name ? choice.champion : one)) : [...laid];
91
91
  /** A workflow's input schema, resolved as the DSL resolves a schema reference, or undefined when it names none. */
92
92
  function inputSchemaOf(text, resolve) {
@@ -229,13 +229,15 @@ export function reviseOf(entries) {
229
229
  * (runPathOverStore): the path it took, the learned revision it ran on, the learned workflow it ran (served first, or
230
230
  * called by its agent) and, for one served first, its digest and the promotion it served under (`workflow_promotion`,
231
231
  * which its grade keeps); and from its root `entries`, each step guard's check of its learned workflows' calls
232
- * (`guards`, learned-nodes.ts guardsOf), when one ran. learning-cost reads path and workflow from here. None for a run
233
- * that does not learn. */
232
+ * (`guards`, learned-nodes.ts guardsOf) and each loop's exit (`loops`, loopsOf: a quote re-pick is a loop's second
233
+ * pass), when one ran. learning-cost reads path and workflow from here. None for a run that does not learn. */
234
234
  export function pathMetrics(launch, classified, entries = []) {
235
235
  if (!launch.learning)
236
236
  return {};
237
237
  const { path, workflow, digest, promotion } = classified ?? { path: "agent", workflow: null };
238
238
  const guards = guardsOf(entries);
239
+ const loops = loopsOf(entries);
240
+ const rows = { ...(guards.length ? { guards } : {}), ...(loops.length ? { loops } : {}) };
239
241
  if (launch.replay) {
240
242
  // A replay run (runner/promotion.ts): path `replay`, whatever its workflow did, so the money rule and the agent's
241
243
  // by-hand cost never read it; how its workflow ended, for the replay's score (learn/promote.ts ReplayRow).
@@ -246,9 +248,9 @@ export function pathMetrics(launch, classified, entries = []) {
246
248
  // evidence. Skipped when a write it needed is not in the graded run's recording (learn/replay-calls.ts): never run.
247
249
  const skipped = replaySkippedIn(entries);
248
250
  const outcome = skipped ? "skipped_write" : path === "workflow" && workflow === name ? "answered" : path === "handed_back" && workflow === name && endedIn(entries, name) === "escalated" ? "handed_back" : "failed";
249
- return { path: "replay", ...(launch.learning.seed ? { learned_revision: launch.learning.seed } : {}), workflow: name, workflow_digest: at, ...(guards.length ? { guards } : {}), replay: { of, outcome, ...(skipped ? { skipped } : {}) } };
251
+ return { path: "replay", ...(launch.learning.seed ? { learned_revision: launch.learning.seed } : {}), workflow: name, workflow_digest: at, ...rows, replay: { of, outcome, ...(skipped ? { skipped } : {}) } };
250
252
  }
251
- return { path, ...(launch.learning.seed ? { learned_revision: launch.learning.seed } : {}), ...(workflow ? { workflow } : {}), ...(digest ? { workflow_digest: digest } : {}), ...(promotion !== undefined ? { workflow_promotion: promotion } : {}), ...(guards.length ? { guards } : {}) };
253
+ return { path, ...(launch.learning.seed ? { learned_revision: launch.learning.seed } : {}), ...(workflow ? { workflow } : {}), ...(digest ? { workflow_digest: digest } : {}), ...(promotion !== undefined ? { workflow_promotion: promotion } : {}), ...rows };
252
254
  }
253
255
  /** What run `entries` (its root's) say its learned workflow answered alone: the workflow and its answer (the model's
254
256
  * 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
@@ -17,6 +17,7 @@ import { CAP_TOLERANCE, money } from "./cap.js";
17
17
  import { holdOf } from "./computer-held.js";
18
18
  import { computerOfPlace, settingOfDefinition } from "./computer-setting.js";
19
19
  import { ApiError, invalid, unsupported } from "./errors.js";
20
+ import { labelsOf } from "./run-labels.js";
20
21
  import { harnessOfBody } from "./harness.js";
21
22
  import { redacted, redactedOutput } from "./key-refusal.js";
22
23
  import { chooseWorkflows, LEARNING_BUDGET, learnedParts, learnsOf, RUN_LEARNING_USE } from "./learning.js";
@@ -447,7 +448,8 @@ export async function startRun(store, deps, entry, body, { trigger, origin, capp
447
448
  const { launch, revision } = await prepareLaunch(deps, entry, body, { ...(trigger ? { trigger } : {}), capped, ...(from ? { from } : {}), ...(title !== undefined ? { title } : {}) });
448
449
  const runId = (deps.newRunId ?? uuidv7)();
449
450
  try {
450
- return await withHeldFiles(deps, runId, launch, () => store.runs.create({ id: runId, agentId: entry.agent.id, revisionId: revision.id, ...(origin ? { origin } : {}) }, { body: launchBody(launch), ...(sealed ? { sealed: sealed(runId) } : {}) }));
451
+ 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) } : {}) }));
451
453
  }
452
454
  catch (error) {
453
455
  // Only another writer of the store got here first under the same origin key: its run is the one asked for.
@@ -508,11 +510,12 @@ export async function startInline(store, deps, inline, body, { origin, sealed }
508
510
  // one across.
509
511
  const { launch } = await prepareLaunch(deps, entry, body, { revision: (storedRevision ?? revision) });
510
512
  const runId = (deps.newRunId ?? uuidv7)();
513
+ const labels = labelsOf(body.labels);
511
514
  try {
512
515
  return await withHeldFiles(deps, runId, launch, () => store.runs.createInline({
513
516
  agent: { id: entry.agent.id, name: inline.name, description: inline.description, ref },
514
517
  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 } : {}) },
515
- run: { id: runId, ...(origin ? { origin } : {}) },
518
+ run: { id: runId, ...(origin ? { origin } : {}), ...(labels ? { labels } : {}) },
516
519
  launch: { body: launchBody(launch), ...(sealed ? { sealed: sealed(runId) } : {}) },
517
520
  }));
518
521
  }
@@ -61,12 +61,18 @@ export declare function sdkInbox(store: Pick<Store, "settings">, runId: string):
61
61
  /** Completion and closure compete on the same inbox. A stale runner cannot close it, and a completion that won
62
62
  * remains available to the next claim even if this one cannot read or journal it. No external SDK call is replayed. */
63
63
  export declare function closeSdkInbox(store: Pick<Store, "settings">, claim: Claim, reason: NonNullable<SdkInbox["closed"]>): Promise<SdkInbox>;
64
+ /** The key a server signs its SDK runs' credentials with: derived from its seal key (seal-key.ts), which stays the
65
+ * store's for its life, so adding, reordering or removing an API token (api-token.ts) never changes a run's credential. */
66
+ export declare const sdkRunSecret: (sealKey: Buffer) => string;
64
67
  export declare class SdkRuns {
65
68
  private readonly store;
66
69
  private readonly data;
67
70
  private readonly secret;
68
71
  private readonly secrets;
69
- constructor(store: Store, data: string, secret: string, secrets?: () => readonly string[]);
72
+ private readonly earlier;
73
+ /** `earlier` are the keys credentials were once signed with (the server's API tokens, before `secret` was its seal
74
+ * key's): a credential any of them signed is still taken, so a run started before an upgrade keeps its credential. */
75
+ constructor(store: Store, data: string, secret: string, secrets?: () => readonly string[], earlier?: readonly string[]);
70
76
  token(runId: string): string;
71
77
  authenticate(runId: string, token: string): Promise<void>;
72
78
  private clean;
package/dist/sdk/runs.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // Backend SDK calls remain in their application. This inbox only records their evidence and immutable completion;
2
2
  // the ordinary fenced runner owns journals, reflection, checking and learning commits.
3
- import { createHmac, timingSafeEqual } from "node:crypto";
3
+ import { createHash, createHmac, timingSafeEqual } from "node:crypto";
4
4
  import { inspectWorkflow } from "@parcha/agentrun-dsl";
5
5
  import { ApiError } from "../errors.js";
6
6
  import { canonical, isObject } from "../store/agent-body.js";
@@ -117,28 +117,41 @@ function checkToolParents(row, events) {
117
117
  }
118
118
  }
119
119
  }
120
+ /** The key a server signs its SDK runs' credentials with: derived from its seal key (seal-key.ts), which stays the
121
+ * store's for its life, so adding, reordering or removing an API token (api-token.ts) never changes a run's credential. */
122
+ export const sdkRunSecret = (sealKey) => createHmac("sha256", sealKey).update("agentrun sdk-run credentials").digest("base64url");
123
+ const sign = (secret, runId) => `ar_sdk_${createHmac("sha256", secret).update(`sdk-run\0${runId}`).digest("base64url")}`;
124
+ const digest = (text) => createHash("sha256").update(text).digest();
120
125
  export class SdkRuns {
121
126
  store;
122
127
  data;
123
128
  secret;
124
129
  secrets;
125
- constructor(store, data, secret, secrets = () => []) {
130
+ earlier;
131
+ /** `earlier` are the keys credentials were once signed with (the server's API tokens, before `secret` was its seal
132
+ * key's): a credential any of them signed is still taken, so a run started before an upgrade keeps its credential. */
133
+ constructor(store, data, secret, secrets = () => [], earlier = []) {
126
134
  this.store = store;
127
135
  this.data = data;
128
136
  this.secret = secret;
129
137
  this.secrets = secrets;
138
+ this.earlier = earlier;
130
139
  }
131
140
  token(runId) {
132
- return `ar_sdk_${createHmac("sha256", this.secret).update(`sdk-run\0${runId}`).digest("base64url")}`;
141
+ return sign(this.secret, runId);
133
142
  }
134
143
  async authenticate(runId, token) {
135
- const expected = Buffer.from(this.token(runId)), actual = Buffer.from(token);
136
- if (expected.length !== actual.length || !timingSafeEqual(expected, actual))
144
+ // Every key compared, on equal-length digests, with no early return.
145
+ const given = digest(token);
146
+ let ok = false;
147
+ for (const key of [this.secret, ...this.earlier])
148
+ ok = timingSafeEqual(given, digest(sign(key, runId))) || ok;
149
+ if (!ok)
137
150
  throw new ApiError("unauthenticated", "This credential is scoped to a different SDK run.");
138
151
  await sdkInbox(this.store, runId);
139
152
  }
140
153
  clean(body, runId) {
141
- const redact = secretRedactor([...this.secrets(), ...(runId ? [this.token(runId)] : [])]);
154
+ const redact = secretRedactor([...this.secrets(), ...(runId ? [this.secret, ...this.earlier].map((key) => sign(key, runId)) : [])]);
142
155
  // Redact values structurally: a long string or encoded credential can be withheld whole,
143
156
  // so treating serialized JSON as prose could remove its delimiters and corrupt the envelope.
144
157
  return redactedOutput(body, redact.heldValues?.() ?? []);
@@ -7,6 +7,7 @@ import { rules as recommended } from "@secretlint/secretlint-rule-preset-recomme
7
7
  // No performance marks: the profiler would leave about 14 a call in the process's global buffer.
8
8
  secretLintProfiler.setEnabled(false);
9
9
  import { keyShaped } from "./secret-name.js";
10
+ import { secretValues } from "./api-token.js";
10
11
  /** Whether a name is a secret's, whatever list names it or none does: one of its `_`-separated segments, in any case, is
11
12
  * KEY, TOKEN, SECRET, PASSWORD, PASSWD, PASS, PAT, CREDENTIAL, CREDENTIALS or DSN, or its last is PWD after another.
12
13
  * The one rule: this cut, the harness log's and a run's environment (secrets.ts' withoutSecrets)
@@ -22,7 +23,8 @@ export function secretCut(envs, names = []) {
22
23
  const secrets = (Array.isArray(envs) ? envs : [envs])
23
24
  .flatMap((env) => Object.getOwnPropertyNames(env).map((name) => [name, env[name]]))
24
25
  .filter(([name, value]) => (keyShaped(name) || names.includes(name)) && typeof value === "string" && value.length >= 8)
25
- .map(([, value]) => value)
26
+ // AGENTRUN_TOKENS's each secret too, not only the list whole (api-token.ts secretValues).
27
+ .flatMap(([name, value]) => secretValues(name, value).filter((part) => part.length >= 8))
26
28
  // The longest first: a key that holds a shorter one is cut whole.
27
29
  .sort((a, b) => b.length - a.length);
28
30
  // `text.removed` counts the values it cut, each once however often it was met; `text.probe` cuts the same and counts
package/dist/secrets.js CHANGED
@@ -11,6 +11,7 @@ import { closeSync, existsSync, readFileSync, readSync } from "node:fs";
11
11
  import { homedir } from "node:os";
12
12
  import { keyShaped } from "./secret-cut.js";
13
13
  import { MIN_SECRET } from "./learn/secrets.js";
14
+ import { secretValues } from "./api-token.js";
14
15
  /** The pipe and how many bytes of it are the secrets: the launcher's, or serve's to a run's process. */
15
16
  export const SECRETS_FD_ENV = "AGENTRUN_SECRETS_FD";
16
17
  export const SECRETS_LEN_ENV = "AGENTRUN_SECRETS_LEN";
@@ -94,7 +95,8 @@ const SECRET_NAME = /(?:^|_)(?:KEY|TOKEN|SECRET|PASSWORD)$/i;
94
95
  * every other key, token, secret or password `env` names. One shorter than the checker's MIN_SECRET,
95
96
  * whitespace aside, matches too much text by chance to be refused, and is left out. */
96
97
  export const hostSecrets = (env, stored) => {
97
- const held = [...SECRET_NAMES.flatMap((name) => [secret(name) ?? "", stored?.(name) ?? ""]), ...mcpSecretValues(mcpCredentials()), ...sealKeys.keys(), ...heldTokens];
98
+ // AGENTRUN_TOKENS's each secret too, not only the list whole (api-token.ts secretValues).
99
+ const held = [...SECRET_NAMES.flatMap((name) => [...secretValues(name, secret(name) ?? ""), stored?.(name) ?? ""]), ...mcpSecretValues(mcpCredentials()), ...sealKeys.keys(), ...heldTokens];
98
100
  const named = Object.entries(env).filter(([name]) => SECRET_NAME.test(name) && !SECRET_NAMES.includes(name)).map(([, value]) => value ?? "");
99
101
  return [...new Set([...held, ...named])].filter((value) => value.replace(/\s+/g, "").length >= MIN_SECRET);
100
102
  };