@parcha/agentrun-serve 0.1.0-beta.50 → 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 (232) hide show
  1. package/CHANGELOG.md +185 -0
  2. package/README.md +236 -30
  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 +17 -7
  8. package/dist/api-only.d.ts +6 -3
  9. package/dist/api-only.js +8 -5
  10. package/dist/archil-routes.d.ts +1 -0
  11. package/dist/archil-routes.js +28 -2
  12. package/dist/capacity.d.ts +50 -0
  13. package/dist/capacity.js +49 -0
  14. package/dist/cli-learning/claude-wire.d.ts +41 -0
  15. package/dist/cli-learning/claude-wire.js +258 -0
  16. package/dist/cli-learning/cli.d.ts +11 -0
  17. package/dist/cli-learning/cli.js +241 -0
  18. package/dist/cli-learning/codex-worktree.d.ts +10 -0
  19. package/dist/cli-learning/codex-worktree.js +119 -0
  20. package/dist/cli-learning/connections.d.ts +62 -0
  21. package/dist/cli-learning/connections.js +87 -0
  22. package/dist/cli-learning/entry.d.ts +1 -0
  23. package/dist/cli-learning/entry.js +4 -0
  24. package/dist/cli-learning/evidence.d.ts +78 -0
  25. package/dist/cli-learning/evidence.js +492 -0
  26. package/dist/cli-learning/hook.d.ts +33 -0
  27. package/dist/cli-learning/hook.js +544 -0
  28. package/dist/cli-learning/install.d.ts +33 -0
  29. package/dist/cli-learning/install.js +335 -0
  30. package/dist/cli-learning/observation-proof.d.ts +14 -0
  31. package/dist/cli-learning/observation-proof.js +10 -0
  32. package/dist/cli-learning/policy.d.ts +48 -0
  33. package/dist/cli-learning/policy.js +363 -0
  34. package/dist/cli-learning/schema.d.ts +16 -0
  35. package/dist/cli-learning/schema.js +27 -0
  36. package/dist/cli-learning/state.d.ts +23 -0
  37. package/dist/cli-learning/state.js +61 -0
  38. package/dist/cli.js +24 -2
  39. package/dist/computer-setting.d.ts +8 -0
  40. package/dist/computer-setting.js +11 -0
  41. package/dist/computers.d.ts +6 -2
  42. package/dist/computers.js +2 -2
  43. package/dist/console/assets/index-B-D0EM3j.js +733 -0
  44. package/dist/console/assets/{index-D0mr9wfZ.css → index-DlQepP2J.css} +1 -1
  45. package/dist/console/index.html +2 -2
  46. package/dist/email/email-faux.d.ts +3 -1
  47. package/dist/email/email-faux.js +3 -2
  48. package/dist/email/routes.js +22 -12
  49. package/dist/fal-price.d.ts +76 -0
  50. package/dist/fal-price.js +368 -0
  51. package/dist/harness-install.d.ts +6 -2
  52. package/dist/harness-install.js +40 -8
  53. package/dist/harness.d.ts +1 -1
  54. package/dist/harness.js +2 -2
  55. package/dist/learn/commit.d.ts +5 -0
  56. package/dist/learn/commit.js +4 -1
  57. package/dist/learn/compile.d.ts +13 -5
  58. package/dist/learn/compile.js +24 -7
  59. package/dist/learn/delete.d.ts +12 -6
  60. package/dist/learn/delete.js +17 -11
  61. package/dist/learn/folder.d.ts +11 -0
  62. package/dist/learn/folder.js +20 -3
  63. package/dist/learn/learning-of.d.ts +8 -0
  64. package/dist/learn/learning-of.js +8 -0
  65. package/dist/learn/learning.sh +14 -1
  66. package/dist/learn/promote.d.ts +51 -7
  67. package/dist/learn/promote.js +51 -8
  68. package/dist/learn/secrets.js +14 -3
  69. package/dist/learning-reset.d.ts +18 -0
  70. package/dist/learning-reset.js +115 -0
  71. package/dist/learning-routes.d.ts +1 -1
  72. package/dist/learning-words.d.ts +6 -1
  73. package/dist/learning-words.js +6 -1
  74. package/dist/learning.d.ts +8 -6
  75. package/dist/learning.js +5 -4
  76. package/dist/llms.txt +1 -0
  77. package/dist/mcp-gateway.d.ts +39 -2
  78. package/dist/mcp-gateway.js +41 -10
  79. package/dist/mcp-pin-first.js +3 -2
  80. package/dist/mcp-private-hosts.d.ts +24 -3
  81. package/dist/mcp-private-hosts.js +53 -3
  82. package/dist/mcp-servers-store.d.ts +1 -0
  83. package/dist/mcp-servers-store.js +2 -1
  84. package/dist/media-duration.d.ts +2 -0
  85. package/dist/media-duration.js +136 -0
  86. package/dist/model-gateway.d.ts +2 -0
  87. package/dist/model-gateway.js +3 -1
  88. package/dist/native/runtimes.d.ts +2 -0
  89. package/dist/native/runtimes.js +2 -0
  90. package/dist/observation/learning.d.ts +32 -0
  91. package/dist/observation/learning.js +66 -0
  92. package/dist/observation/observer.d.ts +8 -1
  93. package/dist/observation/observer.js +89 -9
  94. package/dist/observation/schema.js +12 -4
  95. package/dist/observation/usage-identity.d.ts +9 -0
  96. package/dist/observation/usage-identity.js +11 -0
  97. package/dist/openapi.js +133 -24
  98. package/dist/provider.d.ts +8 -0
  99. package/dist/provider.js +14 -2
  100. package/dist/refusal-words.d.ts +0 -3
  101. package/dist/refusal-words.js +0 -3
  102. package/dist/request-metadata.d.ts +20 -0
  103. package/dist/request-metadata.js +24 -0
  104. package/dist/run-launch.d.ts +27 -4
  105. package/dist/run-launch.js +18 -3
  106. package/dist/run-learning-served.d.ts +2 -2
  107. package/dist/run-usage.d.ts +48 -4
  108. package/dist/run-usage.js +156 -39
  109. package/dist/run-view.d.ts +2 -0
  110. package/dist/run-view.js +8 -7
  111. package/dist/runner/adapter-loop.d.ts +3 -1
  112. package/dist/runner/adapter-loop.js +41 -35
  113. package/dist/runner/adapter-run-spec.d.ts +1 -1
  114. package/dist/runner/adapter-run-spec.js +15 -15
  115. package/dist/runner/audit.d.ts +8 -3
  116. package/dist/runner/audit.js +21 -6
  117. package/dist/runner/beside.d.ts +13 -0
  118. package/dist/runner/beside.js +27 -8
  119. package/dist/runner/claim-secrets.d.ts +2 -1
  120. package/dist/runner/claim-secrets.js +5 -3
  121. package/dist/runner/cli-run-spec.d.ts +1 -1
  122. package/dist/runner/cli-run-spec.js +14 -13
  123. package/dist/runner/conformance/harness.js +4 -2
  124. package/dist/runner/disk-free.d.ts +44 -0
  125. package/dist/runner/disk-free.js +96 -0
  126. package/dist/runner/dispatch.js +4 -2
  127. package/dist/runner/feedback-round.d.ts +12 -8
  128. package/dist/runner/feedback-round.js +16 -30
  129. package/dist/runner/harness-loops.js +8 -3
  130. package/dist/runner/journal-kinds.d.ts +4 -1
  131. package/dist/runner/learning-end.d.ts +2 -1
  132. package/dist/runner/learning-end.js +51 -22
  133. package/dist/runner/main.d.ts +17 -6
  134. package/dist/runner/main.js +187 -45
  135. package/dist/runner/mcp-claim.js +1 -1
  136. package/dist/runner/mcp-run.d.ts +9 -0
  137. package/dist/runner/mcp-run.js +16 -1
  138. package/dist/runner/model-route.js +7 -4
  139. package/dist/runner/presence.d.ts +11 -2
  140. package/dist/runner/presence.js +31 -3
  141. package/dist/runner/promotion.d.ts +40 -21
  142. package/dist/runner/promotion.js +130 -59
  143. package/dist/runner/run-child-host.d.ts +12 -15
  144. package/dist/runner/run-child-host.js +52 -112
  145. package/dist/runner/run-errors.js +2 -0
  146. package/dist/runner/runner-check.d.ts +51 -0
  147. package/dist/runner/runner-check.js +206 -0
  148. package/dist/runner/runner-metrics.d.ts +19 -0
  149. package/dist/runner/runner-metrics.js +49 -0
  150. package/dist/runner/runner.d.ts +37 -0
  151. package/dist/runner/runner.js +58 -6
  152. package/dist/runner/sdk-loop.d.ts +2 -2
  153. package/dist/runner/sdk-loop.js +37 -25
  154. package/dist/runner/store-port.d.ts +3 -0
  155. package/dist/runner/workflow-spec.js +3 -3
  156. package/dist/runs-over-store.d.ts +13 -3
  157. package/dist/runs-over-store.js +71 -16
  158. package/dist/sdk/check.d.ts +6 -5
  159. package/dist/sdk/check.js +17 -16
  160. package/dist/sdk/runs.d.ts +22 -2
  161. package/dist/sdk/runs.js +167 -82
  162. package/dist/server.d.ts +3 -0
  163. package/dist/server.js +230 -43
  164. package/dist/skills/agentrun-serve/SKILL.md +52 -7
  165. package/dist/start-switches.js +2 -0
  166. package/dist/stats.d.ts +4 -0
  167. package/dist/stats.js +1 -1
  168. package/dist/store/agent-body.d.ts +16 -0
  169. package/dist/store/agent-body.js +20 -3
  170. package/dist/store/dialect.d.ts +2 -0
  171. package/dist/store/dialect.js +1 -0
  172. package/dist/store/index.d.ts +3 -3
  173. package/dist/store/index.js +2 -2
  174. package/dist/store/journal/storage.d.ts +2 -0
  175. package/dist/store/journal/storage.js +2 -1
  176. package/dist/store/postgres/connection.d.ts +5 -2
  177. package/dist/store/postgres/connection.js +19 -7
  178. package/dist/store/postgres/dialect.js +1 -0
  179. package/dist/store/postgres/migrate.d.ts +30 -0
  180. package/dist/store/postgres/migrate.js +72 -5
  181. package/dist/store/postgres/migration-lint.d.ts +8 -0
  182. package/dist/store/postgres/migration-lint.js +119 -0
  183. package/dist/store/postgres/migrations/0024_runner_capacity.sql +28 -0
  184. package/dist/store/postgres/migrations/0025_run_attempts.sql +27 -0
  185. package/dist/store/postgres/migrations/0026_run_disk.sql +23 -0
  186. package/dist/store/postgres/store.d.ts +8 -3
  187. package/dist/store/postgres/store.js +31 -11
  188. package/dist/store/schema.d.ts +32 -2
  189. package/dist/store/schema.js +74 -5
  190. package/dist/store/sqlite/run-launch.d.ts +31 -1
  191. package/dist/store/sqlite/run-launch.js +111 -2
  192. package/dist/store/sqlite/run-patch.d.ts +2 -1
  193. package/dist/store/sqlite/run-patch.js +4 -3
  194. package/dist/store/sqlite/store.d.ts +17 -0
  195. package/dist/store/sqlite/store.js +226 -37
  196. package/dist/store/store-schema.d.ts +34 -0
  197. package/dist/store/store-schema.js +125 -0
  198. package/dist/store/store.d.ts +120 -5
  199. package/dist/store/store.js +13 -0
  200. package/dist/store-reads/analytics.d.ts +3 -2
  201. package/dist/store-reads/analytics.js +20 -8
  202. package/dist/store-reads/learning.d.ts +12 -8
  203. package/dist/store-reads/learning.js +33 -24
  204. package/dist/store-reads/loop.d.ts +4 -3
  205. package/dist/store-reads/loop.js +7 -5
  206. package/dist/store-view.d.ts +4 -3
  207. package/dist/store-view.js +11 -7
  208. package/dist/template-eval.js +4 -4
  209. package/dist/templates.d.ts +6 -2
  210. package/dist/templates.js +7 -5
  211. package/dist/timeline/labels.js +1 -1
  212. package/dist/tool-gate.d.ts +4 -2
  213. package/dist/tools.js +1 -1
  214. package/dist/unified-usage.d.ts +24 -0
  215. package/dist/unified-usage.js +400 -0
  216. package/dist/uploads-archil.d.ts +100 -0
  217. package/dist/uploads-archil.js +431 -0
  218. package/dist/uploads.d.ts +52 -1
  219. package/dist/uploads.js +186 -108
  220. package/dist/validate.js +5 -1
  221. package/dist/web-save.d.ts +3 -0
  222. package/dist/web-save.js +17 -2
  223. package/dist/workspace/archil-disk.d.ts +6 -5
  224. package/dist/workspace/archil-disk.js +27 -12
  225. package/dist/workspace/archil-exec.js +1 -1
  226. package/dist/workspace/archil.js +4 -3
  227. package/dist/workspace/revision-skills.js +24 -11
  228. package/dist/workspace/synced-folder.d.ts +3 -3
  229. package/dist/workspace/synced-folder.js +7 -6
  230. package/package.json +10 -10
  231. package/skills/agentrun-serve/SKILL.md +52 -7
  232. package/dist/console/assets/index-D7G6o-1E.js +0 -720
