@parcha/agentrun-serve 0.1.0-beta.48 → 0.1.0-beta.49

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 (106) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +144 -16
  3. package/dist/agent-delete.d.ts +33 -10
  4. package/dist/agent-delete.js +184 -26
  5. package/dist/agents-store.d.ts +6 -2
  6. package/dist/agents-store.js +18 -5
  7. package/dist/agents.d.ts +8 -1
  8. package/dist/agents.js +14 -4
  9. package/dist/answer-json.d.ts +2 -2
  10. package/dist/answer-json.js +3 -4
  11. package/dist/archil-routes.d.ts +1 -1
  12. package/dist/archil-routes.js +4 -3
  13. package/dist/browser-sessions.d.ts +56 -0
  14. package/dist/browser-sessions.js +117 -0
  15. package/dist/computer-routes.d.ts +4 -15
  16. package/dist/computer-routes.js +6 -10
  17. package/dist/console/assets/index-Bzn4eUYF.js +715 -0
  18. package/dist/console/assets/index-CR2ZGei1.css +1 -0
  19. package/dist/console/index.html +2 -2
  20. package/dist/errors.d.ts +4 -1
  21. package/dist/errors.js +15 -5
  22. package/dist/import.js +4 -3
  23. package/dist/learn/check.d.ts +11 -2
  24. package/dist/learn/check.js +12 -9
  25. package/dist/learn/promote.d.ts +7 -1
  26. package/dist/learn/promote.js +47 -0
  27. package/dist/learn/repick.d.ts +34 -0
  28. package/dist/learn/repick.js +201 -0
  29. package/dist/learned-workflow.d.ts +2 -0
  30. package/dist/learned-workflow.js +18 -1
  31. package/dist/learning-setting.d.ts +13 -0
  32. package/dist/learning-setting.js +23 -1
  33. package/dist/llms.txt +1 -1
  34. package/dist/openapi.js +170 -12
  35. package/dist/paid-calls.d.ts +4 -1
  36. package/dist/paid-calls.js +1 -1
  37. package/dist/run-learning-served.d.ts +1 -1
  38. package/dist/run-usage.d.ts +110 -0
  39. package/dist/run-usage.js +312 -0
  40. package/dist/runner/adapter-loop.js +51 -20
  41. package/dist/runner/conformance/harness.d.ts +2 -0
  42. package/dist/runner/conformance/harness.js +18 -4
  43. package/dist/runner/feedback-round.d.ts +29 -1
  44. package/dist/runner/feedback-round.js +54 -3
  45. package/dist/runner/journal-kinds.d.ts +3 -1
  46. package/dist/runner/learning-end.js +49 -18
  47. package/dist/runner/loop-contract.d.ts +3 -0
  48. package/dist/runner/monid-run.js +2 -2
  49. package/dist/runner/promotion.js +8 -2
  50. package/dist/runner/reflect-hook.js +3 -2
  51. package/dist/runs-over-store.d.ts +3 -2
  52. package/dist/runs-over-store.js +9 -7
  53. package/dist/server.d.ts +3 -3
  54. package/dist/server.js +221 -98
  55. package/dist/store/index.d.ts +2 -2
  56. package/dist/store/index.js +1 -1
  57. package/dist/store/journal/storage.js +1 -1
  58. package/dist/store/open.d.ts +1 -1
  59. package/dist/store/open.js +1 -1
  60. package/dist/store/postgres/migrations/0021_purged.sql +13 -0
  61. package/dist/store/postgres/migrations/0022_computer_intervals.sql +27 -0
  62. package/dist/store/schema.d.ts +15 -1
  63. package/dist/store/schema.js +50 -5
  64. package/dist/store/sqlite/connection.d.ts +4 -1
  65. package/dist/store/sqlite/connection.js +5 -0
  66. package/dist/store/sqlite/run-patch.d.ts +8 -3
  67. package/dist/store/sqlite/run-patch.js +15 -7
  68. package/dist/store/sqlite/store.d.ts +5 -2
  69. package/dist/store/sqlite/store.js +249 -48
  70. package/dist/store/sqlite/worker.d.ts +9 -0
  71. package/dist/store/sqlite/worker.js +18 -1
  72. package/dist/store/store.d.ts +142 -9
  73. package/dist/store/store.js +63 -0
  74. package/dist/store-reads/analytics.js +2 -1
  75. package/dist/store-reads/cap.d.ts +8 -2
  76. package/dist/store-reads/cap.js +27 -3
  77. package/dist/store-reads/learning.d.ts +1 -1
  78. package/dist/store-reads/learning.js +5 -2
  79. package/dist/store-reads/runs.js +2 -0
  80. package/dist/store-reads/stats.js +4 -2
  81. package/dist/store-view.d.ts +7 -0
  82. package/dist/store-view.js +61 -20
  83. package/dist/tools.js +9 -0
  84. package/dist/trigger-targets.d.ts +7 -4
  85. package/dist/trigger-targets.js +6 -6
  86. package/dist/triggers.d.ts +2 -1
  87. package/dist/triggers.js +5 -2
  88. package/dist/validate.d.ts +4 -2
  89. package/dist/validate.js +13 -3
  90. package/dist/viewer-credential.d.ts +3 -4
  91. package/dist/viewer-credential.js +6 -4
  92. package/dist/workspace/computer-for-claim.d.ts +5 -1
  93. package/dist/workspace/computer-for-claim.js +47 -18
  94. package/dist/workspace/computer-intervals.d.ts +20 -0
  95. package/dist/workspace/computer-intervals.js +49 -0
  96. package/dist/workspace/computer-janitor.d.ts +7 -3
  97. package/dist/workspace/computer-janitor.js +14 -6
  98. package/dist/workspace/computer-kept.d.ts +7 -2
  99. package/dist/workspace/computer-kept.js +9 -2
  100. package/dist/workspace/resolve-computer.d.ts +7 -4
  101. package/dist/workspace/resolve-computer.js +21 -32
  102. package/dist/workspace/run-end-computers.d.ts +1 -0
  103. package/dist/workspace/run-end-computers.js +4 -1
  104. package/package.json +10 -10
  105. package/dist/console/assets/index-CTGegcKt.css +0 -1
  106. package/dist/console/assets/index-D1Se6mgG.js +0 -715
