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

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 (81) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +51 -1
  3. package/dist/console/assets/index-B8Zn1Iqn.css +1 -0
  4. package/dist/console/assets/index-Jbxjcmdp.js +705 -0
  5. package/dist/console/index.html +2 -2
  6. package/dist/email/account.d.ts +0 -1
  7. package/dist/email/account.js +3 -3
  8. package/dist/email/answer.d.ts +5 -0
  9. package/dist/email/answer.js +35 -0
  10. package/dist/email/mail.js +19 -26
  11. package/dist/email/names.d.ts +30 -0
  12. package/dist/email/names.js +34 -0
  13. package/dist/email/routes.d.ts +1 -0
  14. package/dist/email/routes.js +1 -1
  15. package/dist/email/tools.d.ts +11 -4
  16. package/dist/email/tools.js +91 -46
  17. package/dist/eval-mailbox.d.ts +1 -1
  18. package/dist/eval-mailbox.js +3 -3
  19. package/dist/learn/compile.d.ts +3 -2
  20. package/dist/learn/compile.js +6 -5
  21. package/dist/learn/promote.d.ts +25 -14
  22. package/dist/learn/promote.js +32 -14
  23. package/dist/learning-cost.d.ts +17 -8
  24. package/dist/learning-cost.js +12 -4
  25. package/dist/local-models.d.ts +7 -1
  26. package/dist/local-models.js +11 -5
  27. package/dist/openapi.d.ts +1 -1
  28. package/dist/openapi.js +17 -15
  29. package/dist/port-models.d.ts +4 -1
  30. package/dist/port-models.js +1 -0
  31. package/dist/refusal-words.d.ts +3 -0
  32. package/dist/refusal-words.js +3 -0
  33. package/dist/run-launch.d.ts +2 -0
  34. package/dist/run-launch.js +2 -0
  35. package/dist/run-view.d.ts +3 -4
  36. package/dist/run-view.js +26 -24
  37. package/dist/runner/adapter-loop.d.ts +6 -2
  38. package/dist/runner/adapter-loop.js +45 -12
  39. package/dist/runner/adapter-run-spec.d.ts +1 -0
  40. package/dist/runner/adapter-run-spec.js +37 -1
  41. package/dist/runner/cli-run-spec.js +1 -0
  42. package/dist/runner/journal-kinds.d.ts +22 -0
  43. package/dist/runner/journal-kinds.js +39 -0
  44. package/dist/runner/model-route.d.ts +3 -1
  45. package/dist/runner/model-route.js +18 -3
  46. package/dist/runner/promotion.d.ts +8 -8
  47. package/dist/runner/promotion.js +135 -54
  48. package/dist/server.js +15 -8
  49. package/dist/store/dialect.d.ts +3 -0
  50. package/dist/store/dialect.js +1 -0
  51. package/dist/store/postgres/connection.d.ts +11 -5
  52. package/dist/store/postgres/connection.js +44 -17
  53. package/dist/store/postgres/dialect.js +5 -0
  54. package/dist/store/postgres/store.d.ts +7 -3
  55. package/dist/store/postgres/store.js +1 -0
  56. package/dist/store/sqlite/connection.js +72 -8
  57. package/dist/store/sqlite/run-launch.d.ts +11 -0
  58. package/dist/store/sqlite/run-launch.js +8 -0
  59. package/dist/store/sqlite/store.js +37 -16
  60. package/dist/store/sqlite/worker.d.ts +2 -0
  61. package/dist/store/sqlite/worker.js +13 -10
  62. package/dist/store/store.d.ts +15 -0
  63. package/dist/store-reads/learning.d.ts +30 -13
  64. package/dist/store-reads/learning.js +125 -51
  65. package/dist/template-eval.js +1 -1
  66. package/dist/templates.d.ts +14 -1
  67. package/dist/templates.js +67 -17
  68. package/dist/tool-gate.d.ts +5 -3
  69. package/dist/tool-gate.js +5 -2
  70. package/dist/tools.d.ts +13 -0
  71. package/dist/tools.js +15 -10
  72. package/dist/trigger-adapter.d.ts +3 -32
  73. package/dist/trigger-email.js +30 -77
  74. package/dist/triggers.d.ts +26 -14
  75. package/dist/triggers.js +99 -76
  76. package/dist/workflow/decision-recovery.js +5 -2
  77. package/dist/workflow/decisions.d.ts +7 -0
  78. package/package.json +9 -9
  79. package/templates/README.md +2 -2
  80. package/dist/console/assets/index-BNhZs-jp.css +0 -1
  81. package/dist/console/assets/index-BQv5aOGB.js +0 -700
@@ -4,7 +4,7 @@ import { type RunLaunch } from "../run-launch.js";
4
4
  import { type Store } from "../store/store.js";
