@parcha/agentrun-serve 0.1.0-beta.62 → 0.1.0-beta.63

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 (128) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +32 -13
  3. package/dist/adapters.js +4 -2
  4. package/dist/agent-delete.d.ts +3 -3
  5. package/dist/agent-delete.js +50 -4
  6. package/dist/chatgpt-plan.d.ts +8 -1
  7. package/dist/chatgpt-plan.js +55 -6
  8. package/dist/console/assets/{backend-DEgVn5lC.js → backend-BxQ2G1M0.js} +2 -2
  9. package/dist/console/assets/{index-CG5tELph.js → index-C8Y5Zl8x.js} +2 -2
  10. package/dist/console/assets/share-CjBJ_rxP.js +6 -0
  11. package/dist/console/index.html +1 -1
  12. package/dist/console/share.html +1 -1
  13. package/dist/harness-opencode/adapter.d.ts +3 -1
  14. package/dist/harness-opencode/adapter.js +6 -2
  15. package/dist/harness-opencode/harness.d.ts +4 -0
  16. package/dist/harness-opencode/harness.js +6 -1
  17. package/dist/host-tools.d.ts +18 -3
  18. package/dist/host-tools.js +27 -4
  19. package/dist/learn/ledger.d.ts +37 -16
  20. package/dist/learn/ledger.js +56 -24
  21. package/dist/learn/promote.d.ts +4 -1
  22. package/dist/learning-cost.d.ts +5 -3
  23. package/dist/learning-model.js +7 -5
  24. package/dist/learning-work.d.ts +69 -0
  25. package/dist/learning-work.js +148 -0
  26. package/dist/openapi.js +23 -9
  27. package/dist/run-export.js +7 -4
  28. package/dist/run-launch.d.ts +6 -1
  29. package/dist/run-launch.js +10 -3
  30. package/dist/run-view.js +9 -3
  31. package/dist/runnable.js +5 -5
  32. package/dist/runner/adapter-loop.js +31 -3
  33. package/dist/runner/adapter-run-spec.d.ts +14 -3
  34. package/dist/runner/adapter-run-spec.js +50 -19
  35. package/dist/runner/adapters/index.d.ts +2 -0
  36. package/dist/runner/adapters/index.js +3 -0
  37. package/dist/runner/adapters/pi.d.ts +42 -3
  38. package/dist/runner/adapters/pi.js +114 -13
  39. package/dist/runner/audit.d.ts +8 -2
  40. package/dist/runner/audit.js +34 -18
  41. package/dist/runner/book-cut.d.ts +6 -0
  42. package/dist/runner/book-cut.js +38 -0
  43. package/dist/runner/claim-secrets.d.ts +9 -4
  44. package/dist/runner/claim-secrets.js +10 -5
  45. package/dist/runner/cli-run-spec.d.ts +0 -2
  46. package/dist/runner/cli-run-spec.js +44 -19
  47. package/dist/runner/held.d.ts +6 -3
  48. package/dist/runner/learned-first.d.ts +5 -0
  49. package/dist/runner/learned-first.js +1 -1
  50. package/dist/runner/learning-end.d.ts +15 -8
  51. package/dist/runner/learning-end.js +23 -7
  52. package/dist/runner/loop-contract.d.ts +4 -0
  53. package/dist/runner/main.js +2 -0
  54. package/dist/runner/model-route.d.ts +4 -0
  55. package/dist/runner/model-route.js +1 -1
  56. package/dist/runner/pr-checkout.d.ts +12 -0
  57. package/dist/runner/pr-checkout.js +21 -2
  58. package/dist/runner/promotion.d.ts +9 -2
  59. package/dist/runner/promotion.js +79 -28
  60. package/dist/runner/reflect-hook.d.ts +7 -0
  61. package/dist/runner/reflect-hook.js +2 -1
  62. package/dist/runner/run-child-host.js +21 -12
  63. package/dist/runner/run-child.js +1 -0
  64. package/dist/runner/runner.d.ts +9 -0
  65. package/dist/runner/runner.js +156 -25
  66. package/dist/runner/store-port.d.ts +4 -1
  67. package/dist/runner/workflow-first.js +4 -3
  68. package/dist/runner/workflow-loop.js +13 -1
  69. package/dist/secret-cut.d.ts +4 -0
  70. package/dist/secret-cut.js +1 -1
  71. package/dist/secret-rules.d.ts +2 -0
  72. package/dist/secret-rules.js +63 -19
  73. package/dist/server.js +20 -9
  74. package/dist/share-host.js +6 -3
  75. package/dist/store/schema.d.ts +4 -3
  76. package/dist/store/schema.js +4 -3
  77. package/dist/store/seal.d.ts +8 -2
  78. package/dist/store/seal.js +13 -2
  79. package/dist/store/sqlite/learning-rows.js +2 -1
  80. package/dist/store/sqlite/run-patch.js +4 -4
  81. package/dist/store/sqlite/store.js +28 -4
  82. package/dist/store/store.d.ts +5 -0
  83. package/dist/store-reads/journal.d.ts +2 -0
  84. package/dist/store-reads/journal.js +1 -1
  85. package/dist/store-reads/learning.d.ts +4 -3
  86. package/dist/store-reads/learning.js +62 -18
  87. package/dist/store-view.d.ts +3 -0
  88. package/dist/store-view.js +18 -1
  89. package/dist/tool-list.d.ts +4 -0
  90. package/dist/tool-list.js +4 -0
  91. package/dist/tools.js +2 -2
  92. package/dist/workspace/attach.js +22 -5
  93. package/dist/workspace/kind-skills/desktop/SKILL.md +7 -3
  94. package/package.json +12 -12
  95. package/templates/kyb/agent.md +7 -1
  96. package/templates/kyb/evals/list-file-fuzzy-alias/case.yaml +10 -0
  97. package/templates/kyb/evals/list-file-fuzzy-alias/fixtures/web.json +58 -0
  98. package/templates/kyb/evals/list-file-fuzzy-alias/graders/finds-the-transliteration.md +17 -0
  99. package/templates/kyb/evals/list-file-fuzzy-alias/graders/greps-the-files.md +11 -0
  100. package/templates/kyb/evals/list-file-fuzzy-alias/graders/saves-the-uk-file.md +8 -0
  101. package/templates/kyb/evals/list-file-fuzzy-alias/prompt.md +7 -0
  102. package/templates/kyb/evals/list-file-hit/case.yaml +10 -0
  103. package/templates/kyb/evals/list-file-hit/fixtures/web.json +58 -0
  104. package/templates/kyb/evals/list-file-hit/graders/greps-the-files.md +11 -0
  105. package/templates/kyb/evals/list-file-hit/graders/hits-by-company-number.md +18 -0
  106. package/templates/kyb/evals/list-file-hit/graders/saves-the-uk-file.md +8 -0
  107. package/templates/kyb/evals/list-file-hit/prompt.md +7 -0
  108. package/templates/kyb/evals/list-file-no-hit/case.yaml +10 -0
  109. package/templates/kyb/evals/list-file-no-hit/fixtures/web.json +58 -0
  110. package/templates/kyb/evals/list-file-no-hit/graders/greps-the-files.md +11 -0
  111. package/templates/kyb/evals/list-file-no-hit/graders/no-hit-by-whole-file.md +12 -0
  112. package/templates/kyb/evals/list-file-no-hit/graders/saves-the-uk-file.md +8 -0
  113. package/templates/kyb/evals/list-file-no-hit/prompt.md +7 -0
  114. package/templates/kyb/evals/list-file-short-name/case.yaml +9 -0
  115. package/templates/kyb/evals/list-file-short-name/fixtures/web.json +58 -0
  116. package/templates/kyb/evals/list-file-short-name/graders/finds-the-short-name.md +19 -0
  117. package/templates/kyb/evals/list-file-short-name/graders/greps-the-files.md +11 -0
  118. package/templates/kyb/evals/list-file-short-name/graders/saves-the-uk-file.md +8 -0
  119. package/templates/kyb/evals/list-file-short-name/prompt.md +7 -0
  120. package/templates/kyb/evals/list-file-split-name/case.yaml +11 -0
  121. package/templates/kyb/evals/list-file-split-name/fixtures/web.json +58 -0
  122. package/templates/kyb/evals/list-file-split-name/graders/finds-the-director.md +18 -0
  123. package/templates/kyb/evals/list-file-split-name/graders/greps-the-files.md +11 -0
  124. package/templates/kyb/evals/list-file-split-name/graders/saves-the-uk-file.md +8 -0
  125. package/templates/kyb/evals/list-file-split-name/prompt.md +7 -0
  126. package/templates/kyb/kyb.schema.json +2 -2
  127. package/templates/kyb/rules/SANCTIONS.md +82 -13
  128. package/dist/console/assets/share-CIeFK2Oe.js +0 -6