@@ -15,6 +15,51 @@ import { RunFinal } from "../store/store.js";
15
15
  import { KINDS } from "./journal-kinds.js";
16
16
  import { commandRequest } from "./loop.js";
17
17
  export const FEEDBACK_ROUNDS = ["correction"];
18
+ const END_STATES = ["ended", "stopped", "failed"];
19
+ const OUTCOMES = ["completed", "escalated", "stopped", "cancelled"];
20
+ /** A kept end as a steer's body or a journal entry holds it, else undefined. */
21
+ function keptOf(value) {
22
+ const kept = value;
23
+ if (!kept || typeof kept !== "object" || !END_STATES.includes(kept.state) || typeof kept.endedAt !== "number")
24
+ return undefined;
25
+ if (kept.summary !== undefined && typeof kept.summary !== "string")
26
+ return undefined;
27
+ if (kept.outcome !== undefined && !OUTCOMES.includes(kept.outcome))
28
+ return undefined;
29
+ return { state: kept.state, ...(kept.summary !== undefined ? { summary: kept.summary } : {}), ...(kept.outcome !== undefined ? { outcome: kept.outcome } : {}), endedAt: kept.endedAt };
30
+ }
31
+ /** The end run `run` has now, as a grade's round keeps it: only one a round opens again (reopenableWhere: ended, or
32
+ * stopped by a person), with its end time. */
33
+ function keptEndOfRow(run) {
34
+ if (run.endedAt === null || !(run.state === "ended" || (run.state === "stopped" && run.outcome === "stopped")))
35
+ return undefined;
36
+ return { state: run.state, ...(run.summary !== null ? { summary: run.summary } : {}), ...(run.outcome !== null ? { outcome: run.outcome } : {}), endedAt: run.endedAt };
37
+ }
38
+ /** Whether the run's root `entries` hold a job's end kept for its look-back (KINDS.jobEnd) with no run end after it: the
39
+ * job ended and its look-back is under way, whether or not that look-back has asked anything yet. A follow-up's turn
40
+ * keeps none until its own job's end is kept, so a turn after the run's last end reads false. */
41
+ export function jobEndOpen(entries) {
42
+ return entries.findLastIndex((entry) => entry.kind === KINDS.jobEnd) > entries.findLastIndex((entry) => entry.kind === KINDS.end);
43
+ }
44
+ /** The end run's look-back keeps while it runs, from the run's root `entries` and its command rows, else undefined (no
45
+ * look-back under way, or one whose job's end was never kept):
46
+ * - the job's end its claim kept before the end-of-run step (KINDS.jobEnd, with its time), newer than the run's last end;
47
+ * - else the end a grade's round kept, from its FEEDBACK entry newer than the run's last end;
48
+ * - else from the round's steer the grade wrote, not taken yet (the run opened again, no runner on it yet).
49
+ * A follow-up's own turn keeps none until its job's end is kept: its run reads as going on, as main's does. */
50
+ export function keptEndOf(entries, commands) {
51
+ const last = (kind) => entries.findLastIndex((entry) => entry.kind === kind);
52
+ const end = last(KINDS.end);
53
+ if (jobEndOpen(entries)) {
54
+ const data = entries[last(KINDS.jobEnd)].data;
55
+ return keptOf(data?.end && data.endedAt !== undefined ? { ...data.end, endedAt: data.endedAt } : undefined);
56
+ }
57
+ const fed = last(KINDS.feedback);
58
+ if (fed > end)
59
+ return keptOf(entries[fed].data?.kept);
60
+ const steer = commands.find((command) => command.kind === "steer" && command.takenAt === null && command.refused === null && feedbackOf(command.body)?.kept !== undefined);
61
+ return steer ? feedbackOf(steer.body).kept : undefined;
62
+ }
18
63
  /** What a grade asks for: `correction` for a graded run the agent finished when the grade has words, else none
19
64
  * (undefined): a run its learned workflow answered alone opens none, right or wrong (its grade is kept). A replay run
20
65
  * is never graded. */
