@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
@@ -28,7 +28,8 @@ export type LedgerRow = {
28
28
  export declare const SPEND_KINDS: readonly ["compile", "check", "audit"];
29
29
  export type SpendKind = (typeof SPEND_KINDS)[number];
30
30
  /** One learning cost: the run whose end booked it (`runId`, with its `round` for a compile turn, 0 otherwise), the run
31
- * an audit's shadow audited (`ofRun`), the revision it is for (`workflow` at `digest`; a compile that kept no draft drafted
31
+ * an audit's shadow audited or a check's replay spent on the own model key of (`ofRun`: that run's learning, never its
32
+ * revision's; null for a replay on the server's key), the revision it is for (`workflow` at `digest`; a compile that kept no draft drafted
32
33
  * none: both null; one whose drafts failed their checks, the workflow alone) and its $ (null: unknown). */
33
34
  export type SpendRow = {
34
35
  readonly runId: string;
@@ -43,7 +44,9 @@ export type SpendRow = {
43
44
  /** What record() reads of an ended run: its row (its cost, the bound beside it, its metrics: the run-end classifier's
44
45
  * path, workflow and digest, runner/workflow-first.ts pathMetrics), every round its learning kept (learning_proposals)
45
46
  * and, for an audit's shadow run, the run its launch audits (`auditOf`: its end may name no audit, when it failed first).
46
- * `learns`: whether its launch learns (learnsOfLaunch); false, an end that named no path is the agent's. */
47
+ * `learns`: whether its launch learns (learnsOfLaunch); false, an end that named no path is the agent's. `replay`: a
48
+ * check's replay run's launch (replayOfLaunch), so one whose end named no replay (ended with no loop after a lost
49
+ * claim's loop spent, or failed first) is still its revision's check, on the key its launch names. */
47
50
  export type RunEnd = {
48
51
  readonly id: string;
49
52
  readonly agentId: string;
@@ -57,13 +60,19 @@ export type RunEnd = {
57
60
  }[];
58
61
  readonly auditOf?: string | null;
59
62
  readonly learns?: boolean;
63
+ readonly replay?: LaunchReplay;
60
64
  };
61
- /** RunEnd.auditOf of run `runId` from its stored launch body (`body`, undefined with none): the run its launch audits
62
- * (null when it names none) for an audit's shadow run (learn/audit.ts SHADOW_PREFIX "audit."), undefined for any other. */
63
- export declare const auditOfLaunch: (runId: string, body: unknown) => string | null | undefined;
64
- /** RunEnd.learns from a run's stored launch body (`body`, undefined with none): whether it holds a learning start, as
65
- * run-launch.ts learningStartOfStored reads one. No launch reads as a run that does not learn. */
66
- export declare const learnsOfLaunch: (body: unknown) => boolean;
65
+ /** What a replay run's launch says of its check (run-launch.ts replayBody): the revision it checks and, on a run's own
66
+ * model key, that run (`paid_by`). */
67
+ export type LaunchReplay = {
68
+ readonly workflow: string | null;
69
+ readonly digest: string | null;
70
+ readonly paidBy: string | null;
71
+ };
72
+ /** The RunEnd of ended run `run`, its kept `rounds` and its stored launch body (`body`, undefined with none): what every
73
+ * reader of an end records, one rule (store/sqlite/run-patch.ts recordLedger, which writes the ledger; store-reads/
74
+ * learning.ts runEndOf, which reads a run at another figure or with no row yet). */
75
+ export declare const runEndOfLaunch: (run: Pick<RunEnd, "id" | "agentId" | "startedAt" | "costUsd" | "costAtMostUsd" | "metrics">, rounds: RunEnd["rounds"], body: unknown) => RunEnd;
67
76
  /** What a kept round says of its job as it answered (runner/reflect-hook.ts): when, what the job had cost by then, and
68
77
  * what looking back cost after it. */
69
78
  export type Answered = {
@@ -88,8 +97,8 @@ export declare function lookedOf(proposals: readonly unknown[], rowUsd: number |
88
97
  /** The ledger row and spend rows a run's end writes, from its row and its kept rounds (RunEnd). The job's own $ is its
89
98
  * row's cost less every look-back, never under what it had cost when it answered (a later turn's spend is the job's
90
99
  * too); its row's cost for a run that did not look back. Its compile turns are spend rows of the revision each drafted.
91
- * A replay run's cost is its revision's check, and an audit's shadow run's the run it audits: a spend row each, beside
92
- * its own ledger row. */
100
+ * A replay run's cost is its revision's check (one on a run's own model key, `replay.paid_by`, that run's), and an
101
+ * audit's shadow run's the run it audits: a spend row each, beside its own ledger row. */
93
102
  export declare function record(end: RunEnd): {
94
103
  row: LedgerRow;
95
104
  spend: SpendRow[];
@@ -97,12 +106,15 @@ export declare function record(end: RunEnd): {
97
106
  /** An audit's shadow run of a run, as the reader finds it: `open` while it is queued or running (its cost not known yet),
98
107
  * `ended` once it ended, stopped or failed. A run with none has no entry. */
99
108
  export type Shadow = "open" | "ended";
100
- /** A run's figures (figuresOf), null when unknown: `series_*` are the cost series', the rest GET /runs/{id}'s. */
109
+ /** A run's figures (figuresOf), null when unknown: `series_*` are the cost series', the rest GET /runs/{id}'s.
110
+ * `check_usd` is the replays of a check it started on its own model key (`ofRun` check rows): its learning, as its
111
+ * shadow is, never their revision's; 0 for none. */
101
112
  export type RunFigures = {
102
113
  readonly usd: number | null;
103
114
  readonly compile_usd: number | null;
104
115
  readonly followup_usd: number | null;
105
116
  readonly shadow_usd: number | null;
117
+ readonly check_usd: number | null;
106
118
  readonly share_usd: number | null;
107
119
  readonly series_learning_usd: number | null;
108
120
  readonly series_total_usd: number | null;
@@ -110,17 +122,22 @@ export type RunFigures = {
110
122
  readonly all_in_usd: number | null;
111
123
  };
112
124
  /** One run's figures (RunFigures) from its row and the parts the spend rows give it (its compile turns, its shadow's
113
- * cost, its share): the one formula every reader of a run's cost takes. */
125
+ * cost, its own-key check's, 0 when not given, its share): the one formula every reader of a run's cost takes. */
114
126
  export declare function figuresOf(row: Pick<LedgerRow, "path" | "jobUsd" | "lookBackUsd">, parts: {
115
127
  readonly compile: number | null;
116
128
  readonly shadow: number | null;
129
+ readonly check?: number | null;
117
130
  readonly share: number | null;
118
131
  }): RunFigures;
119
- /** The spend rows read by run: each run's compile turns (null once one is unknown) and each audited run's shadow cost. */
132
+ /** The spend rows read by run: each run's compile turns (null once one is unknown), each audited run's shadow cost, and
133
+ * each run's own-key check (the replays that spent on its key, ownCheck). */
120
134
  export declare function spendByRun(spend: readonly SpendRow[]): {
121
135
  compile: Map<string, number | null>;
122
136
  audit: Map<string, number | null>;
137
+ check: Map<string, number | null>;
123
138
  };
139
+ /** A check's spend row on a run's own model key (record: `replay.paid_by`): that run's learning, never its revision's. */
140
+ export declare const ownCheck: (one: Pick<SpendRow, "kind" | "ofRun">) => boolean;
124
141
  /** An audit's shadow run as its cost reads: `ended` once it is final (FINAL_STATES), `usd` its cost (null while unknown
125
142
  * or only a bound). */
126
143
  export type ShadowCost = {
@@ -148,6 +165,9 @@ export type LedgerRead = {
148
165
  readonly rows: readonly LedgerRow[];
149
166
  readonly spend: readonly SpendRow[];
150
167
  readonly shadows: ReadonlyMap<string, Shadow>;
168
+ /** The runs a replay of whose own-key check is still at work: each one's check, learning and all-in unknown until every
169
+ * replay of it ended (as runAllInOverStore reads it), never a settled $0. Absent: none. */
170
+ readonly openChecks?: ReadonlySet<string>;
151
171
  readonly learning?: ReadonlySet<string>;
152
172
  readonly revisions: readonly RevisionAt[];
153
173
  readonly compileAfter: number;
@@ -165,9 +185,10 @@ export type Summarized = {
165
185
  * and the rows whose end named no path (`unknown_path_runs`, left out of all of it). Every sum is over every run.
166
186
  *
167
187
  * A revision is its workflow and its digest, never the digest alone: two workflows of the same text share a digest, and
168
- * each pays its own way. Its spend is its compile turns and its check's replay runs (spend rows of its workflow at its
169
- * digest), whether or not a record names it or the records were trimmed: one no record names follows the ones that do,
188
+ * each pays its own way. Its spend is its compile turns and its check's replay runs on the server's key (spend rows of
189
+ * its workflow at its digest; a replay on a run's own key is that run's learning, its `check_usd`), whether or not a record names it or the records were trimmed: one no record names follows the ones that do,
170
190
  * at `compileAfter`, `checking` while it is its workflow's newest spend, else `stopped`. It is spread over its first K
171
191
  * served runs (amortize). What no run carries is the booked total less every run's all-in, unknown while any run's
172
- * figures are. */
192
+ * figures are. A replay on a run's own key, like a shadow, is no run of the series: its cost is that run's, counted
193
+ * once. */
173
194
  export declare function summarize(read: LedgerRead): Summarized;
@@ -16,10 +16,30 @@ const textOrNull = (value) => (typeof value === "string" ? value : null);
16
16
  const objectOf = (value) => (value && typeof value === "object" && !Array.isArray(value) ? value : {});
17
17
  /** RunEnd.auditOf of run `runId` from its stored launch body (`body`, undefined with none): the run its launch audits
18
18
  * (null when it names none) for an audit's shadow run (learn/audit.ts SHADOW_PREFIX "audit."), undefined for any other. */
19
- export const auditOfLaunch = (runId, body) => runId.startsWith("audit.") ? textOrNull(objectOf(objectOf(body).audit).of) : undefined;
19
+ const auditOfLaunch = (runId, body) => runId.startsWith("audit.") ? textOrNull(objectOf(objectOf(body).audit).of) : undefined;
20
+ /** RunEnd.replay from a run's stored launch body (`body`, undefined with none): its replay, undefined for a run that is
21
+ * no check's replay. */
22
+ const replayOfLaunch = (body) => {
23
+ const replay = objectOf(body).replay;
24
+ if (!replay || typeof replay !== "object" || Array.isArray(replay))
25
+ return undefined;
26
+ const { workflow, digest, paid_by } = replay;
27
+ return { workflow: textOrNull(workflow), digest: textOrNull(digest), paidBy: textOrNull(paid_by) };
28
+ };
20
29
  /** RunEnd.learns from a run's stored launch body (`body`, undefined with none): whether it holds a learning start, as
21
30
  * run-launch.ts learningStartOfStored reads one. No launch reads as a run that does not learn. */
22
- export const learnsOfLaunch = (body) => objectOf(body).learning !== undefined;
31
+ const learnsOfLaunch = (body) => objectOf(body).learning !== undefined;
32
+ /** The RunEnd of ended run `run`, its kept `rounds` and its stored launch body (`body`, undefined with none): what every
33
+ * reader of an end records, one rule (store/sqlite/run-patch.ts recordLedger, which writes the ledger; store-reads/
34
+ * learning.ts runEndOf, which reads a run at another figure or with no row yet). */
35
+ export const runEndOfLaunch = (run, rounds, body) => {
36
+ const auditOf = auditOfLaunch(run.id, body);
37
+ const replay = replayOfLaunch(body);
38
+ return {
39
+ id: run.id, agentId: run.agentId, startedAt: run.startedAt, costUsd: run.costUsd, costAtMostUsd: run.costAtMostUsd, metrics: run.metrics, rounds,
40
+ learns: learnsOfLaunch(body), ...(auditOf === undefined ? {} : { auditOf }), ...(replay ? { replay } : {}),
41
+ };
42
+ };
23
43
  /** A sum of parts, null once one is unknown; 0 for none. */
24
44
  const sumOf = (parts) => (parts.some((one) => one === null) ? null : noiseOff(parts.reduce((total, one) => total + one, 0)));
25
45
  /** A kept round's Answered; undefined for one that never answered. */
@@ -74,8 +94,8 @@ function compilesIn(rounds) {
74
94
  /** The ledger row and spend rows a run's end writes, from its row and its kept rounds (RunEnd). The job's own $ is its
75
95
  * row's cost less every look-back, never under what it had cost when it answered (a later turn's spend is the job's
76
96
  * too); its row's cost for a run that did not look back. Its compile turns are spend rows of the revision each drafted.
77
- * A replay run's cost is its revision's check, and an audit's shadow run's the run it audits: a spend row each, beside
78
- * its own ledger row. */
97
+ * A replay run's cost is its revision's check (one on a run's own model key, `replay.paid_by`, that run's), and an
98
+ * audit's shadow run's the run it audits: a spend row each, beside its own ledger row. */
79
99
  export function record(end) {
80
100
  const metrics = objectOf(end.metrics);
81
101
  const cost = typeof end.costAtMostUsd === "number" ? "at_most" : end.costUsd === null ? "unknown" : "known";
@@ -92,10 +112,12 @@ export function record(end) {
92
112
  // revision's runs out): a run whose end named no path is the agent's when its launch does not learn; one that learns
93
113
  // and named none is unknown (null).
94
114
  const named = RUN_PATHS.includes(metrics.path) ? metrics.path : null;
95
- const path = audited ? "audit" : named ?? (end.learns === false ? "agent" : null);
115
+ const path = audited ? "audit" : named ?? (end.replay ? "replay" : end.learns === false ? "agent" : null);
96
116
  const audit = objectOf(metrics.audit);
97
- const workflow = textOrNull(audited ? audit.workflow : metrics.workflow);
98
- const digest = textOrNull(audited ? audit.digest : metrics.workflow_digest);
117
+ // A replay whose end named none of its check is read from its launch (RunEnd.replay).
118
+ const launched = path === "replay" ? end.replay : undefined;
119
+ const workflow = textOrNull(audited ? audit.workflow : metrics.workflow) ?? launched?.workflow ?? null;
120
+ const digest = textOrNull(audited ? audit.digest : metrics.workflow_digest) ?? launched?.digest ?? null;
99
121
  // A hand-back a restart cut (pathMetrics workflow_cut) is `cut`, never the workflow's own `back`.
100
122
  const cut = path === "handed_back" && metrics.workflow_cut === true;
101
123
  const notServed = cut ? "cut" : NOT_SERVED.includes(metrics.not_served) ? metrics.not_served : null;
@@ -106,39 +128,46 @@ export function record(end) {
106
128
  const base = { runId: end.id, agentId: end.agentId };
107
129
  const spend = compilesIn(rounds).map((one) => ({ ...base, round: one.round, kind: "compile", ofRun: null, workflow: one.workflow, digest: one.digest, usd: one.usd }));
108
130
  if (path === "replay")
109
- spend.push({ ...base, round: 0, kind: "check", ofRun: null, workflow, digest, usd: rowUsd });
131
+ spend.push({ ...base, round: 0, kind: "check", ofRun: textOrNull(objectOf(metrics.replay).paid_by) ?? launched?.paidBy ?? null, workflow, digest, usd: rowUsd });
110
132
  if (audited)
111
133
  spend.push({ ...base, round: 0, kind: "audit", ofRun: textOrNull(audit.of) ?? end.auditOf ?? null, workflow, digest, usd: rowUsd });
112
134
  return { row, spend };
113
135
  }
114
136
  /** One run's figures (RunFigures) from its row and the parts the spend rows give it (its compile turns, its shadow's
115
- * cost, its share): the one formula every reader of a run's cost takes. */
137
+ * cost, its own-key check's, 0 when not given, its share): the one formula every reader of a run's cost takes. */
116
138
  export function figuresOf(row, parts) {
117
139
  const { compile, shadow, share } = parts;
140
+ const check = parts.check === undefined ? 0 : parts.check;
118
141
  const back = row.lookBackUsd;
119
142
  const followup = back === null || compile === null ? null : noiseOff(Math.max(0, back - compile));
120
- const seriesLearning = sumOf([back, shadow]);
143
+ const seriesLearning = sumOf([back, shadow, check]);
121
144
  const learns = row.path !== "replay" && row.path !== "audit";
122
- const learning = learns ? sumOf([followup, shadow, share]) : 0;
145
+ const learning = learns ? sumOf([followup, shadow, check, share]) : 0;
123
146
  return {
124
- usd: row.jobUsd, compile_usd: compile, followup_usd: followup, shadow_usd: shadow, share_usd: learns ? share : 0,
147
+ usd: row.jobUsd, compile_usd: compile, followup_usd: followup, shadow_usd: shadow, check_usd: check, share_usd: learns ? share : 0,
125
148
  series_learning_usd: seriesLearning, series_total_usd: sumOf([row.jobUsd, seriesLearning]),
126
149
  learning_usd: learning, all_in_usd: learns ? sumOf([row.jobUsd, learning]) : 0,
127
150
  };
128
151
  }
129
- /** The spend rows read by run: each run's compile turns (null once one is unknown) and each audited run's shadow cost. */
152
+ /** The spend rows read by run: each run's compile turns (null once one is unknown), each audited run's shadow cost, and
153
+ * each run's own-key check (the replays that spent on its key, ownCheck). */
130
154
  export function spendByRun(spend) {
131
155
  const compile = new Map();
132
156
  const audit = new Map();
157
+ const check = new Map();
133
158
  const add = (map, key, usd) => map.set(key, map.has(key) ? sumOf([map.get(key), usd]) : usd);
134
159
  for (const one of spend) {
135
160
  if (one.kind === "compile")
136
161
  add(compile, one.runId, one.usd);
137
162
  else if (one.kind === "audit" && one.ofRun !== null)
138
163
  add(audit, one.ofRun, one.usd);
164
+ else if (ownCheck(one))
165
+ add(check, one.ofRun, one.usd);
139
166
  }
140
- return { compile, audit };
167
+ return { compile, audit, check };
141
168
  }
169
+ /** A check's spend row on a run's own model key (record: `replay.paid_by`): that run's learning, never its revision's. */
170
+ export const ownCheck = (one) => one.kind === "check" && one.ofRun !== null;
142
171
  /** A shadow run's row as a ShadowCost. */
143
172
  export const shadowOfRun = (run) => ({ ended: FINAL_STATES.includes(run.state), usd: typeof run.costAtMostUsd === "number" ? null : run.costUsd });
144
173
  /** A run's shadow cost, the one rule the ledger, GET /stats and analytics read: 0 with no shadow (undefined); unknown
@@ -157,19 +186,21 @@ export function shadowCostOf(runId, audit, shadows) {
157
186
  * and the rows whose end named no path (`unknown_path_runs`, left out of all of it). Every sum is over every run.
158
187
  *
159
188
  * A revision is its workflow and its digest, never the digest alone: two workflows of the same text share a digest, and
160
- * each pays its own way. Its spend is its compile turns and its check's replay runs (spend rows of its workflow at its
161
- * digest), whether or not a record names it or the records were trimmed: one no record names follows the ones that do,
189
+ * each pays its own way. Its spend is its compile turns and its check's replay runs on the server's key (spend rows of
190
+ * its workflow at its digest; a replay on a run's own key is that run's learning, its `check_usd`), whether or not a record names it or the records were trimmed: one no record names follows the ones that do,
162
191
  * at `compileAfter`, `checking` while it is its workflow's newest spend, else `stopped`. It is spread over its first K
163
192
  * served runs (amortize). What no run carries is the booked total less every run's all-in, unknown while any run's
164
- * figures are. */
193
+ * figures are. A replay on a run's own key, like a shadow, is no run of the series: its cost is that run's, counted
194
+ * once. */
165
195
  export function summarize(read) {
166
- const ordered = read.rows.filter((row) => row.path !== null && row.path !== "audit").sort((a, b) => a.startedAt - b.startedAt || (a.runId < b.runId ? -1 : a.runId > b.runId ? 1 : 0));
196
+ const paidByRun = new Set(read.spend.filter(ownCheck).map((one) => one.runId));
197
+ const ordered = read.rows.filter((row) => row.path !== null && row.path !== "audit" && !paidByRun.has(row.runId)).sort((a, b) => a.startedAt - b.startedAt || (a.runId < b.runId ? -1 : a.runId > b.runId ? 1 : 0));
167
198
  const unknownPath = read.rows.filter((row) => row.path === null).length;
168
199
  const place = new Map(ordered.map((row, at) => [row.runId, at]));
169
200
  const learns = (runId) => place.has(runId) && (read.learning?.has(runId) ?? true);
170
- const spend = read.spend.filter((one) => (one.kind === "audit" ? place.has(one.ofRun ?? "") : learns(one.runId)));
171
- const { compile, audit } = spendByRun(spend);
172
- const partsOf = (row, share) => ({ compile: compile.has(row.runId) ? compile.get(row.runId) : 0, shadow: shadowCostOf(row.runId, audit, read.shadows), share });
201
+ const spend = read.spend.filter((one) => (one.kind === "audit" || ownCheck(one) ? place.has(one.ofRun ?? "") : learns(one.runId)));
202
+ const { compile, audit, check } = spendByRun(spend);
203
+ const partsOf = (row, share) => ({ compile: compile.has(row.runId) ? compile.get(row.runId) : 0, shadow: shadowCostOf(row.runId, audit, read.shadows), check: read.openChecks?.has(row.runId) ? null : check.has(row.runId) ? check.get(row.runId) : 0, share });
173
204
  // One numbering, the bill's: the runs that do a job, 1 the first; a replay checks a revision and has none.
174
205
  let jobs = 0;
175
206
  const series = ordered.map((row) => {
@@ -181,7 +212,7 @@ export function summarize(read) {
181
212
  digest: path === "agent" || row.workflow === null ? null : row.digest,
182
213
  audited: read.shadows.has(row.runId) || audit.has(row.runId),
183
214
  cost_usd: figures.usd, cost_upper_bound: row.cost === "at_most", learning_usd: figures.series_learning_usd, total_usd: figures.series_total_usd,
184
- compile_usd: figures.compile_usd, followup_usd: figures.followup_usd, shadow_usd: figures.shadow_usd, share_usd: 0, not_served: row.notServed,
215
+ compile_usd: figures.compile_usd, followup_usd: figures.followup_usd, shadow_usd: figures.shadow_usd, check_usd: figures.check_usd, share_usd: 0, not_served: row.notServed,
185
216
  };
186
217
  });
187
218
  const summary = costSummary(tookOverOf(series), null, new Set(series.flatMap((run) => (run.not_served === "cut" ? [run.run_id] : []))));
@@ -190,8 +221,9 @@ export function summarize(read) {
190
221
  const key = (workflow, digest) => `${workflow}\0${digest}`;
191
222
  const parts = new Map();
192
223
  const newest = new Map();
193
- // An audit's row is the run it audits' (its shadow is no run of the series): it is no revision's spend.
194
- for (const one of spend.filter((each) => each.kind !== "audit").sort((a, b) => place.get(a.runId) - place.get(b.runId) || a.round - b.round)) {
224
+ // An audit's row is the run it audits' (its shadow is no run of the series), and a check's on a run's own key that
225
+ // run's: neither is a revision's spend.
226
+ for (const one of spend.filter((each) => each.kind !== "audit" && !ownCheck(each)).sort((a, b) => place.get(a.runId) - place.get(b.runId) || a.round - b.round)) {
195
227
  if (one.workflow === null || one.digest === null)
196
228
  continue;
197
229
  const at = key(one.workflow, one.digest);
@@ -213,11 +213,14 @@ export declare const checkShares: (score: {
213
213
  agreement: number;
214
214
  alone: number;
215
215
  };
216
- /** What a replay's runs are launched with (PromotionRecord.launch). */
216
+ /** What a replay's runs are launched with (PromotionRecord.launch). `keyed`: its runs spend on run `handed_from`'s own
217
+ * model key, a sealed copy of it handed to each (store/seal.ts sealHandedLaunch), each capped at its share of what that
218
+ * run's cap left at its end (runner/promotion.ts keyedCapOf); never created again once that run's claim is gone. */
217
219
  export interface ReplayLaunch {
218
220
  readonly revision: string;
219
221
  readonly body: unknown;
220
222
  readonly handed_from?: string;
223
+ readonly keyed?: true;
221
224
  }
222
225
  /** A tool that stopped a replay's inputs (each a skipped_write row): its catalog name, how many inputs it stopped, and
223
226
  * whether it is an MCP tool its server listed with no readOnlyHint (`no_read_only_hint`: replay may only lack the hint,
@@ -60,12 +60,14 @@ export type CostRun = {
60
60
  learning_usd: number | null;
61
61
  total_usd: number | null;
62
62
  /** `learning_usd`'s parts, each null when unknown: its own compile turns (`compile_usd`, which GET /runs/{id} charges
63
- * to the revision they drafted instead), its follow-up rounds' turns (`followup_usd`) and its audit's shadow run
64
- * (`shadow_usd`). `share_usd`: its share of its revision's compile and check (amortize), which GET /runs/{id}'s
65
- * `learning_usd` carries in place of `compile_usd`. */
63
+ * to the revision they drafted instead), its follow-up rounds' turns (`followup_usd`), its audit's shadow run
64
+ * (`shadow_usd`) and the replays of a check it started on its own model key (`check_usd`). `share_usd`: its share of
65
+ * its revision's compile and check (amortize), which GET /runs/{id}'s `learning_usd` carries in place of
66
+ * `compile_usd`. */
66
67
  compile_usd: number | null;
67
68
  followup_usd: number | null;
68
69
  shadow_usd: number | null;
70
+ check_usd: number | null;
69
71
  share_usd: number | null;
70
72
  /** Why a learned workflow did not serve it alone (NOT_SERVED), null when nothing says. */
71
73
  not_served: NotServed | null;
@@ -44,11 +44,13 @@ export async function learningModelOf(env, revision, options = {}) {
44
44
  return notReady(model, entry.ownKeys?.some(key => !env[key]) ? "key" : "model", refused.reason);
45
45
  return { location: "server", ready: true, model, needs: null, reason: null };
46
46
  }
47
- const needsServerKey = !env[FAUX_ENV] && (!revision || body.sdk
48
- ? noServerKeyFor(env, "Background learning") !== undefined
49
- : serverKeyMissing(env, { kind: "agentic", model: choice.model }));
50
- if (needsServerKey)
51
- return notReady(model, "key", "Add a server-owned model gateway key in Settings → API Keys. Background learning cannot use a caller's per-run key.");
47
+ // A managed agent's learning runs on each run's own model key where the server holds none for its gateway: its compile
48
+ // turn in the run's claim, its check's replays and its audit's shadow on a sealed copy of that key (every run of it
49
+ // brings one: a start without one is refused). Only an SDK agent's compile, tied to no run, needs the server's key.
50
+ if (!env[FAUX_ENV] && revision && !body.sdk && serverKeyMissing(env, { kind: "agentic", model: choice.model }))
51
+ return { location: "server", ready: true, model, needs: null, reason: "Compiles, checks and audits on each run's own model key (`model_key`): this server holds no gateway key of its own. A run's check and audit runs start at its end, within what its cap leaves, and the run lists them in `learning_work` until they end." };
52
+ if (!env[FAUX_ENV] && (!revision || body.sdk) && noServerKeyFor(env, "Background learning") !== undefined)
53
+ return notReady(model, "key", "Add a server-owned model gateway key in Settings → API Keys. A connected agent's background learning is tied to no run, so it cannot use a run's own key.");
52
54
  // Managed agents compile inside their own harness session, with that harness's model and authentication.
53
55
  // SDK agents compile separately through pi's server route. A native application's sign-in is never copied here.
54
56
  try {
@@ -0,0 +1,69 @@
1
+ import { type Settings, type Store } from "./store/store.js";
2
+ /** The smallest cap a run is started with: a child its run's cap leaves less than this for is dropped (`no_budget`). */
3
+ export declare const RUN_CAP_MIN_USD = 0.01;
4
+ /** The most a learning child (a check's replay run, an audit's shadow run) may take from its start: its runner cancels one
5
+ * still at work then. A replay runs one learned workflow on one input and a shadow one agent turn, minutes at most;
6
+ * half an hour leaves room for a slow model and a queue, and ends inside a check's own deadline (promotion.ts
7
+ * REPLAY_DEADLINE_MS), so a cancelled replay is one failed input of its check. A tuning parameter: this one name sets it. */
8
+ export declare const LEARNING_CHILD_MS: number;
9
+ /** Work a claim holding its run's own key starts at its run's end instead of its start (a learned workflow's check):
10
+ * queued by its claim (`later`), run by its end-of-run step after the step and before its audit (runner/audit.ts
11
+ * withAudit), when what the run's cap leaves is known. A claim cut short, or lost, runs none: the next claim decides
12
+ * again. */
13
+ export type AtRunEnd = {
14
+ readonly later: (start: () => Promise<void>) => void;
15
+ readonly run: () => Promise<void>;
16
+ };
17
+ /** One claim's AtRunEnd, each queued start run once, in order; one that throws is logged and the next one runs. */
18
+ export declare function atRunEnd(log: (line: string) => void): AtRunEnd;
19
+ /** The settings row that names the learning work run `runId` started. */
20
+ export declare const learningWorkKey: (runId: string) => string;
21
+ /** One piece of learning work a run started beside its turn: a run it created (`run`), or one that dropped before it was
22
+ * created (`run` null, `dropped` why). `keyed`: the child spends on the run's own model key. `at`: when it was started or
23
+ * dropped (ms). */
24
+ export type LearningChild = {
25
+ readonly run: string | null;
26
+ readonly kind: "replay" | "shadow";
27
+ readonly at: number;
28
+ readonly keyed?: true;
29
+ readonly dropped?: "no_budget";
30
+ };
31
+ /** The `learning_work` field of a run's view. */
32
+ export type LearningWork = {
33
+ readonly state: "none" | "running" | "ended";
34
+ readonly runs: string[];
35
+ readonly ended_at: string | null;
36
+ readonly deadline_at: string | null;
37
+ };
38
+ /** The learning work run `runId` started, in the order it started it; none for a run that started none. */
39
+ export declare function learningChildrenOf(settings: Pick<Settings, "get">, runId: string): Promise<LearningChild[]>;
40
+ /** Appends `child` to the learning work run `runId` started, and moves the run's learning deadline to the child's start +
41
+ * LEARNING_CHILD_MS when later (a dropped child spends nothing and moves nothing), in one guarded write (a
42
+ * compare-and-set, tried again while another write lands first). A child already named is not named twice. Written
43
+ * before the child is created. */
44
+ export declare function noteLearningChild(settings: Pick<Settings, "get" | "putIfAbsent" | "replaceIf">, runId: string, child: LearningChild): Promise<void>;
45
+ /** Moves run `runId`'s learning deadline to `until` (ms) when later, never earlier, in one guarded write: its compile
46
+ * turn's start + its timeout, written before the turn asks the model (runner/learning-end.ts). */
47
+ export declare function noteLearningDeadline(settings: Pick<Settings, "get" | "putIfAbsent" | "replaceIf">, runId: string, until: number): Promise<void>;
48
+ /** What the replay runs run `runId` started on its own model key took beside it: each at its cost once it ended, at its
49
+ * own cap while it has not (the most it may take) or when it ended at a cost not known; 0 for none. Null: unknown (one
50
+ * with neither a cost nor a cap). Its audit's shadow is counted apart (learning-end.ts shadowBesideOf). */
51
+ export declare function keyedBesideOf(store: Pick<Store, "runs" | "settings">, runId: string): Promise<number | null>;
52
+ /** What a run's view knows of its own learning, beside its children: whether it learns at all (a learning start, and no
53
+ * replay or shadow run), whether its end-of-run (compile) turn is going now, whether one began, and when its learning
54
+ * ended (its learning end's time, else its end's). `compileBy`: while it looks back, the most its compile turn may take
55
+ * as the view knows it from the job's end (that end + the turn's timeout; the turn's own start, later, is kept in the row
56
+ * by noteLearningDeadline), else null. */
57
+ export type OwnLearning = {
58
+ readonly learns: boolean;
59
+ readonly compiling: boolean;
60
+ readonly compiled: boolean;
61
+ readonly endedAt: number | null;
62
+ readonly compileBy: number | null;
63
+ };
64
+ /** Run `runId`'s `learning_work`: `running` while its compile turn goes or a child it started has not ended (`runs`, the
65
+ * child run ids not ended), `ended` once every piece it started has finished or dropped (`ended_at`, the last one's end),
66
+ * else `none`. A child whose row is gone or was never created counts as ended at the time it was named: its own end, or
67
+ * its absence, settles it, so the state cannot stay `running` forever. `deadline_at` while running: the later of the
68
+ * row's deadline and the compile turn's bound (`own.compileBy`); null otherwise. */
69
+ export declare function learningWorkOf(store: Pick<Store, "runs" | "settings">, runId: string, own: OwnLearning): Promise<LearningWork>;
@@ -0,0 +1,148 @@
1
+ // The learning work a run started beside its own turn, and the run view's `learning_work` (GET /v2/runs/{run_id}): what
2
+ // its caller reads to know when the run's own model key may be revoked, with no timer.
3
+ //
4
+ // A run's claim writes one settings row per run (learningWorkKey), appending each child it starts BEFORE the child is
5
+ // created: its learned workflow's check replay runs (runner/promotion.ts) and its audit's shadow run (runner/audit.ts), so
6
+ // no child exists that its run does not name. A child that drops before it starts (a check or a shadow its run's cap
7
+ // leaves no room for) is appended as dropped, so the run reads `ended`, never `none`, once it ends. The row holds run ids,
8
+ // kinds and times, nothing of a run's text or secrets, and goes with the run's purge (server.ts forgetRun).
9
+ //
10
+ // A child that spends on its run's own model key (`keyed`, resealed into its launch from the claiming run's) counts against
11
+ // that run's cap beside its own spend (keyedBesideOf, learning-end.ts capSpendOf): at its cost once it ended, at its own
12
+ // cap while it has not, so the run, its compile turn and its children never spend past the cap together.
13
+ //
14
+ // The row also keeps the run's learning deadline (`deadline`, ms): the latest instant any learning work it started may
15
+ // still spend, its caller's key-expiry backstop for a lost signal (the view's `deadline_at`). Each started child moves it
16
+ // to its start + LEARNING_CHILD_MS in the write that names it, and the compile turn's start to its start + its timeout
17
+ // (noteLearningDeadline), never earlier. The bound on a child is enforced: its launch carries its deadline (run-launch.ts
18
+ // Replay.deadlineAt), and the runner holding it cancels it there as a person's cancel is (runner.ts).
19
+ import { FINAL_STATES } from "./store/store.js";
20
+ import { readLaunchBody } from "./run-launch.js";
21
+ /** The smallest cap a run is started with: a child its run's cap leaves less than this for is dropped (`no_budget`). */
22
+ export const RUN_CAP_MIN_USD = 0.01;
23
+ /** The most a learning child (a check's replay run, an audit's shadow run) may take from its start: its runner cancels one
24
+ * still at work then. A replay runs one learned workflow on one input and a shadow one agent turn, minutes at most;
25
+ * half an hour leaves room for a slow model and a queue, and ends inside a check's own deadline (promotion.ts
26
+ * REPLAY_DEADLINE_MS), so a cancelled replay is one failed input of its check. A tuning parameter: this one name sets it. */
27
+ export const LEARNING_CHILD_MS = 30 * 60_000;
28
+ /** One claim's AtRunEnd, each queued start run once, in order; one that throws is logged and the next one runs. */
29
+ export function atRunEnd(log) {
30
+ const queued = [];
31
+ return {
32
+ later: (start) => void queued.push(start),
33
+ run: async () => {
34
+ for (let start = queued.shift(); start; start = queued.shift()) {
35
+ await start().catch((error) => log(`workflow-first: learning work at this run's end did not start (${error?.message ?? error})`));
36
+ }
37
+ },
38
+ };
39
+ }
40
+ /** The settings row that names the learning work run `runId` started. */
41
+ export const learningWorkKey = (runId) => `learning_work:${runId}`;
42
+ const childOf = (value) => {
43
+ if (typeof value !== "object" || value === null)
44
+ return undefined;
45
+ const one = value;
46
+ if (!(typeof one.run === "string" || one.run === null) || (one.kind !== "replay" && one.kind !== "shadow") || typeof one.at !== "number")
47
+ return undefined;
48
+ return { run: one.run, kind: one.kind, at: one.at, ...(one.keyed === true ? { keyed: true } : {}), ...(one.dropped === "no_budget" ? { dropped: "no_budget" } : {}) };
49
+ };
50
+ /** The learning work run `runId` started, in the order it started it; none for a run that started none. */
51
+ export async function learningChildrenOf(settings, runId) {
52
+ const saved = (await settings.get(learningWorkKey(runId)));
53
+ return Array.isArray(saved?.children) ? saved.children.map(childOf).filter((one) => one !== undefined) : [];
54
+ }
55
+ /** Run `runId`'s learning deadline as its row keeps it (ms), or undefined when it keeps none. */
56
+ const deadlineIn = (saved) => {
57
+ const deadline = saved?.deadline;
58
+ return typeof deadline === "number" && Number.isFinite(deadline) ? deadline : undefined;
59
+ };
60
+ /** The later of a kept deadline and a new bound: a deadline only moves later. */
61
+ const later = (kept, bound) => (kept === undefined ? bound : bound === undefined ? kept : Math.max(kept, bound));
62
+ /** Appends `child` to the learning work run `runId` started, and moves the run's learning deadline to the child's start +
63
+ * LEARNING_CHILD_MS when later (a dropped child spends nothing and moves nothing), in one guarded write (a
64
+ * compare-and-set, tried again while another write lands first). A child already named is not named twice. Written
65
+ * before the child is created. */
66
+ export async function noteLearningChild(settings, runId, child) {
67
+ await changeWork(settings, runId, (children, deadline) => {
68
+ if (child.run !== null && children.some((one) => one.run === child.run))
69
+ return undefined;
70
+ return { children: [...children, child], deadline: later(deadline, child.run === null ? undefined : child.at + LEARNING_CHILD_MS) };
71
+ });
72
+ }
73
+ /** Moves run `runId`'s learning deadline to `until` (ms) when later, never earlier, in one guarded write: its compile
74
+ * turn's start + its timeout, written before the turn asks the model (runner/learning-end.ts). */
75
+ export async function noteLearningDeadline(settings, runId, until) {
76
+ await changeWork(settings, runId, (children, deadline) => (deadline !== undefined && deadline >= until ? undefined : { children, deadline: until }));
77
+ }
78
+ /** One guarded write of run `runId`'s learning work row: `change` given its children and deadline, the row it writes, or
79
+ * undefined for none (nothing to change). */
80
+ async function changeWork(settings, runId, change) {
81
+ const key = learningWorkKey(runId);
82
+ for (let tries = 0; tries < 20; tries++) {
83
+ const was = await settings.get(key);
84
+ const children = await learningChildrenOf({ get: async () => was }, runId);
85
+ const next = change(children, deadlineIn(was));
86
+ if (!next)
87
+ return;
88
+ const value = { children: next.children, ...(next.deadline !== undefined ? { deadline: next.deadline } : {}) };
89
+ if (was === undefined) {
90
+ const saved = await settings.putIfAbsent(key, value);
91
+ if (JSON.stringify(saved) === JSON.stringify(value))
92
+ return;
93
+ continue;
94
+ }
95
+ if (await settings.replaceIf(key, was, value))
96
+ return;
97
+ }
98
+ throw new Error(`${key} kept changing under this write; try again`);
99
+ }
100
+ const figure = (usd) => typeof usd === "number" && Number.isFinite(usd) && usd >= 0;
101
+ /** What the replay runs run `runId` started on its own model key took beside it: each at its cost once it ended, at its
102
+ * own cap while it has not (the most it may take) or when it ended at a cost not known; 0 for none. Null: unknown (one
103
+ * with neither a cost nor a cap). Its audit's shadow is counted apart (learning-end.ts shadowBesideOf). */
104
+ export async function keyedBesideOf(store, runId) {
105
+ let sum = 0;
106
+ for (const child of await learningChildrenOf(store.settings, runId)) {
107
+ if (!child.keyed || child.kind !== "replay" || child.run === null)
108
+ continue;
109
+ const row = await store.runs.get(child.run);
110
+ if (!row)
111
+ continue;
112
+ if (FINAL_STATES.includes(row.state) && figure(row.costUsd)) {
113
+ sum += row.costUsd;
114
+ continue;
115
+ }
116
+ const cap = await store.runs.launch(child.run).then((one) => readLaunchBody(one.body)?.maxCostUsd, () => undefined);
117
+ if (!figure(cap))
118
+ return null;
119
+ sum += cap;
120
+ }
121
+ return sum;
122
+ }
123
+ /** Run `runId`'s `learning_work`: `running` while its compile turn goes or a child it started has not ended (`runs`, the
124
+ * child run ids not ended), `ended` once every piece it started has finished or dropped (`ended_at`, the last one's end),
125
+ * else `none`. A child whose row is gone or was never created counts as ended at the time it was named: its own end, or
126
+ * its absence, settles it, so the state cannot stay `running` forever. `deadline_at` while running: the later of the
127
+ * row's deadline and the compile turn's bound (`own.compileBy`); null otherwise. */
128
+ export async function learningWorkOf(store, runId, own) {
129
+ const saved = await store.settings.get(learningWorkKey(runId));
130
+ const children = await learningChildrenOf({ get: async () => saved }, runId);
131
+ const going = [];
132
+ let last = own.compiled && own.endedAt !== null ? own.endedAt : Number.NEGATIVE_INFINITY;
133
+ for (const child of children) {
134
+ const row = child.run === null ? undefined : await store.runs.get(child.run);
135
+ if (row && !FINAL_STATES.includes(row.state)) {
136
+ going.push(row.id);
137
+ continue;
138
+ }
139
+ last = Math.max(last, row?.endedAt ?? child.at);
140
+ }
141
+ if (going.length || (own.learns && own.compiling)) {
142
+ const deadline = later(deadlineIn(saved), own.learns && own.compiling && own.compileBy !== null ? own.compileBy : undefined);
143
+ return { state: "running", runs: going, ended_at: null, deadline_at: deadline === undefined ? null : new Date(deadline).toISOString() };
144
+ }
145
+ if (!children.length && !(own.learns && own.compiled))
146
+ return { state: "none", runs: [], ended_at: null, deadline_at: null };
147
+ return { state: "ended", runs: [], ended_at: Number.isFinite(last) ? new Date(last).toISOString() : null, deadline_at: null };
148
+ }