@@ -10,18 +10,21 @@
10
10
  import { randomUUID } from "node:crypto";
11
11
  import { hostname } from "node:os";
12
12
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
13
- import { COMMAND_KINDS, endedReason } from "./commands.js";
13
+ import { COMMAND_KINDS, endedReason, sendCommand } from "./commands.js";
14
14
  import { COMPUTER_CALL } from "../computer-channel.js";
15
15
  import { COMPUTER_HAND_BACK, COMPUTER_TAKE_OVER } from "../computer-commands.js";
16
16
  import { HELD_COMMANDS } from "../computer-held.js";
17
17
  import { HAND_BACK } from "./hand-back.js";
18
18
  import { KINDS, withdrawnAnswers } from "./journal-kinds.js";
19
19
  import { journalEntries } from "./journal-reader.js";
20
+ import { cliModelWorked, endCostOf, runCostOf } from "./metrics.js";
21
+ import { inLogOrder, isCliRecord } from "../store-reads/journal.js";
22
+ import { bookCutRequests } from "./book-cut.js";
20
23
  import { REAL_TIMER } from "./loop.js";
21
24
  import { ClaimRefused, stopEnd } from "./loop-contract.js";
22
25
  import { FrameTooLarge } from "./run-channel.js";
23
26
  import { isFenced } from "./store-port.js";
24
- import { FINAL_STATES } from "../store/store.js";
27
+ import { FINAL_STATES, RunFinal } from "../store/store.js";
25
28
  import { Unanswered } from "../store/postgres/connection.js";
26
29
  import { clearWaitEnded } from "../browser-wait-ended.js";
27
30
  import { clearBrowserHeld } from "../browser-hold.js";
@@ -35,6 +38,8 @@ const UNKNOWN_READS = 5;
35
38
  /** Passes of the sweep after a claim answered Unanswered: the commit may still be on its way when the first read comes back
36
39
  * empty, so the read is repeated, waiting twice as long each time, before the lease is left to settle it. */
37
40
  const UNKNOWN_SWEEPS = 4;
41
+ /** The longest wait one timer takes (a 32-bit signed count of ms): a longer one fires at once. */
42
+ const MAX_TIMER_MS = 2 ** 31 - 1;
38
43
  /** Most runs a runner holds at once, unless told (RunnerOptions.loops). */
39
44
  /** A final run's status as its end line says it: the store holds a cancel as state 'stopped' with outcome 'cancelled', so
40
45
  * the outcome tells a cancel from a person's resumable stop. */
