@parcha/agentrun-serve 0.1.0-beta.59 → 0.1.0-beta.60

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 (194) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/README.md +188 -106
  3. package/dist/agent-delete.d.ts +6 -9
  4. package/dist/agent-delete.js +5 -3
  5. package/dist/agent-package.js +11 -1
  6. package/dist/api-only.d.ts +2 -2
  7. package/dist/api-only.js +3 -3
  8. package/dist/archil-routes.d.ts +4 -1
  9. package/dist/archil-routes.js +15 -12
  10. package/dist/archil-settings.d.ts +18 -8
  11. package/dist/archil-settings.js +35 -17
  12. package/dist/chatgpt-plan.d.ts +4 -2
  13. package/dist/chatgpt-plan.js +13 -3
  14. package/dist/claude-login-token.d.ts +5 -0
  15. package/dist/claude-login-token.js +8 -0
  16. package/dist/claude-login.d.ts +49 -3
  17. package/dist/claude-login.js +140 -10
  18. package/dist/cli-learning/connections.js +1 -1
  19. package/dist/console/assets/{backend-BztxEAvb.js → backend-QnwGVBeU.js} +1 -1
  20. package/dist/console/assets/index-DZi-muIj.js +629 -0
  21. package/dist/console/assets/{share-L84tlUDW.js → share-pz61zIn9.js} +2 -2
  22. package/dist/console/assets/{styles-CaRKlHke.js → styles-CcceGcu2.js} +31 -31
  23. package/dist/console/assets/styles-fjQBFfMv.css +1 -0
  24. package/dist/console/index.html +3 -3
  25. package/dist/console/share.html +3 -3
  26. package/dist/decisions.d.ts +1 -1
  27. package/dist/decisions.js +2 -2
  28. package/dist/factory-activity.d.ts +68 -0
  29. package/dist/factory-activity.js +153 -0
  30. package/dist/factory-runs.d.ts +11 -0
  31. package/dist/factory-runs.js +52 -0
  32. package/dist/filed-tool.d.ts +32 -0
  33. package/dist/filed-tool.js +122 -0
  34. package/dist/harness-keys.d.ts +1 -2
  35. package/dist/harness-keys.js +1 -2
  36. package/dist/harness-table.d.ts +4 -0
  37. package/dist/harness-table.js +4 -0
  38. package/dist/harness.js +6 -2
  39. package/dist/import-worker.js +2 -2
  40. package/dist/import.d.ts +9 -0
  41. package/dist/import.js +11 -1
  42. package/dist/key-refusal.d.ts +5 -0
  43. package/dist/key-refusal.js +25 -15
  44. package/dist/learn/audit.d.ts +20 -22
  45. package/dist/learn/audit.js +72 -55
  46. package/dist/learn/check.js +1 -1
  47. package/dist/learn/commit.d.ts +35 -43
  48. package/dist/learn/commit.js +62 -270
  49. package/dist/learn/compile.d.ts +4 -4
  50. package/dist/learn/compile.js +6 -7
  51. package/dist/learn/corrections.js +1 -1
  52. package/dist/learn/delete.d.ts +5 -12
  53. package/dist/learn/delete.js +17 -30
  54. package/dist/learn/forget-run.d.ts +16 -0
  55. package/dist/learn/forget-run.js +53 -0
  56. package/dist/learn/index.js +1 -1
  57. package/dist/learn/learning-of.d.ts +0 -4
  58. package/dist/learn/learning-of.js +0 -5
  59. package/dist/learn/{folder.d.ts → legacy/folder.d.ts} +2 -1
  60. package/dist/learn/{folder.js → legacy/folder.js} +4 -7
  61. package/dist/learn/legacy/place.d.ts +16 -0
  62. package/dist/{workspace/learning-workspace.js → learn/legacy/place.js} +12 -42
  63. package/dist/learn/legacy/scrub.d.ts +28 -0
  64. package/dist/learn/legacy/scrub.js +258 -0
  65. package/dist/learn/promote.d.ts +40 -66
  66. package/dist/learn/promote.js +69 -207
  67. package/dist/learn/reset-ledger.d.ts +18 -0
  68. package/dist/learn/reset-ledger.js +14 -0
  69. package/dist/learn/rows.d.ts +186 -0
  70. package/dist/learn/rows.js +376 -0
  71. package/dist/learn/workflow-draft.d.ts +4 -1
  72. package/dist/learn/workflow-draft.js +12 -2
  73. package/dist/learning-reset.d.ts +1 -1
  74. package/dist/learning-reset.js +9 -11
  75. package/dist/learning-routes.d.ts +60 -81
  76. package/dist/learning-routes.js +187 -360
  77. package/dist/learning-words.d.ts +2 -0
  78. package/dist/learning-words.js +2 -0
  79. package/dist/learning.d.ts +18 -24
  80. package/dist/learning.js +35 -66
  81. package/dist/mcp-gateway.d.ts +6 -0
  82. package/dist/mcp-gateway.js +44 -8
  83. package/dist/mcp-resources.d.ts +1 -1
  84. package/dist/native/discovery.d.ts +6 -0
  85. package/dist/native/discovery.js +14 -1
  86. package/dist/native/remote.d.ts +5 -0
  87. package/dist/native/remote.js +16 -0
  88. package/dist/native/runtime.js +3 -2
  89. package/dist/observation/observer.d.ts +6 -6
  90. package/dist/openapi.js +89 -29
  91. package/dist/place-offers.d.ts +3 -0
  92. package/dist/place-offers.js +3 -0
  93. package/dist/place.d.ts +33 -11
  94. package/dist/place.js +61 -26
  95. package/dist/purged-workflow.d.ts +0 -33
  96. package/dist/purged-workflow.js +3 -71
  97. package/dist/redact/match.d.ts +19 -4
  98. package/dist/redact/match.js +123 -30
  99. package/dist/run-launch.d.ts +3 -3
  100. package/dist/run-learning-served.d.ts +3 -3
  101. package/dist/run-learning-served.js +1 -1
  102. package/dist/run-listing.d.ts +1 -1
  103. package/dist/run-timeline-served.d.ts +1 -1
  104. package/dist/run-timeline-served.js +6 -5
  105. package/dist/runnable.js +25 -8
  106. package/dist/runner/adapter-run-spec.js +11 -20
  107. package/dist/runner/audit.d.ts +2 -4
  108. package/dist/runner/audit.js +28 -51
  109. package/dist/runner/cli-run-spec.js +8 -14
  110. package/dist/runner/compare-end.d.ts +0 -2
  111. package/dist/runner/compare-end.js +6 -2
  112. package/dist/runner/disk-free.d.ts +15 -4
  113. package/dist/runner/disk-free.js +25 -7
  114. package/dist/runner/feedback-round.d.ts +1 -1
  115. package/dist/runner/feedback-round.js +2 -2
  116. package/dist/runner/harness-loops.js +2 -3
  117. package/dist/runner/held.d.ts +0 -10
  118. package/dist/runner/held.js +0 -25
  119. package/dist/runner/journal-kinds.d.ts +4 -1
  120. package/dist/runner/journal-kinds.js +1 -1
  121. package/dist/runner/learned-first.d.ts +0 -2
  122. package/dist/runner/learned-first.js +3 -3
  123. package/dist/runner/learning-end.d.ts +12 -16
  124. package/dist/runner/learning-end.js +41 -75
  125. package/dist/runner/learning-seed.d.ts +13 -16
  126. package/dist/runner/learning-seed.js +13 -23
  127. package/dist/runner/main.js +1 -1
  128. package/dist/runner/mcp-run.d.ts +4 -0
  129. package/dist/runner/mcp-run.js +2 -0
  130. package/dist/runner/native-loop.js +2 -3
  131. package/dist/runner/promotion.d.ts +19 -28
  132. package/dist/runner/promotion.js +50 -69
  133. package/dist/runner/reflect-hook.d.ts +2 -2
  134. package/dist/runner/reflect-hook.js +4 -1
  135. package/dist/runner/run-child-host.d.ts +1 -9
  136. package/dist/runner/run-child-host.js +11 -67
  137. package/dist/runner/runner.d.ts +1 -1
  138. package/dist/runner/sdk-loop.js +2 -4
  139. package/dist/sdk/check.d.ts +1 -4
  140. package/dist/sdk/check.js +2 -3
  141. package/dist/sdk/runs.d.ts +20 -7
  142. package/dist/sdk/runs.js +105 -68
  143. package/dist/secrets.d.ts +4 -0
  144. package/dist/secrets.js +44 -10
  145. package/dist/server-fs.d.ts +1 -1
  146. package/dist/server-fs.js +1 -1
  147. package/dist/server-keys.d.ts +6 -0
  148. package/dist/server-keys.js +12 -0
  149. package/dist/server.d.ts +15 -15
  150. package/dist/server.js +214 -164
  151. package/dist/source-sync/auxiliary.js +2 -2
  152. package/dist/store/index.d.ts +1 -1
  153. package/dist/store/index.js +1 -1
  154. package/dist/store/postgres/migrations/0032_learning_rows.sql +65 -0
  155. package/dist/store/schema.d.ts +28 -2
  156. package/dist/store/schema.js +81 -5
  157. package/dist/store/sqlite/learning-rows.d.ts +23 -0
  158. package/dist/store/sqlite/learning-rows.js +559 -0
  159. package/dist/store/sqlite/store.d.ts +7 -1
  160. package/dist/store/sqlite/store.js +84 -18
  161. package/dist/store/store.d.ts +219 -6
  162. package/dist/store/store.js +13 -0
  163. package/dist/store-reads/journal.d.ts +33 -3
  164. package/dist/store-reads/journal.js +99 -4
  165. package/dist/store-reads/learning.d.ts +18 -22
  166. package/dist/store-reads/learning.js +35 -26
  167. package/dist/store-reads/loop.js +1 -1
  168. package/dist/store-view.d.ts +24 -2
  169. package/dist/store-view.js +40 -11
  170. package/dist/templates.d.ts +10 -2
  171. package/dist/templates.js +31 -4
  172. package/dist/tool-plane.d.ts +4 -2
  173. package/dist/tool-plane.js +9 -2
  174. package/dist/web-holds.d.ts +2 -0
  175. package/dist/web-holds.js +5 -2
  176. package/dist/web-run.js +2 -1
  177. package/dist/workspace/archil-exec.js +1 -1
  178. package/dist/workspace/archil.d.ts +1 -1
  179. package/dist/workspace/archil.js +1 -1
  180. package/dist/workspace/computer-deps.js +5 -3
  181. package/dist/workspace/computer-providers.d.ts +11 -1
  182. package/dist/workspace/computer-providers.js +29 -2
  183. package/dist/workspace/index.d.ts +1 -2
  184. package/dist/workspace/index.js +1 -2
  185. package/dist/workspace/paths.d.ts +0 -4
  186. package/dist/workspace/paths.js +0 -6
  187. package/dist/workspace/workspace.d.ts +1 -1
  188. package/dist/workspace/workspace.js +1 -1
  189. package/package.json +13 -13
  190. package/templates/TOOLS.md +46 -0
  191. package/dist/console/assets/index-LwNL4L9q.js +0 -619
  192. package/dist/console/assets/styles-DQo8rzY-.css +0 -1
  193. package/dist/workspace/learning-workspace.d.ts +0 -24
  194. /package/dist/learn/{learning.sh → legacy/learning.sh} +0 -0
