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

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 (322) hide show
  1. package/CHANGELOG.md +160 -1
  2. package/README.md +306 -36
  3. package/dist/adapters.js +1 -1
  4. package/dist/agent-delete.d.ts +14 -4
  5. package/dist/agent-delete.js +30 -58
  6. package/dist/agent-package.d.ts +71 -0
  7. package/dist/agent-package.js +345 -0
  8. package/dist/agents-store.d.ts +28 -18
  9. package/dist/agents-store.js +48 -34
  10. package/dist/api-only.d.ts +30 -8
  11. package/dist/api-only.js +40 -16
  12. package/dist/archil-routes.d.ts +1 -0
  13. package/dist/archil-routes.js +28 -2
  14. package/dist/claude-login.d.ts +1 -0
  15. package/dist/claude-login.js +1 -1
  16. package/dist/cli-learning/cli.d.ts +3 -0
  17. package/dist/cli-learning/cli.js +17 -3
  18. package/dist/cli-learning/connections.js +3 -2
  19. package/dist/cli-learning/schema.js +2 -1
  20. package/dist/cli.js +70 -7
  21. package/dist/composio-preset.d.ts +2 -1
  22. package/dist/composio-preset.js +4 -3
  23. package/dist/composio-triggers.d.ts +4 -0
  24. package/dist/composio-triggers.js +4 -1
  25. package/dist/computer-needs.d.ts +32 -0
  26. package/dist/computer-needs.js +80 -0
  27. package/dist/computer-setting.d.ts +9 -0
  28. package/dist/computer-setting.js +19 -1
  29. package/dist/computers.d.ts +6 -2
  30. package/dist/computers.js +2 -2
  31. package/dist/console/assets/index-BFgyZzF_.js +734 -0
  32. package/dist/console/assets/index-DbilxljH.css +1 -0
  33. package/dist/console/index.html +2 -2
  34. package/dist/console-links.d.ts +1 -0
  35. package/dist/console-links.js +2 -0
  36. package/dist/env-switch.d.ts +14 -0
  37. package/dist/env-switch.js +23 -0
  38. package/dist/errors.d.ts +1 -0
  39. package/dist/errors.js +3 -0
  40. package/dist/eval-previous.js +4 -3
  41. package/dist/fal-price.d.ts +76 -0
  42. package/dist/fal-price.js +365 -0
  43. package/dist/handed-secret.d.ts +4 -0
  44. package/dist/handed-secret.js +10 -0
  45. package/dist/harness-archive.d.ts +15 -5
  46. package/dist/harness-archive.js +71 -34
  47. package/dist/harness-check.d.ts +2 -1
  48. package/dist/harness-check.js +36 -95
  49. package/dist/harness-egress.d.ts +23 -0
  50. package/dist/harness-egress.js +69 -0
  51. package/dist/harness-recipe-entry.d.ts +71 -0
  52. package/dist/harness-recipe-entry.js +184 -0
  53. package/dist/harness-recipe.d.ts +73 -6
  54. package/dist/harness-recipe.js +185 -31
  55. package/dist/harness-sign-in.d.ts +29 -0
  56. package/dist/harness-sign-in.js +122 -0
  57. package/dist/harness-table.d.ts +21 -0
  58. package/dist/harness-table.js +58 -3
  59. package/dist/harness-zip.d.ts +6 -0
  60. package/dist/harness-zip.js +203 -0
  61. package/dist/ids.d.ts +11 -0
  62. package/dist/ids.js +36 -0
  63. package/dist/learn/commit.d.ts +19 -1
  64. package/dist/learn/commit.js +160 -2
  65. package/dist/learn/compile.d.ts +13 -5
  66. package/dist/learn/compile.js +46 -15
  67. package/dist/learn/delete.d.ts +12 -6
  68. package/dist/learn/delete.js +17 -11
  69. package/dist/learn/folder.d.ts +16 -0
  70. package/dist/learn/folder.js +30 -4
  71. package/dist/learn/learning-of.d.ts +8 -0
  72. package/dist/learn/learning-of.js +8 -0
  73. package/dist/learn/learning.sh +29 -4
  74. package/dist/learn/promote.d.ts +51 -7
  75. package/dist/learn/promote.js +51 -8
  76. package/dist/learn/secrets.js +30 -7
  77. package/dist/learning-reset.d.ts +18 -0
  78. package/dist/learning-reset.js +115 -0
  79. package/dist/learning-routes.d.ts +23 -11
  80. package/dist/learning-routes.js +110 -20
  81. package/dist/learning-words.d.ts +5 -0
  82. package/dist/learning-words.js +5 -0
  83. package/dist/learning.d.ts +15 -10
  84. package/dist/learning.js +14 -8
  85. package/dist/llms.txt +1 -0
  86. package/dist/mcp-gateway.d.ts +39 -2
  87. package/dist/mcp-gateway.js +56 -12
  88. package/dist/mcp-pin-first.js +1 -1
  89. package/dist/mcp-probe.d.ts +3 -0
  90. package/dist/mcp-probe.js +7 -2
  91. package/dist/mcp-resources.d.ts +44 -0
  92. package/dist/mcp-resources.js +100 -0
  93. package/dist/mcp-servers-store.d.ts +17 -12
  94. package/dist/mcp-servers-store.js +2 -1
  95. package/dist/media-duration.d.ts +2 -0
  96. package/dist/media-duration.js +136 -0
  97. package/dist/model.d.ts +4 -4
  98. package/dist/model.js +6 -6
  99. package/dist/native/cli.js +9 -2
  100. package/dist/native/connection.d.ts +2 -2
  101. package/dist/native/connection.js +5 -2
  102. package/dist/native/discovery.d.ts +2 -0
  103. package/dist/native/discovery.js +10 -6
  104. package/dist/native/remote-worker-bridge.js +36 -4
  105. package/dist/native/remote.d.ts +18 -1
  106. package/dist/native/remote.js +126 -37
  107. package/dist/native/schema.d.ts +6 -0
  108. package/dist/native/schema.js +31 -6
  109. package/dist/native/source-account.d.ts +13 -0
  110. package/dist/native/source-account.js +114 -0
  111. package/dist/native/source-capture-hooks.d.ts +5 -0
  112. package/dist/native/source-capture-hooks.js +102 -0
  113. package/dist/native/source-mcp-selection.d.ts +13 -0
  114. package/dist/native/source-mcp-selection.js +72 -0
  115. package/dist/native/source-runtime-tools.d.ts +19 -0
  116. package/dist/native/source-runtime-tools.js +103 -0
  117. package/dist/native/source-snapshot-types.d.ts +138 -0
  118. package/dist/native/source-snapshot-types.js +12 -0
  119. package/dist/native/source-snapshot.d.ts +8 -0
  120. package/dist/native/source-snapshot.js +1201 -0
  121. package/dist/observation/learning.js +3 -2
  122. package/dist/openapi.js +211 -47
  123. package/dist/print.js +1 -1
  124. package/dist/provider.d.ts +8 -0
  125. package/dist/provider.js +14 -2
  126. package/dist/purged-workflow.d.ts +12 -0
  127. package/dist/purged-workflow.js +43 -0
  128. package/dist/refusal-words.d.ts +0 -3
  129. package/dist/refusal-words.js +0 -3
  130. package/dist/request-metadata.d.ts +20 -0
  131. package/dist/request-metadata.js +24 -0
  132. package/dist/run-keys.d.ts +46 -0
  133. package/dist/run-keys.js +109 -0
  134. package/dist/run-launch.d.ts +29 -5
  135. package/dist/run-launch.js +44 -4
  136. package/dist/run-learning-served.d.ts +2 -2
  137. package/dist/run-model-key.d.ts +2 -2
  138. package/dist/run-model-key.js +5 -5
  139. package/dist/run-secrets.d.ts +2 -0
  140. package/dist/run-secrets.js +7 -4
  141. package/dist/run-usage.d.ts +48 -4
  142. package/dist/run-usage.js +156 -39
  143. package/dist/run-view.d.ts +18 -1
  144. package/dist/run-view.js +28 -8
  145. package/dist/runner/adapter-loop.d.ts +14 -4
  146. package/dist/runner/adapter-loop.js +150 -31
  147. package/dist/runner/adapter-run-spec.d.ts +1 -1
  148. package/dist/runner/adapter-run-spec.js +35 -22
  149. package/dist/runner/audit.d.ts +10 -3
  150. package/dist/runner/audit.js +30 -7
  151. package/dist/runner/beside.js +2 -1
  152. package/dist/runner/claim-secrets.d.ts +31 -4
  153. package/dist/runner/claim-secrets.js +43 -7
  154. package/dist/runner/cli-run-spec.d.ts +1 -1
  155. package/dist/runner/cli-run-spec.js +32 -20
  156. package/dist/runner/conformance/harness.js +4 -2
  157. package/dist/runner/dispatch.js +4 -2
  158. package/dist/runner/harness-loops.d.ts +6 -0
  159. package/dist/runner/harness-loops.js +16 -3
  160. package/dist/runner/held.d.ts +4 -0
  161. package/dist/runner/journal-kinds.d.ts +5 -0
  162. package/dist/runner/learned-first.d.ts +2 -0
  163. package/dist/runner/learned-first.js +1 -1
  164. package/dist/runner/learning-end.d.ts +9 -3
  165. package/dist/runner/learning-end.js +66 -29
  166. package/dist/runner/learning-seed.d.ts +9 -3
  167. package/dist/runner/learning-seed.js +2 -2
  168. package/dist/runner/main.d.ts +1 -0
  169. package/dist/runner/main.js +20 -13
  170. package/dist/runner/mcp-claim.js +7 -2
  171. package/dist/runner/mcp-run.d.ts +12 -0
  172. package/dist/runner/mcp-run.js +14 -1
  173. package/dist/runner/model-route.js +7 -4
  174. package/dist/runner/monid-run.js +9 -11
  175. package/dist/runner/project-checkpoint.d.ts +35 -0
  176. package/dist/runner/project-checkpoint.js +116 -0
  177. package/dist/runner/project-drain.d.ts +8 -0
  178. package/dist/runner/project-drain.js +25 -0
  179. package/dist/runner/project-host.d.ts +10 -0
  180. package/dist/runner/project-host.js +52 -0
  181. package/dist/runner/promotion.d.ts +51 -24
  182. package/dist/runner/promotion.js +206 -78
  183. package/dist/runner/redact.d.ts +13 -0
  184. package/dist/runner/redact.js +67 -1
  185. package/dist/runner/run-channel.d.ts +9 -0
  186. package/dist/runner/run-channel.js +15 -2
  187. package/dist/runner/run-child-host.d.ts +8 -4
  188. package/dist/runner/run-child-host.js +174 -42
  189. package/dist/runner/run-errors.js +2 -2
  190. package/dist/runner/runner-check.js +5 -2
  191. package/dist/runner/runner.js +41 -12
  192. package/dist/runner/sdk-loop.d.ts +2 -2
  193. package/dist/runner/sdk-loop.js +3 -3
  194. package/dist/runner/store-port.d.ts +3 -0
  195. package/dist/runner/store-secrets.js +7 -3
  196. package/dist/runner/workflow-first.d.ts +4 -0
  197. package/dist/runner/workflow-first.js +13 -0
  198. package/dist/runner/workflow-loop.d.ts +2 -1
  199. package/dist/runner/workflow-loop.js +2 -1
  200. package/dist/runner/workflow-spec.js +4 -4
  201. package/dist/runs-over-store.d.ts +39 -8
  202. package/dist/runs-over-store.js +147 -32
  203. package/dist/sdk/check.d.ts +6 -5
  204. package/dist/sdk/check.js +17 -16
  205. package/dist/sdk/runs.d.ts +11 -1
  206. package/dist/sdk/runs.js +185 -78
  207. package/dist/sdk/schema.js +12 -2
  208. package/dist/sdk/workflows.d.ts +1 -1
  209. package/dist/server.d.ts +68 -32
  210. package/dist/server.js +678 -124
  211. package/dist/skills/agentrun-serve/SKILL.md +2 -1
  212. package/dist/source-sync/adoption.d.ts +15 -0
  213. package/dist/source-sync/adoption.js +36 -0
  214. package/dist/source-sync/auxiliary.d.ts +23 -0
  215. package/dist/source-sync/auxiliary.js +64 -0
  216. package/dist/source-sync/capture-git.d.ts +5 -0
  217. package/dist/source-sync/capture-git.js +272 -0
  218. package/dist/source-sync/capture-project.d.ts +53 -0
  219. package/dist/source-sync/capture-project.js +206 -0
  220. package/dist/source-sync/capture-refusal.d.ts +7 -0
  221. package/dist/source-sync/capture-refusal.js +16 -0
  222. package/dist/source-sync/capture.d.ts +11 -0
  223. package/dist/source-sync/capture.js +22 -0
  224. package/dist/source-sync/checkpoint-gate.d.ts +21 -0
  225. package/dist/source-sync/checkpoint-gate.js +52 -0
  226. package/dist/source-sync/checkpoints.d.ts +66 -0
  227. package/dist/source-sync/checkpoints.js +168 -0
  228. package/dist/source-sync/claim.d.ts +11 -0
  229. package/dist/source-sync/claim.js +48 -0
  230. package/dist/source-sync/destination.d.ts +47 -0
  231. package/dist/source-sync/destination.js +239 -0
  232. package/dist/source-sync/io.d.ts +15 -0
  233. package/dist/source-sync/io.js +52 -0
  234. package/dist/source-sync/local.d.ts +43 -0
  235. package/dist/source-sync/local.js +229 -0
  236. package/dist/source-sync/prepare.d.ts +59 -0
  237. package/dist/source-sync/prepare.js +93 -0
  238. package/dist/source-sync/projects.d.ts +61 -0
  239. package/dist/source-sync/projects.js +130 -0
  240. package/dist/source-sync/registry.d.ts +95 -0
  241. package/dist/source-sync/registry.js +226 -0
  242. package/dist/source-sync/service.d.ts +33 -0
  243. package/dist/source-sync/service.js +118 -0
  244. package/dist/source-sync/skill-edits.d.ts +12 -0
  245. package/dist/source-sync/skill-edits.js +122 -0
  246. package/dist/source-sync/snapshots.d.ts +48 -0
  247. package/dist/source-sync/snapshots.js +448 -0
  248. package/dist/source-sync/types.d.ts +9 -0
  249. package/dist/source-sync/types.js +14 -0
  250. package/dist/source-sync/workspace.d.ts +66 -0
  251. package/dist/source-sync/workspace.js +273 -0
  252. package/dist/store/agent-body.d.ts +8 -0
  253. package/dist/store/agent-body.js +20 -6
  254. package/dist/store/index.d.ts +2 -2
  255. package/dist/store/index.js +1 -1
  256. package/dist/store/journal/storage.d.ts +2 -0
  257. package/dist/store/journal/storage.js +2 -1
  258. package/dist/store/postgres/migrations/0025_run_attempts.sql +27 -0
  259. package/dist/store/postgres/migrations/0026_run_disk.sql +23 -0
  260. package/dist/store/schema.d.ts +15 -1
  261. package/dist/store/schema.js +43 -4
  262. package/dist/store/seal.d.ts +5 -1
  263. package/dist/store/seal.js +12 -3
  264. package/dist/store/sqlite/project-checkpoints.d.ts +11 -0
  265. package/dist/store/sqlite/project-checkpoints.js +70 -0
  266. package/dist/store/sqlite/run-launch.d.ts +14 -0
  267. package/dist/store/sqlite/run-launch.js +58 -7
  268. package/dist/store/sqlite/run-patch.d.ts +2 -1
  269. package/dist/store/sqlite/run-patch.js +4 -3
  270. package/dist/store/sqlite/store.js +319 -153
  271. package/dist/store/store-schema.js +2 -2
  272. package/dist/store/store.d.ts +173 -33
  273. package/dist/store/store.js +14 -1
  274. package/dist/store-reads/learning.d.ts +12 -8
  275. package/dist/store-reads/learning.js +33 -24
  276. package/dist/store-reads/loop.d.ts +4 -3
  277. package/dist/store-reads/loop.js +7 -5
  278. package/dist/store-view.d.ts +3 -1
  279. package/dist/store-view.js +17 -5
  280. package/dist/template-eval.js +4 -4
  281. package/dist/template-import.d.ts +10 -2
  282. package/dist/template-import.js +116 -13
  283. package/dist/templates.d.ts +29 -5
  284. package/dist/templates.js +68 -14
  285. package/dist/timeline/index.d.ts +1 -1
  286. package/dist/timeline/index.js +1 -1
  287. package/dist/timeline/labels.js +1 -1
  288. package/dist/timeline/timeline.d.ts +5 -0
  289. package/dist/timeline/timeline.js +8 -0
  290. package/dist/tool-plane.d.ts +12 -12
  291. package/dist/tools.d.ts +8 -8
  292. package/dist/tools.js +1 -1
  293. package/dist/trigger-launch-hook.d.ts +47 -0
  294. package/dist/trigger-launch-hook.js +90 -0
  295. package/dist/trigger-targets.d.ts +14 -1
  296. package/dist/trigger-targets.js +20 -0
  297. package/dist/triggers.d.ts +54 -5
  298. package/dist/triggers.js +143 -8
  299. package/dist/uploads-archil.js +2 -1
  300. package/dist/uploads.d.ts +0 -3
  301. package/dist/uploads.js +2 -11
  302. package/dist/validate.js +4 -1
  303. package/dist/web-save.d.ts +3 -0
  304. package/dist/web-save.js +17 -2
  305. package/dist/workspace/archil-exec.js +1 -1
  306. package/dist/workspace/archil.js +1 -1
  307. package/dist/workspace/computer-for-claim.d.ts +2 -0
  308. package/dist/workspace/computer-for-claim.js +43 -0
  309. package/dist/workspace/paths.d.ts +6 -0
  310. package/dist/workspace/paths.js +6 -0
  311. package/dist/workspace/resolve-computer.d.ts +1 -0
  312. package/dist/workspace/revision-skills.js +24 -11
  313. package/dist/workspace/run-tools.d.ts +2 -0
  314. package/dist/workspace/run-tools.js +8 -0
  315. package/dist/workspace/synced-folder.d.ts +3 -3
  316. package/dist/workspace/synced-folder.js +7 -6
  317. package/launcher/agentrun-serve +1 -1
  318. package/package.json +10 -10
  319. package/skills/agentrun-serve/SKILL.md +2 -1
  320. package/templates/README.md +5 -2
  321. package/dist/console/assets/index-Bt1B51b7.js +0 -733
  322. package/dist/console/assets/index-sVftE9Ht.css +0 -1
