@parcha/agentrun-serve 0.1.0-beta.51 → 0.1.0-beta.52

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 (135) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +94 -13
  3. package/dist/adapters.js +1 -1
  4. package/dist/agent-delete.d.ts +13 -2
  5. package/dist/agent-delete.js +14 -5
  6. package/dist/agents-store.d.ts +5 -1
  7. package/dist/agents-store.js +10 -4
  8. package/dist/api-only.d.ts +4 -2
  9. package/dist/api-only.js +5 -3
  10. package/dist/archil-routes.d.ts +1 -0
  11. package/dist/archil-routes.js +28 -2
  12. package/dist/computer-setting.d.ts +8 -0
  13. package/dist/computer-setting.js +11 -0
  14. package/dist/computers.d.ts +6 -2
  15. package/dist/computers.js +2 -2
  16. package/dist/console/assets/index-B-D0EM3j.js +733 -0
  17. package/dist/console/assets/index-DlQepP2J.css +1 -0
  18. package/dist/console/index.html +2 -2
  19. package/dist/fal-price.d.ts +76 -0
  20. package/dist/fal-price.js +368 -0
  21. package/dist/learn/commit.d.ts +5 -0
  22. package/dist/learn/commit.js +4 -1
  23. package/dist/learn/compile.d.ts +13 -5
  24. package/dist/learn/compile.js +24 -7
  25. package/dist/learn/delete.d.ts +12 -6
  26. package/dist/learn/delete.js +17 -11
  27. package/dist/learn/folder.d.ts +11 -0
  28. package/dist/learn/folder.js +20 -3
  29. package/dist/learn/learning-of.d.ts +8 -0
  30. package/dist/learn/learning-of.js +8 -0
  31. package/dist/learn/learning.sh +14 -1
  32. package/dist/learn/promote.d.ts +51 -7
  33. package/dist/learn/promote.js +51 -8
  34. package/dist/learning-reset.d.ts +18 -0
  35. package/dist/learning-reset.js +115 -0
  36. package/dist/learning-routes.d.ts +1 -1
  37. package/dist/learning-words.d.ts +5 -0
  38. package/dist/learning-words.js +5 -0
  39. package/dist/learning.d.ts +8 -6
  40. package/dist/learning.js +5 -4
  41. package/dist/llms.txt +1 -0
  42. package/dist/mcp-gateway.d.ts +39 -2
  43. package/dist/mcp-gateway.js +41 -10
  44. package/dist/mcp-pin-first.js +1 -1
  45. package/dist/mcp-servers-store.d.ts +1 -0
  46. package/dist/mcp-servers-store.js +2 -1
  47. package/dist/media-duration.d.ts +2 -0
  48. package/dist/media-duration.js +136 -0
  49. package/dist/openapi.js +45 -12
  50. package/dist/provider.d.ts +8 -0
  51. package/dist/provider.js +14 -2
  52. package/dist/refusal-words.d.ts +0 -3
  53. package/dist/refusal-words.js +0 -3
  54. package/dist/request-metadata.d.ts +20 -0
  55. package/dist/request-metadata.js +24 -0
  56. package/dist/run-launch.d.ts +13 -4
  57. package/dist/run-launch.js +14 -3
  58. package/dist/run-learning-served.d.ts +2 -2
  59. package/dist/run-usage.d.ts +48 -4
  60. package/dist/run-usage.js +156 -39
  61. package/dist/run-view.d.ts +1 -1
  62. package/dist/run-view.js +3 -7
  63. package/dist/runner/adapter-loop.d.ts +3 -1
  64. package/dist/runner/adapter-loop.js +12 -9
  65. package/dist/runner/adapter-run-spec.d.ts +1 -1
  66. package/dist/runner/adapter-run-spec.js +13 -13
  67. package/dist/runner/audit.d.ts +8 -3
  68. package/dist/runner/audit.js +21 -6
  69. package/dist/runner/claim-secrets.d.ts +2 -1
  70. package/dist/runner/claim-secrets.js +5 -3
  71. package/dist/runner/cli-run-spec.d.ts +1 -1
  72. package/dist/runner/cli-run-spec.js +12 -11
  73. package/dist/runner/conformance/harness.js +4 -2
  74. package/dist/runner/dispatch.js +4 -2
  75. package/dist/runner/harness-loops.js +5 -2
  76. package/dist/runner/journal-kinds.d.ts +3 -0
  77. package/dist/runner/learning-end.d.ts +2 -1
  78. package/dist/runner/learning-end.js +47 -22
  79. package/dist/runner/mcp-claim.js +1 -1
  80. package/dist/runner/mcp-run.d.ts +9 -0
  81. package/dist/runner/mcp-run.js +16 -1
  82. package/dist/runner/model-route.js +7 -4
  83. package/dist/runner/promotion.d.ts +40 -21
  84. package/dist/runner/promotion.js +130 -59
  85. package/dist/runner/run-child-host.js +6 -4
  86. package/dist/runner/runner.js +15 -3
  87. package/dist/runner/sdk-loop.d.ts +2 -2
  88. package/dist/runner/sdk-loop.js +3 -3
  89. package/dist/runner/store-port.d.ts +3 -0
  90. package/dist/runner/workflow-spec.js +3 -3
  91. package/dist/runs-over-store.d.ts +5 -2
  92. package/dist/runs-over-store.js +14 -7
  93. package/dist/sdk/check.d.ts +6 -5
  94. package/dist/sdk/check.js +17 -16
  95. package/dist/sdk/runs.js +81 -65
  96. package/dist/server.js +84 -20
  97. package/dist/store/agent-body.d.ts +4 -0
  98. package/dist/store/agent-body.js +4 -1
  99. package/dist/store/index.d.ts +1 -1
  100. package/dist/store/journal/storage.d.ts +2 -0
  101. package/dist/store/journal/storage.js +2 -1
  102. package/dist/store/postgres/migrations/0025_run_attempts.sql +27 -0
  103. package/dist/store/postgres/migrations/0026_run_disk.sql +23 -0
  104. package/dist/store/schema.d.ts +14 -1
  105. package/dist/store/schema.js +42 -4
  106. package/dist/store/sqlite/run-launch.d.ts +22 -0
  107. package/dist/store/sqlite/run-launch.js +72 -7
  108. package/dist/store/sqlite/run-patch.d.ts +2 -1
  109. package/dist/store/sqlite/run-patch.js +4 -3
  110. package/dist/store/sqlite/store.js +141 -29
  111. package/dist/store/store-schema.js +2 -2
  112. package/dist/store/store.d.ts +67 -4
  113. package/dist/store-reads/learning.d.ts +12 -8
  114. package/dist/store-reads/learning.js +33 -24
  115. package/dist/store-reads/loop.d.ts +4 -3
  116. package/dist/store-reads/loop.js +7 -5
  117. package/dist/template-eval.js +4 -4
  118. package/dist/templates.d.ts +3 -0
  119. package/dist/templates.js +7 -5
  120. package/dist/timeline/labels.js +1 -1
  121. package/dist/tools.js +1 -1
  122. package/dist/uploads-archil.js +2 -1
  123. package/dist/uploads.d.ts +0 -3
  124. package/dist/uploads.js +2 -11
  125. package/dist/validate.js +5 -1
  126. package/dist/web-save.d.ts +3 -0
  127. package/dist/web-save.js +17 -2
  128. package/dist/workspace/archil-exec.js +1 -1
  129. package/dist/workspace/archil.js +1 -1
  130. package/dist/workspace/revision-skills.js +24 -11
  131. package/dist/workspace/synced-folder.d.ts +3 -3
  132. package/dist/workspace/synced-folder.js +7 -6
  133. package/package.json +10 -10
  134. package/dist/console/assets/index-Bt1B51b7.js +0 -733
  135. package/dist/console/assets/index-sVftE9Ht.css +0 -1