@@ -8,7 +8,7 @@ import { RUNNER_RECORDS } from "@parcha/agentrun-kernel";
8
8
  import { wireName } from "../catalog.js";
9
9
  import { TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
10
10
  import { Hearing } from "../heard.js";
11
- import { redactedAnswer } from "../key-refusal.js";
11
+ import { redacted, redactedAnswer, withheldWhole } from "../key-refusal.js";
12
12
  import { LEARNED_NODES_MAX, learnedCallEntries } from "../learned-nodes.js";
13
13
  import { computerCallsOf, shownName } from "../computer-calls.js";
14
14
  import { labelled, reflects } from "../reflect-range.js";
@@ -434,17 +434,112 @@ const ANSWERS_KEPT = 32;
434
434
  * purge, which may still hold the purged run's text, never puts that text back once the purge dropped it. */
435
435
  const forgetsOf = new WeakMap();
436
436
  export const servedSince = (store) => forgetsOf.get(store.origin) ?? 0;
437
- /** Run `runId`'s answer rows dropped from what the readers of `store` last served (wholeAnswers): a purged or deleted
438
- * run's text kept in no memory of this process (store-view.ts forgetServed). Counted (servedSince), so no read begun
439
- * before it keeps what it read. The keys it dropped. */
437
+ /** Run `runId`'s answer rows dropped from what the readers of `store` last served (wholeAnswers), and its texts from what
438
+ * they last cut (rowCutsOnce): a purged or deleted run's text kept in no memory of this process (store-view.ts
439
+ * forgetServed). Counted (servedSince), so no read begun before it keeps what it read. The answer keys it dropped. */
440
440
  export function forgetServedAnswers(store, runId) {
441
441
  forgetsOf.set(store.origin, servedSince(store) + 1);
442
442
  const kept = answersServed.get(store.origin);
443
443
  const dropped = [...(kept?.keys() ?? [])].filter((key) => key.startsWith(`${runId}\0`));
444
444
  for (const key of dropped)
445
445
  kept.delete(key);
446
+ forgetCuts(store.origin, runId);
446
447
  return dropped;
447
448
  }
449
+ const cutsKept = new WeakMap();
450
+ const CUT_SETS = 16;
451
+ const CUT_BYTES = 32 * 1024 * 1024;
452
+ /** The bound in force (CUT_BYTES): a test sets a smaller one to see the oldest go. */
453
+ export const cutBudget = { bytes: CUT_BYTES };
454
+ /** What one kept text costs beyond its characters: the Map entry and the boolean or string header, as counted. */
455
+ const CUT_ENTRY = 64;
456
+ const cutCost = (slot, made) => CUT_ENTRY + 2 * (slot.length + (typeof made === "string" ? made.length : 0));
457
+ /** A cut as kept: a string copied into one of its own, unit for unit (lone surrogates as written), so it holds no
458
+ * reference to the text it was sliced from; a boolean as it is. */
459
+ const cutCopy = (made) => (typeof made === "string" ? Buffer.from(made, "utf16le").toString("utf16le") : made);
460
+ /** Run `runId`'s value sets dropped from what the readers of store `origin` last cut (cutsKept). */
461
+ function forgetCuts(origin, runId) {
462
+ const cuts = cutsKept.get(origin);
463
+ if (!cuts)
464
+ return;
465
+ for (const [set, kept] of [...cuts.sets]) {
466
+ if (!set.startsWith(`${runId}\0`))
467
+ continue;
468
+ cuts.sets.delete(set);
469
+ cuts.bytes -= kept.bytes;
470
+ }
471
+ }
472
+ /** The row redactor (`redact`) and the whole-text check (`holds`) of run `runId`'s rows under its `cut` (run-cut.ts
473
+ * runCutValues), as a reader's TimelineOptions takes them: each text cut once per cut, its values in their order and its
474
+ * census mode (cutsKept), what was cut kept only while no run's text was forgotten since `since` (servedSince, taken
475
+ * before the read began). */
476
+ export function rowCutsOnce(store, runId, cut, since) {
477
+ const origin = store.origin;
478
+ const values = cut === "unreadable" ? [] : cut.values;
479
+ const mode = cut === "unreadable" ? "unreadable" : (cut.censusDigest ?? "none");
480
+ const set = `${runId}\0${createHash("sha256").update(JSON.stringify([mode, values])).digest("hex")}`;
481
+ const once = (how, text, cut) => {
482
+ const slot = `${how}\0${createHash("sha256").update(text, "utf16le").digest("base64")}`;
483
+ const held = cutsKept.get(origin);
484
+ const heldSet = held?.sets.get(set);
485
+ const kept = heldSet?.texts.get(slot);
486
+ if (kept !== undefined) {
487
+ // Read again: the most recently used, its set and itself.
488
+ held.sets.delete(set);
489
+ held.sets.set(set, heldSet);
490
+ heldSet.texts.delete(slot);
491
+ heldSet.texts.set(slot, kept);
492
+ return kept;
493
+ }
494
+ const made = cut();
495
+ const cost = cutCost(slot, made);
496
+ if (servedSince(store) !== since || cost > cutBudget.bytes)
497
+ return made;
498
+ const keep = cutCopy(made);
499
+ let cuts = cutsKept.get(origin);
500
+ if (!cuts)
501
+ cutsKept.set(origin, (cuts = { sets: new Map(), bytes: 0 }));
502
+ const texts = cuts.sets.get(set) ?? { texts: new Map(), bytes: 0 };
503
+ cuts.sets.delete(set);
504
+ cuts.sets.set(set, texts);
505
+ texts.texts.set(slot, keep);
506
+ texts.bytes += cost;
507
+ cuts.bytes += cost;
508
+ // The least recently used go first: the set read or written longest ago, its oldest texts (this set is the newest),
509
+ // a set left empty with them, and a set past CUT_SETS whole.
510
+ for (const [oldSet, old] of cuts.sets) {
511
+ if (cuts.bytes <= cutBudget.bytes && cuts.sets.size <= CUT_SETS)
512
+ break;
513
+ if (cuts.sets.size > CUT_SETS) {
514
+ cuts.sets.delete(oldSet);
515
+ cuts.bytes -= old.bytes;
516
+ continue;
517
+ }
518
+ for (const [oldSlot, oldMade] of old.texts) {
519
+ if (cuts.bytes <= cutBudget.bytes)
520
+ break;
521
+ const freed = cutCost(oldSlot, oldMade);
522
+ old.texts.delete(oldSlot);
523
+ old.bytes -= freed;
524
+ cuts.bytes -= freed;
525
+ }
526
+ if (old.texts.size === 0)
527
+ cuts.sets.delete(oldSet);
528
+ }
529
+ return made;
530
+ };
531
+ return {
532
+ redact: (text) => once("redact", text, () => redacted(text, values)),
533
+ holds: (text) => once("holds", text, () => withheldWhole(text, values)),
534
+ };
535
+ }
536
+ /** What the readers of `store` keep of their cuts now: the bytes counted (cutBudget bounds it), the texts and the sets, and
537
+ * each kept text (its set, its slot and what was made of it), so a test can read that nothing a run wrote is kept. */
538
+ export function cutsKeptOf(store) {
539
+ const cuts = cutsKept.get(store.origin);
540
+ const kept = [...(cuts?.sets ?? [])].flatMap(([set, of]) => [...of.texts].map(([slot, made]) => ({ set, slot, made })));
541
+ return { bytes: cuts?.bytes ?? 0, texts: kept.length, sets: cuts?.sets.size ?? 0, kept };
542
+ }
448
543
  /** `rows` (runTimeline's, rendered with `options`) with each final answer whole, as main served a run's answer: the renderer
449
544
  * cuts a row's text at CAPS.text, and its redactor (`options.redact`, key-refusal.ts redacted) reads only the head a row
450
545
  * shows and cuts the rest, ending what it cut in "..." (short of the cap when it replaced a held value there), or giving
@@ -7,7 +7,7 @@ import { type FirstReason, type PastRuns, pathMetrics, workflowCostsOf } from ".
7
7
  import { type Reflect } from "../reflect-range.js";
8
8
  import type { EntryLike, TimelineEvent } from "../timeline/index.js";
9
9
  import type { AnalyticsFilter } from "./analytics.js";
10
- import { type CostStop, type PromotionRecord, type Refused, type ResetRevision } from "../learn/promote.js";
10
+ import { type CostStop, type PromotionRecord, type ResetRevision } from "../learn/promote.js";
11
11
  import type { LearningProposal, Store } from "../store/store.js";
12
12
  /** A run's learning end: the Learning fields its end sets. */
13
13
  export type RunLearningEnd = Learning;
@@ -74,11 +74,8 @@ export declare function agentLearningOverStore(store: Store, agentId: string): P
74
74
  * money rule (workflowCostsOf over the same figures, pastRunsOf). A run still at work, an imported or archived one and a
75
75
  * workflow revision's run are left out. A run that learns whose end named no path is left out too and counted
76
76
  * (`unknown_path_runs`): its path and cost are not known, never `agent` at $0. `limit`: the latest runs shown, each
77
- * keeping its number; the summary is over every run; `bill` is the owner's bill over all of them. Its champion skips
78
- * what `refused` names of the agent's promotion records (purged-workflow.ts refusedOf, the purge gate's), as a run's
79
- * claim does; absent, none. */
80
- export type RefusedFor = (agentId: string, records: readonly PromotionRecord[]) => Promise<Refused>;
81
- export declare function agentCostOverStore(store: Store, agentId: string, limit?: number, refused?: RefusedFor): Promise<{
77
+ * keeping its number; the summary is over every run; `bill` is the owner's bill over all of them. */
78
+ export declare function agentCostOverStore(store: Store, agentId: string, limit?: number): Promise<{
82
79
  runs: CostRun[];
83
80
  summary: CostSummary;
84
81
  total_runs: number;
@@ -89,22 +86,22 @@ export declare function agentCostOverStore(store: Store, agentId: string, limit?
89
86
  }>;
90
87
  /** The agent's ledger read over the one store and summed (learn/ledger.ts summarize): its runs (as runs.list reads
91
88
  * them), each one's ledger row and spend rows (Learning.ledger), its promotion records (the revisions' K and state,
92
- * revisionsOf, skipping what `refused` names) and its audits' shadow runs. `records`: where a run's launch and rounds
93
- * are read (the agent's at once by default, agentRecordsOf). */
94
- export declare function agentLedgerOverStore(store: Store, agentId: string, refused?: RefusedFor, records?: RunRecords): Promise<{
89
+ * revisionsOf; learning records, Learning.records) and its audits' shadow runs. `records`: where a run's launch and
90
+ * rounds are read (the agent's at once by default, agentRecordsOf). */
91
+ export declare function agentLedgerOverStore(store: Store, agentId: string, records?: RunRecords): Promise<{
95
92
  out: Summarized;
96
93
  promotions: PromotionRecord[];
97
- skip: Refused | undefined;
98
94
  listed: RunRecord[];
99
95
  }>;
100
96
  /** Each revision of the agent's learned workflows its promotion records name (one per workflow and digest, in the order
101
97
  * they were first recorded), with the served runs its spend is spread over (K, its check's compile_after) and `state`
102
- * from its newest record: `checking` while its check replays, `serving` for the champion (championOf, skipping what
103
- * `refused` names: the purge gate's, so a purged run's revision is never said to serve), else `stopped`. A revision an
104
- * earlier reset of the agent's learning deleted (`reset`, learn/promote.ts keepResetLedger) comes first, stopped, at the
98
+ * from its newest record: `checking` while its check replays, `serving` for the champion (championOf: a purged run's
99
+ * records are gone with it, so its revision is never said to serve), else `stopped`. A revision an
100
+ * earlier reset of the agent's learning deleted (`reset`, learn/promote.ts keepResetLedger), or a run's purge deleted
101
+ * while other runs still carry its spend (store/sqlite/learning-rows.ts dropRunLearning), comes first, stopped, at the
105
102
  * K it was kept with, unless the records name it again. What each one spent is the ledger's (learn/ledger.ts summarize),
106
103
  * whatever the records say. */
107
- export declare function revisionsOf(records: readonly PromotionRecord[], reset?: readonly ResetRevision[], refused?: Refused): RevisionAt[];
104
+ export declare function revisionsOf(records: readonly PromotionRecord[], reset?: readonly ResetRevision[]): RevisionAt[];
108
105
  /** A run's costs as GET /runs/{id} shows them (RunAllIn, runAllInOverStore). */
109
106
  export type RunAllIn = {
110
107
  path: RunPath | null;
@@ -120,16 +117,15 @@ export type RunAllIn = {
120
117
  * (its row's when absent); one other than its row's (an imported run's estimate, a booking where its end stored none)
121
118
  * is its job's, less its look-back. While the run is at work `usd` is `rowUsd` and the rest null; null while unknown (its shadow still at work, a compile's or
122
119
  * a check's cost unknown), never $0. Undefined for an unknown run. A served run's share is the agent's ledger's
123
- * (agentLedgerOverStore), its revision's champion skipping what `refused` names of the agent's promotion records. */
124
- export declare function runAllInOverStore(store: Store, runId: string, rowUsd?: number | null, refused?: RefusedFor): Promise<RunAllIn | undefined>;
120
+ * (agentLedgerOverStore). */
121
+ export declare function runAllInOverStore(store: Store, runId: string, rowUsd?: number | null): Promise<RunAllIn | undefined>;
125
122
  /** The check the serving promotion was decided on, as the cost summary says it: the champion (championOf) of the learned
126
123
  * workflow the newest run a learned workflow ran first on ran (`workflow` or `handed_back`), its record's check numbers
127
124
  * (the share of the inputs it answered alone that were right on every field, and the agent's share on the same inputs
128
125
  * against the same known answers: `agent_agreed`). `cleared`: the joint
129
126
  * floor's verdict as the check decided it (`check.joint`, learn/field-check.ts), which every promotion passed. Null when
130
- * no run was served, nothing serves now (held, or never promoted), or it was promoted on no input (a dry run). The
131
- * champion skips what `refused` names (the purge gate's). */
132
- export declare function servingReplayOf(records: readonly PromotionRecord[], runs: readonly CostRun[], refused?: Refused): CostReplay | null;
127
+ * no run was served, nothing serves now (held, or never promoted), or it was promoted on no input (a dry run). */
128
+ export declare function servingReplayOf(records: readonly PromotionRecord[], runs: readonly CostRun[]): CostReplay | null;
133
129
  /** Every round run `runId` kept (one a follow-up opened again is a round past its first), oldest first: none when it kept
134
130
  * no learning. The store's proposal(runId) is the newest round alone; a read of what the run's learning did or spent
135
131
  * reads them all. */
@@ -244,12 +240,12 @@ export declare function learnedUseOf(reflect: Pick<Reflect, "after" | "until"> |
244
240
  export declare function usedOnly(started: NonNullable<RunLaunch["learning"]>, terminal: boolean, at: string): RunLearningEnd;
245
241
  /** GET /runs/{id}/learning from the one store, in the shape the route gives (learning-routes.ts runLearningBody): the
246
242
  * run's learning end (runLearningEnd) and the seed it started from as its launch records it, what it held for its
247
- * owner's OK as it stands on its agent's folder's main (`statuses`, learning-routes.ts statusesOf, read only when it held
243
+ * owner's OK as it stands at its agent's newest save (`statuses`, learning-routes.ts statusesOf, read only when it held
248
244
  * something; none: as the merge wrote it), settled once the run is final. Null when the run kept no learning. */
249
245
  export declare function runLearningOverStore(store: Store, runId: string, shown: Shown, secrets: readonly string[], statuses?: (agentId: string) => Promise<ReadonlyMap<string, ItemStatus> | undefined>): Promise<{
250
246
  run: string;
251
247
  state: "dropped" | "merged" | "seeded" | "reflecting";
252
- reason: "cancelled" | "reset" | "use" | "empty" | "seed_failed" | "no_budget" | "unknown_cost" | "crashed" | "reflect_failed" | "checker" | null;
248
+ reason: "cancelled" | "reset" | "seed_failed" | "no_budget" | "unknown_cost" | "crashed" | "reflect_failed" | "empty" | "checker" | "use" | "purged_since_seed" | null;
253
249
  detail: string | null;
254
250
  at: string;
255
251
  workflows: import("../learning.js").LearnedFile[];
@@ -292,7 +288,7 @@ export declare function runLearningOverStore(store: Store, runId: string, shown:
292
288
  };
293
289
  run: string;
294
290
  state: "dropped" | "merged" | "seeded" | "reflecting";
295
- reason: "cancelled" | "reset" | "use" | "empty" | "seed_failed" | "no_budget" | "unknown_cost" | "crashed" | "reflect_failed" | "checker" | null;
291
+ reason: "cancelled" | "reset" | "seed_failed" | "no_budget" | "unknown_cost" | "crashed" | "reflect_failed" | "empty" | "checker" | "use" | "purged_since_seed" | null;
296
292
  detail: string | null;
297
293
  at: string;
298
294
  workflows: import("../learning.js").LearnedFile[];
@@ -202,27 +202,35 @@ export async function agentLearningOverStore(store, agentId) {
202
202
  }
203
203
  return { counts, impact: learningImpact(rows, (row) => learnings.get(row.id) ?? null) };
204
204
  }
205
- export async function agentCostOverStore(store, agentId, limit = Infinity, refused) {
206
- const { out, promotions, skip, listed } = await agentLedgerOverStore(store, agentId, refused);
205
+ /** Agent `agentId`'s cost per run from the one store (GET /agents/{id}/learning/cost, learning-cost.ts): what its ledger
206
+ * says (learn/ledger.ts summarize, agentLedgerOverStore): each of its agentic runs that ended (ended, stopped or
207
+ * failed), oldest first, each run that does a job numbered from 1 (a replay none: the bill's numbering), with its own
208
+ * cost and what learning added for it, the path it took and the learned workflow it ran, the revision of that workflow
209
+ * and whether an audit's shadow ran for it; what the series shows (costSummary); and each learned workflow against the
210
+ * money rule (workflowCostsOf over the same figures, pastRunsOf). A run still at work, an imported or archived one and a
211
+ * workflow revision's run are left out. A run that learns whose end named no path is left out too and counted
212
+ * (`unknown_path_runs`): its path and cost are not known, never `agent` at $0. `limit`: the latest runs shown, each
213
+ * keeping its number; the summary is over every run; `bill` is the owner's bill over all of them. */
214
+ export async function agentCostOverStore(store, agentId, limit = Infinity) {
215
+ const { out, promotions, listed } = await agentLedgerOverStore(store, agentId);
207
216
  const { runs } = out;
208
217
  // Each learned workflow that ran first, where it stands against the money rule, over the figures this series shows: a
209
218
  // workflow over the line shows `needs_revision` with its two numbers, so the page and the launch's decision agree.
210
219
  const workflows = workflowCostsOf(await pastRunsRead(store, agentId, out, listed));
211
- const summary = { ...out.summary, replay: servingReplayOf(promotions, runs, skip) };
220
+ const summary = { ...out.summary, replay: servingReplayOf(promotions, runs) };
212
221
  const bill = { ...out.bill, holds: holdsOf(promotions, runs) };
213
222
  return { runs: runs.slice(Math.max(0, runs.length - limit)), summary, total_runs: runs.length, unknown_cost_runs: runs.filter((run) => run.total_usd === null).length, unknown_path_runs: out.unknown_path_runs, workflows, bill };
214
223
  }
215
224
  /** The agent's ledger read over the one store and summed (learn/ledger.ts summarize): its runs (as runs.list reads
216
225
  * them), each one's ledger row and spend rows (Learning.ledger), its promotion records (the revisions' K and state,
217
- * revisionsOf, skipping what `refused` names) and its audits' shadow runs. `records`: where a run's launch and rounds
218
- * are read (the agent's at once by default, agentRecordsOf). */
219
- export async function agentLedgerOverStore(store, agentId, refused, records) {
226
+ * revisionsOf; learning records, Learning.records) and its audits' shadow runs. `records`: where a run's launch and
227
+ * rounds are read (the agent's at once by default, agentRecordsOf). */
228
+ export async function agentLedgerOverStore(store, agentId, records) {
220
229
  const listed = (await store.runs.list({ agentId })).filter((run) => run.agentId === agentId);
221
230
  const read = await ledgerReadOf(store, agentId, listed, records ?? (await agentRecordsOf(store, agentId, listed)));
222
- const promotions = await promotionsOf(store.settings, agentId);
223
- const skip = refused ? await refused(agentId, promotions) : undefined;
224
- const revisions = revisionsOf(promotions, await resetLedgerOf(store.settings, agentId), skip);
225
- return { out: summarize({ ...read, revisions }), promotions, skip, listed };
231
+ const promotions = await promotionsOf(store.learning, agentId);
232
+ const revisions = revisionsOf(promotions, await resetLedgerOf(store.settings, agentId));
233
+ return { out: summarize({ ...read, revisions }), promotions, listed };
226
234
  }
227
235
  /** How many runs a ledger read reads at once (ledgerReadOf: a run's rounds, its launch, its revision). */
228
236
  const READS_AT_ONCE = 16;
@@ -303,12 +311,13 @@ const revisionOfRow = (row) => {
303
311
  };
304
312
  /** Each revision of the agent's learned workflows its promotion records name (one per workflow and digest, in the order
305
313
  * they were first recorded), with the served runs its spend is spread over (K, its check's compile_after) and `state`
306
- * from its newest record: `checking` while its check replays, `serving` for the champion (championOf, skipping what
307
- * `refused` names: the purge gate's, so a purged run's revision is never said to serve), else `stopped`. A revision an
308
- * earlier reset of the agent's learning deleted (`reset`, learn/promote.ts keepResetLedger) comes first, stopped, at the
314
+ * from its newest record: `checking` while its check replays, `serving` for the champion (championOf: a purged run's
315
+ * records are gone with it, so its revision is never said to serve), else `stopped`. A revision an
316
+ * earlier reset of the agent's learning deleted (`reset`, learn/promote.ts keepResetLedger), or a run's purge deleted
317
+ * while other runs still carry its spend (store/sqlite/learning-rows.ts dropRunLearning), comes first, stopped, at the
309
318
  * K it was kept with, unless the records name it again. What each one spent is the ledger's (learn/ledger.ts summarize),
310
319
  * whatever the records say. */
311
- export function revisionsOf(records, reset = [], refused) {
320
+ export function revisionsOf(records, reset = []) {
312
321
  const newest = new Map();
313
322
  for (const one of records)
314
323
  newest.set(`${one.workflow}\0${one.digest}`, one);
@@ -316,7 +325,7 @@ export function revisionsOf(records, reset = [], refused) {
316
325
  ...reset.filter((one) => !newest.has(`${one.workflow}\0${one.digest}`)).map((one) => ({ workflow: one.workflow, digest: one.digest, k: one.k ?? COMPILE_AFTER_DEFAULT, state: "stopped" })),
317
326
  ...[...newest.values()].map((one) => ({
318
327
  workflow: one.workflow, digest: one.digest, k: one.check?.compile_after ?? COMPILE_AFTER_DEFAULT,
319
- state: one.decided === "replaying" ? "checking" : championOf(records, one.workflow, refused)?.digest === one.digest ? "serving" : "stopped",
328
+ state: one.decided === "replaying" ? "checking" : championOf(records, one.workflow)?.digest === one.digest ? "serving" : "stopped",
320
329
  })),
321
330
  ];
322
331
  }
@@ -331,8 +340,8 @@ export function revisionsOf(records, reset = [], refused) {
331
340
  * (its row's when absent); one other than its row's (an imported run's estimate, a booking where its end stored none)
332
341
  * is its job's, less its look-back. While the run is at work `usd` is `rowUsd` and the rest null; null while unknown (its shadow still at work, a compile's or
333
342
  * a check's cost unknown), never $0. Undefined for an unknown run. A served run's share is the agent's ledger's
334
- * (agentLedgerOverStore), its revision's champion skipping what `refused` names of the agent's promotion records. */
335
- export async function runAllInOverStore(store, runId, rowUsd, refused) {
343
+ * (agentLedgerOverStore). */
344
+ export async function runAllInOverStore(store, runId, rowUsd) {
336
345
  const run = await store.runs.get(runId);
337
346
  if (!run)
338
347
  return undefined;
@@ -346,7 +355,7 @@ export async function runAllInOverStore(store, runId, rowUsd, refused) {
346
355
  }
347
356
  // A served run carries a share of its revision's spend: its figures are the series' own, over the agent's ledger.
348
357
  const served = path !== null && SERVED_PATHS.includes(path) && revisionOfRow(run) !== undefined;
349
- const figures = (served ? (await agentLedgerOverStore(store, run.agentId, refused)).out.figures.get(run.id) : undefined) ?? (await runFiguresOf(store, run));
358
+ const figures = (served ? (await agentLedgerOverStore(store, run.agentId)).out.figures.get(run.id) : undefined) ?? (await runFiguresOf(store, run));
350
359
  // The run's view priced it other than its row does (`rowUsd`: an imported run's catalog estimate, or its booking where
351
360
  // its end stored none): its job is that figure, as its end would have recorded it at that cost (record: less its
352
361
  // look-back), its learning's parts the ledger's.
@@ -380,11 +389,10 @@ async function runFiguresOf(store, run) {
380
389
  * (the share of the inputs it answered alone that were right on every field, and the agent's share on the same inputs
381
390
  * against the same known answers: `agent_agreed`). `cleared`: the joint
382
391
  * floor's verdict as the check decided it (`check.joint`, learn/field-check.ts), which every promotion passed. Null when
383
- * no run was served, nothing serves now (held, or never promoted), or it was promoted on no input (a dry run). The
384
- * champion skips what `refused` names (the purge gate's). */
385
- export function servingReplayOf(records, runs, refused) {
392
+ * no run was served, nothing serves now (held, or never promoted), or it was promoted on no input (a dry run). */
393
+ export function servingReplayOf(records, runs) {
386
394
  const name = runs.findLast((run) => (run.path === "workflow" || run.path === "handed_back") && run.workflow !== null)?.workflow;
387
- const check = name ? championOf(records, name, refused)?.check : undefined;
395
+ const check = name ? championOf(records, name)?.check : undefined;
388
396
  if (!check?.n)
389
397
  return null;
390
398
  const agreed = check.agreed ?? 0, alone = check.alone ?? 0;
@@ -638,8 +646,9 @@ export function callArgsOf(entries) {
638
646
  }
639
647
  else if (entry.kind === KINDS.callStart) {
640
648
  const data = (entry.data ?? {});
649
+ // An SDK learned_workflow start stored withheld names its workflow apart from its input (CallStartData.workflow).
641
650
  if (typeof data.callId === "string" && typeof data.tool === "string")
642
- out.set(data.callId, { tool: data.tool, args: argsOf(data.input) });
651
+ out.set(data.callId, { tool: data.tool, args: typeof data.workflow === "string" ? { name: data.workflow } : argsOf(data.input) });
643
652
  }
644
653
  }
645
654
  return out;
@@ -687,7 +696,7 @@ export function usedOnly(started, terminal, at) {
687
696
  }
688
697
  /** GET /runs/{id}/learning from the one store, in the shape the route gives (learning-routes.ts runLearningBody): the
689
698
  * run's learning end (runLearningEnd) and the seed it started from as its launch records it, what it held for its
690
- * owner's OK as it stands on its agent's folder's main (`statuses`, learning-routes.ts statusesOf, read only when it held
699
+ * owner's OK as it stands at its agent's newest save (`statuses`, learning-routes.ts statusesOf, read only when it held
691
700
  * something; none: as the merge wrote it), settled once the run is final. Null when the run kept no learning. */
692
701
  export async function runLearningOverStore(store, runId, shown, secrets, statuses) {
693
702
  const started = await learningStartOfRun(store, runId);
@@ -700,7 +709,7 @@ export async function runLearningOverStore(store, runId, shown, secrets, statuse
700
709
  return null;
701
710
  // A kept compile's promotion (learn/promote.ts), as the agent's records say now: unread, it stays undecided.
702
711
  if (end.compiled?.digest && row) {
703
- const promoted = promotedOf(await promotionsOf(store.settings, row.agentId).catch(() => []), end.compiled.workflow, end.compiled.digest);
712
+ const promoted = promotedOf(await promotionsOf(store.learning, row.agentId).catch(() => []), end.compiled.workflow, end.compiled.digest);
704
713
  if (promoted !== undefined)
705
714
  end.compiled = { ...end.compiled, promoted };
706
715
  }
@@ -711,7 +720,7 @@ export async function runLearningOverStore(store, runId, shown, secrets, statuse
711
720
  // The run's own grade (PUT /runs/{id}/grade), as its agent keeps it and the PUT answered it, with the round it opened.
712
721
  // Never its `expected` (a person's words, uncut), nor its label (not kept). Its workflow's name is cut as every other
713
722
  // learning name is (`shown.name`): a secret registered after the grade never shows here.
714
- const grade = row ? (await gradesOf(store.settings, row.agentId).catch(() => [])).find((one) => one.run === runId) : undefined;
723
+ const grade = row ? (await gradesOf(store.learning, row.agentId).catch(() => [])).find((one) => one.run === runId) : undefined;
715
724
  if (!grade)
716
725
  return body;
717
726
  const { expected: _, ...graded } = gradeView(grade);
@@ -23,7 +23,7 @@ export async function agentLoopOverStore(store, agentId) {
23
23
  const current = (await store.agents.get(agentId))?.currentRevision;
24
24
  const body = current ? (await store.agents.revision(current))?.body : undefined;
25
25
  const completed_runs = (await lastOwnRuns(store, agentId, loopOf(body?.learning).compile_after)).length;
26
- const promotions = await promotionsOf(store.settings, agentId).catch(() => []);
26
+ const promotions = await promotionsOf(store.learning, agentId).catch(() => []);
27
27
  const compiles = [];
28
28
  for (const run of ended) {
29
29
  for (const kept of await roundsOf(store, run.id).catch(() => [])) {
@@ -10,10 +10,14 @@ import type { PendingAsk } from "./browser-person.js";
10
10
  import { type Approvals } from "./approvals.js";
11
11
  import { type KeptListing, type RunListing, type RunRow, type Store } from "./store/store.js";
12
12
  import type { RecordingView } from "./run-recordings.js";
13
+ import { type FactoryActivity, type FactoryObserved } from "./factory-activity.js";
13
14
  /** What the store-backed view needs beside the store: where its console lives, every secret it never shows (read now, so
14
15
  * one rotated is cut at once), and the agents' saved sign-ins (for the handed-pointer cut). The server passes the same it
15
16
  * passes the file path. */
16
17
  export interface ViewDeps {
18
+ /** Scoped factory lists ask for source/provenance metadata. Ordinary run reads keep their existing shape and cost.
19
+ * "kept": all of it but who observes the run now, for a listing (KeptFactory): that is read when it is listed. */
20
+ readonly factory?: boolean | "kept";
17
21
  readonly origin: string;
18
22
  readonly serverSecrets: () => string[];
19
23
  readonly signIns?: SignInReader;
@@ -27,7 +31,7 @@ export interface ViewDeps {
27
31
  * run's error names a refused key in plain words, as its Timeline's error row does. Default: this process's
28
32
  * environment (the server passes it with the keys a person saved). */
29
33
  readonly keyEnv?: () => NodeJS.ProcessEnv;
30
- /** Each learned item's status on agent `agentId`'s learning folder's main (learning-routes.ts statusesOf): what a run held
34
+ /** Each learned item's status at agent `agentId`'s newest learning save (learning-routes.ts statusesOf): what a run held
31
35
  * for its owner's OK reads as it stands there. None: as the merge wrote it. */
32
36
  readonly statuses?: (agentId: string) => Promise<ReadonlyMap<string, ItemStatus> | undefined>;
33
37
  /** Run `runId`'s screen recordings (run-recordings.ts recordingsOf), the run ended at `endedAt` (null: it has not). Only
@@ -55,6 +59,9 @@ export declare const answerOf: (timeline: readonly TimelineEvent[]) => string |
55
59
  /** The run read from the store: the row, its launch, its timeline, its agent's revision count for the version, its
56
60
  * learning end, and the sign-in cut it serves through. Undefined for an unknown run. */
57
61
  interface StoreRun {
62
+ readonly factory?: Omit<FactoryActivity, "controls" | "observation"> & {
63
+ readonly observation?: FactoryActivity["observation"];
64
+ };
58
65
  readonly native?: Record<string, unknown>;
59
66
  readonly sdk?: Record<string, unknown>;
60
67
  readonly cli_learning?: Record<string, unknown>;
@@ -134,6 +141,10 @@ interface StoreRun {
134
141
  * look-back's own end is in (poll_after_ms 1000, the timeline not final). */
135
142
  readonly lookingBack?: true;
136
143
  }
144
+ /** A runner holds the run's claim now: it is not in a final state, a runner is named on its row, and its lease has not run
145
+ * out (claimed_until >= now, the predicate the claimable query's `claimed_until < ?` is the negation of). `now` is the
146
+ * server's clock, so a test on a moved clock reads a fresh claim as live. */
147
+ export declare function liveOf(runRow: RunRow, now: number): boolean;
137
148
  /** Whether the run's turn stands on a person: a tool call asked for their approval with no answer in its journal (the
138
149
  * view's `approvals`, asksOf), or a browser or desktop hand-over neither answered in its journal nor by a hand-back row.
139
150
  * By the journal alone, never by the clock: a hand-over past its expiry still holds the turn until its expiry is written
@@ -164,7 +175,7 @@ export declare function lookingBackEnd(store: Store, stored: RunRow): Promise<Ke
164
175
  * and for an unknown run. */
165
176
  export declare function toolsUsdOverStore(store: Store, runId: string): Promise<number | null>;
166
177
  /** The start sweep's heal of run `runId` (cost-heal.ts): the same rule as its run read's (bookedCostOf, healOf), from its
167
- * row, its launch and its journal alone, so a sweep over many runs reads no timeline and no learning folder. True when
178
+ * row, its launch and its journal alone, so a sweep over many runs reads no timeline and no learning. True when
168
179
  * it wrote the booking's figure; a failed read or write throws, for the sweep to count. */
169
180
  export declare function healedOverStore(store: Store, runId: string): Promise<boolean>;
170
181
  /** GET /runs/{id}'s answer from the store, byte-identical to runs.ts's view for the same run. Undefined for an unknown run. */
@@ -182,6 +193,17 @@ export declare function summaryOfView(view: Record<string, unknown>): Record<str
182
193
  * sign-in it was handed could not be read: that read may fail only for now, and the run reads whole once it recovers);
183
194
  * and what outside the run it read (LISTING_HELD, LISTING_KEYED). Undefined for an unknown run. */
184
195
  export declare function listingOverStore(store: Store, runId: string, deps: ViewDeps): Promise<RunListing | undefined>;
196
+ /** What a listing keeps for the Agent Factory (RunListing.factory): the run's factory projection as the build's view gave
197
+ * it (`activity`: its watermark of that build's snapshot, its source, controls, last activity, GitHub work and children,
198
+ * all of which move only with a write that moves the run's mark), and who the run is observed through (`observed`), which
199
+ * a scoped list reads at each request (factory-activity.ts observationOf): a lease renewed writes nothing to the run. */
200
+ export type KeptFactory = {
201
+ readonly activity: Omit<FactoryActivity, "observation">;
202
+ readonly observed: FactoryObserved;
203
+ };
204
+ /** What `listing` keeps for the Agent Factory, cut again of the server's secrets as `listedItem` cuts its item when they
205
+ * moved since its build; undefined for a listing built before one was kept, which a scoped list builds again, once. */
206
+ export declare function keptFactory(listing: KeptListing, serverSecrets: readonly string[]): KeptFactory | undefined;
185
207
  /** Whether `listing` is cut of the server's secrets as they are now. A list builds any other again before it shows it
186
208
  * (server.ts runsPage): the run's view cuts a value whole where it holds a secret (a note's name reads [redacted]), which
187
209
  * cutting the built item again could not do. */
@@ -8,7 +8,7 @@ import { isDeepStrictEqual } from "node:util";
8
8
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
9
9
  import { CAPS, isMessageRow } from "./timeline/index.js";
10
10
  import { runLink } from "./console-links.js";
11
- import { redacted, redactedAnswer, redactedOutput, redactedOutputWhole, withheldWhole, withoutLoopback } from "./key-refusal.js";
11
+ import { redacted, redactedAnswer, redactedOutput, redactedOutputWhole, withoutLoopback } from "./key-refusal.js";
12
12
  import { structuredAnswer } from "./answer-json.js";
13
13
  import { isObject } from "./validate.js";
14
14
  import { currentLearning, holdsForOk, learningView, LEARNING_LABEL, secretsShown, shortOf } from "./learning.js";
@@ -28,7 +28,7 @@ import { capNowOf, KINDS } from "./runner/journal-kinds.js";
28
28
  import { laidOf, pathViewOf, roundsOf, runLearningEnd, usedOnly } from "./store-reads/learning.js";
29
29
  import { inReflect, reflectRanges } from "./runner/end-of-run.js";
30
30
  import { correctionCount } from "./learn/corrections.js";
31
- import { forgetServedAnswers, isCliRecord, servedSince, runReflect, runTimeline, wholeAnswerFor, wholeAnswers, withoutFeedbackRounds } from "./store-reads/journal.js";
31
+ import { forgetServedAnswers, isCliRecord, rowCutsOnce, servedSince, runReflect, runTimeline, wholeAnswerFor, wholeAnswers, withoutFeedbackRounds } from "./store-reads/journal.js";
32
32
  import { costOfRun, readRun, runReadState } from "./store-reads/runs.js";
33
33
  import { feedbackOf, keptEndOf } from "./runner/feedback-round.js";
34
34
  import { runCutValues, runErrorWordsOf, underCut } from "./run-cut.js";
@@ -41,6 +41,7 @@ import { approvalsOf } from "./approvals.js";
41
41
  import { FINAL_STATES, stoppedByPerson } from "./store/store.js";
42
42
  import { LISTING_HELD, LISTING_KEYED } from "./store/schema.js";
43
43
  import { createHash } from "node:crypto";
44
+ import { factoryChildren, factoryGithub, factoryLastActivity, factoryObservation, factoryObserved, factorySource } from "./factory-activity.js";
44
45
  /** A run that has ended reads one of these (the old RunRow state → the v2 status: an escalation is a completion with a
45
46
  * review; a stopped run is a cancellation), as runs.ts's STATUS_OF mapped them. A running run reads its status from the
46
47
  * journal, and so does an agentic run a person stopped, which reads running (runReadState). */
@@ -153,7 +154,7 @@ function pausedOf(runRow, entries) {
153
154
  /** A runner holds the run's claim now: it is not in a final state, a runner is named on its row, and its lease has not run
154
155
  * out (claimed_until >= now, the predicate the claimable query's `claimed_until < ?` is the negation of). `now` is the
155
156
  * server's clock, so a test on a moved clock reads a fresh claim as live. */
156
- function liveOf(runRow, now) {
157
+ export function liveOf(runRow, now) {
157
158
  return !FINAL_STATES.includes(runRow.state) && runRow.runner !== null && runRow.claimedUntil !== null && runRow.claimedUntil >= now;
158
159
  }
159
160
  /** Whether the run's turn stands on a person: a tool call asked for their approval with no answer in its journal (the
@@ -193,7 +194,7 @@ async function storeRunOf(store, runId, deps) {
193
194
  await healStoredCost(store, runId, run.heal);
194
195
  if (!run?.shownEnd || !holdsForOk(run.shownEnd) || !deps.statuses)
195
196
  return run && { ...run, learningEnd: run.shownEnd, since };
196
- // What the learning end held for its owner's OK reads as it stands now on its agent's folder's main (learning.ts
197
+ // What the learning end held for its owner's OK reads as it stands now at its agent's newest save (learning.ts
197
198
  // currentLearning); its record stays as the merge wrote it.
198
199
  return { ...run, learningEnd: currentLearning(run.shownEnd, await deps.statuses(run.row.agent)), since };
199
200
  }
@@ -268,7 +269,8 @@ async function storeRunIn(store, runId, deps, cut, since) {
268
269
  // A run that ended reads settled, and its usage row says its cost ("Cost: …"), never what it has cost so far. One
269
270
  // looking back is still going: its look-back's rows come yet.
270
271
  // A call's arguments, or a web call's output, split across two strings are withheld whole (TimelineOptions.holds).
271
- const timelineOptions = { settled: terminal && !lookingBack, ended: terminal && !lookingBack, redact: (text) => redacted(text, values), holds: (text) => withheldWhole(text, values) };
272
+ // Each text cut once per held value set (rowCutsOnce): a polled view cuts only what an earlier read had not.
273
+ const timelineOptions = { settled: terminal && !lookingBack, ended: terminal && !lookingBack, ...rowCutsOnce(store, runId, cut, since) };
272
274
  // Rendered from the records read above, so its usage row and the cost's `plan` (bookedSpend over the same entries) are
273
275
  // of one read.
274
276
  const timeline = withAsks(await wholeAnswers(store, runId, context, await runTimeline(store, runId, context, timelineOptions, records), timelineOptions, wholeAnswerFor(values), since));
@@ -424,7 +426,15 @@ async function storeRunIn(store, runId, deps, cut, since) {
424
426
  const endSaidCost = endCost && !lookingBack ? endSaid !== undefined : false;
425
427
  const endUnread = !lookingBack && bookedCost !== undefined && !endCost && endSaid === null;
426
428
  const heal = lookingBack ? undefined : healOf(endCost, runRow);
427
- return { ...(cli_learning ? { cli_learning } : {}), ...(sdk ? { sdk } : {}), ...(native ? { native } : {}), row, runRow, launch, rows, version, harness, learningEnd: shownEnd, shownEnd, view, unshown, values, live, updatedAtMs, lastProgressAt, budget, paused, browserAsk, computerAsk, approvalsMode, output, ...(review ? { review } : {}), structured, decisions, model, windDown, ...(endCost ? { endCost, endSaidCost } : {}), ...(endUnread ? { endUnread } : {}), ...(heal ? { heal } : {}), ...(lookingBack ? { lookingBack: true } : {}) };
429
+ const factory = deps.factory ? {
430
+ lifecycle_version: await store.runs.changesHead(),
431
+ ...factorySource(launch, harness),
432
+ ...(deps.factory === "kept" ? {} : { observation: await factoryObservation(store, launch, live, liveRow?.updatedAt, deps.now ?? Date.now) }),
433
+ last_activity_at: factoryLastActivity(records),
434
+ github: unshown ? null : factoryGithub(launch, (text) => withoutLoopback(redacted(text, values))),
435
+ children: terminal || FINAL_STATES.includes(runRow.state) || unshown ? [] : await factoryChildren(store, runId, records, (text) => withoutLoopback(redacted(text, values))),
436
+ } : undefined;
437
+ return { ...(factory ? { factory } : {}), ...(cli_learning ? { cli_learning } : {}), ...(sdk ? { sdk } : {}), ...(native ? { native } : {}), row, runRow, launch, rows, version, harness, learningEnd: shownEnd, shownEnd, view, unshown, values, live, updatedAtMs, lastProgressAt, budget, paused, browserAsk, computerAsk, approvalsMode, output, ...(review ? { review } : {}), structured, decisions, model, windDown, ...(endCost ? { endCost, endSaidCost } : {}), ...(endUnread ? { endUnread } : {}), ...(heal ? { heal } : {}), ...(lookingBack ? { lookingBack: true } : {}) };
428
438
  }
429
439
  /** Run read `read` (a run still going, as the store holds it) as the end `ended` keeps (its state, summary and end time:
430
440
  * the end a run looking back keeps), its cost as read. */
@@ -567,7 +577,7 @@ function healOf(endCost, runRow) {
567
577
  return { epoch: runRow.epoch, endedAt: runRow.endedAt, costUsd: endCost.usd, costUpperBound };
568
578
  }
569
579
  /** The start sweep's heal of run `runId` (cost-heal.ts): the same rule as its run read's (bookedCostOf, healOf), from its
570
- * row, its launch and its journal alone, so a sweep over many runs reads no timeline and no learning folder. True when
580
+ * row, its launch and its journal alone, so a sweep over many runs reads no timeline and no learning. True when
571
581
  * it wrote the booking's figure; a failed read or write throws, for the sweep to count. */
572
582
  export async function healedOverStore(store, runId) {
573
583
  const heal = await store.snapshot(async (snapshot) => {
@@ -649,6 +659,11 @@ async function viewOfRun(store, runId, deps, run, read) {
649
659
  const settled = terminal && ended && !run.lookingBack;
650
660
  return {
651
661
  ...(run.cli_learning && !unshown ? { cli_learning: redactedOutput(run.cli_learning, values) } : {}),
662
+ ...(run.factory ? { factory: { ...run.factory, controls: {
663
+ stop: run.factory.control === "managed" && row.kind === "agentic" && status === "working" && state === "working",
664
+ cancel: run.factory.control === "managed" && !terminal && !FINAL_STATES.includes(runRow.state),
665
+ approve: run.factory.control === "managed" && !FINAL_STATES.includes(runRow.state) && pending?.kind === "approval",
666
+ } } } : {}),
652
667
  ...(run.sdk && !unshown ? { sdk: redactedOutput(run.sdk, values) } : {}),
653
668
  ...(run.native && !unshown ? { native: redactedOutput(run.native, values) } : {}),
654
669
  run_id: row.id,
@@ -722,6 +737,7 @@ export function summaryOfView(view) {
722
737
  return {
723
738
  run_id, agent_id, agent_version, console_url, revision, kind, sha, status, state, title,
724
739
  ...(view.cli_learning ? { cli_learning: view.cli_learning } : {}),
740
+ ...(view.factory ? { factory: view.factory, ...(view.computer ? { computer: view.computer } : {}) } : {}),
725
741
  ...(view.sdk ? { sdk: view.sdk } : {}),
726
742
  ...(view.native ? { native: view.native } : {}),
727
743
  ...(effort ? { effort } : {}),
@@ -741,11 +757,12 @@ export function summaryOfView(view) {
741
757
  * and what outside the run it read (LISTING_HELD, LISTING_KEYED). Undefined for an unknown run. */
742
758
  export async function listingOverStore(store, runId, deps) {
743
759
  const cut = secretsDigest(deps.serverSecrets());
744
- const run = await storeRunOf(store, runId, deps);
760
+ // The same read gives what a scoped list shows beside the item (KeptFactory), so that list reads rows alone too.
761
+ const run = await storeRunOf(store, runId, { ...deps, factory: "kept" });
745
762
  if (!run)
746
763
  return undefined;
747
764
  const read = { withheld: false };
748
- const summary = summaryOfView(await viewOfRun(store, runId, deps, run, read));
765
+ const { factory: activity, computer: _computer, ...summary } = summaryOfView(await viewOfRun(store, runId, deps, run, read));
749
766
  const status = String(summary.status);
750
767
  const terminal = TERMINAL.has(status);
751
768
  const asks = terminal ? [] : [run.browserAsk?.expires_at, run.computerAsk?.expires_at].map((at) => (typeof at === "string" ? Date.parse(at) : Number.NaN)).filter((at) => Number.isFinite(at));
@@ -758,8 +775,18 @@ export async function listingOverStore(store, runId, deps) {
758
775
  live: run.live,
759
776
  until: expiries.length ? Math.min(...expiries) : null,
760
777
  flags,
778
+ factory: { activity, observed: factoryObserved(run.launch) },
761
779
  };
762
780
  }
781
+ /** What `listing` keeps for the Agent Factory, cut again of the server's secrets as `listedItem` cuts its item when they
782
+ * moved since its build; undefined for a listing built before one was kept, which a scoped list builds again, once. */
783
+ export function keptFactory(listing, serverSecrets) {
784
+ const kept = listing.factory;
785
+ if (!isObject(kept) || !isObject(kept.activity) || !isObject(kept.observed))
786
+ return undefined;
787
+ const { activity, observed } = kept;
788
+ return listing.cut === secretsDigest(serverSecrets) ? { activity, observed } : { activity: redactedOutput(activity, [...serverSecrets]), observed };
789
+ }
763
790
  /** Whether `listing` is cut of the server's secrets as they are now. A list builds any other again before it shows it
764
791
  * (server.ts runsPage): the run's view cuts a value whole where it holds a secret (a note's name reads [redacted]), which
765
792
  * cutting the built item again could not do. */
@@ -776,8 +803,10 @@ export function listedItem(listing, origin, archivedAt, serverSecrets) {
776
803
  const item = { ...listing.item, console_url: runLink(origin, String(listing.item.run_id)), archived_at: archivedAt === null ? null : iso(archivedAt) };
777
804
  return listing.cut === secretsDigest(serverSecrets) ? item : redactedOutput(item, [...serverSecrets]);
778
805
  }
779
- /** A set of secrets' digest, the same for the same set in any order: what a listing was cut of. */
780
- const secretsDigest = (values) => createHash("sha256").update([...new Set(values)].sort().join("\0")).digest("hex");
806
+ /** A set of secrets' digest, the same for the same set in any order: what a listing was cut of. Of the sorted values'
807
+ * JSON, which escapes a lone surrogate and a NUL as written, so no two sets share it: as UTF-8 every lone surrogate is
808
+ * the one replacement character, and values joined by a NUL read as one value that holds it. */
809
+ const secretsDigest = (values) => createHash("sha256").update(JSON.stringify([...new Set(values)].sort())).digest("hex");
781
810
  /** A run's facts as its view states them, and none of its words: its kind, revision, agent, status and times, and whether
782
811
  * its output is withheld (`unshown`). What a read that serves its own parts (the graph) needs of the run: read off the
783
812
  * run as viewOverStore reads it, with nothing of it served, so nothing is redacted here. Undefined for an unknown run. */