5
5
  import { type ReplayCalls } from "../learn/replay-calls.js";
6
6
  import { type Json } from "../validate.js";
7
- import { type PromotionRecord, type ReplayOutcomes, type ReplayScore } from "../learn/promote.js";
7
+ import { type ReplayOutcomes, type ReplayScore } from "../learn/promote.js";
8
8
  import { type FirstChoice, type Promoted } from "./workflow-first.js";
9
9
  import type { LearningFolder } from "../learn/folder.js";
10
10
  import type { Shown } from "../learning.js";
@@ -36,7 +36,7 @@ export interface PromotionDeps {
36
36
  * it held none by that name. Absent: no champion serves. */
37
37
  readonly champion?: (name: string, commit: string) => Promise<LearnedWorkflow | undefined>;
38
38
  /** The digest of the learned workflow `name` the learning folder's main holds now (the newest revision), or undefined
39
- * when it holds none by that name. Absent: no revision supersedes another. */
39
+ * when it holds none by that name. Absent: no revision queues behind another's replay. */
40
40
  readonly newest?: (name: string) => Promise<string | undefined>;
41
41
  /** The learned workflow an earlier claim of this run served first (its WORKFLOW_FIRST entry, answered or handed back:
42
42
  * workflow-first.ts servedOf), or undefined for a run no claim served yet: a run already executing keeps its revision
@@ -61,7 +61,7 @@ export declare function claimPromotion(deps: Omit<PromotionDeps, "commit" | "cha
61
61
  /** A replay run's claim (launch.replay) of run `runId`, once its first choice is made: refused (ClaimRefused: the run ends
62
62
  * failed, no agent turn, nothing sent) unless its revision's record still says replaying and names it among its runs (it
63
63
  * is reserved before its runs are created), or has none (trimmed), and the claim laid that revision to serve it. A
64
- * superseded, promoted or held revision's replay run never runs (a cancel that never reached it included), nor an older
64
+ * promoted or held revision's replay run never runs (a cancel that never reached it included), nor an older
65
65
  * replay's leftover once its revision replays again; one whose workflow is not laid at its digest (the seed could not be
66
66
  * read, the folder moved on) never falls to the agent's path. Any other run: nothing to check. */
67
67
  export declare function replayClaimed(store: Pick<Store, "settings">, agentId: string, runId: string, launch: RunLaunch, choice: FirstChoice): Promise<void>;
@@ -73,7 +73,7 @@ export declare function replayLaid(launch: RunLaunch, laid: readonly LearnedWork
73
73
  /** The gate workflowFirstOf asks (its `promoted`), at every run's claim, a queued run's included: the workflow that serves
74
74
  * this run first. A run already executing keeps the revision an earlier claim of it served (keptFor). Else the laid
75
75
  * revision (`workflow` at `digest`, the folder's revision as the run's seed holds it) has its promotion moved on (decide:
76
- * a replay started, settled or superseded, a dry-run promote), and then servingNow alone says who serves: the champion
76
+ * a replay started, queued or settled, a dry-run promote), and then servingNow alone says who serves: the champion
77
77
  * (championOf), the laid text when it is the champion, its own text read from its record's commit when not; undefined
78
78
  * when none serves (the agent takes the run). A digest's own record never says it serves. */
79
79
  export declare const promotionGate: (deps: PromotionDeps) => Promoted;
@@ -105,7 +105,7 @@ export interface ReplayAsk {
105
105
  * held on (heldOn), which it promotes only once it answered on: the claim's picker (inputsFor). Its runs end as a claim's
106
106
  * do, and it is decided by the claim path's settle: at a claim that lays the revision, or at its read (replayView).
107
107
  * Refused (ReplayRefused): no such workflow or revision; one replaying already, or another revision of it replaying (one
108
- * at a time); a promoted one (it serves already); fewer than REPLAY_MIN graded inputs it fits (a replay on fewer could
108
+ * 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
109
109
  * only hold it: settle scores none of it), refused before anything is reserved; an agent that does not learn here. The
110
110
  * replay's id and its inputs. */
111
111
  export declare function askReplay(ask: ReplayAsk, name: string, digest: string, inputs: "held" | number): Promise<{
@@ -113,8 +113,8 @@ export declare function askReplay(ask: ReplayAsk, name: string, digest: string,
113
113
  inputs: number;
114
114
  }>;
115
115
  /** A replay as its read answers it (GET .../replays/{replay_id}). `status`: `running` while its record says replaying,
116
- * `done` once promoted or held, `failed` when superseded (its runs cancelled) or when none of its runs started by its
117
- * deadline (nothing was replayed; held, its `reason` says so). `outcomes`: what its own runs did (outcomesOf), so far
116
+ * `done` once promoted or held, `failed` when none of its runs started by its deadline (nothing was replayed; held, its
117
+ * `reason` says so). A replay is never cancelled for a newer revision: that one queues behind it. `outcomes`: what its own runs did (outcomesOf), so far
118
118
  * while it runs, and once decided as its record kept them, whatever the agent's grades kept now; never the thresholds'
119
119
  * reading (a run answered under its guard's threshold stays answered: `score` hands it back). `score` and `cost_usd`
120
120
  * the decided record's, else the runs ended so far at the revision's serving thresholds, and null while a run's cost
@@ -128,7 +128,7 @@ type ReplayView = {
128
128
  readonly outcomes: ReplayOutcomes;
129
129
  readonly score: ReplayScore;
130
130
  readonly cost_usd: number | null;
131
- readonly decided?: PromotionRecord["decided"];
131
+ readonly decided?: "promote" | "hold";
132
132
  readonly reason?: string;
133
133
  };
134
134
  /** Reads replay `id` of `name` at `digest`, settling it first as a claim of its revision would (the claim path's settle)
@@ -6,7 +6,7 @@ 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";
@@ -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)
@@ -92,7 +92,7 @@ const plural = (n, one) => `${n} ${one}${n === 1 ? "" : "s"}`;
92
92
  /** The gate workflowFirstOf asks (its `promoted`), at every run's claim, a queued run's included: the workflow that serves
93
93
  * this run first. A run already executing keeps the revision an earlier claim of it served (keptFor). Else the laid
94
94
  * 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
95
+ * a replay started, queued or settled, a dry-run promote), and then servingNow alone says who serves: the champion
96
96
  * (championOf), the laid text when it is the champion, its own text read from its record's commit when not; undefined
97
97
  * when none serves (the agent takes the run). A digest's own record never says it serves. */
98
98
  export const promotionGate = (deps) => {
@@ -179,8 +179,9 @@ async function keptFor(deps, workflow, digest) {
179
179
  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
180
  return workflow;
181
181
  }
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). */
182
+ /** Moves the laid revision's promotion on: a new digest is replayed (or promoted on its dry run), or queued while another
183
+ * replays; a replaying one settled once its runs ended; the replay ahead of a queued one settled, then the queued one
184
+ * started. It decides nothing about who serves (servingNow does). */
184
185
  async function decide(deps, workflow, digest) {
185
186
  const { store, agentId, log } = deps;
186
187
  const now = deps.now ?? Date.now;
@@ -191,8 +192,8 @@ async function decide(deps, workflow, digest) {
191
192
  log(`workflow-first: ${workflow.name} at ${digest} is held (${record.reason}); it does not serve this run`);
192
193
  return;
193
194
  }
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`);
195
+ if (record?.decided === "skipped") {
196
+ log(`workflow-first: ${workflow.name} at ${digest} was skipped (${record.reason}); it does not serve this run`);
196
197
  return;
197
198
  }
198
199
  if (record?.decided === "replaying") {
@@ -202,48 +203,141 @@ async function decide(deps, workflow, digest) {
202
203
  log(`workflow-first: ${workflow.name} at ${digest} is replaying on ${plural(record.runs?.length ?? 0, "graded input")}; it does not serve this run`);
203
204
  return;
204
205
  }
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) {
206
+ // A new revision, or a queued one. One replay at a time, and a running replay finishes: the laid one moves only when it
207
+ // is the newest revision (the one the learning folder's main holds now); a run pinned to an older commit lays an older
208
+ // text and starts nothing, whenever it was launched (a queued one it lays is skipped for the newest). With the records at
209
+ // the trim's cap a revision with none may be one whose record the trim dropped (a skipped or held one): it starts only
210
+ // when it is the newest too, so a skipped draft never replays once its record is gone. `seen`, the queue as read before
211
+ // the newest check: every queue change below (queued, skips, a start) is one guarded write kept only while the queue
212
+ // is still that (sameQueue), so a claim that read an older main never skips a newer revision a later claim queued
213
+ // meanwhile.
214
+ const seen = await promotionsOf(store.settings, agentId);
215
+ let records = seen;
216
+ const ahead = [...replayingOf(records, workflow.name, digest), ...replayingOf(records, workflow.name, digest, "queued")];
217
+ const trimmed = records.length >= PROMOTIONS_KEPT;
218
+ if (ahead.length || record || trimmed) {
211
219
  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`);
220
+ if (newest !== digest && (ahead.length || record || newest !== undefined)) {
221
+ if (record && newest !== undefined)
222
+ await skip(deps, record, newest);
223
+ else
224
+ 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
225
  return;
215
226
  }
216
- for (const rival of rivals)
217
- await supersede(deps, rival, digest);
227
+ // The replay at work finishes: decided here once its runs ended (its verdict stands), never cancelled. While it
228
+ // runs, the laid revision is queued behind it.
229
+ for (const rival of replayingOf(records, workflow.name, digest))
230
+ await settleRival(deps, workflow.name, rival);
231
+ records = await promotionsOf(store.settings, agentId);
232
+ const running = replayingOf(records, workflow.name, digest)[0];
233
+ if (running)
234
+ return enqueue(deps, workflow, digest, record, running, seen);
218
235
  }
219
- // A new revision: no record of it, nothing owed, so the agent's newest REPLAY_INPUTS (the one picker, inputsFor).
236
+ // Its replay starts now, and only the newest queued revision replays next: any queued before it is skipped in the same
237
+ // write, and says so. Kept while its record is still none (or still the queued one read here) and the queue is still seen.
238
+ const older = replayingOf(seen, workflow.name, digest, "queued");
239
+ const skips = older.map((one) => skippedFor(deps, one, digest));
240
+ const fresh = (was, items) => ownStill(record)(was) && sameQueue(items, seen, workflow.name, digest);
241
+ const after = record ? `, queued since ${record.at} behind another revision's replay` : "";
242
+ const skipped = () => { for (const one of older)
243
+ log(`workflow-first: ${one.workflow} at ${one.digest} skipped: ${skips[0].reason}`); };
244
+ // No replay of it yet, nothing owed, so the agent's newest REPLAY_INPUTS (the one picker, inputsFor).
220
245
  const { graded } = await inputsFor(deps, workflow, digest, records, "held");
221
246
  if (graded.length < REPLAY_MIN) {
222
247
  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)
248
+ const kept = await recordPromotion(store.settings, agentId, { workflow: workflow.name, digest, at: iso(now()), decided: "promote", source: "dry_run", reason, ...seedOf(deps) }, fresh, skips);
249
+ if (kept.won) {
250
+ skipped();
225
251
  log(`workflow-first: ${workflow.name} at ${digest}: ${reason}`);
252
+ }
226
253
  return;
227
254
  }
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);
255
+ 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
256
  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`);
257
+ const rival = replayingOf(await promotionsOf(store.settings, agentId), workflow.name, digest)[0];
258
+ 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`);
259
+ return;
260
+ }
261
+ skipped();
262
+ 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`);
263
+ }
264
+ /** Whether `was`, the laid revision's newest record now, is still `record`, the one its claim read: none, or the same
265
+ * queued record. */
266
+ const ownStill = (record) => (was) => (record ? was?.decided === "queued" && was.at === record.at : was === undefined);
267
+ /** The revisions of `name` other than `digest` queued in `records`, each by digest and when it was queued. */
268
+ const queueOf = (records, name, digest) => replayingOf(records, name, digest, "queued").map((one) => `${one.digest}@${one.at}`).sort().join(",");
269
+ /** Whether the queue in `items` (now, in the guarded write) is still the one in `seen` (read before the claim's newest
270
+ * check). Main only moves on, so a claim whose newest check read an older main read the records before any claim that
271
+ * read the newer main acted: when one did (queued its revision, skipped or started the one queued), the queue moved,
272
+ * and the stale claim's write is refused. A refused claim that was the newest after all (two read the same queue)
273
+ * changes nothing either; the next claim of the newest revision, which every new run lays, makes the change. */
274
+ const sameQueue = (items, seen, name, digest) => queueOf(items, name, digest) === queueOf(seen, name, digest);
275
+ /** Queues `workflow` at `digest`, the newest revision, behind `running`, the replay at work (a record of it already
276
+ * queued is left as it is), and skips each revision queued before it (only the newest queued one replays next), in one
277
+ * guarded write: kept only while its own record is still the one read and the queue is still `seen` (sameQueue). */
278
+ async function enqueue(deps, workflow, digest, record, running, seen) {
279
+ const { store, agentId, log } = deps;
280
+ const now = deps.now ?? Date.now;
281
+ const behind = `${running.digest}'s replay on ${plural(running.runs?.length ?? 0, "graded input")}`;
282
+ const reason = `queued behind ${behind}: a running replay finishes; the newest revision queued meanwhile replays next`;
283
+ const older = replayingOf(seen, workflow.name, digest, "queued");
284
+ const writes = [...(record ? [] : [{ workflow: workflow.name, digest, at: iso(now()), decided: "queued", source: "replay", reason, ...seedOf(deps) }]), ...older.map((one) => skippedFor(deps, one, digest))];
285
+ if (!writes.length) {
286
+ log(`workflow-first: ${workflow.name} at ${digest} is queued behind ${behind}; it does not serve this run`);
287
+ return;
288
+ }
289
+ 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));
290
+ if (!kept.won) {
291
+ 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`);
292
+ return;
293
+ }
294
+ log(`workflow-first: ${workflow.name} at ${digest} is ${record ? "queued" : "new: queued"} behind ${behind}; it replays once that one is decided`);
295
+ for (const one of older)
296
+ log(`workflow-first: ${one.workflow} at ${one.digest} skipped: ${writes.at(-1).reason}`);
297
+ }
298
+ /** `record`, a revision queued behind another's replay, skipped for `by`, a newer revision that came before its replay
299
+ * could start: it never replays and never serves. Never silent: the record names `by` and says why. */
300
+ function skippedFor(deps, record, by) {
301
+ const now = deps.now ?? Date.now;
302
+ const reason = `a newer draft ${by} arrived before its replay could start: only the newest queued revision replays next`;
303
+ return { workflow: record.workflow, digest: record.digest, at: iso(now()), decided: "skipped", source: "replay", reason, skipped_by: by, ...(record.commit ? { commit: record.commit } : {}) };
304
+ }
305
+ /** Skips the laid revision's own queued `record` for `by`, the newest revision (its claim laid an older text): kept only
306
+ * while it is still that queued record. */
307
+ async function skip(deps, record, by) {
308
+ const one = skippedFor(deps, record, by);
309
+ const kept = await recordPromotion(deps.store.settings, deps.agentId, one, (was) => was?.decided === "queued" && was.at === record.at);
310
+ if (kept.won)
311
+ deps.log(`workflow-first: ${record.workflow} at ${record.digest} skipped: ${one.reason}`);
312
+ }
313
+ /** Decides `running`, the replay at work ahead of the laid (newest) revision, as a claim laying it would (relaunch, then
314
+ * settle) once its runs ended: its text read at its record's commit, its verdict standing (promote or hold) though a
315
+ * newer revision waits. No refit is written from it: the folder's main holds the newer revision, and a refit would land
316
+ * over it. Left replaying while a run of it is at work, or when its text cannot be read (its read, replayView, decides
317
+ * it then). */
318
+ async function settleRival(deps, name, running) {
319
+ const text = running.commit && deps.champion ? await deps.champion(name, running.commit).catch(() => undefined) : undefined;
320
+ if (!text || workflowDigest(text) !== running.digest) {
321
+ 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`);
233
322
  return;