@@ -0,0 +1,368 @@
1
+ // fal's pricing, for the run's MCP gateway (mcp-gateway.ts McpMeter): a job sent to a fal MCP server (run_model,
2
+ // submit_job, each request of submit_jobs) is priced before it leaves, at fal's unit price for its endpoint times the
3
+ // units fal bills it by.
4
+ // - The unit price is the server's own get_pricing, asked with exactly `{ endpoint_id: "<id>" }` (a contract: a fake
5
+ // server matches arguments by equality), one endpoint a call, kept PRICE_TTL_MS.
6
+ // - The units are read from the job's input (unitsBefore). Nothing is guessed: an input that leaves out the size or
7
+ // length its model would default is unpriceable.
8
+ // - fal's reply states no cost, so the charge is this estimate (chargeOfJob).
9
+ // fal can bill what get_pricing does not expose (a minimum, a discount, a rate that depends on a setting such as
10
+ // resolution): a booked figure is fal's list price for the job, not its invoice.
11
+ // fal's hosted server also keeps one submission_key journal per fal account, which refuses a key it has seen with another
12
+ // request: a server at fal's own host scopes each key to the run before it leaves (falKeys).
13
+ import { createHash } from "node:crypto";
14
+ import { mediaSeconds } from "./media-duration.js";
15
+ import { SAVE_MAX_BYTES, SERVER_SLOTS } from "./web-save.js";
16
+ /** The host of fal's hosted MCP server (its key endpoint /mcp and its sign-in endpoint /mcp-relay). */
17
+ export const FAL_MCP_HOST = "mcp.fal.ai";
18
+ /** A pin's `meter` for a fal server. */
19
+ export const FAL_METER = "fal";
20
+ /** How long a unit price read from get_pricing is used. */
21
+ export const PRICE_TTL_MS = 5 * 60_000;
22
+ /** One deadline for reading an input media file's length. */
23
+ export const MEDIA_TIMEOUT_MS = 120_000;
24
+ /** Whether a saved server is fal's: its owner's toolkit for it is `fal`, or its URL is on fal's MCP host. */
25
+ export function falServer(url, toolkit) {
26
+ return toolkit === FAL_METER || URL.parse(url)?.hostname === FAL_MCP_HOST;
27
+ }
28
+ /** The `meter` a save pins for a server at `url` with `toolkit` (mcp-gateway.ts mcpPinOf). */
29
+ export const meterNamed = (url, toolkit) => (falServer(url, toolkit) ? FAL_METER : undefined);
30
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
31
+ const jobOf = (given) => {
32
+ const one = isObject(given) ? given : {};
33
+ return { endpoint: typeof one.endpoint_id === "string" && one.endpoint_id ? one.endpoint_id : undefined, input: one.input, ...(Number.isInteger(one.index) ? { index: one.index } : {}) };
34
+ };
35
+ /** The jobs a call of fal's `tool` submits: one for run_model and submit_job, one per request for submit_jobs. Undefined
36
+ * for a tool that submits none (get_pricing, wait_for_jobs, ...), which fal does not bill. */
37
+ export function falJobsOf(tool, args) {
38
+ if (tool === "run_model" || tool === "submit_job")
39
+ return [jobOf(args)];
40
+ if (tool !== "submit_jobs")
41
+ return undefined;
42
+ const requests = isObject(args) && Array.isArray(args.requests) ? args.requests : [];
43
+ return requests.length ? requests.map(jobOf) : [jobOf(undefined)];
44
+ }
45
+ /** fal's image_size presets, in pixels. */
46
+ const SIZES = { square_hd: [1024, 1024], square: [512, 512], portrait_4_3: [768, 1024], portrait_16_9: [576, 1024], landscape_4_3: [1024, 768], landscape_16_9: [1024, 576] };
47
+ /** A unit as one of it reads: "per image". */
48
+ const ONE = { images: "image", megapixels: "megapixel", seconds: "second", minutes: "minute", audios: "audio", "compute seconds": "compute second" };
49
+ const oneOf = (unit) => ONE[unit] ?? unit;
50
+ /** Units fal counts only once the job has run. */
51
+ const AFTER_ONLY = new Set(["compute seconds", "1m tokens"]);
52
+ const positive = (value) => typeof value === "number" && Number.isFinite(value) && value > 0;
53
+ /** An image's megapixels as billed: rounded up to a whole one. */
54
+ const megapixels = (width, height) => Math.ceil((width * height) / 1e6);
55
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
56
+ /** How many outputs the input asks for (num_images, else num_outputs, else 1), or undefined for a count that is none. */
57
+ function countOf(input, unit) {
58
+ const field = input.num_images !== undefined ? "num_images" : input.num_outputs !== undefined ? "num_outputs" : undefined;
59
+ if (!field)
60
+ return { n: 1, from: `1 ${oneOf(unit === "megapixels" ? "images" : unit)} by default` };
61
+ const n = input[field];
62
+ return Number.isInteger(n) && n > 0 ? { n: n, from: field } : undefined;
63
+ }
64
+ /** The length in seconds the input names: `duration` ("5", "5s" or a number), duration_seconds, seconds_total,
65
+ * music_length_ms, or a music composition plan's sections. */
66
+ function namedSeconds(input) {
67
+ for (const [field, per] of [["duration", 1], ["duration_seconds", 1], ["seconds_total", 1], ["music_length_ms", 1000]]) {
68
+ const given = input[field];
69
+ if (given === undefined)
70
+ continue;
71
+ const said = typeof given === "string" && /^\d+(\.\d+)?s?$/.test(given.trim()) ? Number.parseFloat(given) : given;
72
+ return positive(said) ? { seconds: said / per, from: field } : "bad";
73
+ }
74
+ const sections = isObject(input.composition_plan) ? input.composition_plan.sections : undefined;
75
+ if (Array.isArray(sections) && sections.length) {
76
+ const each = sections.map((section) => (isObject(section) ? section.duration_ms : undefined));
77
+ return each.every(positive) ? { seconds: each.reduce((sum, ms) => sum + ms, 0) / 1000, from: "its composition plan's sections" } : "bad";
78
+ }
79
+ return undefined;
80
+ }
81
+ /** The audio and video URLs among the input's own fields (audio_url, video_url, video_urls, ...): an image has no length. */
82
+ function mediaOf(input) {
83
+ const urls = [];
84
+ for (const [field, value] of Object.entries(input)) {
85
+ if (!/(audio|video)_urls?$/.test(field))
86
+ continue;
87
+ for (const one of Array.isArray(value) ? value : [value])
88
+ if (typeof one === "string" && one)
89
+ urls.push(one);
90
+ }
91
+ return urls;
92
+ }
93
+ /** ffmpeg-api/compose's timeline end in seconds: the last keyframe's end across its tracks (timestamp and duration are
94
+ * milliseconds, by its OpenAPI). */
95
+ function composeSeconds(input) {
96
+ const frames = (Array.isArray(input.tracks) ? input.tracks : []).flatMap((track) => (isObject(track) && Array.isArray(track.keyframes) ? track.keyframes : []));
97
+ const ends = frames.map((frame) => (isObject(frame) && typeof frame.timestamp === "number" && frame.timestamp >= 0 && positive(frame.duration) ? frame.timestamp + frame.duration : Number.NaN));
98
+ return ends.length && ends.every(Number.isFinite) ? Math.max(...ends) / 1000 : undefined;
99
+ }
100
+ const COMPOSE = "fal-ai/ffmpeg-api/compose";
101
+ /** The units fal bills a job of `endpoint` by, in `unit` (get_pricing's), read from its `input`. */
102
+ export function unitsBefore(endpoint, unit, input) {
103
+ const bills = `fal bills ${endpoint} per ${oneOf(unit)}`;
104
+ if (AFTER_ONLY.has(unit))
105
+ return { unknown: `${bills}, which can't be known before the job runs` };
106
+ if (!isObject(input))
107
+ return { unknown: `${bills}, and this job has no input to count them from` };
108
+ if (unit === "images" || unit === "audios") {
109
+ const count = countOf(input, unit);
110
+ return count ? { units: count.n, from: count.from } : { unknown: `${bills}, and this job's input does not say how many as a whole number above 0` };
111
+ }
112
+ if (unit === "megapixels") {
113
+ const count = countOf(input, unit);
114
+ const size = input.image_size;
115
+ const pixels = typeof size === "string" && Object.hasOwn(SIZES, size) ? SIZES[size] : isObject(size) && positive(size.width) && positive(size.height) ? [size.width, size.height] : undefined;
116
+ if (!count || !pixels)
117
+ return { unknown: `${bills}, and this job's input names no image_size (a preset such as landscape_4_3, or a width and height) and count to work them out from` };
118
+ return { units: megapixels(pixels[0], pixels[1]) * count.n, from: `image_size ${typeof size === "string" ? size : `${pixels[0]}x${pixels[1]}`}, ${plural(count.n, "image")}` };
119
+ }
120
+ if (unit === "1000 characters") {
121
+ const lines = typeof input.text === "string" ? [input.text] : Array.isArray(input.inputs) ? input.inputs.map((line) => (isObject(line) ? line.text : undefined)) : [];
122
+ if (!lines.length || !lines.every((line) => typeof line === "string"))
123
+ return { unknown: `${bills}, and this job's input has no text to count` };
124
+ const characters = lines.reduce((sum, line) => sum + line.length, 0);
125
+ return { units: characters / 1000, from: `the ${characters} characters of its ${typeof input.text === "string" ? "text" : plural(lines.length, "line")}` };
126
+ }
127
+ if (unit === "seconds" || unit === "minutes") {
128
+ const per = unit === "minutes" ? 60 : 1;
129
+ if (endpoint === COMPOSE) {
130
+ const end = composeSeconds(input);
131
+ return end ? { units: end / per, from: "its timeline's end" } : { unknown: `${bills}, and this job's tracks have no keyframes with a timestamp and a duration to read its length from` };
132
+ }
133
+ const named = namedSeconds(input);
134
+ if (named === "bad")
135
+ return { unknown: `${bills}, and the length this job's input names is not a number above 0` };
136
+ if (named)
137
+ return { units: named.seconds / per, from: named.from };
138
+ const media = mediaOf(input);
139
+ if (media.length)
140
+ return { media };
141
+ return { unknown: `${bills}, and this job's input names no length (duration, duration_seconds, seconds_total or music_length_ms)` };
142
+ }
143
+ return { unknown: `${bills}, a unit this server can't count` };
144
+ }
145
+ /** The units a completed job's `output` states, in `unit`: its images, their megapixels, a duration in seconds (its own,
146
+ * or its video's or audio's). Undefined when it states none. */
147
+ export function unitsAfter(unit, output) {
148
+ if (!isObject(output))
149
+ return undefined;
150
+ const images = Array.isArray(output.images) && output.images.length ? output.images : undefined;
151
+ if (unit === "images")
152
+ return images?.length;
153
+ if (unit === "megapixels")
154
+ return images?.every((image) => isObject(image) && positive(image.width) && positive(image.height)) ? images.reduce((sum, image) => sum + megapixels(image.width, image.height), 0) : undefined;
155
+ if (unit === "seconds" || unit === "minutes") {
156
+ const seconds = [output.duration, output.duration_seconds, ...[output.video, output.audio].map((file) => (isObject(file) ? file.duration : undefined))].find(positive);
157
+ return seconds === undefined ? undefined : seconds / (unit === "minutes" ? 60 : 1);
158
+ }
159
+ return undefined;
160
+ }
161
+ /** fal's unit price for `endpoint` in get_pricing's answer: its own entry of `prices`, in USD. */
162
+ export function priceIn(answer, endpoint) {
163
+ const prices = isObject(answer) && Array.isArray(answer.prices) ? answer.prices : [];
164
+ const own = prices.find((price) => isObject(price) && price.endpoint_id === endpoint);
165
+ if (!isObject(own) || own.currency !== "USD" || typeof own.unit !== "string" || !own.unit || typeof own.unit_price !== "number" || !Number.isFinite(own.unit_price) || own.unit_price < 0)
166
+ return undefined;
167
+ return { unitPrice: own.unit_price, unit: own.unit };
168
+ }
169
+ /** A tool result's body: its structured content, else its text as JSON; undefined when it is neither. */
170
+ function bodyOf(result) {
171
+ if (isObject(result.structuredContent))
172
+ return result.structuredContent;
173
+ const text = (Array.isArray(result.content) ? result.content : []).flatMap((block) => (isObject(block) && block.type === "text" && typeof block.text === "string" ? [block.text] : [])).join("");
174
+ try {
175
+ return JSON.parse(text);
176
+ }
177
+ catch {
178
+ return undefined;
179
+ }
180
+ }
181
+ /** In whole millionths of a dollar. */
182
+ const usd = (dollars) => Math.round(dollars * 1e6) / 1e6;
183
+ const shown = (n) => String(Math.round(n * 1e6) / 1e6);
184
+ /** A MediaReader over the public-host guard web_fetch and web_save download through (`guard`: their fetch options),
185
+ * within web_save's size cap and download slots. */
186
+ export const publicMedia = (guard, slots = SERVER_SLOTS) => async (url, signal) => {
187
+ const { publicDownload } = await import("@parcha/pi-browser");
188
+ const bound = AbortSignal.any([signal, AbortSignal.timeout(MEDIA_TIMEOUT_MS)]);
189
+ const release = await slots.take(bound);
190
+ try {
191
+ const file = await publicDownload(url, { ...(await guard()), maxBytes: SAVE_MAX_BYTES, signal: bound });
192
+ if (!file.bytes)
193
+ throw new Error(`the host answered ${file.status}`);
194
+ return file.bytes;
195
+ }
196
+ finally {
197
+ release();
198
+ }
199
+ };
200
+ /** A reply in which fal says it refused the job's input: status "rejected", or an error of type validation_error or
201
+ * with field_errors. */
202
+ const refusedInput = (item) => item.status === "rejected" || (isObject(item.error) && (item.error.type === "validation_error" || Array.isArray(item.error.field_errors)));
203
+ /** What one job charged, by its reply `item` (run_model's reply, or its own entry of submit_jobs'): $0 when the
204
+ * submission was replayed or fal refused its input; a completed job's stated units at its unit price; else its hold
205
+ * (still running, or nothing stated). Null for a job with no price whose reply says it was accepted. */
206
+ function chargeOfJob(quote, item) {
207
+ const hold = "holdUsd" in quote ? quote.holdUsd : null;
208
+ if (!isObject(item))
209
+ return hold;
210
+ if (item.submission_replayed === true)
211
+ return 0;
212
+ // fal refused the input before it made a job (no request_id, and a validation error or a rejection it says so in):
213
+ // nothing to bill. Any other reply without a job (a timeout, an unknown error) may hide one, so it stays at its hold.
214
+ if (typeof item.request_id !== "string" && refusedInput(item))
215
+ return 0;
216
+ if (!("holdUsd" in quote))
217
+ return null;
218
+ const after = item.status === "completed" ? unitsAfter(quote.unit, item.result) : undefined;
219
+ return after === undefined ? quote.holdUsd : usd(quote.unitPrice * after);
220
+ }
221
+ /** fal's tools that take a submission_key: the three that submit jobs, and get_submission, which reads one back. */
222
+ const KEYED = new Set(["run_model", "submit_job", "submit_jobs", "get_submission"]);
223
+ /** fal's longest submission_key: its tools declare `^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$`. */
224
+ export const KEY_MAX = 128;
225
+ const hex16 = (text) => createHash("sha256").update(text).digest("hex").slice(0, 16);
226
+ /** The submission keys of one run on fal's hosted server (McpMeter.keys). fal's journal is per account, so the same key
227
+ * from two runs (a model makes the same key for the same task) would bind the second run's request to the first's and be
228
+ * refused. Each key leaves as the agent's key and `.<16 hex of the run>`: the same run's key leaves the same each time,
229
+ * so a retry is deduped, and another run's never matches it. A key too long for KEY_MAX with that suffix keeps its start
230
+ * and a hash of the whole key in its place, never cut into another key, and ends `:<16 hex of the run>` instead: its
231
+ * shortened start is itself a valid key, and the different mark keeps an agent key that spells it from leaving as the
232
+ * same key. `back` reads each scoped key in a reply as the agent's: by the keys this gateway sent, else by taking the
233
+ * suffix off. */
234
+ export function falKeys(run) {
235
+ const mark = hex16(`agentrun fal submission_key\0${run}`);
236
+ const tail = mark.length + 1;
237
+ const own = new Map();
238
+ const scoped = (key) => {
239
+ if (typeof key !== "string" || !key)
240
+ return key;
241
+ const sent = key.length + tail <= KEY_MAX ? `${key}.${mark}` : `${key.slice(0, KEY_MAX - tail - 17)}.${hex16(key)}:${mark}`;
242
+ own.set(sent, key);
243
+ return sent;
244
+ };
245
+ const anyScoped = new RegExp(`[A-Za-z0-9._:-]+[.:]${mark}(?![A-Za-z0-9._:-])`, "g");
246
+ return {
247
+ out(tool, args) {
248
+ if (!KEYED.has(tool))
249
+ return args;
250
+ let sent = Object.hasOwn(args, "submission_key") ? { ...args, submission_key: scoped(args.submission_key) } : args;
251
+ if (tool === "submit_jobs" && Array.isArray(args.requests))
252
+ sent = { ...sent, requests: args.requests.map((one) => (isObject(one) && Object.hasOwn(one, "submission_key") ? { ...one, submission_key: scoped(one.submission_key) } : one)) };
253
+ return sent;
254
+ },
255
+ back(text) {
256
+ if (!text.includes(mark))
257
+ return text;
258
+ // One pass: a key read back once is never read again, so an agent's key that ends like a scoped one stays as it is.
259
+ const known = [...own.keys()].sort((a, b) => b.length - a.length);
260
+ return text.replace(anyScoped, (token) => {
261
+ const sent = known.find((key) => token.endsWith(key));
262
+ return sent ? `${token.slice(0, -sent.length)}${own.get(sent)}` : token.slice(0, -tail);
263
+ });
264
+ },
265
+ };
266
+ }
267
+ /** A fal server's meter: fal's unit prices read through the gateway's `ask`, kept per endpoint for PRICE_TTL_MS.
268
+ * `media` reads an input media file (none: such a job is unpriceable); `now`, the clock; `run`, the run whose
269
+ * submission keys it scopes (falKeys; none: they leave as the agent sent them). */
270
+ export function falMeter({ media, now = Date.now, run } = {}) {
271
+ const prices = new Map();
272
+ const unitPrice = async (endpoint, ask) => {
273
+ const kept = prices.get(endpoint);
274
+ if (kept && now() - kept.at < PRICE_TTL_MS)
275
+ return kept;
276
+ const answer = await ask("get_pricing", { endpoint_id: endpoint });
277
+ const unread = (why) => ({ why: `fal's price for ${endpoint} could not be read (its get_pricing ${why})` });
278
+ if (!answer)
279
+ return unread("did not answer");
280
+ if (answer.isError === true)
281
+ return unread("answered an error");
282
+ const price = priceIn(bodyOf(answer), endpoint);
283
+ if (!price)
284
+ return unread("lists no USD price for it");
285
+ const read = { ...price, at: now() };
286
+ prices.set(endpoint, read);
287
+ return read;
288
+ };
289
+ /** The longest of the media at `urls`, in seconds, or the URL whose length could not be read. */
290
+ const longest = async (urls, signal) => {
291
+ const lengths = await Promise.all([...new Set(urls)].map(async (url) => {
292
+ try {
293
+ return (media && mediaSeconds(await media(url, signal))) || { unread: url };
294
+ }
295
+ catch {
296
+ return { unread: url };
297
+ }
298
+ }));
299
+ return lengths.find((one) => typeof one !== "number") ?? Math.max(...lengths);
300
+ };
301
+ const quoteJob = async (job, ask, signal) => {
302
+ if (!job.endpoint)
303
+ return { job, why: "this job names no endpoint_id to price" };
304
+ const price = await unitPrice(job.endpoint, ask);
305
+ if ("why" in price)
306
+ return { job, why: price.why };
307
+ let units = unitsBefore(job.endpoint, price.unit, job.input);
308
+ if ("media" in units) {
309
+ const seconds = await longest(units.media, signal);
310
+ if (typeof seconds !== "number")
311
+ return { job, why: `fal bills ${job.endpoint} per ${oneOf(price.unit)} of its input media, and the length of ${seconds.unread.slice(0, 200)} could not be read` };
312
+ units = { units: seconds / (price.unit === "minutes" ? 60 : 1), from: units.media.length > 1 ? "the longest of its input media, read before the call" : "its input media's length, read before the call" };
313
+ }
314
+ if ("unknown" in units)
315
+ return { job, why: units.unknown };
316
+ return { job, holdUsd: usd(price.unitPrice * units.units), unitPrice: price.unitPrice, unit: price.unit, at: price.at, words: `fal's price for ${job.endpoint}: $${price.unitPrice} per ${oneOf(price.unit)} × ${shown(units.units)} (${units.from})` };
317
+ };
318
+ return {
319
+ ...(run ? { keys: falKeys(run) } : {}),
320
+ bills: (tool) => falJobsOf(tool, {}) !== undefined,
321
+ async quote(tool, args, ask, signal) {
322
+ const quotes = [];
323
+ // One at a time: each endpoint's price is read once, the next job's from what the last one kept.
324
+ for (const job of falJobsOf(tool, args) ?? [])
325
+ quotes.push(await quoteJob(job, ask, signal));
326
+ const priced = quotes.filter((quote) => "holdUsd" in quote);
327
+ const unpriced = quotes.find((quote) => "why" in quote);
328
+ const basis = priced.length ? `${priced.map((quote) => quote.words).join("; ")}, from get_pricing at ${new Date(Math.min(...priced.map((quote) => quote.at))).toISOString()}` : "fal's price for it could not be worked out";
329
+ const holdUsd = usd(priced.reduce((sum, quote) => sum + quote.holdUsd, 0));
330
+ return {
331
+ holdUsd,
332
+ basis: unpriced && priced.length ? `${basis}; not counting what could not be priced` : basis,
333
+ ...(unpriced ? { unpriceable: unpriced.why } : {}),
334
+ chargeOf(reply) {
335
+ if (!reply)
336
+ return null;
337
+ const body = bodyOf(reply);
338
+ if (tool !== "submit_jobs")
339
+ return chargeOfJob(quotes[0], body);
340
+ // submit_jobs: each job by its own entry of the reply, matched by the index the call gave it.
341
+ const lists = isObject(body) ? Object.values(body).filter((value) => Array.isArray(value) && value.length > 0 && value.every((item) => isObject(item) && Number.isInteger(item.index))) : [];
342
+ const items = lists[0];
343
+ // A reply that lists no job by its index: read as one, each job at its hold.
344
+ if (!items)
345
+ return unpriced ? null : holdUsd;
346
+ let total = 0;
347
+ for (const [at, quote] of quotes.entries()) {
348
+ const charge = chargeOfJob(quote, items.find((item) => item.index === (quote.job.index ?? at)) ?? "missing");
349
+ if (charge === null)
350
+ return null;
351
+ total += charge;
352
+ }
353
+ return usd(total);
354
+ },
355
+ };
356
+ },
357
+ };
358
+ }
359
+ /** The meter of a pinned server (mcp-gateway.ts McpPin entry): fal's for one marked `fal` at its save, or, for a pin made
360
+ * before servers were marked, one whose URL is on fal's MCP host. Only a server at fal's host scopes its submission keys
361
+ * to `deps.run`: the journal they collide in is that server's, and a server marked `fal` elsewhere (a template eval's
362
+ * fake, whose answers and log graders read by the agent's own key) receives them as the agent sent them. */
363
+ export const meterFor = (pinned, deps) => {
364
+ if (!falServer(pinned.url, pinned.meter))
365
+ return undefined;
366
+ const { run, ...rest } = deps ?? {};
367
+ return falMeter({ ...rest, ...(run && URL.parse(pinned.url)?.hostname === FAL_MCP_HOST ? { run } : {}) });
368
+ };
@@ -160,16 +160,20 @@ export declare function processIdentity(pid: number): string | undefined;
160
160
  * way. A hold its installer left (gone, or past that bound, or unreadable and older than HOLD_WRITING_MS) is taken over
