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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +144 -16
  3. package/dist/agent-delete.d.ts +33 -10
  4. package/dist/agent-delete.js +184 -26
  5. package/dist/agents-store.d.ts +6 -2
  6. package/dist/agents-store.js +18 -5
  7. package/dist/agents.d.ts +8 -1
  8. package/dist/agents.js +14 -4
  9. package/dist/answer-json.d.ts +2 -2
  10. package/dist/answer-json.js +3 -4
  11. package/dist/archil-routes.d.ts +1 -1
  12. package/dist/archil-routes.js +4 -3
  13. package/dist/browser-sessions.d.ts +56 -0
  14. package/dist/browser-sessions.js +117 -0
  15. package/dist/computer-routes.d.ts +4 -15
  16. package/dist/computer-routes.js +6 -10
  17. package/dist/console/assets/index-Bzn4eUYF.js +715 -0
  18. package/dist/console/assets/index-CR2ZGei1.css +1 -0
  19. package/dist/console/index.html +2 -2
  20. package/dist/errors.d.ts +4 -1
  21. package/dist/errors.js +15 -5
  22. package/dist/import.js +4 -3
  23. package/dist/learn/check.d.ts +11 -2
  24. package/dist/learn/check.js +12 -9
  25. package/dist/learn/promote.d.ts +7 -1
  26. package/dist/learn/promote.js +47 -0
  27. package/dist/learn/repick.d.ts +34 -0
  28. package/dist/learn/repick.js +201 -0
  29. package/dist/learned-workflow.d.ts +2 -0
  30. package/dist/learned-workflow.js +18 -1
  31. package/dist/learning-setting.d.ts +13 -0
  32. package/dist/learning-setting.js +23 -1
  33. package/dist/llms.txt +1 -1
  34. package/dist/openapi.js +170 -12
  35. package/dist/paid-calls.d.ts +4 -1
  36. package/dist/paid-calls.js +1 -1
  37. package/dist/run-learning-served.d.ts +1 -1
  38. package/dist/run-usage.d.ts +110 -0
  39. package/dist/run-usage.js +312 -0
  40. package/dist/runner/adapter-loop.js +51 -20
  41. package/dist/runner/conformance/harness.d.ts +2 -0
  42. package/dist/runner/conformance/harness.js +18 -4
  43. package/dist/runner/feedback-round.d.ts +29 -1
  44. package/dist/runner/feedback-round.js +54 -3
  45. package/dist/runner/journal-kinds.d.ts +3 -1
  46. package/dist/runner/learning-end.js +49 -18
  47. package/dist/runner/loop-contract.d.ts +3 -0
  48. package/dist/runner/monid-run.js +2 -2
  49. package/dist/runner/promotion.js +8 -2
  50. package/dist/runner/reflect-hook.js +3 -2
  51. package/dist/runs-over-store.d.ts +3 -2
  52. package/dist/runs-over-store.js +9 -7
  53. package/dist/server.d.ts +3 -3
  54. package/dist/server.js +221 -98
  55. package/dist/store/index.d.ts +2 -2
  56. package/dist/store/index.js +1 -1
  57. package/dist/store/journal/storage.js +1 -1
  58. package/dist/store/open.d.ts +1 -1
  59. package/dist/store/open.js +1 -1
  60. package/dist/store/postgres/migrations/0021_purged.sql +13 -0
  61. package/dist/store/postgres/migrations/0022_computer_intervals.sql +27 -0
  62. package/dist/store/schema.d.ts +15 -1
  63. package/dist/store/schema.js +50 -5
  64. package/dist/store/sqlite/connection.d.ts +4 -1
  65. package/dist/store/sqlite/connection.js +5 -0
  66. package/dist/store/sqlite/run-patch.d.ts +8 -3
  67. package/dist/store/sqlite/run-patch.js +15 -7
  68. package/dist/store/sqlite/store.d.ts +5 -2
  69. package/dist/store/sqlite/store.js +249 -48
  70. package/dist/store/sqlite/worker.d.ts +9 -0
  71. package/dist/store/sqlite/worker.js +18 -1
  72. package/dist/store/store.d.ts +142 -9
  73. package/dist/store/store.js +63 -0
  74. package/dist/store-reads/analytics.js +2 -1
  75. package/dist/store-reads/cap.d.ts +8 -2
  76. package/dist/store-reads/cap.js +27 -3
  77. package/dist/store-reads/learning.d.ts +1 -1
  78. package/dist/store-reads/learning.js +5 -2
  79. package/dist/store-reads/runs.js +2 -0
  80. package/dist/store-reads/stats.js +4 -2
  81. package/dist/store-view.d.ts +7 -0
  82. package/dist/store-view.js +61 -20
  83. package/dist/tools.js +9 -0
  84. package/dist/trigger-targets.d.ts +7 -4
  85. package/dist/trigger-targets.js +6 -6
  86. package/dist/triggers.d.ts +2 -1
  87. package/dist/triggers.js +5 -2
  88. package/dist/validate.d.ts +4 -2
  89. package/dist/validate.js +13 -3
  90. package/dist/viewer-credential.d.ts +3 -4
  91. package/dist/viewer-credential.js +6 -4
  92. package/dist/workspace/computer-for-claim.d.ts +5 -1
  93. package/dist/workspace/computer-for-claim.js +47 -18
  94. package/dist/workspace/computer-intervals.d.ts +20 -0
  95. package/dist/workspace/computer-intervals.js +49 -0
  96. package/dist/workspace/computer-janitor.d.ts +7 -3
  97. package/dist/workspace/computer-janitor.js +14 -6
  98. package/dist/workspace/computer-kept.d.ts +7 -2
  99. package/dist/workspace/computer-kept.js +9 -2
  100. package/dist/workspace/resolve-computer.d.ts +7 -4
  101. package/dist/workspace/resolve-computer.js +21 -32
  102. package/dist/workspace/run-end-computers.d.ts +1 -0
  103. package/dist/workspace/run-end-computers.js +4 -1
  104. package/package.json +10 -10
  105. package/dist/console/assets/index-CTGegcKt.css +0 -1
  106. package/dist/console/assets/index-D1Se6mgG.js +0 -715