234
323
  }
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`);
324
+ const ports = { ...deps, commit: undefined };
325
+ await relaunch(ports, text, running.digest, running);
326
+ const decided = await settle(ports, text, running.digest, running);
327
+ if (decided?.decided === "hold")
328
+ deps.log(`workflow-first: ${name} at ${running.digest} held with a newer revision waiting: no refit of it is written`);
236
329
  }
237
330
  /** Reserves a replay of `workflow` at `digest` on `graded`, then starts its runs: its replaying record names the replay
238
331
  * runs it will start (their ids, and the replay's own, minted here), kept only when `still` holds of the digest's record
239
332
  * now and no other revision of the workflow replays, in the one guarded write. Only the writer that kept it starts them:
240
333
  * 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 = []) {
334
+ * person's (askReplay) are this one reservation. `owed`: the held runs among `graded` it must answer on (heldOn). `also`:
335
+ * records kept in the same write (a claim's skips of the revisions queued before it). */
336
+ async function reserve(deps, workflow, digest, graded, reason, still, owed = [], also = []) {
243
337
  const now = deps.now ?? Date.now;
244
338
  const ids = graded.map(() => uuidv7());
245
339
  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);
340
+ 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
341
  if (reserved.won)
248
342
  for (const [i, one] of graded.entries())
249
343
  await startReplay(deps, workflow, digest, one.grade.run, one.launch, ids[i], launch);
@@ -274,28 +368,11 @@ function replayLaunchOf(deps) {
274
368
  return { revision: deps.revisionId, body: launchBody(base), ...(deps.sealKey && deps.runId ? { handed_from: deps.runId } : {}) };
275
369
  }
276
370
  /** 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. */
371
+ * id. A replay settled meanwhile, and a newer replay of the same revision its owner started since (a held revision may
372
+ * be replayed again), are not: an older replay's late decision never lands over a newer one. */
279
373
  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
374
  /** 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
375
+ * on its row): once its replay is decided with runs still at work (past its deadline). How many were sent their cancel. The
299
376
  * record is the durable half: a cancel that is lost (a crash after the record, a write that fails) leaves a run whose
300
377
  * claim refuses it (replayClaimed: its revision no longer replays), so each cancel is tried and a failed one only logged. */
301
378
  async function cancelUnended(deps, record) {
@@ -703,7 +780,7 @@ async function revisionOf(ask, records, name, digest) {
703
780
  * held on (heldOn), which it promotes only once it answered on: the claim's picker (inputsFor). Its runs end as a claim's
704
781
  * do, and it is decided by the claim path's settle: at a claim that lays the revision, or at its read (replayView).
705
782
  * 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
783
+ * 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
784
  * only hold it: settle scores none of it), refused before anything is reserved; an agent that does not learn here. The
708
785
  * replay's id and its inputs. */
709
786
  export async function askReplay(ask, name, digest, inputs) {
@@ -718,7 +795,7 @@ export async function askReplay(ask, name, digest, inputs) {
718
795
  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
796
  const rival = replayingOf(records, name, digest)[0];
720
797
  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.`);