@@ -28,7 +73,8 @@ export function feedbackOf(body) {
28
73
  const text = body?.text;
29
74
  if (!fed || typeof fed !== "object" || !FEEDBACK_ROUNDS.includes(fed.round) || typeof fed.correct !== "boolean" || typeof text !== "string")
30
75
  return undefined;
31
- return { round: fed.round, correct: fed.correct, text };
76
+ const kept = keptOf(fed.kept);
77
+ return { round: fed.round, correct: fed.correct, text, ...(kept ? { kept } : {}) };
32
78
  }
33
79
  /** The feedback round the run's root `entries` say its next end closes: its newest FEEDBACK entry when no end came after
34
80
  * it, else undefined. */
@@ -88,9 +134,14 @@ export async function openFeedbackRound(store, grade, label, canTurn = () => tru
88
134
  // run's route (`canTurn` false), the grade is kept and the run is not opened again, never left to fail with no key.
89
135
  if (launch && !canTurn(launch))
90
136
  return null;
91
- const feedback = { round, correct: grade.correct };
137
+ // The run's end as the grade found it: the round keeps it (the run reads it while it looks back, and its end writes it
138
+ // again), and opens the run again only at that end (`endedAt`), never at a later one a message's turn wrote meanwhile.
139
+ const kept = keptEndOfRow(run);
140
+ if (!kept)
141
+ return null;
142
+ const feedback = { round, correct: grade.correct, kept };
92
143
  try {
93
- const steer = await store.runs.reopen(grade.run, { kind: "steer", body: { text: words, feedback } });
144
+ const steer = await store.runs.reopen(grade.run, { kind: "steer", body: { text: words, feedback } }, { endedAt: kept.endedAt });
94
145
  return { round, command: steer.id };
95
146
  }
96
147
  catch (error) {
@@ -343,10 +343,12 @@ export interface EndData {
343
343
  readonly review?: EndReview;
344
344
  }
345
345
  /** How a run's job's own turn ended (KINDS.jobEnd): the end it gives the run (its summary cut of every secret the runner
346
- * holds), and a CLI's error answer the end writes as its error row (`failedWith`). */
346
+ * holds), a CLI's error answer the end writes as its error row (`failedWith`), and the end's time (`endedAt`): the run
347
+ * reads that end while it looks back, and its end is written at that time (feedback-round.ts KeptEnd). */
347
348
  export interface JobEndData {
348
349
  readonly end: EndData;
349
350
  readonly failedWith?: string;
351
+ readonly endedAt?: number;
350
352
  }
351
353
  /** An escalated workflow run's review as its end keeps it: the escalation's kind, the escalate node's label (else the node
352
354
  * it escalated at), and its summary (else the run's). Served as the run's `review`, `at` its end. */
@@ -22,10 +22,11 @@ import { createHash } from "node:crypto";
22
22
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
23
23
  import { isMessageRow } from "../timeline/index.js";
24
24
  import { correctionRefused, learningCommit } from "../learn/commit.js";
25
- import { checkDraft, problemWords, unstorable } from "../learn/index.js";
25
+ import { CAPS, checkDraft, problemWords, unstorable } from "../learn/index.js";
26
+ import { repickRewrite } from "../learn/repick.js";
26
27
  import { folderAt, readLearning, readSnapshot, runMergeOf, snapshotAt, textsAt } from "../learn/folder.js";
27
28
  import { completedRun, compileStoppedOf, lastOwnRuns, compileDue, compilePrompt, compileReference, COMPILE_TRACES, DRAFT_FAILED, heldNamesOf, newCompileAttempt } from "../learn/compile.js";
28
- import { loopOf } from "../learning-setting.js";
29
+ import { loopOf, repickOf } from "../learning-setting.js";
29
30
  import { CHECK_TEXT_MAX, promotionOf, promotionsOf, recordPromotion } from "../learn/promote.js";
30
31
  import { draftDecisionProviders, draftDryRun, draftFiles, draftMcpTools, unpricedCalls, WORKFLOWS_DIR } from "../learn/workflow-draft.js";
31
32
  import { DECISION_PROVIDER_KEYS } from "../tool-plane.js";
@@ -357,25 +358,46 @@ export async function checkDraftOf(deps, input) {
357
358
  }
358
359
  const { tools, gated, deniedBy, decisions, outputSchema, workflowAdapters, manifest } = await draftTools(deps, input.runId);
359
360
  const dsl = await import("@parcha/agentrun-dsl");
361
+ // The owner's learning.repick (learning-setting.ts), read as the draft is checked: a change reaches the workflows
362
+ // compiled after it, never one main already holds. An SDK bridge's runNode is its own (it picks every model and takes
363
+ // none of the compact state rule), so an SDK agent's drafts are never rewritten.
364
+ const repick = workflowAdapters === undefined ? repickOf(await learningOfRun(deps.store, input.runId)) : undefined;
360
365
  // A draft whose text on main has a status is a person's call (retired, or waiting for their OK): never changed.
361
366
  const kept = at.snapshot.workflows.filter((item) => item.status !== "active").map((item) => item.file);
362
- const changes = [changeOf(jsonPath, json), changeOf(readmePath, readme)];
363
- const check = (dryRuns) => checkDraft({
364
- changes, refuseValues: input.refuse, tools, dsl,
367
+ const check = (text, dryRuns) => checkDraft({
368
+ changes: [changeOf(jsonPath, text), changeOf(readmePath, readme)], refuseValues: input.refuse, tools, dsl,
365
369
  ...(Object.keys(gated).length ? { gated } : {}), ...(Object.keys(deniedBy).length ? { deniedBy } : {}), ...(decisions ? { decisions } : {}),
366
370
  ...(workflowAdapters !== undefined ? { workflowAdapters } : {}), ...(kept.length ? { kept } : {}), ...(dryRuns ? { dryRuns } : {}),
371
+ ...(repick?.repick ? { repick: true } : {}),
367
372
  });
368
- const statics = check();
369
- if (statics.length)
370
- return refused(statics);
371
- const ran = check({ [jsonPath]: await draftDryRun(dsl, json, example, outputSchema) });
372
- if (ran.length)
373
- return refused(ran);
374
- const files = [{ path: jsonPath, text: json }, { path: readmePath, text: readme }];
373
+ const checked = async (text) => {
374
+ const statics = check(text);
375
+ return statics.length ? statics : check(text, { [jsonPath]: await draftDryRun(dsl, text, example, outputSchema) });
376
+ };
377
+ const problems = await checked(json);
378
+ if (problems.length)
379
+ return refused(problems);
380
+ // With learning.repick on, what is committed is the draft with its answer's re-pick reading the run's pages on its
381
+ // second pass (learn/repick.ts), through the same checks and dry run, so the digest that serves is the doc the
382
+ // promotion check replays. A rewrite they refuse (one past CAPS.file even on one line) leaves the draft as compiled,
383
+ // which the log says by rule alone.
384
+ let text = json;
385
+ const rewritten = repick?.repick ? repickRewrite(JSON.parse(json), repick.repick_max_chars) : undefined;
386
+ if (rewritten) {
387
+ const marked = workflowText(rewritten);
388
+ const again = marked === json ? [] : await checked(marked);
389
+ if (!again.length)
390
+ text = marked;
391
+ else
392
+ deps.log?.(`learning.repick: workflow ${name} is kept as compiled; its re-pick over the run's pages failed the checks (${[...new Set(again.map((problem) => problem.rule))].join(", ")})`);
393
+ }
394
+ if (text !== json && at.texts[jsonPath] === text && at.texts[readmePath] === readme)
395
+ return { errors: [] };
396
+ const files = [{ path: jsonPath, text }, { path: readmePath, text: readme }];
375
397
  return {
376
398
  errors: [],
377
- kept: { name, files, ...((await heldOf(deps.store, json, manifest)) ? { held: [readmePath] } : {}), ...(revised ? { bases: { [jsonPath]: revised.base, [readmePath]: revised.base } } : {}) },
378
- digest: workflowDigest({ workflow: json }),
399
+ kept: { name, files, ...((await heldOf(deps.store, text, manifest)) ? { held: [readmePath] } : {}), ...(revised ? { bases: { [jsonPath]: revised.base, [readmePath]: revised.base } } : {}) },
400
+ digest: workflowDigest({ workflow: text }),
379
401
  };
380
402
  }
381
403
  /** The backend manifest is data describing existing callbacks, not a server MCP connection. */
@@ -413,17 +435,26 @@ async function describedOf(tools, store) {
413
435
  }
414
436
  /** The most of an agent's kept learning, newest first, read for a held workflow's ask since its hold (compileAskOf). */
415
437
  const HELD_ASKED_READ = 200;
416
- /** The loop's numbers (learning-setting.ts loopOf) of the revision run `runId` runs: its definition's `learning`. */
417
- async function loopOfRun(store, runId) {
438
+ /** The definition's `learning` of the revision run `runId` runs; undefined when it can't be read. */
439
+ async function learningOfRun(store, runId) {
418
440
  try {
419
441
  const run = await store.runs.get(runId);
420
442
  const revision = run ? await store.agents.revision(run.revisionId) : undefined;
421
- return loopOf(revision?.body?.learning);
443
+ return revision?.body?.learning;
422
444
  }
423
445
  catch {
424
- return loopOf(undefined);
446
+ return undefined;
425
447
  }
426
448
  }
449
+ /** The loop's numbers (learning-setting.ts loopOf) of the revision run `runId` runs: its definition's `learning`. */
450
+ async function loopOfRun(store, runId) {
451
+ return loopOf(await learningOfRun(store, runId));
452
+ }
453
+ /** A rewritten workflow.json's text: indented as JSON.stringify indents, or on one line when only that fits CAPS.file. */
454
+ const workflowText = (doc) => {
455
+ const text = `${JSON.stringify(doc, null, 2)}\n`;
456
+ return Buffer.byteLength(text) <= CAPS.file ? text : `${JSON.stringify(doc)}\n`;
457
+ };
427
458
  /** Compile once: run `runId`'s compile turn whose drafts all failed their checks is the compile's attempt, kept as a
428
459
  * promotion record of the shape a check's stop has (runner/promotion.ts stopUnchecked): a hold with nothing checked,
429
460
  * its reason (DRAFT_FAILED) naming the failed checks. A first compile's earns the one recompile, as a check's hold
@@ -42,6 +42,9 @@ export type EndOfRunTurn = (input: {
42
42
  readonly claim: Claim;
43
43
  /** How the job ended. */
44
44
  readonly outcome: "completed" | "failed";
45
+ /** When the job's end was kept (the run's `ended_at`, kept before the step looks back), in epoch milliseconds: the
46
+ * time the job answered. Absent from a loop that keeps none. */
47
+ readonly endedAt?: number;
45
48
  /** The run was cut before it could look back: by a person's stop (`stopped`), by one during the end-of-run turn
46
49
  * (`stopped-looking`), or by a fault (`faulted`). The step must not call `ask`: it returns only what a cut run keeps. */
47
50
  readonly cut?: "stopped" | "stopped-looking" | "faulted";
@@ -44,7 +44,7 @@ export function monidForClaim(pin, env, work, runId, capped = () => false, fake)
44
44
  // left as a crash leaves it: the run is stopping or its claim is going.
45
45
  const estimated = async (ledger, callId, name, at, input, signal) => {
46
46
  const client = await clientOf();
47
- const step = await paidStep(ledger, callId, { name, holdUsd: 0, basis: READ_BASIS, by: "monid" }, () => client.run({ provider: at.provider, endpoint: `/${at.endpoint}`, input, maxCost: 0 }, signal), (outcome) => {
47
+ const step = await paidStep(ledger, callId, { name, holdUsd: 0, basis: READ_BASIS, by: "monid", reported: true }, () => client.run({ provider: at.provider, endpoint: `/${at.endpoint}`, input, maxCost: 0 }, signal), (outcome) => {
48
48
  if (!("result" in outcome))
49
49
  return null;
50
50
  const usd = chargeOf(outcome.result);
@@ -88,7 +88,7 @@ export function monidForClaim(pin, env, work, runId, capped = () => false, fake)
88
88
  /** One paid step for the call `callId` of `name` on the run's ledger `ledger`: held at `held.usd`, `send` run, settled at
89
89
  * what monid says it charged; a charge above the hold stops the run (overHold). */
90
90
  const paidCall = async (ledger, callId, name, held, send) => {
91
- const paid = await paidStep(ledger, callId, { name, holdUsd: held.usd, basis: held.basis, by: "monid" }, send, (outcome) => {
91
+ const paid = await paidStep(ledger, callId, { name, holdUsd: held.usd, basis: held.basis, by: "monid", reported: true }, send, (outcome) => {
92
92
  if (!("result" in outcome))
93
93
  return null;
94
94
  const usd = chargeOf(outcome.result);
@@ -3,7 +3,7 @@ import { loopOf } from "../learning-setting.js";
3
3
  import { LEARNED_WORKFLOW_TOOL } from "../learned-workflow.js";
4
4
  import { launchBody, readLaunchBody } from "../run-launch.js";
5
5
  import { uuidv7 } from "../runs-over-store.js";
6
- import { FINAL_STATES, RunFinal, StoreConstraint } from "../store/store.js";
6
+ import { FINAL_STATES, RunFinal, RunPurged, StoreConstraint } from "../store/store.js";
7
7
  import { openRunMcpAuth, sealRunMcpAuth } from "../store/seal.js";
8
8
  import { isCliRecord, piShaped, runEntries, runTimeline } from "../store-reads/journal.js";
9
9
  import { pinAnnotations, recordedCalls, replayCalls, SKIPPED_WRITE, toolClassOf, toolWord, unmarkedWords } from "../learn/replay-calls.js";
@@ -745,7 +745,9 @@ async function handedTo(deps, launch, id) {
745
745
  /** Starts the replay of `workflow` at `digest` on agent run `of` (its launch `from`) as run `id` (the id its reserved
746
746
  * record names), with the replay's chosen `launch` (replayLaunchOf: its run launch, revision and handed credentials,
747
747
  * handedTo), whichever claim creates it. False when a run by that id exists already: another claim created it (a
748
- * relaunch and the reserving claim at once), and it is left to that one. */
748
+ * relaunch and the reserving claim at once), and it is left to that one; false too when run `of` was purged since its
749
+ * launch was read (the store refuses it, RunPurged, nothing written): the replay never starts, counted so past its
750
+ * deadline. */
749
751
  async function startReplay(deps, workflow, digest, of, from, id, launch) {
750
752
  const { store, agentId } = deps;
751
753
  const base = readLaunchBody(launch.body);
@@ -760,6 +762,10 @@ async function startReplay(deps, workflow, digest, of, from, id, launch) {
760
762
  catch (error) {
761
763
  if (error instanceof StoreConstraint && (await store.runs.get(id)))
762
764
  return false;
765
+ if (error instanceof RunPurged) {
766
+ deps.log(`workflow-first: ${workflow.name} at ${digest}: the replay ${id} is not started: the run it replays was purged`);
767
+ return false;
768
+ }
763
769
  throw error;
764
770
  }
765
771
  }
@@ -33,8 +33,9 @@ export function createReflectHook(deps) {
33
33
  return undefined;
34
34
  const now = deps.now ?? Date.now;
35
35
  // When the job answered and what it cost: as the step starts, the run's spend so far is the job's. A compile turn an
36
- // earlier claim asked first (cut by a crash or a lost claim) reads that ask's, which it kept with its prompt.
37
- let answeredAt = new Date(now()).toISOString();
36
+ // earlier claim asked first (cut by a crash or a lost claim) reads that ask's, which it kept with its prompt. A run's
37
+ // first round answered when its job's end was kept (the run's end time), never after it.
38
+ let answeredAt = new Date(round === 1 && input.endedAt !== undefined ? input.endedAt : now()).toISOString();
38
39
  let job = facts.costUsd;
39
40
  const firstAsk = (kept) => {
40
41
  if (typeof kept?.answered_at !== "string" || (typeof kept.job_cost_usd !== "number" && kept.job_cost_usd !== null))
@@ -24,8 +24,9 @@ export declare const WAITS_ON_A_PERSON = "The run is waiting on a person.";
24
24
  export declare function archiveRun(store: RunsStore, runId: string, archived: boolean): Promise<void>;
25
25
  /** Stops the run: one stop command row, which the run's runner reads and applies (it aborts the turn in flight, withdraws a
26
26
  * tool call waiting for approval, and ends the run stopped). A stop always lands — one command, no second path. An imported
27
- * or already-ended run has none to stop: `false`, nothing written (store.command refuses a final run, RunFinal). */
28
- export declare function stop(store: RunsStore, runId: string): Promise<boolean>;
27
+ * run, or one that reads ended (`moment.terminal`: one looking back after its job's end among them, whose end its
28
+ * look-back never undoes), has none to stop: `false`, nothing written (and store.command refuses a final run, RunFinal). */
29
+ export declare function stop(store: RunsStore, moment: RunMoment): Promise<boolean>;
29
30
  /** Cancels the run: one cancel command row, which the run's runner reads and applies (it ends the run cancelled, aborting
30
31
  * the turn in flight and cancelling a tool call waiting for approval). Returns whether a cancel was requested — the old
31
32
  * cancel's checks and their result, verbatim: an imported run, or one already ended or ending, has none to cancel (false,
@@ -78,14 +78,16 @@ export async function archiveRun(store, runId, archived) {
78
78
  }
79
79
  /** Stops the run: one stop command row, which the run's runner reads and applies (it aborts the turn in flight, withdraws a
80
80
  * tool call waiting for approval, and ends the run stopped). A stop always lands — one command, no second path. An imported
81
- * or already-ended run has none to stop: `false`, nothing written (store.command refuses a final run, RunFinal). */
82
- export async function stop(store, runId) {
83
- const row = await store.runs.get(runId);
84
- if (!row || row.importedFrom)
81
+ * run, or one that reads ended (`moment.terminal`: one looking back after its job's end among them, whose end its
82
+ * look-back never undoes), has none to stop: `false`, nothing written (and store.command refuses a final run, RunFinal). */
83
+ export async function stop(store, moment) {
84
+ if (moment.importedSource !== undefined)
85
+ return false;
86
+ await refuseSdkStop(store, moment.id);
87
+ if (moment.terminal)
85
88
  return false;
86
- await refuseSdkStop(store, runId);
87
89
  try {
88
- await sendCommand(store, runId, { kind: "stop", body: {} });
90
+ await sendCommand(store, moment.id, { kind: "stop", body: {} });
89
91
  return true;
90
92
  }
91
93
  catch (error) {
@@ -509,7 +511,7 @@ export async function startInline(store, deps, inline, body, { origin, sealed }
509
511
  const entry = stored
510
512
  ? firstOfVersion ? { ...stored, agent: { ...stored.agent, name: inline.name, description: inline.description } } : stored
511
513
  : {
512
- agent: { id: uuidv7(), name: inline.name, description: inline.description, currentRevision: null, createdAt: Date.now(), archivedAt: null, externalRef: ref },
514
+ agent: { id: uuidv7(), name: inline.name, description: inline.description, currentRevision: null, createdAt: Date.now(), archivedAt: null, externalRef: ref, purgedAt: null },
513
515
  revision: null, version: 0, revisions: 0, sizes: new Map(),
514
516
  };
515
517
  // A store revision is the revision the run path reads as a pi Revision (its body is the revision body), as pinnedOf hands
package/dist/server.d.ts CHANGED
@@ -208,9 +208,9 @@ export type ServeOptions = {
208
208
  /** A test's seam: step 2 of DELETE /agents/{id} (agent-delete.ts) in place of the learning module's deleteLearning over
209
209
  * the agent's learning folder (learn/delete.ts), the server's own. */
210
210
  deleteLearning?: DeleteLearning;
211
- /** A test's seam: awaited at each step's point of DELETE /agents/{id} (agent-delete.ts AgentDeleteStep), so a throw
212
- * there stops the delete as a crash would. */
213
- agentDeleteAt?: (step: AgentDeleteStep, agentId: string) => void | Promise<void>;
211
+ /** A test's seam: awaited at each step's point of DELETE /agents/{id} and DELETE /runs/{id} (agent-delete.ts
212
+ * AgentDeleteStep), with the agent's id or the run's, so a throw there stops the delete as a crash would. */
213
+ agentDeleteAt?: (step: AgentDeleteStep, id: string) => void | Promise<void>;
214
214
  /** A test's seam: awaited with a request's path and answer once its work under an Idempotency-Key is done, before the
215
215
  * answer is kept, so a test can hold a request there while a DELETE /agents/{id} runs. */
216
216
  beforeKeep?: (path: string, answer: unknown) => void | Promise<void>;