161
161
  * by one taker alone: the one that links it to a name of that very file's removes it, and only while it is still that
162
162
  * file, so a hold another taker made meanwhile is never removed. */
163
- export declare function takeHold(dir: string, { isAlive, identity, host, pidns, timeoutMs }?: {
163
+ export declare function takeHold(dir: string, { isAlive, identity, host, pidns, timeoutMs, holdPath, recoverUnknownOwner }?: {
164
164
  isAlive?: (pid: number) => boolean;
165
165
  identity?: (pid: number) => string | undefined;
166
166
  host?: string;
167
167
  pidns?: string;
168
168
  timeoutMs?: number;
169
+ holdPath?: string;
170
+ recoverUnknownOwner?: boolean;
169
171
  }): Promise<string | undefined>;
170
172
  /** Lets go of the hold on installs into `dir` that `token` took; a hold of another's (one that took over this one past
171
173
  * its bound) stays. */
172
- export declare function releaseHold(dir: string, token: string): Promise<void>;
174
+ export declare function releaseHold(dir: string, token: string, { holdPath }?: {
175
+ holdPath?: string;
176
+ }): Promise<void>;
173
177
  /** The server's one installer of a harness into `dir`: `ensure()` resolves once it is installed whole, installing it first
174
178
  * when it is not, and every caller while an install runs waits for that one. While another process installs it (it holds
175
179
  * installHoldOf), this one waits for that install instead of starting its own. A failed install is not kept: the next call
@@ -506,6 +506,24 @@ export function processIdentity(pid) {
506
506
  return undefined;
507
507
  }
508
508
  }
509
+ /** Only the kernel UUID and numeric process-start format proves a boot. An absent,
510
+ * malformed or adapter-specific identity cannot establish that an owner is gone. */
511
+ function identityBoot(value) {
512
+ if (typeof value !== "string")
513
+ return undefined;
514
+ const match = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}):[0-9]+$/i.exec(value);
515
+ return match?.[0] === value ? match[1].toLowerCase() : undefined;
516
+ }
517
+ /** A caller protecting legacy ownerless locks needs a complete, well-formed owner
518
+ * record before process liveness or boot identity can authorize recovery. */
519
+ function ownerProof(held) {
520
+ return held !== undefined && typeof held.host === "string" && held.host.length > 0
521
+ && typeof held.pid === "number" && Number.isSafeInteger(held.pid) && held.pid > 0 && held.pid <= 0x7fffffff
522
+ && typeof held.startedAt === "number" && Number.isSafeInteger(held.startedAt) && held.startedAt >= 0
523
+ && typeof held.token === "string" && held.token.length > 0
524
+ && (held.pidns === undefined || (typeof held.pidns === "string" && /^pid:\[[0-9]+\]$/.exec(held.pidns)?.[0] === held.pidns))
525
+ && (held.identity === undefined || identityBoot(held.identity) !== undefined);
526
+ }
509
527
  /** The hold at `at` as written, or undefined when it cannot be read (gone, cut short, not one). */