@@ -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;
@@ -1,7 +1,7 @@
1
1
  import { type TimelineEvent } from "./timeline/index.js";
2
2
  import { type ItemStatus, type Learning } from "./learning.js";
3
3
  import { type RunLaunch } from "./run-launch.js";
4
- import { type Pending, type RunMoment, type RunView, type SignInReader, type Status, type ComputerAsk } from "./run-view.js";
4
+ import { type Pending, type RunMoment, type RunView, type SignInReader, type Status, type ComputerAsk, windDownOf } from "./run-view.js";
5
5
  import { type BookedSpend, type RunCost } from "./runner/metrics.js";
6
6
  import { type EndData } from "./runner/journal-kinds.js";
7
7
  import { type RunReadState, readRun } from "./store-reads/runs.js";
@@ -77,6 +77,8 @@ interface StoreRun {
77
77
  /** The budget card the run shows while it stands parked at its cap (pending, kind budget), or undefined when it is not
78
78
  * parked there. Also the source of the `budgetWaiting` fact. */
79
79
  readonly budget: Pending | undefined;
80
+ /** How the run wound down for its cap (run-view.ts windDownOf): its `stopped_for` and `budget_refused_calls`. */
81
+ readonly windDown: ReturnType<typeof windDownOf>;
80
82
  /** Whether a workflow run stands paused in its process now (pausedOf): the source of the `paused` fact. */
81
83
  readonly paused: boolean;
82
84
  /** The browser hand-over the run's agent waits on (the newest ask still waiting), or undefined. Also the `browserAsk`
@@ -18,7 +18,7 @@ import { COMPUTER_UNAVAILABLE_CODE, lostEndMessage } from "./computer-lost.js";
18
18
  import { refusedEndMessage, RUNNER_REFUSED_CODE } from "./runner/presence.js";
19
19
  import { launchOf } from "./handed-values.js";
20
20
  import { learningStartOf, seedFailed } from "./run-launch.js";
21
- import { momentOf, pendingOf, stoppedTurn, approvalOf, asksOf, answersOf, activePauseOf, budgetOf, browserPending, computerPending, redactorOf, servedRunErrorWith, servedReviewWith, statusOf, WITHHELD_SIGN_IN, WITHHELD_TITLE, costWordsOfView, freeOf, stopAsked, usersOf, withAsks, withApprovalRows, } from "./run-view.js";
21
+ import { momentOf, pendingOf, stoppedTurn, approvalOf, asksOf, answersOf, activePauseOf, budgetOf, browserPending, computerPending, redactorOf, servedRunErrorWith, servedReviewWith, statusOf, WITHHELD_SIGN_IN, WITHHELD_TITLE, costWordsOfView, freeOf, stopAsked, usersOf, withAsks, withApprovalRows, windDownOf, } from "./run-view.js";
22
22
  import { reflects } from "./reflect-range.js";
23
23
  import { freeCeilingMessage, overCapMessage, SPEND_CAP_REACHED } from "@parcha/agentrun-kernel/kernel/cap";
24
24
  import { booksDecisions, decisionsOverStore, parallelChargedDecisions } from "./store-reads/decisions.js";
@@ -344,6 +344,10 @@ async function storeRunIn(store, runId, deps, cut, since) {
344
344
  // The budget card the run shows while it stands parked at its cap, from its journal's agentrun.budget park (none once a
345
345
  // raise clears it). Read over the same meta cap and rows the card's figures and time come from.
346
346
  const budget = budgetOf(records.entries, { meta, rows, updatedAt: iso(updatedAtMs) });
347
+ // How it wound down for its cap (run-view.ts windDownOf), under the cap it has now; its end-of-run turns' entries are
348
+ // learning's, never the job's.
349
+ const reflectTurns = reflectRanges(records.submissions ?? [], records.entries);
350
+ const windDown = windDownOf(records.entries, capUsd, (id) => inReflect(reflectTurns, id));
347
351
  const pause = activePauseOf(records.entries);
348
352
  // Whether a workflow run stands paused in its process now (its parked row with the pause's words, its newest pause not
349
353
  // resumed), the `paused` fact the status table reads for a paused workflow.
@@ -418,7 +422,7 @@ async function storeRunIn(store, runId, deps, cut, since) {
418
422
  const endSaidCost = endCost && !lookingBack ? endSaid !== undefined : false;
419
423
  const endUnread = !lookingBack && bookedCost !== undefined && !endCost && endSaid === null;
420
424
  const heal = lookingBack ? undefined : healOf(endCost, runRow);
421
- return { ...(cli_learning ? { cli_learning } : {}), ...(sdk ? { sdk } : {}), ...(native ? { native } : {}), row, runRow, launch, rows, version, harness, learningEnd: shownEnd, shownEnd, view, unshown, values, live, updatedAtMs, lastProgressAt, budget, paused, browserAsk, computerAsk, approvalsMode, output, ...(review ? { review } : {}), structured, decisions, plan, model, ...(endCost ? { endCost, endSaidCost } : {}), ...(endUnread ? { endUnread } : {}), ...(heal ? { heal } : {}), ...(lookingBack ? { lookingBack: true } : {}) };
425
+ return { ...(cli_learning ? { cli_learning } : {}), ...(sdk ? { sdk } : {}), ...(native ? { native } : {}), row, runRow, launch, rows, version, harness, learningEnd: shownEnd, shownEnd, view, unshown, values, live, updatedAtMs, lastProgressAt, budget, paused, browserAsk, computerAsk, approvalsMode, output, ...(review ? { review } : {}), structured, decisions, plan, model, windDown, ...(endCost ? { endCost, endSaidCost } : {}), ...(endUnread ? { endUnread } : {}), ...(heal ? { heal } : {}), ...(lookingBack ? { lookingBack: true } : {}) };
422
426
  }
423
427
  /** Run read `read` (a run still going, as the store holds it) as the end `ended` keeps (its state, summary and end time:
424
428
  * the end a run looking back keeps), its cost as read. */
@@ -675,6 +679,11 @@ async function viewOfRun(store, runId, deps, run, read) {
675
679
  pending,
676
680
  // Its own spend: an audit's shadow run of it is learning (GET /runs/{id}'s cost.learning_usd), never its cost.usd.
677
681
  cost: costOfView(run),
682
+ // Why a completed run stopped: `budget` when it wound down to stay under its cap (its model told to wrap up, or its
683
+ // tool calls refused, under the cap it has now: windDownOf), else null; and how many tool calls the cap's wrap-up
684
+ // refused (stoppedfor/1). A run paused at its cap (pending budget) or failed for it (spend_cap_reached) says so there.
685
+ stopped_for: status === "completed" && run.windDown.woundDown ? "budget" : null,
686
+ budget_refused_calls: run.windDown.refusedCalls,
678
687
  // The run an audit's shadow run audits (launch.audit, runner/audit.ts); null for any other run.
679
688
  audit_of: launch?.audit?.of ?? null,
680
689
  // The path it took and the learned workflow that served it, as its record keeps them: the read the cost per run makes
@@ -705,14 +714,14 @@ export async function summaryOverStore(store, runId, deps) {
705
714
  }
706
715
  /** What a list shows of a run's view (summaryOverStore). */
707
716
  export function summaryOfView(view) {
708
- const { run_id, agent_id, agent_version, console_url, revision, kind, sha, status, state, title, effort, created_at, ended_at, error, review, pending, cost, archived_at, imported_from, trigger, labels, learning } = view;
717
+ const { run_id, agent_id, agent_version, console_url, revision, kind, sha, status, state, title, effort, created_at, ended_at, error, review, pending, cost, stopped_for, budget_refused_calls, archived_at, imported_from, trigger, labels, learning } = view;
709
718
  return {
710
719
  run_id, agent_id, agent_version, console_url, revision, kind, sha, status, state, title,
711
720
  ...(view.cli_learning ? { cli_learning: view.cli_learning } : {}),
712
721
  ...(view.sdk ? { sdk: view.sdk } : {}),
713
722
  ...(view.native ? { native: view.native } : {}),
714
723
  ...(effort ? { effort } : {}),
715
- created_at, ended_at, error, review, pending, cost, archived_at, imported_from, trigger, labels,
724
+ created_at, ended_at, error, review, pending, cost, stopped_for, budget_refused_calls, archived_at, imported_from, trigger, labels,
716
725
  learning: learning ? shortOf(learning) : null,
717
726
  // Read off the run's record, so a list carries it with no read of the run's journal.
718
727
  path: view.path, workflow: view.workflow,
@@ -751,8 +760,11 @@ export async function listingOverStore(store, runId, deps) {
751
760
  * (server.ts runsPage): the run's view cuts a value whole where it holds a secret (a note's name reads [redacted]), which
752
761
  * cutting the built item again could not do. */
753
762
  export function builtOfNow(listing, serverSecrets) {
754
- return listing.cut === secretsDigest(serverSecrets);
763
+ return listing.cut === secretsDigest(serverSecrets) && LISTING_SINCE.every((field) => field in listing.item);
755
764
  }
765
+ /** List item fields an earlier server's listing was built without: a listing that lacks one is built again, once, so
766
+ * every list item carries them (stoppedfor/1). */
767
+ const LISTING_SINCE = ["stopped_for", "budget_refused_calls"];
756
768
  /** A listing's list item as a list serves it (listingOverStore): its console link at `origin`, its archive time now
757
769
  * (`archivedAt`, ms, the run's or its agent's), and, when the server's secrets moved between its build and this (within
758
770
  * one list), every string in it cut again of them (redactedOutput), so a secret saved since never shows. */
@@ -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)
@@ -1,13 +1,17 @@
1
- import type { Store } from "./store/index.js";
1
+ import { type Store, UPLOAD_PREFIX } from "./store/index.js";
2
2
  import { type GithubReach } from "./template-source.js";
3
3
  import { type Package, type TemplateRegistry } from "./templates.js";
4
4
  /** The settings key that holds the GitHub accounts this server's owner trusts as publishers, lower-cased. */
5
5
  export declare const TRUSTED_PUBLISHERS = "templates.trusted_publishers";
6
+ /** An uploaded package's id is this and its manifest's name: the next upload of that name replaces it. */
7
+ export { UPLOAD_PREFIX };
6
8
  export type TemplateImportDeps = {
7
9
  registry: TemplateRegistry;
8
10
  store: Pick<Store, "importedTemplates" | "settings">;
9
11
  /** Where GitHub is read (template-source.ts GithubReach): GitHub's hosts and this server's App token when it has one. */
10
12
  reach: (signal: AbortSignal) => Promise<GithubReach>;
13
+ /** The API-only profile: an upload is taken, a GitHub source refused (its backend sends the package). */
14
+ apiOnly?: boolean;
11
15
  };
12
16
  /** An imported package read from its files, checked whole, with its id and origin: PackageError when it does not check. */
13
17
  export declare function importedPackage(id: string, origin: {
@@ -18,8 +22,12 @@ export declare function importedPackage(id: string, origin: {
18
22
  /** The packages the store keeps, put in the registry beside the bundled ones; one this build no longer takes is left out,
19
23
  * said through `skipped`, never a stop of the start. */
20
24
  export declare function loadImported(deps: Pick<TemplateImportDeps, "registry" | "store">, skipped: (id: string, why: string) => void): Promise<void>;
25
+ /** The uploads served here whose row the store no longer keeps (an agent's purge removed it: Agents.purge), no longer
26
+ * served. Only the package read before the store is removed, so an upload put in meanwhile stays served. */
27
+ export declare function dropRemovedUploads(deps: Pick<TemplateImportDeps, "registry" | "store">): Promise<void>;
21
28
  /** POST /v2/templates/import: the package read at its source's commit and checked; a dry run answers it, storing nothing;
22
- * else it is stored and served (201), in place of the one under its id. `signal` ends the read (the request's). */
29
+ * else it is stored and served (201), in place of the one under its id. `signal` ends the read (the request's). An
30
+ * upload ({files}) is uploadTemplate's. */
23
31
  export declare function importTemplate(deps: TemplateImportDeps, raw: unknown, signal: AbortSignal): Promise<{
24
32
  status: 200 | 201;
25
33
  pkg: Package;
@@ -1,15 +1,74 @@
1
- // POST /v2/templates/import and the imported packages' life here: read from GitHub (template-source.ts), checked by the one
2
- // checker (templates.ts readPackage, over the files held in memory), stored (store `imported_templates`) and loaded beside
3
- // the bundled packages at each start. The first import stored from a GitHub account needs its owner's "I trust <account>",
4
- // remembered server-side (settings TRUSTED_PUBLISHERS). Nothing in a package runs.
1
+ // POST /v2/templates/import and the imported packages' life here: read from GitHub (template-source.ts), or uploaded whole
2
+ // as its files ({files}, by `agentrun deploy`), checked by the one checker (templates.ts readPackage, over the files held
3
+ // in memory), stored (store `imported_templates`) and loaded beside the bundled packages at each start. The first import
4
+ // stored from a GitHub account needs its owner's "I trust <account>", remembered server-side (settings
5
+ // TRUSTED_PUBLISHERS); an upload needs none, as only this server's owner (its session or its token) sends one, and it
6
+ // goes with the last agent applied from it (store Agents.purge). Nothing in a package runs.
7
+ import { packageSha256 } from "./agent-package.js";
5
8
  import { ApiError, invalid } from "./errors.js";
9
+ import { UPLOAD_PREFIX } from "./store/index.js";
6
10
  import { fetchPackageFiles, ImportRefused, IMPORT_LIMITS, parseSource, resolveSha } from "./template-source.js";
7
- import { memoryFiles, PackageError, readPackage } from "./templates.js";
11
+ import { MANIFEST, manifestName, memoryFiles, PackageError, readPackage } from "./templates.js";
8
12
  import { isObject, unknownFields } from "./validate.js";
9
13
  /** The settings key that holds the GitHub accounts this server's owner trusts as publishers, lower-cased. */
10
14
  export const TRUSTED_PUBLISHERS = "templates.trusted_publishers";
11
- /** The folder name a package's id ends in: its path's last part, else the repository's name (agent.md's `name` is it). */
12
- const nameOf = (id) => id.slice("github:".length).split("/").at(-1);
15
+ /** An uploaded package's id is this and its manifest's name: the next upload of that name replaces it. */
16
+ export { UPLOAD_PREFIX };
17
+ /** The folder name a package's id ends in: an upload's name, else its path's last part, else the repository's name
18
+ * (agent.md's `name` is it). */
19
+ const nameOf = (id) => (id.startsWith(UPLOAD_PREFIX) ? id.slice(UPLOAD_PREFIX.length) : id.slice("github:".length).split("/").at(-1));
20
+ /** An upload's sha: the digest an export names (agent-package.ts packageSha256), which `agentrun deploy` locks. */
21
+ const uploadSha = (files) => packageSha256([...files].map(([path, data]) => ({ path, encoding: "base64", content: data.toString("base64") })));
22
+ const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
23
+ /** A path part that is not plain, or a character no package path holds (a control character, a backslash). */
24
+ const NOT_PLAIN = (path) => /[\0-\x1f\x7f\\]/.test(path) || path.split("/").some((part) => part === "" || part === "." || part === "..");
25
+ /** An upload's files ({path, encoding, content}) as the package's bytes by path: 422 under files.<i> for one that is not
26
+ * that shape; the GitHub import's own refusals (ImportRefused "package") for a path that is not plain or is there twice,
27
+ * over its count and over the bytes it keeps. */
28
+ function uploadFiles(raw) {
29
+ const shape = "files is a list of {path, encoding, content}: each file of the package, its encoding utf8 or base64";
30
+ if (!Array.isArray(raw) || raw.length === 0)
31
+ throw invalid([{ field: "files", reason: "wrong_type", message: shape }]);
32
+ if (raw.length > IMPORT_LIMITS.files)
33
+ throw new ImportRefused("package", `The package holds over ${IMPORT_LIMITS.files} files.`);
34
+ const issues = [];
35
+ const read = [];
36
+ raw.forEach((one, i) => {
37
+ if (!isObject(one) || typeof one.path !== "string" || typeof one.content !== "string")
38
+ return void issues.push({ field: `files.${i}`, reason: "wrong_type", message: shape });
39
+ for (const issue of unknownFields(one, ["path", "encoding", "content"]))
40
+ issues.push({ ...issue, field: `files.${i}.${issue.field}` });
41
+ if (one.encoding !== "utf8" && one.encoding !== "base64")
42
+ return void issues.push({ field: `files.${i}.encoding`, reason: "not_an_option", message: "encoding is utf8 or base64" });
43
+ if (one.encoding === "base64" && !BASE64.test(one.content))
44
+ return void issues.push({ field: `files.${i}.content`, reason: "invalid", message: `${JSON.stringify(one.path)}'s content is not base64` });
45
+ read.push([one.path, Buffer.from(one.content, one.encoding)]);
46
+ });
47
+ if (issues.length)
48
+ throw invalid(issues);
49
+ const files = new Map();
50
+ let kept = 0;
51
+ for (const [path, data] of read) {
52
+ if (NOT_PLAIN(path))
53
+ throw new ImportRefused("package", `The package holds ${JSON.stringify(path)}, a path that is not plain: refused.`);
54
+ if (files.has(path))
55
+ throw new ImportRefused("package", `The package holds ${JSON.stringify(path)} twice: refused.`);
56
+ kept += data.length;
57
+ if (kept > IMPORT_LIMITS.packageBytes)
58
+ throw new ImportRefused("package", `The package's files are over the ${IMPORT_LIMITS.packageBytes} bytes an import keeps.`);
59
+ files.set(path, data);
60
+ }
61
+ // A path that is a file and a folder's name at once (agent.md and agent.md/x) is no folder a package could be.
62
+ for (const path of files.keys()) {
63
+ const parts = path.split("/");
64
+ for (let end = 1; end < parts.length; end++) {
65
+ const folder = parts.slice(0, end).join("/");
66
+ if (files.has(folder))
67
+ throw new ImportRefused("package", `The package holds ${JSON.stringify(folder)} as a file and as a folder: refused.`);
68
+ }
69
+ }
70
+ return files;
71
+ }
13
72
  /** An imported package read from its files, checked whole, with its id and origin: PackageError when it does not check. */
14
73
  export function importedPackage(id, origin, files) {
15
74
  const read = readPackage(memoryFiles(nameOf(id), `${id}@${origin.sha}`, files));
@@ -28,6 +87,17 @@ export async function loadImported(deps, skipped) {
28
87
  }
29
88
  }
30
89
  }
90
+ /** The uploads served here whose row the store no longer keeps (an agent's purge removed it: Agents.purge), no longer
91
+ * served. Only the package read before the store is removed, so an upload put in meanwhile stays served. */
92
+ export async function dropRemovedUploads(deps) {
93
+ const served = deps.registry.list().filter((pkg) => pkg.origin !== null && pkg.id.startsWith(UPLOAD_PREFIX));
94
+ if (!served.length)
95
+ return;
96
+ const stored = new Set(await deps.store.importedTemplates.ids());
97
+ for (const pkg of served)
98
+ if (!stored.has(pkg.id) && deps.registry.get(pkg.id) === pkg)
99
+ deps.registry.remove(pkg.id);
100
+ }
31
101
  /** Whether `publisher` is one the owner trusts (case-insensitive, as GitHub's account names are). */
32
102
  async function trusted(deps, publisher) {
33
103
  const list = await deps.store.settings.get(TRUSTED_PUBLISHERS);
@@ -64,25 +134,58 @@ function refusalOf(error) {
64
134
  }
65
135
  throw error;
66
136
  }
67
- /** The body POST /v2/templates/import takes, checked: 422 naming each field that is wrong. */
68
- function bodyOf(body) {
69
- const issues = unknownFields(body, ["source", "dry_run", "trust_publisher"]);
137
+ /** The body POST /v2/templates/import takes, checked: 422 naming each field that is wrong. A GitHub source ({source}), or
138
+ * the package's files ({files}, an upload); on an API-only server, the files alone. */
139
+ function bodyOf(body, apiOnly) {
140
+ const issues = unknownFields(body, ["source", "files", "dry_run", "trust_publisher"]);
70
141
  if (body.dry_run !== undefined && typeof body.dry_run !== "boolean")
71
142
  issues.push({ field: "dry_run", reason: "wrong_type", message: "dry_run is true or false" });
72
143
  if (body.trust_publisher !== undefined && typeof body.trust_publisher !== "boolean")
73
144
  issues.push({ field: "trust_publisher", reason: "wrong_type", message: "trust_publisher is true or false" });
74
145
  if (typeof body.source === "string" && body.source.length > 1024)
75
146
  issues.push({ field: "source", reason: "too_long", message: "source is at most 1024 characters" });
147
+ if (body.files !== undefined && body.source !== undefined)
148
+ issues.push({ field: "files", reason: "not_allowed", message: "The body is {source} or {files}: source or files, not both." });
149
+ if (body.files !== undefined && body.trust_publisher !== undefined)
150
+ issues.push({ field: "trust_publisher", reason: "not_allowed", message: "An upload is this server's owner's own package, so an upload asks no publisher's trust: trust_publisher goes with a source alone." });
151
+ if (apiOnly && body.source !== undefined)
152
+ issues.push({ field: "source", reason: "not_allowed", message: "This server serves the API alone: a package is uploaded here as {files}, never read from GitHub." });
76
153
  if (issues.length)
77
154
  throw invalid(issues);
155
+ if (body.files !== undefined)
156
+ return { files: body.files, dryRun: body.dry_run === true };
78
157
  return { source: parseSource(body.source), dryRun: body.dry_run === true, trustPublisher: body.trust_publisher === true };
79
158
  }
159
+ /** An upload: its files checked as an import's are, its id `upload:<name>` (its manifest's name), its sha the package's
160
+ * sha256; a dry run answers it, storing nothing; else it is stored and served (201), in place of the one of its name. */
161
+ async function uploadTemplate(deps, raw, dryRun) {
162
+ let pkg;
163
+ let files;
164
+ try {
165
+ files = uploadFiles(raw);
166
+ const id = `${UPLOAD_PREFIX}${manifestName(files.get(MANIFEST)?.toString("utf8") ?? "") ?? ""}`;
167
+ pkg = importedPackage(id, { source: id, sha: uploadSha(files), publisher: "" }, files);
168
+ }
169
+ catch (error) {
170
+ refusalOf(error);
171
+ }
172
+ const replaced = deps.registry.get(pkg.id)?.origin?.sha ?? null;
173
+ if (dryRun)
174
+ return { status: 200, pkg, trusted: true, replaced };
175
+ await deps.store.importedTemplates.put({ id: pkg.id, source: pkg.origin.source, sha: pkg.origin.sha, publisher: "", files: Object.fromEntries([...files].map(([path, data]) => [path, data.toString("base64")])) });
176
+ deps.registry.put(pkg);
177
+ return { status: 201, pkg, trusted: true, replaced };
178
+ }
80
179
  /** POST /v2/templates/import: the package read at its source's commit and checked; a dry run answers it, storing nothing;
81
- * else it is stored and served (201), in place of the one under its id. `signal` ends the read (the request's). */
180
+ * else it is stored and served (201), in place of the one under its id. `signal` ends the read (the request's). An
181
+ * upload ({files}) is uploadTemplate's. */
82
182
  export async function importTemplate(deps, raw, signal) {
83
183
  if (!isObject(raw))
84
- throw invalid([{ field: "body", reason: "wrong_type", message: "The body is {source, dry_run?, trust_publisher?}." }]);
85
- const { source, dryRun, trustPublisher } = bodyOf(raw);
184
+ throw invalid([{ field: "body", reason: "wrong_type", message: "The body is {source, dry_run?, trust_publisher?} or {files, dry_run?}." }]);
185
+ const body = bodyOf(raw, deps.apiOnly === true);
186
+ if ("files" in body)
187
+ return uploadTemplate(deps, body.files, body.dryRun);
188
+ const { source, dryRun, trustPublisher } = body;
86
189
  const read = AbortSignal.any([signal, AbortSignal.timeout(IMPORT_LIMITS.ms)]);
87
190
  let pkg;
88
191
  let files;