@@ -50,6 +50,9 @@ export interface AgentRow {
50
50
  /** The reference of the agent this one mirrors in another system ("<source>:<kind>:<id>"), or null for one made here. An
51
51
  * agent with a reference is read-only from here: it is written on the first run that names it and never edited. */
52
52
  readonly externalRef: string | null;
53
+ /** When the agent was purged (Agents.purge): its row is then a tombstone, its name and description blanked; null when it
54
+ * was not. */
55
+ readonly purgedAt: number | null;
53
56
  }
54
57
  /** The template package an agent was applied from, kept on the revision the apply made (its first): the package's id
55
58
  * (a bundled one's name, an imported one's `github:<owner>/<repo>[/<path>]`), its SemVer version, and the commit SHA it
@@ -215,7 +218,32 @@ export interface RunRow {
215
218
  readonly labels: RunLabels;
216
219
  readonly startedAt: number;
217
220
  readonly endedAt: number | null;
221
+ /** When the run was purged (Runs.purge): its row is then a tombstone, its cost and times kept, everything else of it
222
+ * gone; null when it was not. */
223
+ readonly purgedAt: number | null;
224
+ }
225
+ /** What a purge keeps of a run on its tombstone's metrics (`purged`), read from its journal before that goes: the reads of
226
+ * its spend that read the journal answer from it after (store-reads/cap.ts). `meters`: /usage's meter figures
227
+ * (metersOverStore); `spend`: what it spent as a run that reads running reads it (spendOverStore); `learning`: how its
228
+ * learning ended as GET /stats counts it (store-reads/learning.ts learningCountsOverStore), its state and reason alone,
229
+ * null for none. */
230
+ export interface PurgeKept {
231
+ readonly meters: unknown;
232
+ readonly spend: {
233
+ readonly usd: number | null;
234
+ readonly basis?: string;
235
+ };
236
+ readonly learning: {
237
+ readonly state: string;
238
+ readonly reason: string | null;
239
+ } | null;
218
240
  }
241
+ /** A run's metrics as its tombstone keeps them (Runs.purge): what the totals and the analytics read of them, never a
242
+ * call's arguments or results, a prompt, a URL or a grader's words. Each number (or an unknown one's null) at the top;
243
+ * each tool's calls and errors by its name (GET /stats' top tools); the effort (its analytics group) and the cost basis
244
+ * (metrics.ts storedBasisOf), each a code; and `purged`, `kept`. Everything else goes: its models, a grader's verdict, an
245
+ * audit's or a replay's link, a learned loop's nodes, the path it took (no reader of a tombstone reads it). */
246
+ export declare function tombstoneMetrics(metrics: unknown, kept: PurgeKept): Record<string, unknown>;
219
247
  /** What a runner may change on its run's row, under its claim. A final state with no `endedAt` is stamped now. */
220
248
  export interface RunPatch {
221
249
  readonly state?: RunState;
@@ -231,6 +259,10 @@ export interface RunPatch {
231
259
  * fence); null clears them. While the run runs, a sign-in hashing to one of these cannot be forgotten (sign-ins-store.ts). */
232
260
  readonly signInHanded?: readonly string[] | null;
233
261
  readonly endedAt?: number | null;
262
+ /** A final patch that writes the end the run's job kept before its look-back (feedback-round.ts KeptEnd): a stop or a
263
+ * cancel waiting at its commit cut the look-back, never the job's end, and is refused (refuseLeftovers), unless a
264
+ * person's message waits too: that message's run is the one they stop or cancel. */
265
+ readonly keepsEnd?: boolean;
234
266
  }
235
267
  /** The row runs.update answers. When the patch wrote `signInHanded` (the runner's bind at its claim), `save` rides with it:
236
268
  * whether this run holds the sign-in's save lease — true unless another run already holds one of the handed pointers,
@@ -657,6 +689,17 @@ export declare class AgentDeleting extends Error {
657
689
  name: string;
658
690
  constructor(agentId: string);
659
691
  }
692
+ /** A write to a purged agent (Agents.purge): a revision, its current revision moved, its name or description, its archive,
693
+ * a run or a trigger of it. Refused, nothing written: its purge time is read under the agent row's lock, in the
694
+ * transaction that would write, so of a purge and such a write one commits first and the other sees it (the purge blanks
695
+ * what the write wrote, or the write is refused). A purged agent's row is its tombstone: nothing of it is written again. */
696
+ export declare class AgentPurged extends Error {
697
+ readonly agentId: string;
698
+ readonly archivedAt: number | null;
699
+ readonly purgedAt: number;
700
+ name: string;
701
+ constructor(agentId: string, archivedAt: number | null, purgedAt: number);
702
+ }
660
703
  /** An agent's removal refused while a trigger of it is left (Agents.remove): a trigger keeps things outside its row (its
661
704
  * registration upstream, its adapter settings) that only the trigger engine removes, so its row never goes with the
662
705
  * agent's. Nothing written. */