798
+ 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
799
  const { graded, owed, named } = await inputsFor({ store: ask.store, agentId: ask.agentId }, found.workflow, digest, records, inputs);
723
800
  if (graded.length < REPLAY_MIN) {
724
801
  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 +832,9 @@ export async function replayView(ask, name, digest, id) {
755
832
  let record = await find();
756
833
  if (!record)
757
834
  throw new ReplayRefused("missing", `${name} at ${digest} has no replay ${id}.`);
835
+ // A replay a newer draft cancelled (a beta.39 `superseded` record, read as skipped, promotionsOf): decided, never run to a verdict.
836
+ if (record.decided === "skipped")
837
+ 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
838
  const textOf = async (one) => (one.commit ? (await workflowsAt(ask, one.commit).catch(() => [])).find((text) => text.name === name && workflowDigest(text) === digest) : undefined);
759
839
  let text = record.decided === "replaying" ? await textOf(record) : undefined;
760
840
  const ports = record.decided === "replaying" && text && record.launch ? readPorts(ask, record.launch) : undefined;
@@ -763,10 +843,11 @@ export async function replayView(ask, name, digest, id) {
763
843
  await settle(ports, text, digest, record);
764
844
  record = (await find()) ?? record;
765
845
  }
766
- const decided = record.decided === "replaying" ? undefined : record.decided;
846
+ // Only a replaying, promote or hold record carries a replay's id.
847
+ const decided = record.decided === "promote" || record.decided === "hold" ? record.decided : undefined;
767
848
  const inputs = record.runs?.length ?? 0;
768
849
  const said = decided ? { decided, reason: record.reason } : {};
769
- const kept = record.replay && decided && decided !== "superseded" ? record.replay : undefined;
850
+ const kept = record.replay && decided ? record.replay : undefined;
770
851
  if (kept) {
771
852
  // Decided: its record's numbers alone. With not one of its reserved runs ever created (none counted: a decided
772
853
  // replay counted every run there was, and none is created after), nothing was replayed (settle's reason says so).
@@ -777,7 +858,7 @@ export async function replayView(ask, name, digest, id) {
777
858
  const read = await replayRows(ask, record, true);
778
859
  text ??= await textOf(record);
779
860
  return {
780
- replay: id, workflow: name, digest, status: decided === undefined ? "running" : decided === "superseded" ? "failed" : "done", inputs,
861
+ replay: id, workflow: name, digest, status: decided === undefined ? "running" : "done", inputs,
781
862
  outcomes: read?.outcomes ?? NO_OUTCOMES,
782
863
  score: scoreRows(read?.scored ?? [], text ? thresholdsOf(text.workflow) : new Map()), cost_usd: read?.cost ?? null, ...said,
783
864
  };
package/dist/server.js CHANGED
@@ -136,8 +136,9 @@ import { webhook } from "./trigger-webhook.js";
136
136
  import { SCHEME_NAMES } from "./trigger-signatures.js";
137
137
  import { permissionFrom, pinnedEffect, toolEffect } from "./tool-gate.js";
138
138
  import { mcpNameOf as mcpToolOf, mcpToolName } from "./tool-names.js";
139
- import { CATCHUP_WINDOW_S, FAILURES_TO_PAUSE, HISTORY_KEPT, MIN_EVERY_S, PAYLOAD_KEPT_BYTES, SOURCE_KINDS, TARGET_KINDS, Triggers } from "./triggers.js";
140
- import { applyBodyOf, choiceUnrunnable, COMPUTER_FIX, compiled, githubTriggerUnconnected, githubTriggerWords, madeTriggerIssues, mcpSetUp, onServerName, onServers, packageDetail, packageModel, packageTiers, packageView, pickComputer, readPackages, serversFor, TemplateRegistry } from "./templates.js";
139
+ import { CATCHUP_WINDOW_S, FAILURES_TO_PAUSE, HISTORY_KEPT, MIN_EVERY_S, SOURCE_KINDS, TARGET_KINDS, Triggers } from "./triggers.js";
140
+ import { PAYLOAD_KEPT_BYTES } from "./trigger-adapter.js";
141
+ import { applyBodyOf, choiceUnrunnable, COMPOSIO_TRIGGER_FIX, composioTriggerSkipped, COMPUTER_FIX, compiled, githubTriggerUnconnected, githubTriggerWords, madeTriggerIssues, mcpSetUp, onServerName, onServers, packageDetail, packageModel, packageTiers, packageView, pickComputer, readPackages, notSetUpYet, serversFor, TemplateRegistry } from "./templates.js";
141
142
  import { deleteTemplate, importTemplate, loadImported } from "./template-import.js";
142
143
  import { templateInstallLink, templateLink } from "./console-links.js";
143
144
  import { GITHUB_HOSTS } from "./template-source.js";
@@ -2157,9 +2158,10 @@ async function startHolding(options, data, checked, stops) {
2157
2158
  // Each webhook trigger's signing secret, minted as it is made: handed back in the apply's first answer alone, as POST
2158
2159
  // /triggers hands back its own, so the owner can give it to the sender.
2159
2160
  const secrets = [];
2160
- // A github trigger on a server GitHub is not connected to is skipped, never the apply: the agent stands, and the
2161
- // answer says to connect GitHub and apply again (a warning under triggers.<i>).
2162
- const unconnected = new Set();
2161
+ // A trigger this server can't set up yet (templates.ts TRIGGER_NOT_SET_UP_YET: a github one with GitHub not connected,
2162
+ // a composio one Composio can't reach or run as here) is skipped, never the apply: the agent stands, and the answer
2163
+ // says what to do (a warning under triggers.<i>). Kept with its refusal, whose words the warning carries.
2164
+ const unconnected = new Map();
2163
2165
  try {
2164
2166
  for (const [i, trigger] of made.triggers.entries()) {
2165
2167
  try {
@@ -2169,8 +2171,8 @@ async function startHolding(options, data, checked, stops) {
2169
2171
  secrets.push({ trigger_id: madeId, secret });
2170
2172
  }
2171
2173
  catch (error) {
2172
- if (error instanceof ApiError && error.code === "github_not_connected" && isObject(trigger.source) && trigger.source.kind === "github") {
2173
- unconnected.add(i);
2174
+ if (error instanceof ApiError && isObject(trigger.source) && notSetUpYet(trigger.source.kind, error.code)) {
2175
+ unconnected.set(i, error);
2174
2176
  continue;
2175
2177
  }
2176
2178
  if (error instanceof ApiError && error.code === "input_invalid" && error.extra.fields)
@@ -2207,12 +2209,17 @@ async function startHolding(options, data, checked, stops) {
2207
2209
  const githubTriggers = made.triggers.flatMap((trigger, i) => (isObject(trigger.source) && trigger.source.kind === "github"
2208
2210
  ? [unconnected.has(i) ? { field: `triggers.${i}`, reason: NOT_SET_UP, message: githubTriggerUnconnected(pkg.name, trigger.source) } : { field: `triggers.${i}`, reason: "not_an_option", message: githubTriggerWords(pkg.name, trigger.source) }]
2209
2211
  : []));
2212
+ // Each composio trigger it skipped: which, the refusal's words, and where to make it once that's fixed.
2213
+ const composioSkipped = made.triggers.flatMap((trigger, i) => {
2214
+ const refused = unconnected.get(i);
2215
+ return refused && isObject(trigger.source) && trigger.source.kind === "composio" ? [{ field: `triggers.${i}`, reason: NOT_SET_UP, message: composioTriggerSkipped(pkg.name, trigger, refused.message), fix: COMPOSIO_TRIGGER_FIX }] : [];
2216
+ });
2210
2217
  // Each trigger it made, a webhook trigger's with its secret's metadata; the values go back beside the answer, never in it
2211
2218
  // (the route adds them to the first answer to the owner's session, after the Idempotency-Key's record is written).
2212
2219
  const minted = new Map(secrets.map(({ trigger_id, secret }) => [trigger_id, secret]));
2213
2220
  // Which saved server each MCP need runs on (null: none here, said under mcp.<toolkit>).
2214
2221
  const used = Object.fromEntries(mapped.map(({ need, server }) => [need.toolkit, server]));
2215
- const applied = { template: pkg.id, version: pkg.version, agent_id: entry.agent.id, servers: used, trigger_ids: ids, ...templateWebhookSecrets([...minted.keys()], new Date().toISOString()), warnings: [...skipped, ...kept, ...modelWarnings, ...computerWarnings, ...unpinned, ...warnings, ...hooks, ...githubTriggers, ...appShort] };
2222
+ const applied = { template: pkg.id, version: pkg.version, agent_id: entry.agent.id, servers: used, trigger_ids: ids, ...templateWebhookSecrets([...minted.keys()], new Date().toISOString()), warnings: [...skipped, ...kept, ...modelWarnings, ...computerWarnings, ...unpinned, ...warnings, ...hooks, ...githubTriggers, ...composioSkipped, ...appShort] };
2216
2223
  return { applied, minted };
2217
2224
  }
2218
2225
  /** A run create's issues told from the input this server checks (explain.ts): an agentic run's input schema in force
@@ -50,6 +50,9 @@ export interface Dialect {
50
50
  * trigger's firings, an agent's current revision) is not interleaved with another. `"update"`: the run row of a write
51
51
  * that moves its epoch (a release, a run's end), held against every write under the claim (`shareLock`) as well. */
52
52
  lockRow(tx: LockExecutor, table: string, column: string, value: string, mode?: "update"): Promise<void>;
53
+ /** lockRow (its first form) of every row whose `column` is one of `values`, in one statement and in `column`'s order, so
54
+ * two transactions holding overlapping sets never wait on each other in a cycle. */
55
+ lockRows(tx: LockExecutor, table: string, column: string, values: readonly string[]): Promise<void>;
53
56
  /** Holds the named lock until the transaction ends: two transactions that each check, then write what the other checks. */
54
57
  lockKey(tx: LockExecutor, key: string): Promise<void>;
55
58
  }
@@ -29,6 +29,7 @@ export const SQLITE = {
29
29
  claimOneLock: "",
30
30
  shareLock: "",
31
31
  lockRow: async () => undefined,
32
+ lockRows: async () => undefined,
32
33
  lockKey: async () => undefined,
33
34
  };
34
35
  /** The SET fragment every statement that settles command rows (taken or refused) carries: a computer call's params go
@@ -30,12 +30,18 @@ export interface PgConnectionOptions {
30
30
  readonly poolSize?: number;
31
31
  /** Deadlines on the store's own (test) clock, bound as parameters, instead of the database's (postgresDialect). */
32
32
  readonly testClock?: boolean;
33
- /** How long getting a connection may take (STORE_CONNECT_TIMEOUT_MS by default): a new one's connect and startup, or a
34
- * wait for one of the pool's to come free. Past it the call is refused (StoreDeadline, naming the database's place,
35
- * never its URL), never left hanging on a database that does not answer. */
33
+ /** How long a new connection's connect and startup may take (STORE_CONNECT_TIMEOUT_MS by default). Past it the call is
34
+ * refused (StoreDeadline, naming the database's place, never its URL, in words that say it does not answer), never left
35
+ * hanging on a database that does not answer. */
36
36
  readonly connectTimeoutMs?: number;
37
+ /** How long a call may wait for one of the pool's connections to come free while every one is in use
38
+ * (STORE_WRITE_DEADLINE_MS by default, and never less than connectTimeoutMs): a busy pool is waited out to a write's own
39
+ * deadline, never failed at the connect timeout. Past it the call is refused (StoreDeadline, in words that say every
40
+ * connection stayed in use), nothing of it sent. */
41
+ readonly poolWaitMs?: number;
37
42
  }
38
- /** The default bound on getting a connection to the store's Postgres (PgConnectionOptions.connectTimeoutMs), in ms. Below
43
+ /** The default bound on a new connection's connect and startup to the store's Postgres (PgConnectionOptions.connectTimeoutMs),
44
+ * in ms; a wait for a busy pool's connection to come free has its own, longer bound (PgConnectionOptions.poolWaitMs). Below
39
45
  * the runner's stop margin (runner.ts: lease 30 s, renew every 10 s, stop margin 5 s; a claim is let go when no renew has
40
46
  * landed within lease - margin = 25 s of the last one's send, so two renew ticks, at +10 s and +20 s, fall inside it): a
41
47
  * renew that cannot get a connection gives up within 4 s, inside the 5 s margin, and the next tick tries again. A renew
@@ -70,7 +76,7 @@ export declare class PgConnection implements StoreConnection {
70
76
  readonly where: string;
71
77
  private constructor();
72
78
  /** The pool on `url` in `schema`, and (owner) the owner lock: StoreOwned when another server holds the schema. */
73
- static open({ url, schema, owner, busyTimeoutMs, poolSize, testClock, connectTimeoutMs, ownerWaitMs, onOwnerWait, onOwnerLost, ownerCheck }: PgConnectionOptions): Promise<PgConnection>;
79
+ static open({ url, schema, owner, busyTimeoutMs, poolSize, testClock, connectTimeoutMs, poolWaitMs, ownerWaitMs, onOwnerWait, onOwnerLost, ownerCheck }: PgConnectionOptions): Promise<PgConnection>;
74
80
  get<T extends object>(sql: string, ...params: SqliteValue[]): Promise<T | undefined>;
75
81
  all<T extends object>(sql: string, ...params: SqliteValue[]): Promise<T[]>;
76
82
  /** One statement on its own (autocommit), its changes counted: the shared code's run outside a transaction. */