@@ -26,6 +26,47 @@ export interface Claim {
26
26
  readonly lost?: {
27
27
  readonly runner: string;
28
28
  };
29
+ /** Which turn of the run this claim works and which attempt at it (run_attempts, RunAttemptRow): set by the claim that
30
+ * took the run, absent on a claim read back (claimsOf) and on a store that keeps none (a test's). */
31
+ readonly turn?: number;
32
+ readonly attempt?: number;
33
+ }
34
+ /** Why a claim let its run go while the run was still at work, so another claim does that work again: `drain`, its
35
+ * runner closed (a deploy, a scale-down) and handed the run back; `retry`, its loop ended interrupted on its own (or its
36
+ * end was refused) and the run was released to be tried again; `lease_lapse`, its runner was there but could not renew
37
+ * the claim before it ran out; `crash`, the claim's lease ran out with nothing said of it (its runner died). */
38
+ export type AttemptCause = "drain" | "crash" | "lease_lapse" | "retry";
39
+ /** One claim of a run (store schema `run_attempts`), written by the claim itself: the turn it works and its attempt at
40
+ * it. A turn is the work one claim starts afresh: the run's first, a follow-up's, a resume after a park. A claim that
41
+ * takes over a turn another claim was cut from (its run still running, and that claim let it go for `cut`, or its lease
42
+ * ran out) works the same turn again: its attempt is one more, and `cause` says why the one before was cut. Infra's
43
+ * work, not the run's: every request the cut attempt made is made again. `journalFrom`: the first journal entry id this
44
+ * claim could write (the run's next id when it claimed), so each entry of the run's journal is read as its claim's. */
45
+ export interface RunAttemptRow {
46
+ readonly runId: string;
47
+ readonly epoch: number;
48
+ readonly turn: number;
49
+ readonly attempt: number;
50
+ /** Why the attempt before was cut; null on a turn's first attempt. */
51
+ readonly cause: AttemptCause | null;
52
+ /** Why this claim let the run go with its turn unfinished (`drain`, `retry`, `lease_lapse`); null while it holds the
53
+ * run, and when it ended the turn (an answer, a park, the run's end) or died without a word. */
54
+ readonly cut: Exclude<AttemptCause, "crash"> | null;
55
+ readonly runner: string;
56
+ readonly from: RunState;
57
+ readonly journalFrom: number;
58
+ /** When the claim took the run, on the store's clock (ms). */
59
+ readonly claimedAt: number;
60
+ }
61
+ /** Each claim of a run, its turn and attempt (RunAttemptRow): written in the claim's own transaction, its `cut` in its
62
+ * release's. Data only: nothing reads it to decide what a run does. */
63
+ export interface RunAttempts {
64
+ /** The claim at `epoch` lost its lease while its runner was there (runner.ts loseClaim): its cut, and the cause of the
65
+ * claim that took the run over from it if that one was read as a crash. Unfenced and idempotent: a cut already said, or
66
+ * a claim with no row, is left as it is. */
67
+ lapsed(runId: string, epoch: number): Promise<void>;
68
+ /** The run's claims, by epoch. */
69
+ forRun(runId: string): Promise<RunAttemptRow[]>;
29
70
  }
30
71
  /** A command the server wrote for a run (stop, cancel, steer, approve, deny, raise): one row, read by the run's runner in id order
31
72
  * and marked taken, or refused with why. `body` is JSON. */