@@ -674,6 +717,8 @@ export declare class ExternalBodyConflict extends Error {
674
717
  name: string;
675
718
  constructor(ref: string, version: string);
676
719
  }
720
+ /** An agent's rows. Every write to an agent that exists (put, archive, addRevision, setCurrent; templates.upgrade; a run
721
+ * or a trigger of it) is refused once it is purged (AgentPurged), nothing written, and pinOnce writes no pin then. */
677
722
  export interface Agents {
678
723
  /** Creates the agent, or renames it (name, description) when it exists. */
679
724
  put(agent: {
@@ -695,8 +740,10 @@ export interface Agents {
695
740
  hasExternalVersion(agentId: string, version: string): Promise<boolean>;
696
741
  /** The revision that maps `version` of its owning system, or undefined before that version's first run. */
697
742
  externalRevision(agentId: string, version: string): Promise<RevisionRow | undefined>;
743
+ /** The agents, by `archived` (default false). A purged agent (Agents.purge) only with `purged`: what a total counts. */
698
744
  list(options?: {
699
745
  archived?: boolean;
746
+ purged?: boolean;
700
747
  }): Promise<AgentRow[]>;
701
748
  /** Archives the agent, or unarchives it. Archived, every trigger of it that is on is turned off in the same transaction
702
749
  * (`disabled` set to `why`, JSON; its scope rows dropped), and those are the answer: from its commit no firing starts a
@@ -722,13 +769,21 @@ export interface Agents {
722
769
  revisions(agentId: string): Promise<RevisionRow[]>;
723
770
  /** Pins a revision saved with no MCP pin (before pins were made at save) at its first run: `pin` is written only while
724
771
  * the revision still has none, and the pin it has then is the answer, so two first runs at once agree on one. Null when
725
- * there is no such revision. */
772
+ * there is no such revision, or its agent is purged (nothing written). */
726
773
  pinOnce(revisionId: string, pin: unknown): Promise<unknown>;
727
774
  /** The agent's own rows gone, in one transaction (the last write of DELETE /agents/{id}, agent-delete.ts): its learning
728
775
  * rows and kept proposals, its sign-ins and their tombstones, its revisions and the agent. Only once it has no run and
729
776
  * no trigger left (runs.remove and the trigger engine's remove each first): refused while a run is (StoreConstraint)
730
777
  * or a trigger is (TriggersLeft), read under the agent row's lock, nothing written. An agent with no row is no write. */
731
778
  remove(agentId: string): Promise<void>;
779
+ /** The last write of DELETE /agents/{id} for an archived agent made here (agent-delete.ts purgeAgent), in one
780
+ * transaction under the agent row's lock: its learning rows, its sign-ins and their tombstones, the answer a template
781
+ * apply kept naming it, its revisions' content (body, skills, package, note, pins) and its own name and description
782
+ * blanked, and its purge time set last. Only once each of its runs is purged (Runs.purge) and no trigger is left:
783
+ * refused while a run is not (StoreConstraint) or a trigger is (TriggersLeft), nothing written. Its row and its
784
+ * revisions' ids stay, so its runs' tombstones and every total over them read as before. An agent with no row, or one
785
+ * purged already, is no write. On SQLite, once it commits, a WAL checkpoint (Runs.purge). */
786
+ purge(agentId: string): Promise<void>;
732
787
  }
733
788
  export interface Templates {
734
789
  /** A template applied: the agent, its first revision (with the package) and its triggers, in one transaction, all or
@@ -849,7 +904,8 @@ export interface Runs {
849
904
  /** A queued run of `revisionId`, its row's only writer until a runner claims it. With `origin`, the origin row is written
850
905
  * in the same transaction, so a retry under the same key finds this run (runOfOrigin); a key already used is refused
851
906
  * (StoreConstraint), and nothing is written. With `launch`, its launch row is written in the same transaction too (all
852
- * or nothing). */
907
+ * or nothing). A launch made from another run (its body's `replay.of`, `audit.of`) takes that run's row lock and
908
+ * reads it in the same transaction: made from a purged run, it is refused (RunPurged), nothing written. */
853
909
  create(run: {
854
910
  id: string;
855
911
  agentId: string;
@@ -900,7 +956,9 @@ export interface Runs {
900
956
  learning: unknown;
901
957
  }[]>;
902
958
  /** Newest first, at most `limit` (no limit: all). `archived` filters on the run's own archive time (true: archived,
903
- * false: not); its agent's archive is read apart. A built-in learning run (one a kept learning names) is never listed. `labels`: only runs holding every one of these labels, key and value. */
959
+ * false: not); its agent's archive is read apart. A built-in learning run (one a kept learning names) is never listed. `labels`: only runs holding every one of these labels, key and value.
960
+ * A purged run (Runs.purge) only with `purged`: the readers of money and counts (usage, stats, analytics) and an
961
+ * import's read of the sessions it holds, never a reader of a run's content. */
904
962
  list(filter: {
905
963
  agentId?: string;
906
964
  revisionId?: string;
@@ -908,6 +966,7 @@ export interface Runs {
908
966
  archived?: boolean;
909
967
  labels?: RunLabels;
910
968
  limit?: number;
969
+ purged?: boolean;
911
970
  }): Promise<RunRow[]>;
912
971
  /** A page of a runs list, in one read: newest first, `offset` rows on, at most `limit`, and whether more follow (`more`).
913
972
  * Each with its listing as its row keeps it (RUN_LISTING_COLUMNS: null while none has been built), whether that is
@@ -975,11 +1034,32 @@ export interface Runs {
975
1034
  /** Archives the run (its own archive time), or unarchives it: idempotent. */
976
1035
  archive(runId: string, archived: boolean): Promise<void>;
977
1036
  /** Every run of agent `agentId` with its state, oldest first, its built-in learning runs included (which list leaves
978
- * out): what deleting the agent stops and removes. */
1037
+ * out): what deleting the agent stops and removes, with the runner that holds each (null: none) and its purge time. */
979
1038
  every(agentId: string): Promise<{
980
1039
  id: string;
981
1040
  state: RunState;
1041
+ runner: string | null;
1042
+ purgedAt: number | null;
982
1043
  }[]>;
1044
+ /** The runs made from run `runId` that hold what it was given or did, by id: each run whose launch replays its input
1045
+ * (the launch body's `replay.of`) or audits it (`audit.of`: its audit's shadow run), and each learning run its kept
1046
+ * learning names (learning_proposals' learning_run_id). What purging the run purges with it. */
1047
+ madeFrom(runId: string): Promise<string[]>;
1048
+ /** A run purged, in one transaction under its row's lock (DELETE /runs/{id}, agent-delete.ts): its journal, commands,
1049
+ * origin, launch, live view and viewers, its channel posts with their tries and what each channel was told of it, a
1050
+ * trigger's conversation that names it and its changes in the run-change feed gone; a trigger's last run, a firing's run
1051
+ * or wait and a machine's token that name it let go (null); its kept learning's content blanked, each row kept with its
1052
+ * proposal's state alone, as the learning meter and the list of learning runs read it; its row's content blanked
1053
+ * (summary, labels, handed sign-ins, listing) with `kept` folded into its metrics (`purged`), and its purge time set
1054
+ * last. Its id, agent, revision, state, outcome, times, cost and metrics stay: a tombstone, which every total sums as
1055
+ * before. Only a run that is final and that no runner holds: one that is not is refused (StoreConstraint), nothing
1056
+ * written; so is one a run made from it (madeFrom's replays and shadow) not purged names (RunsMadeFromLeft): each is
1057
+ * purged first, and Runs.create, under the same row lock, makes none once it is purged. A run with no row, or one
1058
+ * purged already, is no write. On SQLite, once it commits, a WAL checkpoint (TRUNCATE): with secure_delete on in every
1059
+ * connection, neither the file nor its WAL keeps the purged bytes after it. A checkpoint another connection holds back
1060
+ * is retried once, then told to the store's `warn`; it never fails the purge. Postgres: the old row versions are the
1061
+ * database's until its VACUUM. */
1062
+ purge(runId: string, kept: PurgeKept): Promise<void>;
983
1063
  /** The run's rows gone, in one transaction: its journal, commands, origin, launch, live view and viewers, its channel
984
1064
  * posts with their tries and what each channel was told of it, its kept learning, its changes in the run-change feed,
985
1065
  * a trigger's conversation that names it, and the run (a firing or trigger that names it keeps no run: ON DELETE SET
@@ -993,11 +1073,14 @@ export interface Runs {
993
1073
  * so its next turn is booked on top of what it spent), and `command` (the follow-up's steer) is written untaken for it.
994
1074
  * Only an agentic run that ended completed (state 'ended') or that a person stopped (state 'stopped', outcome
995
1075
  * 'stopped'), not imported and not a learning run, reopens: a workflow, a failed or cancelled run, any other, or none
996
- * is RunFinal, and nothing is written. */
1076
+ * is RunFinal, and nothing is written. With `endedAt`, only the run whose end is at that time (a grade's round opens
1077
+ * the end it read, never a later one): any other is RunFinal too. */
997
1078
  reopen(runId: string, command: {
998
1079
  kind: string;
999
1080
  body?: unknown;
1000
- }, options?: LaunchSealedWrite): Promise<Command>;
1081
+ }, options?: LaunchSealedWrite & {
1082
+ readonly endedAt?: number;
1083
+ }): Promise<Command>;
1001
1084
  /** Wakes a parked run: its wake_at set to now on the deadlines' clock, so a runner claims it at its next poll (the
1002
1085
  * claimable rule's wake branch) and its loop reads what it waits on again. True when the run was parked; a run in any
1003
1086
  * other state (or none) is left as it is, false. Its claim, if one holds it while it parks, is let go as before: the
@@ -1334,6 +1417,39 @@ export interface ComputerLedgerRow {
1334
1417
  readonly detail: Readonly<Record<string, unknown>>;
1335
1418
  readonly updatedAt: number;
1336
1419
  }
1420
+ /** One computer a run's claim made through its provider (store schema `computer_intervals`): by the provider's own id
1421
+ * for it (`providerId`), what its create asked for (null where it asked none), when it was made, whether the run's park
1422
+ * kept it past its claim, and when the provider's delete of it answered ok (`endedAt`; null while none did). */
1423
+ export interface ComputerIntervalRow {
1424
+ readonly runId: string;
1425
+ /** The provider's id in this server's registry (its setting's provider: "docker", "e2b", ...). */
1426
+ readonly provider: string;
1427
+ /** The provider's own id for the computer: what its invoice and console name it by. */
1428
+ readonly providerId: string;
1429
+ /** sandbox, desktop or phone; null when not known. */
1430
+ readonly kind: string | null;
1431
+ readonly gpuType: string | null;
1432
+ readonly gpuCount: number | null;
1433
+ readonly cpus: number | null;
1434
+ readonly memoryMb: number | null;
1435
+ readonly startedAt: number;
1436
+ readonly kept: boolean;
1437
+ readonly endedAt: number | null;
1438
+ }
1439
+ /** Each computer a run made, from its create to its proven delete: how long it lived for its run, and one left running
1440
+ * after its run (no `endedAt`). Every write is idempotent. */
1441
+ export interface ComputerIntervals {
1442
+ /** The computer's row, made: a second call for the same provider and id changes nothing (a retried create answers the
1443
+ * computer it made). */
1444
+ opened(row: Omit<ComputerIntervalRow, "kept" | "endedAt">): Promise<void>;
1445
+ /** The computer was kept past its claim (the run's park). */
1446
+ kept(provider: string, providerId: string): Promise<void>;
1447
+ /** The provider's delete of the computer answered ok at `at`: its end, written only while none is (a later delete of
1448
+ * one already ended never moves it). A computer with no row is left without one. */
1449
+ ended(provider: string, providerId: string, at: number): Promise<void>;
1450
+ /** The run's computers, by when each was made. */
1451
+ forRun(runId: string): Promise<ComputerIntervalRow[]>;
1452
+ }
1337
1453
  /** The labels of the sessions a provider runs with none of its own (a phone provider's), so its list, an attach by
1338
1454
  * labels and the janitor outlive a restart. */
1339
1455
  export interface ComputerLedger {
@@ -1742,6 +1858,8 @@ export interface Store {
1742
1858
  readonly sealedKeys: SealedKeys;
1743
1859
  /** The labels of the sessions a provider runs with none of its own (a phone provider's). */
1744
1860
  readonly computerLedger: ComputerLedger;
1861
+ /** Each computer a run made, from its create to its proven delete. */
1862
+ readonly computerIntervals: ComputerIntervals;
1745
1863
  /** The people's own machines paired with this server, and the codes that pair them (spec/computer/attach.md). */
1746
1864
  readonly pairedComputers: PairedComputers;
1747
1865
  /** The tokens minted for hosted machines that dial this server, each kept as its SHA-256. */
@@ -1763,9 +1881,9 @@ export interface Store {
1763
1881
  readonly sealedSecrets: SealedSecrets;
1764
1882
  /** Runs `work`, writes that replace a secret the store kept in the clear (it answers how many rows it rewrote), so the
1765
1883
  * bytes they replace are not left in the store's files. SQLite: a marker file beside the database is written first;
1766
- * secure_delete is on while `work` runs (a rewritten row's old bytes zeroed in its page); then, when a row was rewritten
1767
- * or an earlier start left the marker, a VACUUM (no free page or free block keeps a copy an earlier, ordinary update
1768
- * left) and a WAL checkpoint (TRUNCATE: the log keeps no older frame). The marker is removed once the checkpoint is
1884
+ * secure_delete is on in every connection from its open, so a rewritten row's old bytes are zeroed in its page; then,
1885
+ * when a row was rewritten or an earlier start left the marker, a VACUUM (no free page or free block keeps a copy an
1886
+ * update left before secure_delete was on) and a WAL checkpoint (TRUNCATE: the log keeps no older frame). The marker is removed once the checkpoint is
1769
1887
  * done; `left` says why it was kept, for the next start to finish. Postgres: `work` alone (a replaced row version is
1770
1888
  * the database's until its vacuum). */
1771
1889
  secureRewrite?(work: () => Promise<number>, options?: SecureRewriteOptions): Promise<SecureRewrite>;
@@ -1954,6 +2072,21 @@ export declare class StoreConstraint extends Error {
1954
2072
  export declare class AnswerTaken extends StoreConstraint {
1955
2073
  constructor(message: string, index: string);
1956
2074
  }
2075
+ /** A run's purge refused while a run made from it (a replay of its input, its audit's shadow run: Runs.madeFrom) is not
2076
+ * purged: one was made after the purge read them (a claim that read the run's launch before). `runs`: those runs. A
2077
+ * StoreConstraint, so the caller answers it as a run not final; nothing written. */
2078
+ export declare class RunsMadeFromLeft extends StoreConstraint {
2079
+ readonly runId: string;
2080
+ readonly runs: readonly string[];
2081
+ constructor(runId: string, runs: readonly string[]);
2082
+ }
2083
+ /** A run made from a purged run (its launch's `replay.of` or `audit.of` names it): refused, nothing written. Its source's
2084
+ * input is gone, and a copy of it is never made again (Runs.create). `runId`: the purged run. */
2085
+ export declare class RunPurged extends Error {
2086
+ readonly runId: string;
2087
+ readonly made: string;
2088
+ constructor(runId: string, made: string);
2089
+ }
1957
2090
  /** An agent's current revision is not the one a conditional write expected (addRevision's `ifCurrent`): another write
1958
2091
  * moved it first. `current` is the agent's current revision now. Nothing was written. */
1959
2092
  export declare class RevisionMoved extends Error {
@@ -8,6 +8,28 @@ export function endedReason(state) {
8
8
  export function stoppedByPerson(run, kind) {
9
9
  return run.state === "stopped" && run.outcome === "stopped" && kind === "agentic" && run.importedFrom === null;
10
10
  }
11
+ /** A run's metrics as its tombstone keeps them (Runs.purge): what the totals and the analytics read of them, never a
12
+ * call's arguments or results, a prompt, a URL or a grader's words. Each number (or an unknown one's null) at the top;
13
+ * each tool's calls and errors by its name (GET /stats' top tools); the effort (its analytics group) and the cost basis
14
+ * (metrics.ts storedBasisOf), each a code; and `purged`, `kept`. Everything else goes: its models, a grader's verdict, an
15
+ * audit's or a replay's link, a learned loop's nodes, the path it took (no reader of a tombstone reads it). */
16
+ export function tombstoneMetrics(metrics, kept) {
17
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
18
+ const count = (value) => (typeof value === "number" && Number.isFinite(value) ? value : 0);
19
+ const from = isObject(metrics) ? metrics : {};
20
+ const out = {};
21
+ for (const [key, value] of Object.entries(from))
22
+ if (value === null || (typeof value === "number" && Number.isFinite(value)))
23
+ out[key] = value;
24
+ if (isObject(from.tools))
25
+ out.tools = Object.fromEntries(Object.entries(from.tools).map(([name, each]) => [name, { calls: count(isObject(each) ? each.calls : 0), errors: count(isObject(each) ? each.errors : 0) }]));
26
+ // A code is a word with no space (an effort level, a cost basis).
27
+ for (const key of ["effort", "costBasis"])
28
+ if (typeof from[key] === "string" && /^[\w-]{1,64}$/.test(from[key]))
29
+ out[key] = from[key];
30
+ out.purged = kept;
31
+ return out;
32
+ }
11
33
  /** A firing a trigger has no room for: `due` firings are DUE_KEPT already. Nothing was written. */
12
34
  export class TriggerFull extends Error {
13
35
  triggerId;
@@ -40,6 +62,22 @@ export class AgentDeleting extends Error {
40
62
  this.agentId = agentId;
41
63
  }
42
64
  }
65
+ /** A write to a purged agent (Agents.purge): a revision, its current revision moved, its name or description, its archive,
66
+ * a run or a trigger of it. Refused, nothing written: its purge time is read under the agent row's lock, in the
67
+ * transaction that would write, so of a purge and such a write one commits first and the other sees it (the purge blanks
68
+ * what the write wrote, or the write is refused). A purged agent's row is its tombstone: nothing of it is written again. */
69
+ export class AgentPurged extends Error {
70
+ agentId;
71
+ archivedAt;
72
+ purgedAt;
73
+ name = "AgentPurged";
74
+ constructor(agentId, archivedAt, purgedAt) {
75
+ super(`the agent ${agentId} is purged`);
76
+ this.agentId = agentId;
77
+ this.archivedAt = archivedAt;
78
+ this.purgedAt = purgedAt;
79
+ }
80
+ }
43
81
  /** An agent's removal refused while a trigger of it is left (Agents.remove): a trigger keeps things outside its row (its
44
82
  * registration upstream, its adapter settings) that only the trigger engine removes, so its row never goes with the
45
83
  * agent's. Nothing written. */
@@ -235,6 +273,31 @@ export class AnswerTaken extends StoreConstraint {
235
273
  this.name = "AnswerTaken";
236
274
  }
237
275
  }
276
+ /** A run's purge refused while a run made from it (a replay of its input, its audit's shadow run: Runs.madeFrom) is not
277
+ * purged: one was made after the purge read them (a claim that read the run's launch before). `runs`: those runs. A
278
+ * StoreConstraint, so the caller answers it as a run not final; nothing written. */
279
+ export class RunsMadeFromLeft extends StoreConstraint {
280
+ runId;
281
+ runs;
282
+ constructor(runId, runs) {
283
+ super(`run ${runId} has runs made from it not purged (${runs.join(", ")}): each is purged first`);
284
+ this.runId = runId;
285
+ this.runs = runs;
286
+ this.name = "RunsMadeFromLeft";
287
+ }
288
+ }
289
+ /** A run made from a purged run (its launch's `replay.of` or `audit.of` names it): refused, nothing written. Its source's
290
+ * input is gone, and a copy of it is never made again (Runs.create). `runId`: the purged run. */
291
+ export class RunPurged extends Error {
292
+ runId;
293
+ made;
294
+ constructor(runId, made) {
295
+ super(`run ${made} is made from run ${runId}, which is purged: it is not started`);
296
+ this.runId = runId;
297
+ this.made = made;
298
+ this.name = "RunPurged";
299
+ }
300
+ }
238
301
  /** An agent's current revision is not the one a conditional write expected (addRevision's `ifCurrent`): another write
239
302
  * moved it first. `current` is the agent's current revision now. Nothing was written. */
240
303
  export class RevisionMoved extends Error {
@@ -21,7 +21,8 @@ export async function analytics(store, filter = {}) {
21
21
  }
22
22
  const fromMs = filter.from === undefined ? null : Date.parse(filter.from);
23
23
  const toMs = filter.to === undefined ? null : Date.parse(filter.to);
24
- const runs = await store.runs.list(filter.agent !== undefined ? { agentId: filter.agent } : {});
24
+ // Purged runs too: a tombstone keeps its state, times, cost and metrics, which these figures read.
25
+ const runs = await store.runs.list({ purged: true, ...(filter.agent !== undefined ? { agentId: filter.agent } : {}) });
25
26
  const agentArchived = new Map();
26
27
  const harnessOf = new Map();
27
28
  const facts = [];
@@ -1,7 +1,13 @@
1
1
  import type { Context } from "@earendil-works/chord/context";
2
2
  import { type Meters } from "../cap.js";
3
- import type { Store } from "../store/store.js";
4
- import { type CostBasis } from "../runner/metrics.js";
3
+ import type { PurgeKept, Store } from "../store/store.js";
4
+ import { cliModelWorked, type CostBasis } from "../runner/metrics.js";
5
+ /** A CLI run whose model answered or called a tool with no model request booked (metrics.ts cliModelWorked): what it
6
+ * spent no booking read, so its spend is unknown. */
7
+ export declare const unbookedCli: (entries: Parameters<typeof cliModelWorked>[0]) => boolean;
8
+ /** What a purged run's tombstone keeps of its journal's figures (Runs.purge folds them into its metrics), read only for a
9
+ * run whose journal reads empty; undefined for any other run. */
10
+ export declare function purgeKept(store: Store, runId: string): Promise<PurgeKept | undefined>;
5
11
  /** What a run has spent, as the cap reads it, from the one store's journal: its model requests and its paid tool calls. */
6
12
  export declare function spentOverStore(store: Store, runId: string, context: Context): Promise<number | null>;
7
13
  /** What a run has spent (spentOverStore) and how its model requests were priced so far (metrics.ts costBasisOf), from one
@@ -3,15 +3,34 @@ import { bookedListSpend, bookedSpend, cliModelWorked, costBasisOf, costIsBooked
3
3
  import { isCliRecord, runEntries, withPaidCosts } from "./journal.js";
4
4
  /** A CLI run whose model answered or called a tool with no model request booked (metrics.ts cliModelWorked): what it
5
5
  * spent no booking read, so its spend is unknown. */
6
- const unbookedCli = (entries) => isCliRecord(entries) && bookedSpend(entries, "model").requests === 0 && cliModelWorked(entries);
6
+ export const unbookedCli = (entries) => isCliRecord(entries) && bookedSpend(entries, "model").requests === 0 && cliModelWorked(entries);
7
+ /** What a purged run's tombstone keeps of its journal's figures (Runs.purge folds them into its metrics), read only for a
8
+ * run whose journal reads empty; undefined for any other run. */
9
+ export async function purgeKept(store, runId) {
10
+ const row = await store.runs.get(runId);
11
+ if (!row || row.purgedAt === null)
12
+ return undefined;
13
+ return row.metrics?.purged;
14
+ }
7
15
  /** What a run has spent, as the cap reads it, from the one store's journal: its model requests and its paid tool calls. */
8
16
  export async function spentOverStore(store, runId, context) {
9
- return spentOf(await runEntries(store, runId, context));
17
+ const entries = await runEntries(store, runId, context);
18
+ if (!entries.length) {
19
+ const kept = await purgeKept(store, runId);
20
+ if (kept)
21
+ return kept.spend.usd;
22
+ }
23
+ return spentOf(entries);
10
24
  }
11
25
  /** What a run has spent (spentOverStore) and how its model requests were priced so far (metrics.ts costBasisOf), from one
12
26
  * read of its journal; `basis` undefined while it booked no model request. */
13
27
  export async function spendOverStore(store, runId, context) {
14
28
  const entries = await runEntries(store, runId, context);
29
+ if (!entries.length) {
30
+ const kept = await purgeKept(store, runId);
31
+ if (kept)
32
+ return { usd: kept.spend.usd, basis: kept.spend.basis };
33
+ }
15
34
  const model = bookedSpend(entries, "model");
16
35
  return { usd: spentOf(entries), basis: model.requests > 0 ? costBasisOf(model) : undefined };
17
36
  }
@@ -40,8 +59,13 @@ function spentOf(entries) {
40
59
  * file-backed run held each on its root. A run with no journal reads as a store that was never there: every figure 0, tokens unknown. */
41
60
  export async function metersOverStore(store, runId, context) {
42
61
  const raw = await runEntries(store, runId, context);
43
- if (!raw.length)
62
+ if (!raw.length) {
63
+ // A purged run's journal is gone: its figures are the ones its purge read from it (Runs.purge, PurgeKept).
64
+ const kept = await purgeKept(store, runId);
65
+ if (kept)
66
+ return kept.meters;
44
67
  return { tools: 0, tokens: null, browser: { usd: 0, seconds: 0 }, others: 0, known: { tokens: 0, browser: 0, others: 0 } };
68
+ }
45
69
  const figures = meterFiguresFrom(withPaidCosts(raw).map((entry) => ({ conversation: Number(entry.conversationId ?? 0), entry })));
46
70
  // A run whose record carries no cost of its own (a CLI harness's, a workflow's): its tokens meter is its model requests
47
71
  // at what they were booked at (metrics.ts bookedSpend, the one reader), never the $0 its record reads.
@@ -308,7 +308,7 @@ export declare function runLearningOverStore(store: Store, runId: string, shown:
308
308
  feedback_status: "running" | "ended" | "not_run" | null;
309
309
  source: "feedback" | "eval";
310
310
  graded_at: string;
311
- path: "agent" | "workflow" | "replay" | "handed_back" | "audit";
311
+ path: "agent" | "workflow" | "replay" | "audit" | "handed_back";
312
312
  workflow_digest: string | null;
313
313
  feedback: "correction" | null;
314
314
  run_id: string;
@@ -116,9 +116,12 @@ export async function learningCountsOverStore(store, filter, records) {
116
116
  const out = { runs: 0, merged: 0, dropped: {}, in_progress: 0 };
117
117
  const agentArchived = new Map();
118
118
  const workflow = new Map();
119
- const listed = await store.runs.list(filter.agent !== undefined ? { agentId: filter.agent } : {});
119
+ // Purged runs too: a tombstone keeps how its learning ended (PurgeKept.learning), which these counts read as before.
120
+ const listed = await store.runs.list({ purged: true, ...(filter.agent !== undefined ? { agentId: filter.agent } : {}) });
120
121
  const byAgent = new Map();
121
122
  for (const run of listed) {
123
+ if (run.purgedAt !== null)
124
+ continue;
122
125
  const runs = byAgent.get(run.agentId);
123
126
  if (runs)
124
127
  runs.push(run);
@@ -147,7 +150,7 @@ export async function learningCountsOverStore(store, filter, records) {
147
150
  workflow.set(run.revisionId, (await store.agents.revision(run.revisionId))?.kind === "workflow");
148
151
  if (workflow.get(run.revisionId))
149
152
  continue;
150
- const learning = await runLearningEnd(store, run.id, undefined, await recordsOf(run.agentId));
153
+ const learning = run.purgedAt !== null ? run.metrics?.purged?.learning : await runLearningEnd(store, run.id, undefined, await recordsOf(run.agentId));
151
154
  // A reason this server does not give is not counted.
152
155
  if (!learning || (learning.reason !== null && !LEARNING_REASONS.includes(learning.reason)))
153
156
  continue;
@@ -76,7 +76,9 @@ function joins(store, context) {
76
76
  /** The runs, newest first; `agent`, `revision` and `labels` (every one held) narrow it. Archived runs are listed too (the
77
77
  * server filters them), with the archive time coalesced onto each row, and a not-ended run's cost its booked-so-far spend. */
78
78
  export async function listRuns(store, filter, context) {
79
+ // Purged runs too: /usage sums their cost from their tombstones, as before their purge.
79
80
  const runs = await store.runs.list({
81
+ purged: true,
80
82
  ...(filter.agent !== undefined ? { agentId: filter.agent } : {}),
81
83
  ...(filter.revision !== undefined ? { revisionId: filter.revision } : {}),
82
84
  ...(filter.labels !== undefined ? { labels: filter.labels } : {}),
@@ -5,7 +5,8 @@ const RUN_STATES = ["running", "completed", "failed", "stopped", "escalated"];
5
5
  const emptyCounts = () => ({ total: 0, running: 0, completed: 0, failed: 0, stopped: 0, escalated: 0 });
6
6
  /** Every agent, by name then id (the old order), with its archive and name. */
7
7
  async function allAgents(store) {
8
- const [live, archived] = await Promise.all([store.agents.list({ archived: false }), store.agents.list({ archived: true })]);
8
+ // A purged agent (an archived one's tombstone) still counts, as its runs' cost does.
9
+ const [live, archived] = await Promise.all([store.agents.list({ archived: false, purged: true }), store.agents.list({ archived: true, purged: true })]);
9
10
  return [...live.map((a) => ({ id: a.id, name: a.name, archived: false })), ...archived.map((a) => ({ id: a.id, name: a.name, archived: true }))].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
10
11
  }
11
12
  /** The store's counts and cost sums (the old AgentStoreReader.stats), from A's run rows and agents: one pass over the
@@ -13,7 +14,8 @@ async function allAgents(store) {
13
14
  export async function stats(store) {
14
15
  const agents = await allAgents(store);
15
16
  const archivedAgent = new Set(agents.filter((a) => a.archived).map((a) => a.id));
16
- const runs = await store.runs.list({});
17
+ // A purged run's tombstone keeps its state and cost: every count and sum reads it as before its purge.
18
+ const runs = await store.runs.list({ purged: true });
17
19
  // Per agent, the runs whose own archive is null (shown) and the count whose own archive is set (hidden).
18
20
  const shown = new Map();
19
21
  const hidden = new Map();
@@ -5,6 +5,7 @@ import { type Pending, type RunMoment, type RunView, type SignInReader, type Sta
5
5
  import { type BookedSpend, type RunCost } from "./runner/metrics.js";
6
6
  import { type EndData } from "./runner/journal-kinds.js";
7
7
  import { type RunReadState, readRun } from "./store-reads/runs.js";
8
+ import { type KeptEnd } from "./runner/feedback-round.js";
8
9
  import type { PendingAsk } from "./browser-person.js";
9
10
  import { type Approvals } from "./approvals.js";
10
11
  import { type KeptListing, type RunListing, type RunRow, type Store } from "./store/store.js";
@@ -124,6 +125,9 @@ interface StoreRun {
124
125
  readonly costUsd: number;
125
126
  readonly costUpperBound: boolean;
126
127
  };
128
+ /** The run looks back after its job's end (`row` and `runRow` read as that end): nothing of it is settled until the
129
+ * look-back's own end is in (poll_after_ms 1000, the timeline not final). */
130
+ readonly lookingBack?: true;
127
131
  }
128
132
  /** Whether the run's turn stands on a person: a tool call asked for their approval with no answer in its journal (the
129
133
  * view's `approvals`, asksOf), or a browser or desktop hand-over neither answered in its journal nor by a hand-back row.
@@ -139,6 +143,9 @@ export declare function standsOnPerson(approvals: ReadonlyMap<string, {
139
143
  * True when written; false when another write got there first, or when the write failed (said, never thrown: a read
140
144
  * never fails on its heal, and the next read or start sweep writes it again). */
141
145
  export declare function healStoredCost(store: Store, runId: string, heal: NonNullable<StoreRun["heal"]>): Promise<boolean>;
146
+ /** The end run `runId` keeps while it looks back after its job ended, as every reader serves it (lookingBackOf), else
147
+ * undefined: a run that reads ended while it is still learning from that end. */
148
+ export declare function lookingBackEnd(store: Store, runId: string): Promise<KeptEnd | undefined>;
142
149
  /** What run `runId`'s paid tool calls cost, the run read's `cost.tools_usd` (server.ts allInViewOf): the charges its
143
150
  * paid-tools session booked (a monid endpoint's, a priced MCP tool's, Parallel's behind the web tools, the browser's
144
151
  * time), joined and rounded by the one rule its `usd` is (costWordsOf), less those in its end-of-run turn, which are