510
528
  async function readHold(at) {
511
529
  try {
@@ -525,17 +543,29 @@ async function readHold(at) {
525
543
  * way. A hold its installer left (gone, or past that bound, or unreadable and older than HOLD_WRITING_MS) is taken over
526
544
  * by one taker alone: the one that links it to a name of that very file's removes it, and only while it is still that
527
545
  * file, so a hold another taker made meanwhile is never removed. */
528
- export async function takeHold(dir, { isAlive = alive, identity = processIdentity, host = hostname(), pidns = pidNamespace(), timeoutMs = INSTALL_TIMEOUT_MS } = {}) {
529
- const at = installHoldOf(dir);
546
+ export async function takeHold(dir, { isAlive = alive, identity = processIdentity, host = hostname(), pidns = pidNamespace(), timeoutMs = INSTALL_TIMEOUT_MS, holdPath = installHoldOf(dir), recoverUnknownOwner = true } = {}) {
547
+ const at = holdPath;
530
548
  await mkdir(dirname(at), { recursive: true });
531
549
  const token = randomUUID();
532
550
  const draft = `${at}.${token}`;
533
551
  const own = identity(process.pid);
534
- await writeFile(draft, JSON.stringify({ host, ...(pidns ? { pidns } : {}), pid: process.pid, ...(own ? { identity: own } : {}), startedAt: Date.now(), token }));
552
+ const ownBoot = identityBoot(own);
553
+ await writeFile(draft, JSON.stringify({ host, ...(pidns ? { pidns } : {}), pid: process.pid, ...(own ? { identity: own } : {}), startedAt: Date.now(), token }), { mode: 0o600 });
535
554
  /** Whether a hold's pid can be asked of this process table: written on this host, in this pid namespace where both
536
555
  * name one. Another namespace's (another container's on the same data, with the same hostname) is judged as another
537
- * host's. */
538
- const local = (held) => held.host === host && (typeof held.pidns !== "string" || pidns === undefined || held.pidns === pidns);
556
+ * host's. Strict owner proof also withholds a PID check when only one side knows its namespace. */
557
+ const local = (held) => held.host === host && (recoverUnknownOwner
558
+ ? typeof held.pidns !== "string" || pidns === undefined || held.pidns === pidns
559
+ : held.pidns === pidns);
560
+ /** An unbounded local-command hold cannot expire after a reboot. A known previous
561
+ * kernel boot on this host proves its owner gone even if the PID namespace changed.
562
+ * A container recreated within the same boot still needs proof that its old namespace
563
+ * died; never inspect its PID from this namespace or steal a live sibling's hold.
564
+ * Finite installer holds retain their existing foreign-namespace timeout policy. */
565
+ const previousBoot = (held) => {
566
+ const boot = identityBoot(held.identity);
567
+ return timeoutMs === Infinity && held.host === host && ownBoot !== undefined && boot !== undefined && boot !== ownBoot;
568
+ };
539
569
  /** Whether a hold of this host's is still its installer's: that process alive, by its identity where both are known. */
540
570
  const installing = (held) => {
541
571
  if (!isAlive(held.pid))
@@ -557,8 +587,10 @@ export async function takeHold(dir, { isAlive = alive, identity = processIdentit
557
587
  if (!judged)
558
588
  continue;
559
589
  const held = await readHold(at);
590
+ if (!recoverUnknownOwner && !ownerProof(held))
591
+ return undefined;
560
592
  const live = typeof held?.pid === "number" && typeof held.startedAt === "number"
561
- ? local(held) ? installing(held) : Date.now() - held.startedAt <= timeoutMs + HOLD_STOP_MS
593
+ ? !previousBoot(held) && (local(held) ? installing(held) : Date.now() - held.startedAt <= timeoutMs + HOLD_STOP_MS)
562
594
  : Date.now() - judged.mtimeMs <= HOLD_WRITING_MS;
563
595
  if (live)
564
596
  return undefined;
@@ -596,8 +628,8 @@ export async function takeHold(dir, { isAlive = alive, identity = processIdentit
596
628
  }
597
629
  /** Lets go of the hold on installs into `dir` that `token` took; a hold of another's (one that took over this one past
598
630
  * its bound) stays. */
599
- export async function releaseHold(dir, token) {
600
- const at = installHoldOf(dir);
631
+ export async function releaseHold(dir, token, { holdPath = installHoldOf(dir) } = {}) {
632
+ const at = holdPath;
601
633
  if ((await readHold(at))?.token === token)
602
634
  await rm(at, { force: true });
603
635
  }
package/dist/harness.d.ts CHANGED
@@ -9,7 +9,7 @@ export declare const DEFAULT_HARNESS: HarnessId;
9
9
  export declare const HARNESS_ID_PATTERN = "^[a-z][a-z0-9-]{0,39}$";
10
10
  /** The names serve's own runs carry where a harness id goes, so a harness module may not take one (its start is refused):
11
11
  * `learning`, the launch harness the stores' learning queries match; `sdk`, an SDK run's launch harness
12
- * (sdk/runs.ts); and the names analytics files a run's harness under: `workflow`, a workflow revision's, and each SDK
12
+ * (sdk/runs.ts); `cli`, a connected CLI capture; and the names analytics files a run's harness under: `workflow`, a workflow revision's, and each SDK
13
13
  * runtime's (sdk/schema.ts SDK_BINDING). Also every name a plain object already has that the id pattern admits
14
14
  * (`constructor`): serve looks harnesses up by id in plain objects, where such an id would read Object's own member. */
15
15
  export declare const RESERVED_HARNESS_IDS: readonly string[];
package/dist/harness.js CHANGED
@@ -8,11 +8,11 @@ export const DEFAULT_HARNESS = "pi";
8
8
  export const HARNESS_ID_PATTERN = "^[a-z][a-z0-9-]{0,39}$";
9
9
  /** The names serve's own runs carry where a harness id goes, so a harness module may not take one (its start is refused):
10
10
  * `learning`, the launch harness the stores' learning queries match; `sdk`, an SDK run's launch harness
11
- * (sdk/runs.ts); and the names analytics files a run's harness under: `workflow`, a workflow revision's, and each SDK
11
+ * (sdk/runs.ts); `cli`, a connected CLI capture; and the names analytics files a run's harness under: `workflow`, a workflow revision's, and each SDK
12
12
  * runtime's (sdk/schema.ts SDK_BINDING). Also every name a plain object already has that the id pattern admits
13
13
  * (`constructor`): serve looks harnesses up by id in plain objects, where such an id would read Object's own member. */
14
14
  export const RESERVED_HARNESS_IDS = Object.freeze([
15
- "learning", "sdk", "workflow", ...SDK_RUNTIMES,
15
+ "learning", "sdk", "cli", "codex-cli", "claude-code-cli", "workflow", ...SDK_RUNTIMES,
16
16
  ...Object.getOwnPropertyNames(Object.prototype).filter((name) => new RegExp(HARNESS_ID_PATTERN).test(name)),
17
17
  ]);
18
18
  /** The harnesses that run on a person's ChatGPT plan (chatgpt-plan.ts): those whose requests go to OpenAI's Responses
@@ -23,6 +23,11 @@ export type LearningChange = {
23
23
  /** The commit the run started from: a file that is not on main as it was on it (a person retired or approved it,
24
24
  * another run's merge changed it) is a conflict. The script checks it on main as it commits. */
25
25
  seed?: string;
26
+ /** A commit the folder must still hold for the merge to land, its correction alone included (which no `same` covers):
27
+ * the run's seed, when this folder held it as the run's end began (runner/learning-end.ts). A reset of the agent's
28
+ * learning since removed it, so the whole merge is a conflict that says so. Absent when the run's seed was read from
29
+ * another folder than this one (a Mode 2 run's end writes the folder on its disk). */
30
+ mustHold?: string;
26
31
  /** A file checked against another commit than `seed`, by its path: a workflow the run's compile turn revised from
27
32
  * main's text, against the commit it read that text at. */
28
33
  bases?: Readonly<Record<string, string>>;
@@ -17,6 +17,8 @@ function blobOf(snapshot, path) {
17
17
  /** A write's failure as a result: the script's precondition (a file changed since the seed: a conflict), a write past
18
18
  * what one exec carries, or the folder unavailable (retry later). */
19
19
  function failure(error) {
20
+ if (error instanceof FolderRefused && error.seed !== undefined)
21
+ return { ok: false, reason: "conflict", problems: [{ rule: "kept", detail: "the agent's learning was reset after the run started, so what it learned has nothing to land on" }] };
20
22
  if (error instanceof FolderRefused)
21
23
  return { ok: false, reason: "conflict", problems: [...error.same, ...error.absent].map((path) => ({ rule: "kept", path, detail: `${path} changed on main after the run started` })) };
22
24
  if (error instanceof FolderTooLarge)
@@ -73,7 +75,8 @@ export async function learningCommit(ws, change, opts = {}) {
73
75
  else
74
76
  writes.push({ path: CORRECTIONS_FILE, text });
75
77
  }
76
- return { result: { pending: true, ...(refusedCorrection ? { refusedCorrection } : {}) }, change: { by: run(change.runId, change.reason, change.round), writes, ...(same.length ? { same } : {}) } };
78
+ // `mustHold`: the script refuses the whole merge when the folder no longer holds it (a reset removed it).
79
+ return { result: { pending: true, ...(refusedCorrection ? { refusedCorrection } : {}) }, change: { by: run(change.runId, change.reason, change.round), writes, ...(same.length ? { same } : {}), ...(change.mustHold ? { seed: change.mustHold } : {}) } };
77
80
  }, opts.retries ?? 3);
78
81
  const { result } = done;
79
82
  return "merged" in result ? await already(ws, change, result.merged.merge, result.merged) : landed({ ...done, result });
@@ -138,16 +138,24 @@ export declare const agentRun: (run: {
138
138
  }) => boolean;
139
139
  /** The agent's newest `n` runs that `keep` keeps (of those the store lists by `listed`: e.g. only ended, not archived),
140
140
  * newest first, picked before anything else limits them: runs it does not keep, however many, never push them out of the
141
- * read (it reads more of the agent's runs until it has `n`, or there are no more). */
141
+ * read (it reads more of the agent's runs until it has `n`, or there are no more). Only runs on no named disk: a run on
142
+ * one learns nothing (learn/learning-of.ts), so learning never reads it. */
142
143
  export declare function lastRunsOf(store: Pick<Store, "runs">, agentId: string, n: number, keep: (row: RunRow) => boolean, listed?: {
143
144
  readonly state?: "ended";
144
145
  readonly archived?: false;
145
146
  }): Promise<RunRow[]>;
147
+ /** Which of agent `agentId`'s runs its learning may read, by its reset watermark (learn/promote.ts resetAtOf): every run
148
+ * when its learning was never reset; else only a run that started after it and did not read its learning seed at or
149
+ * before it (its launch's `seededAt`: a run whose start read the seed before the reset, its row made after it). When
150
+ * it was reset, one read of that one number of the runs started after it (Store.runs.seededBefore); none when not.
151
+ * Every learning read of "the agent's runs" takes it: compile_after's count and a check's inputs (lastOwnRuns), a
152
+ * compile's traces, an audit's draws, the money rule's past runs. */
153
+ export declare function sinceReset(store: Pick<Store, "runs" | "settings">, agentId: string): Promise<(row: Pick<RunRow, "id" | "startedAt">) => boolean>;
146
154
  /** The agent's last `n` completed runs of its own (agentRun: not one its learned workflow answered alone, not a replay
147
- * nor a shadow audit; never `exceptRunId`, an archived run or an imported one), newest first (lastRunsOf: runs its
148
- * workflow served since never push them out of the read). The one read of what compile_after counts and of a check's
149
- * inputs. */
150
- export declare const lastOwnRuns: (store: Pick<Store, "runs">, agentId: string, n: number, exceptRunId?: string) => Promise<RunRow[]>;
155
+ * nor a shadow audit; never `exceptRunId`, an archived run or an imported one) since its learning's reset (sinceReset),
156
+ * newest first (lastRunsOf: runs its workflow served since never push them out of the read). The one read of what
157
+ * compile_after counts and of a check's inputs. */
158
+ export declare const lastOwnRuns: (store: Pick<Store, "runs" | "settings">, agentId: string, n: number, exceptRunId?: string) => Promise<RunRow[]>;
151
159
  /** Whether a run's look-back compiles its agent's job: the run completed, the agent has no learned workflow (active or
152
160
  * waiting for its owner's OK), and it has `compileAfter` completed
153
161
  * agent runs (its definition's compile_after, learning-setting.ts), the ending one counted. */
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { LEARNED_MAX_TURNS, WORKFLOW_NAME } from "./workflow-draft.js";
3
- import { championOf, checkShares, promotionOf } from "./promote.js";
3
+ import { championOf, checkShares, promotionOf, resetAtOf } from "./promote.js";
4
4
  import { listed } from "../learning-words.js";
5
5
  import { excerptShown, redactSecrets } from "./secrets.js";
6
6
  import { isShadowRun } from "./audit.js";
@@ -115,20 +115,37 @@ const OWN_PAGE_MIN = 200;
115
115
  const OWN_PAGE_GROWTH = 4;
116
116
  /** The agent's newest `n` runs that `keep` keeps (of those the store lists by `listed`: e.g. only ended, not archived),
117
117
  * newest first, picked before anything else limits them: runs it does not keep, however many, never push them out of the
118
- * read (it reads more of the agent's runs until it has `n`, or there are no more). */
118
+ * read (it reads more of the agent's runs until it has `n`, or there are no more). Only runs on no named disk: a run on
119
+ * one learns nothing (learn/learning-of.ts), so learning never reads it. */
119
120
  export async function lastRunsOf(store, agentId, n, keep, listed = {}) {
120
121
  for (let limit = Math.max(OWN_PAGE_MIN, 3 * n);; limit *= OWN_PAGE_GROWTH) {
121
- const page = await store.runs.list({ agentId, ...listed, limit });
122
+ const page = await store.runs.list({ agentId, disk: null, ...listed, limit });
122
123
  const found = page.filter(keep).slice(0, n);
123
124
  if (found.length >= n || page.length < limit)
124
125
  return found;
125
126
  }
126
127
  }
128
+ /** Which of agent `agentId`'s runs its learning may read, by its reset watermark (learn/promote.ts resetAtOf): every run
129
+ * when its learning was never reset; else only a run that started after it and did not read its learning seed at or
130
+ * before it (its launch's `seededAt`: a run whose start read the seed before the reset, its row made after it). When
131
+ * it was reset, one read of that one number of the runs started after it (Store.runs.seededBefore); none when not.
132
+ * Every learning read of "the agent's runs" takes it: compile_after's count and a check's inputs (lastOwnRuns), a
133
+ * compile's traces, an audit's draws, the money rule's past runs. */
134
+ export async function sinceReset(store, agentId) {
135
+ const at = await resetAtOf(store.settings, agentId);
136
+ if (at === undefined)
137
+ return () => true;
138
+ const before = new Set(await store.runs.seededBefore(agentId, at));
139
+ return (row) => row.startedAt > at && !before.has(row.id);
140
+ }
127
141
  /** The agent's last `n` completed runs of its own (agentRun: not one its learned workflow answered alone, not a replay
128
- * nor a shadow audit; never `exceptRunId`, an archived run or an imported one), newest first (lastRunsOf: runs its
129
- * workflow served since never push them out of the read). The one read of what compile_after counts and of a check's
130
- * inputs. */
131
- export const lastOwnRuns = (store, agentId, n, exceptRunId) => lastRunsOf(store, agentId, n, (row) => row.id !== exceptRunId && agentRun(row) && row.archivedAt === null && !row.importedFrom, { state: "ended", archived: false });
142
+ * nor a shadow audit; never `exceptRunId`, an archived run or an imported one) since its learning's reset (sinceReset),
143
+ * newest first (lastRunsOf: runs its workflow served since never push them out of the read). The one read of what
144
+ * compile_after counts and of a check's inputs. */
145
+ export const lastOwnRuns = async (store, agentId, n, exceptRunId) => {
146
+ const since = await sinceReset(store, agentId);
147
+ return lastRunsOf(store, agentId, n, (row) => row.id !== exceptRunId && agentRun(row) && row.archivedAt === null && !row.importedFrom && since(row), { state: "ended", archived: false });
148
+ };
132
149
  /** Whether a run's look-back compiles its agent's job: the run completed, the agent has no learned workflow (active or
133
150
  * waiting for its owner's OK), and it has `compileAfter` completed
134
151
  * agent runs (its definition's compile_after, learning-setting.ts), the ending one counted. */