@@ -216,6 +257,10 @@ export interface RunRow {
216
257
  readonly signInHanded: readonly string[] | null;
217
258
  /** The caller's labels, given at its start (RunLabels): opaque to the server, kept as given, {} when none. */
218
259
  readonly labels: RunLabels;
260
+ /** The disk the run's launch named as its own (a customer's Archil disk: the launch body's `archil_disk` of kind "launch"),
261
+ * by its id, written once with the queued run; null for a run on the default disk (its launch named none, or its agent's
262
+ * own). A run on a named disk learns nothing, so learning reads only runs with none (learn/learning-of.ts). */
263
+ readonly disk: string | null;
219
264
  readonly startedAt: number;
220
265
  readonly endedAt: number | null;
221
266
  /** When the run was purged (Runs.purge): its row is then a tombstone, its cost and times kept, everything else of it
@@ -966,8 +1011,13 @@ export interface Runs {
966
1011
  runId: string;
967
1012
  learning: unknown;
968
1013
  }[]>;
1014
+ /** The ids of agent `agentId`'s runs started after `at` whose learning seed was read at or before it (the launch body's
1015
+ * `learning.seededAt`): a reset's watermark (learn/compile.ts sinceReset). Reads that one number of the runs started
1016
+ * after `at` alone. */
1017
+ seededBefore(agentId: string, at: number): Promise<string[]>;
969
1018
  /** Newest first, at most `limit` (no limit: all). `archived` filters on the run's own archive time (true: archived,
970
1019
  * 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.
1020
+ * `disk`: only the runs on that disk (RunRow.disk), null for the default disk's; not given, every disk's.
971
1021
  * A purged run (Runs.purge) only with `purged`: the readers of money and counts (usage, stats, analytics) and an
972
1022
  * import's read of the sessions it holds, never a reader of a run's content. */
973
1023
  list(filter: {
@@ -976,6 +1026,7 @@ export interface Runs {
976
1026
  state?: RunState;
977
1027
  archived?: boolean;
978
1028
  labels?: RunLabels;
1029
+ disk?: string | null;
979
1030
  limit?: number;
980
1031
  purged?: boolean;
981
1032
  }): Promise<RunRow[]>;
@@ -1044,13 +1095,15 @@ export interface Runs {
1044
1095
  }): Promise<string[]>;
1045
1096
  /** Archives the run (its own archive time), or unarchives it: idempotent. */
1046
1097
  archive(runId: string, archived: boolean): Promise<void>;
1047
- /** Every run of agent `agentId` with its state, oldest first, its built-in learning runs included (which list leaves
1048
- * out): what deleting the agent stops and removes, with the runner that holds each (null: none) and its purge time. */
1098
+ /** Every run of agent `agentId` with its state, oldest first, its built-in learning runs and purged runs included
1099
+ * (which list leaves out): what deleting the agent stops and removes, with the runner that holds each (null: none),
1100
+ * its purge time and its disk (RunRow.disk: where a learning folder of the agent may be, learn/learning-of.ts namedDisksOf). */
1049
1101
  every(agentId: string): Promise<{
1050
1102
  id: string;
1051
1103
  state: RunState;
1052
1104
  runner: string | null;
1053
1105
  purgedAt: number | null;
1106
+ disk: string | null;
1054
1107
  }[]>;
1055
1108
  /** The runs made from run `runId` that hold what it was given or did, by id: each run whose launch replays its input
1056
1109
  * (the launch body's `replay.of`) or audits it (`audit.of`: its audit's shadow run), and each learning run its kept
@@ -1068,8 +1121,9 @@ export interface Runs {
1068
1121
  * purged first, and Runs.create, under the same row lock, makes none once it is purged. A run with no row, or one
1069
1122
  * purged already, is no write. On SQLite, once it commits, a WAL checkpoint (TRUNCATE): with secure_delete on in every
1070
1123
  * connection, neither the file nor its WAL keeps the purged bytes after it. A checkpoint another connection holds back
1071
- * is retried once, then told to the store's `warn`; it never fails the purge. Postgres: the old row versions are the
1072
- * database's until its VACUUM. */
1124
+ * leaves the scrub's marker, for the next start's scrub; a marker that cannot be written throws, the purge committed,
1125
+ * and the retried DELETE arranges it again (Store.purgeScrub). Postgres: the old row versions are the database's until
1126
+ * its VACUUM. */
1073
1127
  purge(runId: string, kept: PurgeKept): Promise<void>;
1074
1128
  /** The run's rows gone, in one transaction: its journal, commands, origin, launch, live view and viewers, its channel
1075
1129
  * posts with their tries and what each channel was told of it, its kept learning, its changes in the run-change feed,
@@ -1899,6 +1953,8 @@ export interface Store {
1899
1953
  readonly computerLedger: ComputerLedger;
1900
1954
  /** Each computer a run made, from its create to its proven delete. */
1901
1955
  readonly computerIntervals: ComputerIntervals;
1956
+ /** Each claim of a run: the turn it works and its attempt at it, and why it let the run go unfinished. */
1957
+ readonly runAttempts: RunAttempts;
1902
1958
  /** The people's own machines paired with this server, and the codes that pair them (spec/computer/attach.md). */
1903
1959
  readonly pairedComputers: PairedComputers;
1904
1960
  /** The tokens minted for hosted machines that dial this server, each kept as its SHA-256. */
@@ -1926,6 +1982,12 @@ export interface Store {
1926
1982
  * done; `left` says why it was kept, for the next start to finish. Postgres: `work` alone (a replaced row version is
1927
1983
  * the database's until its vacuum). */
1928
1984
  secureRewrite?(work: () => Promise<number>, options?: SecureRewriteOptions): Promise<SecureRewrite>;
1985
+ /** A DELETE of a run or agent already purged (agent-delete.ts): a purge can commit and then fail to write the scrub's
1986
+ * marker (Runs.purge), and its retry finds the row purged. SQLite with a file, when no marker is there: the purge's
1987
+ * WAL checkpoint again, and the marker when another connection still holds the log back; with the marker there, no
1988
+ * write, but the marker is the purge's too, so a rewrite under way that wrote it removes it only after a checkpoint
1989
+ * that truncates the log. Postgres and a store with no file: nothing. */
1990
+ purgeScrub(): Promise<void>;
1929
1991
  /** Reads the store's schema version and its runner floor now, without a lock or a write: a runner reads it at each
1930
1992
  * renewal (runner/main.ts), and stops once the floor is above the version its build knows. */
1931
1993
  schemaState?(): Promise<StoreSchemaState>;
@@ -1950,6 +2012,7 @@ export interface Store {
1950
2012
  state?: ReleasedState;
1951
2013
  wakeAt?: number | null;
1952
2014
  backoffUntil?: number | null;
2015
+ cut?: "drain" | "retry";
1953
2016
  }): Promise<void>;
1954
2017
  /** The run's journal: pi-durable's Storage for this one run, every commit fenced by the claim (store/journal). Its commit
1955
2018
  * holds the store's one connection while it runs, so it awaits nothing but its own statements, under a deadline. */
@@ -6,7 +6,7 @@ import { type PastRun, workflowCostsOf } from "../runner/workflow-first.js";
6
6
  import { type Reflect } from "../reflect-range.js";
7
7
  import type { EntryLike, TimelineEvent } from "../timeline/index.js";
8
8
  import type { AnalyticsFilter } from "./analytics.js";
9
- import { type PromotionRecord } from "../learn/promote.js";
9
+ import { type PromotionRecord, type ResetRevision } from "../learn/promote.js";
10
10
  import type { LearningProposal, Store } from "../store/store.js";
11
11
  /** A run's learning end: the Learning fields its end sets. */
12
12
  export type RunLearningEnd = Learning;
@@ -120,8 +120,10 @@ export type CompileSpend = {
120
120
  * its own) and its check (the replay runs that ran it: metrics.path `replay` of its workflow at its digest); unknown
121
121
  * once a part's cost is (null, or only a bound). A compile whose drafts all failed drafted none: no revision carries it
122
122
  * (the bill's unattributed does). It is spread over its first K served runs (`workflow` or `handed_back` of its workflow
123
- * at its digest), K its check's compile_after; `state` from its newest record. */
124
- export declare function revisionLedgerOf(records: readonly PromotionRecord[], rows: readonly LedgerRow[], compiles?: readonly CompileSpend[]): ReturnType<typeof amortize>;
123
+ * at its digest), K its check's compile_after; `state` from its newest record. A revision an earlier reset of the agent's
124
+ * learning deleted (`reset`, learn/promote.ts keepResetLedger) is one too, first, stopped, at the K it was kept with,
125
+ * unless the records name it again. */
126
+ export declare function revisionLedgerOf(records: readonly PromotionRecord[], rows: readonly LedgerRow[], compiles?: readonly CompileSpend[], reset?: readonly ResetRevision[]): ReturnType<typeof amortize>;
125
127
  /** Run `runId`'s path and its costs as GET /runs/{id} shows them (A8): `path` its record's (metrics.path, RUN_PATHS:
126
128
  * `agent` for a run that does not learn; null while it has not ended, for a workflow revision's run, and for a run that
127
129
  * learns whose end named none); `usd` its own spend, the job's (runCostOf's `cost_usd`: its row's cost, `rowUsd` when
@@ -177,9 +179,11 @@ export declare function costRunOf(store: RunRecords, run: RunRecord, n: number |
177
179
  workflow: string | null;
178
180
  }): Promise<Omit<CostRun, "took_over">>;
179
181
  /** The runs the money rule reads for agent `agentId` (runner/workflow-first.ts costLineOf), one set for the run's launch
180
- * and the cost page: of its newest PAST_RUNS runs, each that ended (ended, stopped or failed), is neither imported nor
181
- * archived nor a workflow revision's run, with its all-in cost (allInOf). `known`: all-in costs already read, by run id
182
- * (the cost page's series), read again for no run; `records`, where any other's rows are read (the store's by default). */
182
+ * and the cost page: of its newest PAST_RUNS runs on no named disk (learn/learning-of.ts: one on a named disk learns
183
+ * nothing), each that ended (ended, stopped or failed) since its learning's reset (learn/compile.ts sinceReset: a
184
+ * workflow before it is not the one it learned after, whatever its name), is neither imported nor archived nor a
185
+ * workflow revision's run, with its all-in cost (allInOf). `known`: all-in costs already read, by run id (the cost
186
+ * page's series), read again for no run; `records`, where any other's rows are read (the store's by default). */
183
187
  export declare function pastRunsOverStore(store: Store, agentId: string, known?: ReadonlyMap<string, number | null>, records?: RunRecords): Promise<PastRun[]>;
184
188
  /** The money rule's decision for agent `agentId` (runner/workflow-first.ts costStopOf) over the runs a run's launch reads
185
189
  * (pastRunsOverStore), as the launch reads them: runs that can't be read now stop nothing (workflowFirstOf serves). What
@@ -273,7 +277,7 @@ export declare function usedOnly(started: NonNullable<RunLaunch["learning"]>, te
273
277
  export declare function runLearningOverStore(store: Store, runId: string, shown: Shown, secrets: readonly string[], statuses?: (agentId: string) => Promise<ReadonlyMap<string, ItemStatus> | undefined>): Promise<{
274
278
  run: string;
275
279
  state: "dropped" | "merged" | "seeded" | "reflecting";
276
- reason: "cancelled" | "use" | "empty" | "crashed" | "reflect_failed" | "no_budget" | "checker" | "unknown_cost" | "seed_failed" | null;
280
+ reason: "cancelled" | "reset" | "use" | "empty" | "crashed" | "reflect_failed" | "no_budget" | "checker" | "unknown_cost" | "seed_failed" | null;
277
281
  detail: string | null;
278
282
  at: string;
279
283
  workflows: import("../learning.js").LearnedFile[];
@@ -316,7 +320,7 @@ export declare function runLearningOverStore(store: Store, runId: string, shown:
316
320
  };
317
321
  run: string;
318
322
  state: "dropped" | "merged" | "seeded" | "reflecting";
319
- reason: "cancelled" | "use" | "empty" | "crashed" | "reflect_failed" | "no_budget" | "checker" | "unknown_cost" | "seed_failed" | null;
323
+ reason: "cancelled" | "reset" | "use" | "empty" | "crashed" | "reflect_failed" | "no_budget" | "checker" | "unknown_cost" | "seed_failed" | null;
320
324
  detail: string | null;
321
325
  at: string;
322
326
  workflows: import("../learning.js").LearnedFile[];
@@ -8,7 +8,7 @@ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
8
8
  import { currentLearning, holdsForOk, LEARNING_REASONS } from "../learning.js";
9
9
  import { runLearningBody } from "../learning-routes.js";
10
10
  import { learningStartOf, learningStartOfStored, readLaunchBody, seedFailed } from "../run-launch.js";
11
- import { said, STOPPED } from "../learning-words.js";
11
+ import { said, seedStopped } from "../learning-words.js";
12
12
  import { learningImpact } from "../learning-run.js";
13
13
  import { amortize, billOf, costSummary, JOB_PATHS, noiseOff, RUN_PATHS, runCostOf, SERVED_PATHS, tookOverOf } from "../learning-cost.js";
14
14
  import { COMPILE_AFTER_DEFAULT } from "../learning-setting.js";
@@ -20,9 +20,9 @@ import { correctionCount } from "../learn/corrections.js";
20
20
  import { runEntries, runReflect, runTimeline, withoutFeedbackRounds } from "./journal.js";
21
21
  import { FINAL_STATES, StoreLaunchMissing } from "../store/store.js";
22
22
  import { KINDS } from "../runner/journal-kinds.js";
23
- import { promotedOf } from "../learn/compile.js";
23
+ import { promotedOf, sinceReset } from "../learn/compile.js";
24
24
  import { isShadowRun, shadowRunId } from "../learn/audit.js";
25
- import { championOf, checkShares, gradesOf, gradeView, promotionsOf } from "../learn/promote.js";
25
+ import { championOf, checkShares, gradesOf, gradeView, promotionsOf, resetLedgerOf } from "../learn/promote.js";
26
26
  const timeOf = (ms) => new Date(ms).toISOString();
27
27
  const usdOrNull = (value) => (typeof value === "number" && Number.isFinite(value) ? value : null);
28
28
  const textOrNull = (value) => (typeof value === "string" ? value : null);
@@ -251,8 +251,9 @@ export async function agentCostOverStore(store, agentId, limit = Infinity) {
251
251
  const replay = servingReplayOf(promotions, runs);
252
252
  // The owner's bill: booked $, every run of the series (billOf), from the series' first run on a served path (the
253
253
  // summary's takeover: read from the run rows by their place, as the promotion feed is trimmed and its oldest record need
254
- // not be the first promotion), and each revision's compile and check over the served runs that carry it.
255
- const ledger = await agentLedgerOf(records, promotions, listed);
254
+ // not be the first promotion), and each revision's compile and check over the served runs that carry it: runs on no
255
+ // named disk alone, as a run on one learns nothing and serves nothing (learn/learning-of.ts).
256
+ const ledger = await agentLedgerOf(records, promotions, listed.filter((run) => run.disk === null), await resetLedgerOf(store.settings, agentId));
256
257
  const summary = costSummary(runs, replay);
257
258
  const booked = billOf(runs, summary);
258
259
  // What no run carries is the booked total less every run's all-in (A8), so a revision whose records aged out of the
@@ -315,7 +316,7 @@ function allInV2Of(run, compiles, shares) {
315
316
  }
316
317
  /** The agent's revision ledger (revisionLedgerOf) over `listed` (its runs, as runs.list read them): its ended runs that do
317
318
  * a job or check one (no shadow, no imported or archived run), and the compile turns their rounds asked, by run. */
318
- async function agentLedgerOf(records, promotions, listed) {
319
+ async function agentLedgerOf(records, promotions, listed, reset) {
319
320
  const rows = listed.filter((one) => FINAL_STATES.includes(one.state) && !one.importedFrom && one.archivedAt === null && !isShadowRun(one.id));
320
321
  const compiles = new Map();
321
322
  for (const row of rows) {
@@ -323,7 +324,7 @@ async function agentLedgerOf(records, promotions, listed) {
323
324
  if (asked.length)
324
325
  compiles.set(row.id, asked);
325
326
  }
326
- return { ...revisionLedgerOf(promotions, rows, [...compiles.values()].flat()), compiles };
327
+ return { ...revisionLedgerOf(promotions, rows, [...compiles.values()].flat(), reset), compiles };
327
328
  }
328
329
  /** Each revision of the agent's learned workflows (one per workflow and digest its promotion records name, in the order
329
330
  * they were first recorded) with its learning spend, and what its served runs carry of it (amortize), over `rows`: the
@@ -333,21 +334,26 @@ async function agentLedgerOf(records, promotions, listed) {
333
334
  * its own) and its check (the replay runs that ran it: metrics.path `replay` of its workflow at its digest); unknown
334
335
  * once a part's cost is (null, or only a bound). A compile whose drafts all failed drafted none: no revision carries it
335
336
  * (the bill's unattributed does). It is spread over its first K served runs (`workflow` or `handed_back` of its workflow
336
- * at its digest), K its check's compile_after; `state` from its newest record. */
337
- export function revisionLedgerOf(records, rows, compiles = []) {
337
+ * at its digest), K its check's compile_after; `state` from its newest record. A revision an earlier reset of the agent's
338
+ * learning deleted (`reset`, learn/promote.ts keepResetLedger) is one too, first, stopped, at the K it was kept with,
339
+ * unless the records name it again. */
340
+ export function revisionLedgerOf(records, rows, compiles = [], reset = []) {
338
341
  const ordered = [...rows].sort((a, b) => a.startedAt - b.startedAt || (a.id < b.id ? -1 : 1));
339
342
  const newest = new Map();
340
343
  for (const record of records)
341
344
  newest.set(`${record.workflow}\0${record.digest}`, record);
342
345
  const sum = (parts) => (parts.some((one) => one === null) ? null : noiseOff(parts.reduce((total, one) => total + one, 0)));
343
- const ran = (row, record) => { const at = revisionOfRow(row); return at?.workflow === record.workflow && at.digest === record.digest; };
344
- const revisions = [...newest.values()].map((record) => {
345
- const replays = ordered.filter((row) => metricOf(row).path === "replay" && ran(row, record));
346
+ const ran = (row, workflow, digest) => { const at = revisionOfRow(row); return at?.workflow === workflow && at.digest === digest; };
347
+ const spendOf = (workflow, digest, k, state) => {
348
+ const replays = ordered.filter((row) => metricOf(row).path === "replay" && ran(row, workflow, digest));
346
349
  const check = sum(replays.map((row) => (typeof row.costAtMostUsd === "number" ? null : row.costUsd)));
347
- const compile = sum(compiles.filter((one) => one.workflow === record.workflow && one.digest === record.digest).map((one) => one.usd));
348
- const state = record.decided === "replaying" ? "checking" : championOf(records, record.workflow)?.digest === record.digest ? "serving" : "stopped";
349
- return { workflow: record.workflow, digest: record.digest, compile_usd: compile, check_usd: check, spend_usd: sum([compile, check]), k: record.check?.compile_after ?? COMPILE_AFTER_DEFAULT, state };
350
- });
350
+ const compile = sum(compiles.filter((one) => one.workflow === workflow && one.digest === digest).map((one) => one.usd));
351
+ return { workflow, digest, compile_usd: compile, check_usd: check, spend_usd: sum([compile, check]), k, state };
352
+ };
353
+ const revisions = [
354
+ ...reset.filter((one) => !newest.has(`${one.workflow}\0${one.digest}`)).map((one) => spendOf(one.workflow, one.digest, one.k ?? COMPILE_AFTER_DEFAULT, "stopped")),
355
+ ...[...newest.values()].map((record) => spendOf(record.workflow, record.digest, record.check?.compile_after ?? COMPILE_AFTER_DEFAULT, record.decided === "replaying" ? "checking" : championOf(records, record.workflow)?.digest === record.digest ? "serving" : "stopped")),
356
+ ];
351
357
  const served = ordered.flatMap((row) => {
352
358
  const at = revisionOfRow(row);
353
359
  return SERVED_PATHS.includes(metricOf(row).path) && at ? [{ run_id: row.id, ...at }] : [];
@@ -381,8 +387,9 @@ export async function runAllInOverStore(store, runId, rowUsd) {
381
387
  // Its share of its revision's compile and check: a served run's, over the agent's ledger.
382
388
  let shares = new Map();
383
389
  if (path !== null && SERVED_PATHS.includes(path) && revisionOfRow(run)) {
384
- const listed = (await store.runs.list({ agentId: run.agentId })).filter((one) => one.agentId === run.agentId);
385
- shares = (await agentLedgerOf(await agentRecordsOf(store, run.agentId, listed), await promotionsOf(store.settings, run.agentId), listed)).shares;
390
+ // Over the agent's runs on no named disk, as the cost page's ledger reads (learn/learning-of.ts).
391
+ const listed = (await store.runs.list({ agentId: run.agentId, disk: null })).filter((one) => one.agentId === run.agentId);
392
+ shares = (await agentLedgerOf(await agentRecordsOf(store, run.agentId, listed), await promotionsOf(store.settings, run.agentId), listed, await resetLedgerOf(store.settings, run.agentId))).shares;
386
393
  }
387
394
  const figures = { run_id: run.id, ...cost };
388
395
  const compiles = await compilesOf(store, run.id);
@@ -476,13 +483,16 @@ export async function costRunOf(store, run, n, { path, workflow }) {
476
483
  return { n, run_id: run.id, started_at: new Date(run.startedAt).toISOString(), path, workflow, digest, audited, cost_usd, cost_upper_bound, learning_usd, total_usd };
477
484
  }
478
485
  /** The runs the money rule reads for agent `agentId` (runner/workflow-first.ts costLineOf), one set for the run's launch
479
- * and the cost page: of its newest PAST_RUNS runs, each that ended (ended, stopped or failed), is neither imported nor
480
- * archived nor a workflow revision's run, with its all-in cost (allInOf). `known`: all-in costs already read, by run id
481
- * (the cost page's series), read again for no run; `records`, where any other's rows are read (the store's by default). */
486
+ * and the cost page: of its newest PAST_RUNS runs on no named disk (learn/learning-of.ts: one on a named disk learns
487
+ * nothing), each that ended (ended, stopped or failed) since its learning's reset (learn/compile.ts sinceReset: a
488
+ * workflow before it is not the one it learned after, whatever its name), is neither imported nor archived nor a
489
+ * workflow revision's run, with its all-in cost (allInOf). `known`: all-in costs already read, by run id (the cost
490
+ * page's series), read again for no run; `records`, where any other's rows are read (the store's by default). */
482
491
  export async function pastRunsOverStore(store, agentId, known, records = store) {
483
492
  const kinds = new Map();
484
493
  const kept = [];
485
- const page = await store.runs.list({ agentId, limit: PAST_RUNS });
494
+ const since = await sinceReset(store, agentId);
495
+ const page = (await store.runs.list({ agentId, disk: null, limit: PAST_RUNS })).filter(since);
486
496
  // Each run's audit shadow is read off the page (allInOf's shadowSpendOf): a shadow starts after the run it audits ends,
487
497
  // so it is newer than that run and on the same page of the newest runs; one not on it was never started.
488
498
  const shadows = new Map(page.filter((run) => isShadowRun(run.id)).map((run) => [run.id, run]));
@@ -713,8 +723,7 @@ export function usedOnly(started, terminal, at) {
713
723
  // A start that could not be made (a folder unreadable) handed the run nothing: said so from its start, as the end hook
714
724
  // says it for a run that learns, never "seeded" and then `use`. No proposal is written for it.
715
725
  if (seedFailed(started)) {
716
- const why = started.seedFailed === "unreadable" ? STOPPED.unreadable : started.seedFailed === "not_copied" ? STOPPED.notCopied : STOPPED.noSeed;
717
- return { state: "dropped", reason: "seed_failed", detail: said.stopped(why), at };
726
+ return { state: "dropped", reason: "seed_failed", detail: said.stopped(seedStopped(started.seedFailed)), at };
718
727
  }
719
728
  return terminal ? { state: "dropped", reason: "use", detail: said.use, at } : { state: "seeded", reason: null, detail: said.seeded(correctionCount(started.section), started.workflows?.length ?? 0), at };
720
729
  }
@@ -17,9 +17,10 @@ export type LoopCompile = {
17
17
  draft_errors: string[];
18
18
  };
19
19
  /** The agent's compile turns (every round of each run, roundsOf: newest first, LOOP_COMPILES_MAX), over its ended runs
20
- * (not imported, not archived), and how many completed runs of its own count toward its compile. A compile's `promoted`
21
- * is its revision's promotion as the records say now (null while undecided): whether it serves now is the promotions
22
- * read's `serving`. */
20
+ * (not imported, not archived) since its learning's reset (sinceReset: a compile before it wrote what the reset
21
+ * deleted), and how many completed runs of its own count toward its compile. A compile's `promoted` is its revision's
22
+ * promotion as the records say now (null while undecided): whether it serves now is the promotions read's `serving`.
23
+ * Runs on no named disk alone: one on a named disk learns nothing (learn/learning-of.ts). */
23
24
  export declare function agentLoopOverStore(store: Store, agentId: string): Promise<{
24
25
  compiles: LoopCompile[];
25
26
  completed_runs: number;
@@ -4,18 +4,20 @@
4
4
  // own words only: no input, no answer.
5
5
  import { FINAL_STATES } from "../store/store.js";
6
6
  import { promotionOf, promotionsOf } from "../learn/promote.js";
7
- import { lastOwnRuns, promotedOf } from "../learn/compile.js";
7
+ import { lastOwnRuns, promotedOf, sinceReset } from "../learn/compile.js";
8
8
  import { loopOf } from "../learning-setting.js";
9
9
  import { roundsOf } from "./learning.js";
10
10
  /** How many compile turns the read gives, the newest. */
11
11
  export const LOOP_COMPILES_MAX = 50;
12
12
  const texts = (list) => (Array.isArray(list) ? list.filter((one) => typeof one === "string") : []);
13
13
  /** The agent's compile turns (every round of each run, roundsOf: newest first, LOOP_COMPILES_MAX), over its ended runs
14
- * (not imported, not archived), and how many completed runs of its own count toward its compile. A compile's `promoted`
15
- * is its revision's promotion as the records say now (null while undecided): whether it serves now is the promotions
16
- * read's `serving`. */
14
+ * (not imported, not archived) since its learning's reset (sinceReset: a compile before it wrote what the reset
15
+ * deleted), and how many completed runs of its own count toward its compile. A compile's `promoted` is its revision's
16
+ * promotion as the records say now (null while undecided): whether it serves now is the promotions read's `serving`.
17
+ * Runs on no named disk alone: one on a named disk learns nothing (learn/learning-of.ts). */
17
18
  export async function agentLoopOverStore(store, agentId) {
18
- const ended = (await store.runs.list({ agentId })).filter((run) => run.agentId === agentId && FINAL_STATES.includes(run.state) && !run.importedFrom && run.archivedAt === null).sort((a, b) => a.startedAt - b.startedAt || (a.id < b.id ? -1 : 1));
19
+ const since = await sinceReset(store, agentId);
20
+ const ended = (await store.runs.list({ agentId, disk: null })).filter((run) => run.agentId === agentId && FINAL_STATES.includes(run.state) && !run.importedFrom && run.archivedAt === null && since(run)).sort((a, b) => a.startedAt - b.startedAt || (a.id < b.id ? -1 : 1));
19
21
  // The completed runs of the agent's own toward its compile (what compileDue counts), at most compile_after: the tab
20
22
  // says "N of compile_after" from this, never from the one page of runs it reads.
21
23
  const current = (await store.agents.get(agentId))?.currentRevision;
@@ -1429,11 +1429,11 @@ async function runOnce(ctx, one, n, fakes, mail, feeds) {
1429
1429
  // their own, into the fakes' logs, and outlive the eval. Each one the apply made is deleted at once.
1430
1430
  // An email or feed case's run is its one trigger's: that one stays, until the run is read.
1431
1431
  let kept;
1432
- for (const id of Array.isArray(applied.trigger_ids) ? applied.trigger_ids.map(String) : []) {
1433
- if (via !== undefined && !kept && expectOk(`reading the package's trigger ${id}`, await api("GET", `/triggers/${encodeURIComponent(id)}`)).name === via)
1434
- kept = id;
1432
+ for (const one of Array.isArray(applied.triggers) ? applied.triggers : []) {
1433
+ if (via !== undefined && !kept && one.name === via)
1434
+ kept = one.trigger_id;
1435
1435
  else
1436
- made.triggers.add(id);
1436
+ made.triggers.add(one.trigger_id);
1437
1437
  }
1438
1438
  await deleteTriggers(api, made, true);
1439
1439
  if (via !== undefined && !kept)
@@ -140,6 +140,7 @@ export type Package = {
140
140
  /** Each run's limit: its spend cap (the agent's max_cost_usd). */
141
141
  budget?: {
142
142
  per_run_usd: number;
143
+ max_requests?: number;
143
144
  };
144
145
  /** The agent's `learning`, as a definition takes it: true, false, or the loop's settings (agree_on, each path a required
145
146
  * field of the output schema). */
@@ -292,6 +293,7 @@ export declare function packageView(p: Package): {
292
293
  secrets: string[];
293
294
  budget: {
294
295
  per_run_usd: number;
296
+ max_requests?: number;
295
297
  } | null;
296
298
  learning: LearningSetting;
297
299
  approvals_default: "ask" | "never";
@@ -365,6 +367,7 @@ export declare function packageDetail(p: Package): {
365
367
  secrets: string[];
366
368
  budget: {
367
369
  per_run_usd: number;
370
+ max_requests?: number;
368
371
  } | null;
369
372
  learning: LearningSetting;
370
373
  approvals_default: "ask" | "never";
package/dist/templates.js CHANGED
@@ -691,10 +691,12 @@ export function readPackage(from, { evalFixtures = true } = {}) {
691
691
  const secrets = list(f.secrets, "secrets", (secret) => /^[A-Z][A-Z0-9_]{0,127}$/.test(secret));
692
692
  for (const secret of secrets.filter((name) => !PACKAGE_SECRETS.includes(name)))
693
693
  bad(MANIFEST, `secrets names ${secret}, a key this server cannot hold: a package needs the keys Settings saves and a run is handed (${PACKAGE_SECRETS.join(", ")})`);
694
- // Each run's limit: its spend cap (per_run_usd, the agent's max_cost_usd), required once a budget is given.
694
+ // Each run's limits: its spend cap (per_run_usd, the agent's max_cost_usd), required once a budget is given, and the most
695
+ // requests on free models it makes (max_requests, the agent's max_requests), which a dollar cap cannot bound.
695
696
  const perRun = (value) => typeof value === "number" && Number.isFinite(value) && value > 0;
696
- if (f.budget !== undefined && !(isObject(f.budget) && !unknownFields(f.budget, ["per_run_usd"]).length && perRun(f.budget.per_run_usd)))
697
- bad(MANIFEST, "budget is {per_run_usd: a number above 0}");
697
+ const requests = (value) => value === undefined || (typeof value === "number" && Number.isSafeInteger(value) && value >= 1);
698
+ if (f.budget !== undefined && !(isObject(f.budget) && !unknownFields(f.budget, ["per_run_usd", "max_requests"]).length && perRun(f.budget.per_run_usd) && requests(f.budget.max_requests)))
699
+ bad(MANIFEST, "budget is {per_run_usd: a number above 0, max_requests: a whole number of free-model requests above 0, when given}");
698
700
  const learningIssue = f.learning === undefined ? undefined : learningSettingIssue(f.learning, "learning");
699
701
  if (learningIssue)
700
702
  bad(MANIFEST, learningIssue);
@@ -940,7 +942,7 @@ export function readPackage(from, { evalFixtures = true } = {}) {
940
942
  ...(typeof f.license === "string" ? { license: f.license } : {}), ...(isObject(f.author) ? { author: f.author } : {}), ...(typeof f.repository === "string" ? { repository: f.repository } : {}),
941
943
  ...(typeof f.category === "string" ? { category: f.category } : {}), tags,
942
944
  ...(harness ? { harness } : {}), ...(isObject(f.model) ? { model: { ...f.model, ...(choices ? { choices } : {}) } } : {}), ...(typeof f.effort === "string" ? { effort: f.effort } : {}),
943
- ...(tools ? { tools } : {}), mcp, ...(computer ? { computer } : {}), ...(toolPolicy ? { toolPolicy } : {}), ...(f.checkout === "pull_request" ? { checkout: "pull_request" } : {}), parameters, ...(inputSchema ? { inputSchema } : {}), secrets, ...(isObject(f.budget) ? { budget: { per_run_usd: f.budget.per_run_usd } } : {}), ...(f.learning !== undefined ? { learning: learningSettingOf(f.learning) } : {}), ...(f.approvals === "ask" || f.approvals === "never" ? { approvals: f.approvals } : {}),
945
+ ...(tools ? { tools } : {}), mcp, ...(computer ? { computer } : {}), ...(toolPolicy ? { toolPolicy } : {}), ...(f.checkout === "pull_request" ? { checkout: "pull_request" } : {}), parameters, ...(inputSchema ? { inputSchema } : {}), secrets, ...(isObject(f.budget) ? { budget: { per_run_usd: f.budget.per_run_usd, ...(f.budget.max_requests !== undefined ? { max_requests: f.budget.max_requests } : {}) } } : {}), ...(f.learning !== undefined ? { learning: learningSettingOf(f.learning) } : {}), ...(f.approvals === "ask" || f.approvals === "never" ? { approvals: f.approvals } : {}),
944
946
  triggers: triggers, ...(isObject(f.output) ? { output: { schema: f.output.schema } } : {}), ...(isObject(outputSchema) ? { outputSchema } : {}), instructions, skills, evals,
945
947
  };
946
948
  // What an apply makes, made here with each parameter's default, else a sample of its type, and checked as POST
@@ -1302,7 +1304,7 @@ export function compiled(p, parameters, chosen, _deps) {
1302
1304
  name: p.displayName ? filled(p.displayName, parameters) : p.name, description: p.description, instructions: filled(p.instructions, parameters),
1303
1305
  ...(chosen.harness ? { harness: chosen.harness } : {}), ...(chosen.model ? { model: chosen.model } : {}), ...(chosen.modelTiers && Object.keys(chosen.modelTiers).length ? { model_tiers: chosen.modelTiers } : {}), ...(p.effort ? { thinking: p.effort } : {}),
1304
1306
  ...(pick ? { computer: pick.computer } : {}), ...(tools ? { tools } : {}), ...(Object.keys(settings).length ? { tool_settings: settings } : {}),
1305
- ...(p.learning !== undefined ? { learning: p.learning } : {}), ...(p.budget?.per_run_usd ? { max_cost_usd: p.budget.per_run_usd } : {}), skills,
1307
+ ...(p.learning !== undefined ? { learning: p.learning } : {}), ...(p.budget?.per_run_usd ? { max_cost_usd: p.budget.per_run_usd } : {}), ...(p.budget?.max_requests ? { max_requests: p.budget.max_requests } : {}), skills,
1306
1308
  // The apply's choice: unattended only when it says never (none given: the agent asks).
1307
1309
  ...(chosen.approvals === "never" ? { approvals: "never" } : {}),
1308
1310
  // The package's typed input (manifest `inputs`): what each run's input is checked against, and how the model reads it.
@@ -134,7 +134,7 @@ const fetchOutcome = (result) => {
134
134
  // web_fetch answers a page, `{ok, url, status, title, text, links, refused?, error?}`.
135
135
  registerLabel("web_fetch", fetchLabel, fetchFold, { name: "Fetch web pages" });
136
136
  registerOutcome("web_fetch", fetchOutcome);
137
- // web_save answers `{ok: true, path, bytes, content_type, url}` or `{ok: false, url, path?, refused | error}` (web-save.ts):
137
+ // web_save answers `{ok: true, path, bytes, content_type, duration_s?, url}` or `{ok: false, url, path?, refused | error}` (web-save.ts):
138
138
  // the path it answered, else the one asked (a bare name under media/, as it saves one), and the host it was asked for.
139
139
  const savedAt = (a, result) => {
140
140
  const answered = result && str(obj(json(result.text))?.path);
package/dist/tools.js CHANGED
@@ -628,7 +628,7 @@ export const TOOLS = Object.freeze({
628
628
  // web_save (web-save.ts). It makes no paid request, so nothing books it. No node or call node names it: a workflow's
629
629
  // effect has only a local work path, not the run's Workspace.
630
630
  [WEB_SAVE_TOOL]: {
631
- summary: `Download one public file into the run's work/ (a bare name under media/), never overwriting: { url, path } -> { ok: true, path, bytes, content_type, url } or { ok: false, url, refused | error }; at most ${SAVE_MAX_BYTES / (1024 * 1024)} MiB, a media type only when its bytes agree.`,
631
+ summary: `Download one public file into the run's work/ (a bare name under media/), never overwriting: { url, path } -> { ok: true, path, bytes, content_type, duration_s?, url } (duration_s an mp3, wav, mp4 or m4a's length in seconds) or { ok: false, url, refused | error }; at most ${SAVE_MAX_BYTES / (1024 * 1024)} MiB, a media type only when its bytes agree.`,
632
632
  needs: [],
633
633
  nodes: false,
634
634
  bind: async (host) => {
@@ -32,7 +32,8 @@ import { archilWorkspace } from "./workspace/archil.js";
32
32
  import { agentDirName, runKey } from "./workspace/paths.js";
33
33
  import { runDiskOf } from "./workspace/run-disk.js";
34
34
  import { isWorkspaceError, WorkspaceError } from "./workspace/index.js";
35
- import { answerOf, copyFilesInto, INPUTS_DIR, isUploadedFile, MAX_FILES_PER_RUN, MAX_UPLOAD_BYTES, mismatchOf, pathProblem, readyFilesOf, reservation, sentInOneCall, slots, uuidv7, } from "./uploads.js";
35
+ import { answerOf, copyFilesInto, INPUTS_DIR, isUploadedFile, MAX_FILES_PER_RUN, MAX_UPLOAD_BYTES, mismatchOf, pathProblem, readyFilesOf, reservation, sentInOneCall, slots, } from "./uploads.js";
36
+ import { uuidv7 } from "./agents-store.js";
36
37
  /** The folder of the uploads disk the files are kept under. */
37
38
  export const UPLOADS_KEY = "files";
38
39
  const RECORD = "file.json";
package/dist/uploads.d.ts CHANGED
@@ -51,9 +51,6 @@ export type UploadedFile = {
51
51
  created_at: string;
52
52
  expires_at: null;
53
53
  };
54
- /** A UUIDv7, the form of the agent store's agent and run ids: 48 bits of Unix milliseconds, then random bits, so ids
55
- * sort by creation time. The store mints its own inside it and exports no minter. */
56
- export declare function uuidv7(now?: number): string;
57
54
  /** Why `path` is not the contract's FilePathString (relative, `/` between segments, no empty segment and none that starts
58
55
  * with `.`, no backslash or NUL, at most 1024 characters), or a segment is longer than a name on disk; undefined when it
59
56
  * is one. */
package/dist/uploads.js CHANGED
@@ -3,10 +3,11 @@
3
3
  // for it at its start and copied into its workspace at its claim. Each file is `<data>/files/<file_id>/`: its bytes
4
4
  // (`bytes`) and its record (`file.json`, the contract's File), both 0600, the record written whole. A ready file's bytes
5
5
  // never change, and a run gets a copy of them through its Workspace, never a link: nothing a run does reaches the upload.
6
- import { createHash, randomBytes } from "node:crypto";
6
+ import { createHash } from "node:crypto";
7
7
  import { copyFile, link, lstat, mkdir, open, readdir, readFile, rename, rm, unlink } from "node:fs/promises";
8
8
  import { DISK_DIR } from "./server-fs.js";
9
9
  import { dirname, join } from "node:path";
10
+ import { uuidv7 } from "./agents-store.js";
10
11
  import { ApiError, invalid } from "./errors.js";
11
12
  import { typeOf } from "./file-types.js";
12
13
  import { readJson, serialBy, tempOf, writeDurable } from "./files.js";
@@ -59,16 +60,6 @@ export const uploadUrl = (id) => `/v2/files/${id}`;
59
60
  /** Test seams, tests only: as a run's copy starts, with the run's Workspace, before any file is copied; and as a file
60
61
  * sent in one call writes its record, with the file's folder, its bytes in place. */
61
62
  export const uploadTestHooks = {};
62
- /** A UUIDv7, the form of the agent store's agent and run ids: 48 bits of Unix milliseconds, then random bits, so ids
63
- * sort by creation time. The store mints its own inside it and exports no minter. */
64
- export function uuidv7(now = Date.now()) {
65
- const bytes = randomBytes(16);
66
- bytes.writeUIntBE(now, 0, 6);
67
- bytes[6] = (bytes[6] & 0x0f) | 0x70;
68
- bytes[8] = (bytes[8] & 0x3f) | 0x80;
69
- const hex = bytes.toString("hex");
70
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
71
- }
72
63
  /** Why `path` is not the contract's FilePathString (relative, `/` between segments, no empty segment and none that starts
73
64
  * with `.`, no backslash or NUL, at most 1024 characters), or a segment is longer than a name on disk; undefined when it
74
65
  * is one. */
package/dist/validate.js CHANGED
@@ -18,7 +18,7 @@ export const isObject = (value) => typeof value === "object" && value !== null &
18
18
  /** How long an Idempotency-Key answers with its first answer (capabilities' limits.idempotency_ttl_s). */
19
19
  export const IDEMPOTENCY_TTL_S = 86_400;
20
20
  export const stable = (value) => Array.isArray(value) ? `[${value.map(stable).join(",")}]` : isObject(value) ? `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${stable(value[k])}`).join(",")}}` : JSON.stringify(value);
21
- export const DEFINITION_FIELDS = ["id", "version", "name", "description", "instructions", "workflow", "model", "model_tiers", "thinking", "harness", "place", "computer", "learning", "skills", "tools", "tool_settings", "approvals", "max_cost_usd", "input_schema", "output_schema", "checkout", "native", "sdk", "cli_learning"];
21
+ export const DEFINITION_FIELDS = ["id", "version", "name", "description", "instructions", "workflow", "model", "model_tiers", "thinking", "harness", "place", "computer", "learning", "skills", "tools", "tool_settings", "approvals", "max_cost_usd", "max_requests", "input_schema", "output_schema", "checkout", "native", "sdk", "cli_learning"];
22
22
  /** What an agentic definition may ask the server to check out in each run's folder before its first turn
23
23
  * (runner/pr-checkout.ts): `pull_request`, the pull request the run's GitHub event names, at its head, read-only, in
24
24
  * `repo/`; `none` clears it on an edit. */
@@ -175,6 +175,10 @@ export function definitionIssues(definition, { at = "definition", creating = tru
175
175
  if (!(typeof d.max_cost_usd === "number" && Number.isFinite(d.max_cost_usd) && d.max_cost_usd >= 0))
176
176
  out.push(issue(`${at}.max_cost_usd`, "wrong_type", `${at}.max_cost_usd is a number of at least 0, in US dollars: above 0 sets the agent's default cap, 0 clears it`));
177
177
  }
178
+ // The agent's own limit on each run's requests on free models, under the server's (AGENTRUN_FREE_MODEL_REQUESTS, which
179
+ // wins when lower): above 0 sets it, 0 clears it, and an edit that leaves it out keeps the agent's (agents-store.ts).
180
+ if (d.max_requests !== undefined && !(typeof d.max_requests === "number" && Number.isSafeInteger(d.max_requests) && d.max_requests >= 0))
181
+ out.push(issue(`${at}.max_requests`, "wrong_type", `${at}.max_requests is a whole number of at least 0: above 0 sets the most requests on free models each run makes (the server's own limit holds when it is lower), 0 clears it`));
178
182
  // The server's checkout before each run's first turn: kept by an edit that leaves it out, cleared by `none`.
179
183
  if (d.checkout !== undefined) {
180
184
  if (d.workflow !== undefined)
@@ -16,11 +16,14 @@ export declare const MEDIA_DIR = "media";
16
16
  export declare const PATH_MAX_CHARS = 1024;
17
17
  export declare const TYPE_MAX_CHARS = 255;
18
18
  export declare const WORDS_MAX_CHARS = 2000;
19
+ /** `duration_s`: an audio or video file's length in seconds (to the millisecond), when its bytes give it (mp3, wav, mp4,
20
+ * m4a, mov: media-duration.ts); absent for any other file, so an agent can time a cut or price a job billed by length. */
19
21
  export type Saved = {
20
22
  ok: true;
21
23
  path: string;
22
24
  bytes: number;
23
25
  content_type: string;
26
+ duration_s?: number;
24
27
  url: string;
25
28
  };
26
29
  export type Unsaved = {