@@ -86,7 +91,7 @@ const message = (error) => (error instanceof Error ? error.message : String(erro
86
91
  /** The run states a run patch makes final: a commit that lands one is the run's end, and its release. */
87
92
  const FINAL = new Set(["ended", "stopped", "failed"]);
88
93
  export function startRunner(options) {
89
- const { store, createLoop, name = runnerName(), loops = RUNNER_LOOPS, leaseMs = RUNNER_LEASE_MS, renewEveryMs = RUNNER_RENEW_EVERY_MS, stopMarginMs = RUNNER_STOP_MARGIN_MS, pollMs = 1_000, commandPollMs = 500, resumeTries = 3, resumeBackoffMs = 5_000, interruptBackoffMs = 1_000, unknownBackoffMs = 200, endWaitMs = 5_000, drainMs = 0, memory, census, censusMs = CENSUS_MS, endRetryBackoffMs = END_RETRY_BACKOFF_MS, endRetryCapMs = END_RETRY_CAP_MS, endRetryAtCap = END_RETRY_AT_CAP, onEvent = () => { }, runEnded, redact: given = processSecretRedactor(), now = Date.now, onBeat = () => { }, clock = { now: () => Date.now(), ...REAL_TIMER }, } = options;
94
+ const { store, createLoop, name = runnerName(), loops = RUNNER_LOOPS, leaseMs = RUNNER_LEASE_MS, renewEveryMs = RUNNER_RENEW_EVERY_MS, stopMarginMs = RUNNER_STOP_MARGIN_MS, pollMs = 1_000, commandPollMs = 500, resumeTries = 3, resumeBackoffMs = 5_000, interruptBackoffMs = 1_000, unknownBackoffMs = 200, endWaitMs = 5_000, drainMs = 0, memory, census, censusMs = CENSUS_MS, endRetryBackoffMs = END_RETRY_BACKOFF_MS, endRetryCapMs = END_RETRY_CAP_MS, endRetryAtCap = END_RETRY_AT_CAP, onEvent = () => { }, runEnded, redact: given = processSecretRedactor(), now = Date.now, learningClock = Date.now, onBeat = () => { }, clock = { now: () => Date.now(), ...REAL_TIMER }, } = options;
90
95
  // The one instance every run's loop gets (LoopDeps.redact), able to hold what each claim opens from the store
91
96
  // (redact.ts holdClaimed): a stored key is cut wherever a key of the runner's environment is.
92
97
  const redact = heldRedactor(given);
@@ -505,7 +510,7 @@ export function startRunner(options) {
505
510
  * in its journal, a reopen would find no turn to follow (its next claim would read the run as never started), so it
506
511
  * reads as a stop that is over (cancelled), as it read before a stop and a cancel were told apart.
507
512
  */
508
- const endRun = async (claim, given, take, withdrawnAs = "withdrawn", landed = () => { }) => {
513
+ const endRun = async (claim, given, take, withdrawnAs = "withdrawn", landed = () => { }, cost) => {
509
514
  // Why the run ended, as its end and its row say it: cut of every secret the runner holds (an error's text may echo one).
510
515
  const data = { ...given, summary: redact(given.summary) };
511
516
  // Unknown means it may withdraw: false only once the journal was read and no call of it waits.
@@ -538,7 +543,7 @@ export function startRunner(options) {
538
543
  }
539
544
  const id = (await journal.mintId());
540
545
  writes.push({ type: "entry", value: { id, conversationId, kind: KINDS.end, data: data } });
541
- journal.stage({ run: { state: data.state, summary: data.summary, ...(data.outcome ? { outcome: data.outcome } : {}), ...(neverSent ? { costUsd: 0 } : {}), ...counted }, effect: id, ...(take.length ? { take: take.map((command) => ({ command, effect: id })) } : {}) });
546
+ journal.stage({ run: { state: data.state, summary: data.summary, ...(data.outcome ? { outcome: data.outcome } : {}), ...(cost ?? (neverSent ? { costUsd: 0 } : {})), ...counted }, effect: id, ...(take.length ? { take: take.map((command) => ({ command, effect: id })) } : {}) });
542
547
  const result = await journal.commit([writes], () => { }, BACKGROUND_CONTEXT);
543
548
  if (result.stored !== 1)
544
549
  throw result.refused ?? new Error("the run's end was not stored");
@@ -549,7 +554,7 @@ export function startRunner(options) {
549
554
  throw error;
550
555
  if (mayWithdraw)
551
556
  throw new EndNotWithdrawn(claim.runId, error);
552
- await store.runs.update(claim, { state: data.state, summary: data.summary, ...(data.outcome === "cancelled" ? { outcome: data.outcome } : {}), ...counted }, take.length ? { take } : undefined);
557
+ await store.runs.update(claim, { state: data.state, summary: data.summary, ...(data.outcome === "cancelled" ? { outcome: data.outcome } : {}), ...cost, ...counted }, take.length ? { take } : undefined);
553
558
  landed();
554
559
  }
555
560
  // An ended run's Screen has no ended-while-waiting state to keep (browser-wait-ended.ts): its row goes with the end.
@@ -561,16 +566,16 @@ export function startRunner(options) {
561
566
  };
562
567
  /** Ends the run under `claim` stopped on its untaken `stop` (or cancel) row (endRun). False when that end may withdraw a
563
568
  * call and the journal would not take it or could not be read: the refusal is then the run's (endRefused). */
564
- const endStopped = async (claim, stop, landed) => {
569
+ const endStopped = async (claim, stop, landed, cost) => {
565
570
  try {
566
571
  const end = stopEnd(stop.kind === "cancel");
567
- await endRun(claim, end, [stop.id], stop.kind === "cancel" ? "canceled" : "withdrawn", landed);
572
+ await endRun(claim, end, [stop.id], stop.kind === "cancel" ? "canceled" : "withdrawn", landed, cost);
568
573
  return true;
569
574
  }
570
575
  catch (error) {
571
576
  if (!(error instanceof EndNotWithdrawn))
572
577
  throw error;
573
- await endRefused(claim, stop, error, landed);
578
+ await endRefused(claim, stop, error, landed, cost);
574
579
  return false;
575
580
  }
576
581
  };
@@ -597,14 +602,14 @@ export function startRunner(options) {
597
602
  * 11 tries at the cap): 6 growing waits (5 s to 160 s, 315 s in all), then 11 of 5 min, so about an hour (3,615 s) of
598
603
  * retries, and the 18th refusal gives up.
599
604
  */
600
- const endRefused = async (claim, stop, refused, landed) => {
605
+ const endRefused = async (claim, stop, refused, landed, cost) => {
601
606
  const tries = await store.retry(claim, stop.id);
602
607
  const why = message(refused.cause);
603
608
  if (tries >= endRetryCapFrom + endRetryAtCap) {
604
609
  emit({ type: "error", runId: claim.runId, step: "end", message: `run ${claim.runId} ended without withdrawing: journal unreadable or refusing (after ${tries} tries; the last: ${why})` });
605
610
  // On its row alone, so no outcome 'stopped' (endRun): a run whose journal never took its end is never reopened.
606
611
  const end = stopEnd(stop.kind === "cancel");
607
- await store.runs.update(claim, { state: end.state, summary: redact(end.summary), ...(end.outcome === "cancelled" ? { outcome: end.outcome } : {}), ...(await censusFor(claim.runId)) }, { take: [stop.id] });
612
+ await store.runs.update(claim, { state: end.state, summary: redact(end.summary), ...(end.outcome === "cancelled" ? { outcome: end.outcome } : {}), ...cost, ...(await censusFor(claim.runId)) }, { take: [stop.id] });
608
613
  landed();
609
614
  await releaseStopped(claim, stop);
610
615
  return;
@@ -647,16 +652,33 @@ export function startRunner(options) {
647
652
  return true;
648
653
  }
649
654
  };
655
+ /** What the run under `claim` booked in its journal, as an end stores its cost (metrics.ts endCostOf, the rule every end
656
+ * stores by, over its booking as learning-end.ts reads it): a figure, or a bound when a cut request's hold is counted
657
+ * in it. A request an earlier claim left out is booked first, cut at its hold, as a loop's booking books it before it
658
+ * sends anything (book-cut.ts). Undefined when the journal cannot be read: the end then stores no cost, as it did. */
659
+ const bookedOf = async (claim) => {
660
+ try {
661
+ await bookCutRequests(store.journal(claim), BACKGROUND_CONTEXT, () => store.flush());
662
+ const entries = inLogOrder(await journalEntries(store.journal(claim), BACKGROUND_CONTEXT));
663
+ return endCostOf(runCostOf(entries, { unbooked: isCliRecord(entries) && cliModelWorked(entries) }));
664
+ }
665
+ catch {
666
+ return undefined;
667
+ }
668
+ };
650
669
  /** A claim of a run whose stopped end was refused (its untaken stop row has tries): it only ends the run, with no loop,
651
- * so no turn, model request or tool runs on a run that is stopping. */
652
- const endRetried = async (claim, stop) => {
670
+ * so no turn, model request or tool runs on a run that is stopping. `booked`: a learning child past its deadline, which
671
+ * an earlier claim's loop may have spent on before its runner went (its spend booked in its journal): its end stores
672
+ * that booking as its cost (bookedOf), so what it spent stays its run's, never an unknown no read heals. */
673
+ const endRetried = async (claim, stop, booked = false) => {
653
674
  // Renewed with the held claims (renewAll) until its end lands: its end waits for the run's census too.
654
675
  const only = { claim, landed: false, renewing: false };
655
676
  endOnly.add(only);
656
677
  try {
657
678
  // A run stopped before any loop started still has its one start line, ahead of its end.
658
679
  await announceStart(claim);
659
- if (await endStopped(claim, stop, () => (only.landed = true)))
680
+ const cost = booked ? await bookedOf(claim) : undefined;
681
+ if (await endStopped(claim, stop, () => (only.landed = true), cost))
660
682
  await releaseStopped(claim, stop);
661
683
  }
662
684
  catch (error) {
@@ -671,6 +693,7 @@ export function startRunner(options) {
671
693
  const stoppedBefore = held.stopping;
672
694
  held.ending = true;
673
695
  clock.clearTimeout(held.deadline);
696
+ clearTimeout(held.learningTimer);
674
697
  const { claim } = held;
675
698
  // The runner's own end of the run, once its write lands: the claim is renewed until then (renewAll), no further.
676
699
  const landed = () => {
@@ -743,10 +766,11 @@ export function startRunner(options) {
743
766
  // A run let go unfinished says why on its claim's attempt (run_attempts cut): a runner's close drained it, or its
744
767
  // loop ended interrupted on its own and the run is tried again. The next claim works its turn again.
745
768
  const cut = end.state !== "interrupted" ? undefined : closedItself ? "retry" : held.stoppedFor === "shutdown" ? "drain" : undefined;
769
+ const wakeAt = end.state === "parked" ? parkedWake(held, end.wakeAt) : undefined;
746
770
  await release(claim, {
747
771
  // Parked again with nothing written (LoopEnd `again`): the release parks the row, its words left as they stood.
748
772
  ...(end.state === "parked" && end.again ? { state: "parked" } : {}),
749
- ...(end.state === "parked" && end.wakeAt !== undefined ? { wakeAt: end.wakeAt }
773
+ ...(wakeAt !== undefined ? { wakeAt }
750
774
  : inARow > 0 ? { backoffUntil: now() + interruptBackoffMs * 2 ** Math.min(inARow - 1, 6) }
751
775
  : {}),
752
776
  ...(cut ? { cut } : {}),
@@ -770,10 +794,18 @@ export function startRunner(options) {
770
794
  }
771
795
  }
772
796
  };
797
+ /** When parked run `held` wakes: its loop's `wakeAt`, or a learning child's deadline when sooner, so a child parked
798
+ * (for an approval, a raise) is claimed again at its deadline and ends there (claimMore's overdue claim), never left
799
+ * parked past it holding its copy of its run's key, its run's learning_work running. The learning clock is the store's
800
+ * but in a test. */
801
+ const parkedWake = (held, wakeAt) => held.learningDeadline === undefined ? wakeAt : wakeAt === undefined ? held.learningDeadline : Math.min(wakeAt, held.learningDeadline);
773
802
  /** A parked run's resume that threw: one more try on the row that woke it, released parked with a backoff; after
774
- * `resumeTries`, that row refused with why and the run released parked with nothing to wake it. */
803
+ * `resumeTries`, that row refused with why and the run released parked with nothing to wake it but a learning child's
804
+ * deadline (parkedWake). */
775
805
  const resumeFailed = async (held, why) => {
776
806
  const { claim } = held;
807
+ const wake = parkedWake(held, undefined);
808
+ const wakeAt = wake === undefined ? {} : { wakeAt: wake };
777
809
  const untaken = (await store.commands(claim.runId, 0)).filter((row) => row.takenAt === null);
778
810
  const stop = endingRow(untaken);
779
811
  const woke = untaken[0];
@@ -792,22 +824,26 @@ export function startRunner(options) {
792
824
  await store.take(claim, woke.id, "refused", reason);
793
825
  emit({ type: "refused", runId: claim.runId, commandId: woke.id, reason });
794
826
  await store.flush();
795
- await release(claim, { state: "parked" });
827
+ await release(claim, { state: "parked", ...wakeAt });
796
828
  }
797
829
  else {
798
830
  await store.flush();
799
- await release(claim, { state: "parked", backoffUntil: now() + resumeBackoffMs * 2 ** (tries - 1) });
831
+ await release(claim, { state: "parked", ...wakeAt, backoffUntil: now() + resumeBackoffMs * 2 ** (tries - 1) });
800
832
  }
801
833
  }
802
834
  else {
803
835
  await store.flush();
804
- await release(claim, { state: "parked" });
836
+ await release(claim, { state: "parked", ...wakeAt });
805
837
  }
806
838
  emit({ type: "released", runId: claim.runId, epoch: claim.epoch, end: "parked" });
807
839
  };
808
- const hold = (claim, sentAt, mib = 0) => {
840
+ /** Holds `claim` and starts its loop. `learningDeadline`: a learning child's deadline, read at its claim
841
+ * (learningDeadlinesOf), at which its loop sends no model request more and the runner cancels it if still at work
842
+ * (cancelOverdue). */
843
+ const hold = (claim, sentAt, mib = 0, learningDeadline) => {
809
844
  const fence = { lost: false };
810
845
  const abort = new AbortController();
846
+ const pastDeadline = learningDeadline === undefined ? undefined : new AbortController();
811
847
  let firstDelivered;
812
848
  const delivered = new Promise((resolve) => (firstDelivered = resolve));
813
849
  // Set below, once held is made: the loop's end commit lands only after start(), well after.
@@ -821,6 +857,7 @@ export function startRunner(options) {
821
857
  journal: (forClaim) => fenced(store.journal(forClaim), fence, forClaim.runId, () => ending()),
822
858
  flush: () => store.flush(),
823
859
  signal: abort.signal,
860
+ ...(pastDeadline ? { pastDeadline: pastDeadline.signal } : {}),
824
861
  delivered,
825
862
  // A delivery under way first (its rows are the loop's already), then one more read of the run's new rows.
826
863
  deliverNow: async () => {
@@ -831,16 +868,18 @@ export function startRunner(options) {
831
868
  },
832
869
  redact,
833
870
  });
834
- const held = { passed: new Set(), claim, loop, fence, abort, cursor: 0, stopping: false, ending: false, landed: false, sealed: false, renewing: false, delivering: false, deliverAgain: false, mib };
871
+ const held = { passed: new Set(), claim, loop, fence, abort, cursor: 0, stopping: false, ending: false, landed: false, sealed: false, renewing: false, delivering: false, deliverAgain: false, mib, ...(learningDeadline !== undefined && pastDeadline ? { learningDeadline, pastDeadline } : {}) };
835
872
  heldNow = held;
836
873
  // The loop's own end landed: the run is ending from here, its teardown included (no renew, no lost claim).
837
874
  ending = () => {
838
875
  held.ending = true;
839
876
  held.landed = true;
840
877
  clock.clearTimeout(held.deadline);
878
+ clearTimeout(held.learningTimer);
841
879
  };
842
880
  runs.set(claim.runId, held);
843
881
  armDeadline(held, deadlineOf(claim, sentAt));
882
+ armLearningDeadline(held);
844
883
  emit({ type: "claimed", claim });
845
884
  void announceStart(claim);
846
885
  held.done = (async () => {
@@ -979,13 +1018,41 @@ export function startRunner(options) {
979
1018
  // One read of those claims' rows, made only when the batch has a queued or a released run.
980
1019
  const reread = claims.filter((claim) => claim.from === "queued" || claim.from === "running" || claim.from === "parked");
981
1020
  const rows = reread.length ? await store.commandsOf(reread.map((claim) => ({ runId: claim.runId, after: 0 }))) : new Map();
1021
+ // The learning children's deadlines among the batch, one read for all of it (learningDeadlinesOf), before any loop
1022
+ // starts on one: a batch whose read failed is given back whole, for a later claim to read again; a child at or past
1023
+ // its deadline on the learning clock only ends, cancelled as a person's cancel ends an unstarted run, so nothing of it
1024
+ // spends past the bound its run's caller was promised (learning_work.deadline_at).
1025
+ const deadlines = await learningDeadlinesOf(claims);
982
1026
  for (const claim of claims) {
983
- const stop = endingRow((rows.get(claim.runId) ?? []).filter((row) => row.takenAt === null));
984
- const endsOnly = stop !== undefined && (claim.from === "queued" || stop.tries > 0 || (claim.from === "running" && (await neverStarted(claim))) || (claim.from === "parked" && (await keptElsewhere(claim))));
1027
+ if (!(deadlines instanceof Map)) {
1028
+ emit({ type: "error", runId: claim.runId, step: "learning deadline", message: deadlines.unread });
1029
+ await release(claim, {}).then(() => emit({ type: "handed-back", runId: claim.runId, epoch: claim.epoch, cause: "give_back" }), () => { });
1030
+ continue;
1031
+ }
1032
+ const deadline = deadlines.get(claim.runId);
1033
+ const overdue = deadline !== undefined && learningClock() >= deadline;
1034
+ let stop = endingRow((rows.get(claim.runId) ?? []).filter((row) => row.takenAt === null));
1035
+ if (overdue && stop?.kind !== "cancel") {
1036
+ emit({ type: "learning-deadline", runId: claim.runId });
1037
+ const cancelled = await sendCommand(store, claim.runId, { kind: "cancel", body: {} }).then(() => true, (error) => {
1038
+ emit({ type: "error", runId: claim.runId, step: "learning deadline", message: message(error) });
1039
+ return false;
1040
+ });
1041
+ if (!cancelled) {
1042
+ await release(claim, {}).catch(() => { });
1043
+ continue;
1044
+ }
1045
+ stop = endingRow((await store.commands(claim.runId, 0)).filter((row) => row.takenAt === null));
1046
+ if (!stop) {
1047
+ await release(claim, {}).catch(() => { });
1048
+ continue;
1049
+ }
1050
+ }
1051
+ const endsOnly = stop !== undefined && (overdue || claim.from === "queued" || stop.tries > 0 || (claim.from === "running" && (await neverStarted(claim))) || (claim.from === "parked" && (await keptElsewhere(claim))));
985
1052
  if (stop && endsOnly && !closed && !killed && !runs.has(claim.runId)) {
986
1053
  const key = `${claim.runId}:${claim.epoch}`;
987
1054
  endingClaims.add(key);
988
- const ending = endRetried(claim, stop);
1055
+ const ending = endRetried(claim, stop, overdue);
989
1056
  endings.add(ending);
990
1057
  void ending.finally(() => {
991
1058
  endings.delete(ending);
@@ -1007,7 +1074,7 @@ export function startRunner(options) {
1007
1074
  replaced.add(before);
1008
1075
  void before.done.finally(() => replaced.delete(before));
1009
1076
  }
1010
- hold(claim, sentAt, weights.get(claim.runId) ?? 0);
1077
+ hold(claim, sentAt, weights.get(claim.runId) ?? 0, deadline);
1011
1078
  }
1012
1079
  catch (error) {
1013
1080
  // The loop could not be made: the run fails here, so it is not claimed again and again.
@@ -1091,12 +1158,76 @@ export function startRunner(options) {
1091
1158
  let claiming;
1092
1159
  /** A run was queued while a poll was in flight (claimNow): one more poll follows that poll's end at once. */
1093
1160
  let pollAgain = false;
1161
+ /** The learning deadlines of the learning children among a poll's `claims` (a check's replay, an audit's shadow: each
1162
+ * its launch's, learning-work.ts LEARNING_CHILD_MS), in one read for the whole batch (store.runs.learningDeadlines),
1163
+ * before any loop starts on one: a run that is no learning child is absent, and a store without that read or without
1164
+ * commands (a test's) has none. `{ unread }` when the read failed: the batch is given back for a later claim to read
1165
+ * again. */
1166
+ const learningDeadlinesOf = async (claims) => {
1167
+ if (claims.length === 0 || !store.runs.learningDeadlines || !store.command)
1168
+ return new Map();
1169
+ try {
1170
+ return await store.runs.learningDeadlines(claims.map((claim) => claim.runId));
1171
+ }
1172
+ catch (error) {
1173
+ return { unread: message(error) };
1174
+ }
1175
+ };
1176
+ /** Held learning child `held` at its deadline on the learning clock: its loop sends no model request more (its
1177
+ * pastDeadline signal, which its request gate reads before each), and it is cancelled as a person's cancel is (a cancel
1178
+ * row, its loop's ordinary stop: its spend booked once at its end, its copy of a key erased by that end's write), that
1179
+ * row handed to its loop at once, never at the next command tick. Serve has no run deadline, so this is what bounds a
1180
+ * learning child's spend on its run's key (learning_work.deadline_at). A cancel not written is tried again at the next
1181
+ * poll (endOverdue); its gate stays shut meanwhile. */
1182
+ const cancelOverdue = (held) => {
1183
+ if (held.overdue || held.ending || held.fence.lost)
1184
+ return;
1185
+ held.overdue = true;
1186
+ held.pastDeadline?.abort();
1187
+ emit({ type: "learning-deadline", runId: held.claim.runId });
1188
+ if (!store.command)
1189
+ return;
1190
+ void sendCommand(store, held.claim.runId, { kind: "cancel", body: {} }).then(() => {
1191
+ if (held.sealed || !delivering())
1192
+ return;
1193
+ if (held.delivering)
1194
+ held.deliverAgain = true;
1195
+ else
1196
+ void deliver(held);
1197
+ }, (error) => {
1198
+ // Final already: it ended on its own.
1199
+ if (error instanceof RunFinal)
1200
+ return;
1201
+ held.overdue = false;
1202
+ emit({ type: "error", runId: held.claim.runId, step: "learning deadline", message: message(error) });
1203
+ });
1204
+ };
1205
+ /** Held learning child `held`'s deadline, on the learning clock: cancelOverdue at it, by a timer on its own (re-armed
1206
+ * while the deadline is past a timer's longest wait), so neither waits for a poll. */
1207
+ const armLearningDeadline = (held) => {
1208
+ if (held.learningDeadline === undefined || held.ending || held.sealed)
1209
+ return;
1210
+ const wait = held.learningDeadline - learningClock();
1211
+ if (wait <= 0)
1212
+ return cancelOverdue(held);
1213
+ // Unref'd: a runner killed with the child held (a crash) leaves nothing that keeps its process up.
1214
+ held.learningTimer = setTimeout(() => armLearningDeadline(held), Math.min(wait, MAX_TIMER_MS)).unref();
1215
+ };
1216
+ /** Every held learning child at its deadline on the learning clock (cancelOverdue), swept at each poll: the timer's
1217
+ * backstop, and a cancel that was not written tried again. */
1218
+ const endOverdue = () => {
1219
+ const at = learningClock();
1220
+ for (const held of runs.values())
1221
+ if (held.learningDeadline !== undefined && at >= held.learningDeadline)
1222
+ cancelOverdue(held);
1223
+ };
1094
1224
  const poll = () => {
1095
1225
  if (closed || killed)
1096
1226
  return;
1097
1227
  clearTimeout(pollTimer);
1098
1228
  pollAgain = false;
1099
1229
  beat();
1230
+ endOverdue();
1100
1231
  const claimed = claimMore();
1101
1232
  claiming = claimed;
1102
1233
  void claimed.finally(() => {
@@ -1,8 +1,11 @@
1
1
  import { type Store } from "../store/store.js";
2
2
  export type RunnerStore = Pick<Store, "leaseClock" | "claim" | "renew" | "renewMany" | "release" | "journal" | "flush" | "commands" | "commandsOf" | "take" | "retry" | "watchCommands"> & {
3
- readonly runs: Pick<Store["runs"], "claimMany" | "claimable" | "claimsOf" | "update"> & Partial<Pick<Store["runs"], "launch" | "get">>;
3
+ readonly runs: Pick<Store["runs"], "claimMany" | "claimable" | "claimsOf" | "update"> & Partial<Pick<Store["runs"], "launch" | "get" | "learningDeadlines">>;
4
4
  /** The revision's kind, read for a run's start line (runner.ts). A store without it (a test's) says no start or end line. */
5
5
  readonly agents?: Pick<Store["agents"], "revision">;
6
+ /** Writes a command row: the cancel of a learning child at its deadline (runner.ts cancelOverdue). A store without
7
+ * it (a test's) cancels none. */
8
+ readonly command?: Store["command"];
6
9
  /** The runs' live view (run_live): the runner's live ticker writes each run's held state there. A store without it (a
7
10
  * test's) has no live view. */
8
11
  readonly live?: Store["live"];
@@ -391,15 +391,16 @@ export function pathMetrics(launch, classified, entries = [], choice) {
391
391
  const chose = choice ? { first_choice: choice } : {};
392
392
  if (launch.replay) {
393
393
  // A replay run (runner/promotion.ts): path `replay`, whatever its workflow did, so the money rule and the agent's
394
- // by-hand cost never read it; how its workflow ended, for the replay's score (learn/promote.ts ReplayRow).
395
- const { of, workflow: name, digest: at } = launch.replay;
394
+ // by-hand cost never read it; how its workflow ended, for the replay's score (learn/promote.ts ReplayRow); and the run
395
+ // whose own key it spent on (`paid_by`), whose learning its cost is (learn/ledger.ts record).
396
+ const { of, workflow: name, digest: at, paidBy } = launch.replay;
396
397
  // Handed back when the workflow ended escalated (an escalate node: the workflow knowing its limits), however
397
398
  // many of its nodes failed on the way and were recovered (a map's collected item); a workflow that itself ended failed
398
399
  // (a credential or tool the replay ran without, a step's output off its schema), or was refused, is failed: no
399
400
  // evidence. Skipped when a write it needed is not in the graded run's recording (learn/replay-calls.ts): never run.
400
401
  const skipped = replaySkippedIn(entries);
401
402
  const outcome = skipped ? "skipped_write" : path === "workflow" && workflow === name ? "answered" : path === "handed_back" && workflow === name && endedIn(entries, name) === "escalated" ? "handed_back" : "failed";
402
- return { path: "replay", ...(launch.learning.seed ? { learned_revision: launch.learning.seed } : {}), workflow: name, workflow_digest: at, ...rows, ...chose, replay: { of, outcome, ...(skipped ? { skipped } : {}), ...verdict } };
403
+ return { path: "replay", ...(launch.learning.seed ? { learned_revision: launch.learning.seed } : {}), workflow: name, workflow_digest: at, ...rows, ...chose, replay: { of, ...(paidBy ? { paid_by: paidBy } : {}), outcome, ...(skipped ? { skipped } : {}), ...verdict } };
403
404
  }
404
405
  // A served run a trigger started (learn/audit.ts auditableLaunch) is never audited: counted on the promotions read.
405
406
  const notAuditable = SERVED_PATHS.includes(path) && !auditableLaunch(launch);
@@ -133,7 +133,10 @@ function workflowLoop(specOf, deps) {
133
133
  takingDone = true;
134
134
  if (raising.takes.length === 0)
135
135
  return;
136
- const data = { capUsd: raising.capUsd ?? raising.state?.capUsd ?? 0, takes: raising.takes, ...(raising.state?.pause ? { pause: raising.state.pause } : {}) };
136
+ // The pause the raises answered: the one the newest raise was checked against (lastRaise), as the agentic loop records
137
+ // it. A retry of a raise taken before changes nothing, so it names that raise's pause, never a pause the run stands at
138
+ // since, which would read as answered and let the held step run into the same cap again.
139
+ const data = { capUsd: raising.capUsd ?? raising.state?.capUsd ?? 0, takes: raising.takes, ...(raising.state?.lastRaise?.pause ? { pause: raising.state.lastRaise.pause } : {}) };
137
140
  await append(journal, context, KINDS.raise, data, { ...(raising.resumes ? { run: { summary: null } } : {}), take: raising.takes });
138
141
  };
139
142
  /** Whether the run is paused by its journal: its newest pause entry has no resume entry after it. */
@@ -230,6 +233,15 @@ function workflowLoop(specOf, deps) {
230
233
  // A paused run (or one a pause row woke) parks again here, before any step runs; a resume goes on.
231
234
  if (await takePauses(claim, deps.journal(claim), BACKGROUND_CONTEXT))
232
235
  return { state: "parked" };
236
+ // Paused at its cap by its journal, and no raise of this claim resumed it (each refused, or a retry of one before): its
237
+ // pause stands, its budget entry unanswered, so it parks again on that entry with nothing written, before any step
238
+ // runs. Run, the held step would meet the same cap and write a second budget entry at it. Whatever the row said at the
239
+ // claim: a woken claim lost before its release leaves the row running with the pause unanswered. A person's stop goes
240
+ // on to end the run. A run whose root is not made yet (its first claim) has no pause to read.
241
+ const paused = async (journal) => Boolean(await journal.conversation(ROOT_CONVERSATION_ID, BACKGROUND_CONTEXT)) && (await raiseStateOf(journal, BACKGROUND_CONTEXT)).pause !== undefined;
242
+ if ((claim.from === "parked" || spec?.cap !== undefined) && !raising.resumes && stopReason === undefined && (await paused(deps.journal(claim)))) {
243
+ return { state: "parked", again: true };
244
+ }
233
245
  const hooks = {
234
246
  park: (refusal) => { heldRefusal ??= refusal; parkController.abort(); },
235
247
  paused: pauseInForce,
@@ -43,6 +43,10 @@ export type ScrubOptions = {
43
43
  /** The shell command whose output `text` is, when the caller knows it (a tool call's, ruling LVI): a command that reads
44
44
  * one file alone (`cat ~/.pgpass`) gives `path` when none is given, and an env command's output is a dump. */
45
45
  readonly command?: string;
46
+ /** `text` is lines flattened onto one, every run of blanks made a space (a run's title: runs-over-store.ts
47
+ * prepareLaunch): a prompt inside the line opens a command as a line's start would, and an env command's output
48
+ * runs on after it to the next prompt (env-dump). */
49
+ readonly flattened?: boolean;
46
50
  /** The homes the caller holds (rulings E, VII): a bare `/home/<user>` with no segment after it, or a Claude project
47
51
  * folder's `-home-<user>-` outside `.claude/projects/`, is cut only for one of these. When not given, this process's
48
52
  * user's home and $HOME. */
@@ -374,7 +374,7 @@ export function processHomes() {
374
374
  * finds in the view (one pass a view, on first ask). */
375
375
  function contextOf(view, opts) {
376
376
  let lint;
377
- return { held: heldOf(opts), source: view.source, homes: opts.homes ?? processHomes(), path: opts.path ?? commandReadPath(opts.command), command: opts.command, lint: () => (lint ??= lintFinds(view.text)), lines: lineBounds(view.text, ...view.decodedStrings, view.strings) };
377
+ return { held: heldOf(opts), source: view.source, homes: opts.homes ?? processHomes(), path: opts.path ?? commandReadPath(opts.command), command: opts.command, flattened: opts.flattened === true, lint: () => (lint ??= lintFinds(view.text)), lines: lineBounds(view.text, ...view.decodedStrings, view.strings) };
378
378
  }
379
379
  /** Whether a cut text holds nothing the scrub must cut: no known format the format rules still find in any view of any
380
380
  * chunk of it (each marker read as a blank, so a marker is never one), and no held value in any form (valueMatcher:
@@ -32,6 +32,8 @@ export type ScrubContext = {
32
32
  /** The shell command whose output the text is, when the caller knows it (ruling LVI): an env command's output is a
33
33
  * dump though the command stands in no line of the text. */
34
34
  readonly command?: string;
35
+ /** The text is lines flattened onto one (a run's title): a prompt mid-line opens a command (flatDumps). */
36
+ readonly flattened?: boolean;
35
37
  readonly lint: () => Promise<readonly LintFind[]>;
36
38
  /** Where the line holding an offset starts and ends: a line break, or a JSON string's own quote the view decoded
37
39
  * (ruling XXVIII). Absent: line breaks alone. */