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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (185) hide show
  1. package/CHANGELOG.md +68 -1
  2. package/README.md +218 -20
  3. package/dist/acp-package.d.ts +24 -6
  4. package/dist/adapter-facts.d.ts +0 -4
  5. package/dist/adapter-facts.js +1 -4
  6. package/dist/adapters.d.ts +3 -12
  7. package/dist/adapters.js +1 -70
  8. package/dist/agent-delete.d.ts +33 -10
  9. package/dist/agent-delete.js +184 -26
  10. package/dist/agents-store.d.ts +6 -2
  11. package/dist/agents-store.js +18 -5
  12. package/dist/agents.d.ts +8 -1
  13. package/dist/agents.js +14 -4
  14. package/dist/answer-json.d.ts +10 -0
  15. package/dist/answer-json.js +23 -0
  16. package/dist/api-only.d.ts +5 -2
  17. package/dist/api-only.js +10 -2
  18. package/dist/archil-routes.d.ts +1 -1
  19. package/dist/archil-routes.js +4 -3
  20. package/dist/browser-live.d.ts +9 -4
  21. package/dist/browser-live.js +18 -5
  22. package/dist/browser-sessions.d.ts +56 -0
  23. package/dist/browser-sessions.js +117 -0
  24. package/dist/cap.js +7 -9
  25. package/dist/cli.js +6 -6
  26. package/dist/computer-routes.d.ts +6 -14
  27. package/dist/computer-routes.js +8 -10
  28. package/dist/computers.d.ts +6 -2
  29. package/dist/computers.js +4 -2
  30. package/dist/conformance.d.ts +4 -0
  31. package/dist/conformance.js +6 -0
  32. package/dist/console/assets/index-Bzn4eUYF.js +715 -0
  33. package/dist/console/assets/index-CR2ZGei1.css +1 -0
  34. package/dist/console/index.html +2 -2
  35. package/dist/errors.d.ts +4 -1
  36. package/dist/errors.js +15 -5
  37. package/dist/harness-check.d.ts +3 -1
  38. package/dist/harness-check.js +99 -70
  39. package/dist/harness-cursor.d.ts +10 -27
  40. package/dist/harness-cursor.js +5 -84
  41. package/dist/harness-goose.d.ts +4 -29
  42. package/dist/harness-goose.js +6 -86
  43. package/dist/harness-module.d.ts +4 -0
  44. package/dist/harness-module.js +1 -0
  45. package/dist/harness-owned.d.ts +52 -0
  46. package/dist/harness-owned.js +92 -0
  47. package/dist/harness-recipe.js +2 -24
  48. package/dist/harness-table.d.ts +109 -6
  49. package/dist/harness-table.js +242 -28
  50. package/dist/harness.js +2 -2
  51. package/dist/import.js +4 -3
  52. package/dist/key-refusal.d.ts +2 -1
  53. package/dist/key-refusal.js +18 -2
  54. package/dist/learn/check.d.ts +11 -2
  55. package/dist/learn/check.js +12 -9
  56. package/dist/learn/promote.d.ts +18 -1
  57. package/dist/learn/promote.js +47 -0
  58. package/dist/learn/repick.d.ts +34 -0
  59. package/dist/learn/repick.js +201 -0
  60. package/dist/learn/secrets.d.ts +4 -0
  61. package/dist/learn/secrets.js +23 -0
  62. package/dist/learned-workflow.d.ts +2 -0
  63. package/dist/learned-workflow.js +18 -1
  64. package/dist/learning-model.d.ts +18 -0
  65. package/dist/learning-model.js +77 -0
  66. package/dist/learning-setting.d.ts +13 -0
  67. package/dist/learning-setting.js +23 -1
  68. package/dist/llms.txt +1 -0
  69. package/dist/model-form.js +12 -12
  70. package/dist/model.d.ts +5 -4
  71. package/dist/model.js +19 -13
  72. package/dist/openapi.js +203 -15
  73. package/dist/page.d.ts +1 -0
  74. package/dist/page.js +1 -1
  75. package/dist/paid-calls.d.ts +4 -1
  76. package/dist/paid-calls.js +1 -1
  77. package/dist/run-learning-served.d.ts +1 -1
  78. package/dist/run-secrets.d.ts +2 -2
  79. package/dist/run-secrets.js +6 -5
  80. package/dist/run-trace.js +6 -3
  81. package/dist/run-usage.d.ts +110 -0
  82. package/dist/run-usage.js +312 -0
  83. package/dist/runner/adapter-loop.d.ts +4 -1
  84. package/dist/runner/adapter-loop.js +52 -22
  85. package/dist/runner/adapter-run-spec.d.ts +3 -2
  86. package/dist/runner/adapter-run-spec.js +8 -4
  87. package/dist/runner/adapters/index.d.ts +4 -2
  88. package/dist/runner/adapters/index.js +6 -42
  89. package/dist/runner/cli-run-spec.js +10 -6
  90. package/dist/runner/conformance/harness.d.ts +2 -0
  91. package/dist/runner/conformance/harness.js +18 -4
  92. package/dist/runner/conformance/host-tools.d.ts +4 -0
  93. package/dist/runner/conformance/host-tools.js +14 -0
  94. package/dist/runner/feedback-round.d.ts +29 -1
  95. package/dist/runner/feedback-round.js +54 -3
  96. package/dist/runner/journal-kinds.d.ts +3 -1
  97. package/dist/runner/learning-end.js +49 -18
  98. package/dist/runner/loop-contract.d.ts +3 -0
  99. package/dist/runner/meta-tools.js +4 -2
  100. package/dist/runner/monid-run.js +2 -2
  101. package/dist/runner/presence.d.ts +3 -0
  102. package/dist/runner/presence.js +19 -12
  103. package/dist/runner/promotion.d.ts +62 -4
  104. package/dist/runner/promotion.js +154 -17
  105. package/dist/runner/reflect-hook.js +3 -2
  106. package/dist/runner/sdk-loop.js +25 -1
  107. package/dist/runner/workflow-spec.js +3 -2
  108. package/dist/runs-over-store.d.ts +5 -3
  109. package/dist/runs-over-store.js +11 -11
  110. package/dist/sdk/check.d.ts +31 -0
  111. package/dist/sdk/check.js +58 -0
  112. package/dist/sdk/runs.d.ts +10 -2
  113. package/dist/sdk/runs.js +87 -17
  114. package/dist/sdk/schema.js +11 -3
  115. package/dist/server.d.ts +6 -3
  116. package/dist/server.js +297 -98
  117. package/dist/store/index.d.ts +2 -2
  118. package/dist/store/index.js +1 -1
  119. package/dist/store/journal/storage.js +1 -1
  120. package/dist/store/open.d.ts +1 -1
  121. package/dist/store/open.js +1 -1
  122. package/dist/store/postgres/migrations/0021_purged.sql +13 -0
  123. package/dist/store/postgres/migrations/0022_computer_intervals.sql +27 -0
  124. package/dist/store/schema.d.ts +15 -1
  125. package/dist/store/schema.js +50 -5
  126. package/dist/store/sqlite/connection.d.ts +4 -1
  127. package/dist/store/sqlite/connection.js +5 -0
  128. package/dist/store/sqlite/run-patch.d.ts +8 -3
  129. package/dist/store/sqlite/run-patch.js +15 -7
  130. package/dist/store/sqlite/store.d.ts +5 -2
  131. package/dist/store/sqlite/store.js +283 -77
  132. package/dist/store/sqlite/worker.d.ts +9 -0
  133. package/dist/store/sqlite/worker.js +18 -1
  134. package/dist/store/store.d.ts +162 -27
  135. package/dist/store/store.js +63 -0
  136. package/dist/store-reads/analytics.js +2 -1
  137. package/dist/store-reads/cap.d.ts +8 -2
  138. package/dist/store-reads/cap.js +27 -3
  139. package/dist/store-reads/learning.d.ts +1 -1
  140. package/dist/store-reads/learning.js +5 -2
  141. package/dist/store-reads/runs.js +2 -0
  142. package/dist/store-reads/stats.js +4 -2
  143. package/dist/store-view.d.ts +12 -3
  144. package/dist/store-view.js +70 -27
  145. package/dist/template-eval.js +5 -2
  146. package/dist/template-github-permissions.d.ts +5 -1
  147. package/dist/template-github-permissions.js +7 -3
  148. package/dist/timeline/index.d.ts +1 -1
  149. package/dist/timeline/index.js +1 -1
  150. package/dist/timeline/timeline.d.ts +8 -0
  151. package/dist/timeline/timeline.js +18 -6
  152. package/dist/tool-gate.d.ts +8 -4
  153. package/dist/tool-gate.js +6 -7
  154. package/dist/tool-plane.d.ts +4 -0
  155. package/dist/tool-plane.js +10 -10
  156. package/dist/tools.js +9 -0
  157. package/dist/trigger-targets.d.ts +14 -2
  158. package/dist/trigger-targets.js +73 -4
  159. package/dist/triggers.d.ts +2 -1
  160. package/dist/triggers.js +5 -2
  161. package/dist/validate.d.ts +4 -2
  162. package/dist/validate.js +18 -4
  163. package/dist/viewer-credential.d.ts +24 -0
  164. package/dist/viewer-credential.js +53 -0
  165. package/dist/workspace/computer-for-claim.d.ts +5 -1
  166. package/dist/workspace/computer-for-claim.js +47 -18
  167. package/dist/workspace/computer-intervals.d.ts +20 -0
  168. package/dist/workspace/computer-intervals.js +49 -0
  169. package/dist/workspace/computer-janitor.d.ts +7 -3
  170. package/dist/workspace/computer-janitor.js +14 -6
  171. package/dist/workspace/computer-kept.d.ts +7 -2
  172. package/dist/workspace/computer-kept.js +9 -2
  173. package/dist/workspace/resolve-computer.d.ts +9 -1
  174. package/dist/workspace/resolve-computer.js +29 -22
  175. package/dist/workspace/run-end-computers.d.ts +1 -0
  176. package/dist/workspace/run-end-computers.js +4 -1
  177. package/package.json +18 -10
  178. package/templates/code-review/agent.md +2 -3
  179. package/templates/code-review/evals/mentions-defused/case.yaml +0 -1
  180. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +0 -27
  181. package/templates/code-review/evals/other-repo/case.yaml +0 -1
  182. package/templates/code-review/evals/other-repo/fixtures/github-mcp.json +0 -18
  183. package/templates/code-review/evals/other-repo/graders/no-other-repo.md +1 -1
  184. package/dist/console/assets/index-BBFzAxLB.js +0 -715
  185. package/dist/console/assets/index-BRi-Rgq6.css +0 -1
@@ -2,6 +2,7 @@ import type { AdapterFacts, AgentAdapter, SessionSpec } from "@parcha/agentrun-k
2
2
  import { type HarnessPins, type LoadedSdk } from "./harness-install.js";
3
3
  import { type HarnessEntry } from "./harness-table.js";
4
4
  import type { ModelRef } from "./model.js";
5
+ import { type InstallFix } from "./provider.js";
5
6
  import type { SkillCheck, SkillFiles } from "./skills.js";
6
7
  /** Whether this server runs from npx's cache (`npx @parcha/agentrun-serve`), where there is no project to install a
7
8
  * package into: npm keeps what npx runs under `<npm cache>/_npx/<hash>/node_modules`. Read from where this file is, not
@@ -53,6 +54,8 @@ export declare const HARNESS_LOG_EVENT = "harness";
53
54
  * place, or one serve holds, never reaches the log.
54
55
  */
55
56
  export declare function harnessLog(harness: string, env: NodeJS.ProcessEnv, write?: (line: string) => void): (message: string, fields?: Record<string, unknown>) => void;
57
+ /** What an adapter's own setup error says installing fixes, by the code its facts name for each: none for any other error. */
58
+ export declare function fixOf(facts: AdapterFacts, error: unknown): InstallFix | undefined;
56
59
  /** The reason the start's probe gives for `error`: its message, ending with the restart (RESTART) where installing is
57
60
  * the fix. A message whose install line is npx's has no `fix`: running that line is the restart. */
58
61
  export declare function startReason(error: unknown): string;
@@ -148,18 +151,6 @@ export declare function codexOf(env: NodeJS.ProcessEnv, needs: AdapterNeeds, loa
148
151
  * its wire's do (providerFor): serve's gateway (AGENT_MODEL_BASE_URL), OpenAI or OpenRouter, on the Responses API,
149
152
  * through the adapter's proxy. */
150
153
  export declare function opencodeOf(env: NodeJS.ProcessEnv, needs: AdapterNeeds, load?: () => Promise<typeof import("./harness-opencode/index.js")>, npx?: boolean): Promise<AgentAdapter>;
151
- /** Goose's adapter (its package's gooseAdapter, acp-package.ts), on the binary its owner installed into the data's
152
- * harnesses directory (`agentrun harness install goose`, harness-goose.ts) and from nowhere else: not there, or not the
153
- * pinned binary, it says that command, and nothing here installs it. Its model goes where claude-agent's does (the host's
154
- * Anthropic Messages provider, providerFor), through a model proxy of its own, priced and capped as every run is. */
155
- export declare function gooseOf(env: NodeJS.ProcessEnv, needs: AdapterNeeds): Promise<AgentAdapter>;
156
- /** Cursor's adapter (its package's cursorAdapter, acp-package.ts), on the release its owner installed into the data's
157
- * harnesses directory (`agentrun harness install cursor`, harness-cursor.ts), its launcher and every file beside it the
158
- * pinned ones, and on its owner's Cursor API key (CURSOR_API_KEY), which the adapter reads by name from `env` at each
159
- * start and hands to Cursor's process alone. Its model is Cursor's, billed to the owner's Cursor plan: no proxy and no
160
- * price of ours; the run stops at the owner's turn and tool-call limits (cursorLimitsOf). `cursor/default` runs Cursor's
161
- * own default model. */
162
- export declare function cursorOf(env: NodeJS.ProcessEnv, needs: AdapterNeeds): Promise<AgentAdapter>;
163
154
  /** Why `harness` cannot run here, or undefined when it can (its entry's refusal): its package and pins, its provider, and
164
155
  * the adapter's own check of the model `given` names (with none, a model of its wire's vendor: whether it runs here at
165
156
  * all). `atStart`: asked by the start's probe, whose offers hold until a restart, so a reason installing fixes ends
package/dist/adapters.js CHANGED
@@ -139,7 +139,7 @@ export function harnessLog(harness, env, write = (line) => void process.stderr.w
139
139
  };
140
140
  }
141
141
  /** What an adapter's own setup error says installing fixes, by the code its facts name for each: none for any other error. */
142
- function fixOf(facts, error) {
142
+ export function fixOf(facts, error) {
143
143
  const code = error?.code;
144
144
  return code === facts.install.codes.install ? "install" : code === facts.install.codes.pins ? "pins" : undefined;
145
145
  }
@@ -369,75 +369,6 @@ export async function opencodeOf(env, needs, load = () => import("./harness-open
369
369
  const skills = needs.skills && servedSkills(needs.skills);
370
370
  return opencode.openCodeAdapter({ model: provider.modelId, provider: { origin: provider.origin, credential: provider.credential }, price: priceOf({ ...needs, model: provider.priceModel }), log: harnessLog(openCodeFacts.id, env), ...(needs.confine ? { confine: needs.confine } : {}), ...(skills?.length ? { skills } : {}), ...(standIn ? { standIn } : {}) });
371
371
  }
372
- /** Goose's adapter (its package's gooseAdapter, acp-package.ts), on the binary its owner installed into the data's
373
- * harnesses directory (`agentrun harness install goose`, harness-goose.ts) and from nowhere else: not there, or not the
374
- * pinned binary, it says that command, and nothing here installs it. Its model goes where claude-agent's does (the host's
375
- * Anthropic Messages provider, providerFor), through a model proxy of its own, priced and capped as every run is. */
376
- export async function gooseOf(env, needs) {
377
- const [{ acpPackage }, { gooseMissing, GOOSE_ID }] = await Promise.all([import("./acp-package.js"), import("./harness-goose.js")]);
378
- const acp = acpPackage();
379
- // What no key fixes is said first, as claudeOf does: the binary, checked off the event loop.
380
- const found = await gooseMissing(env);
381
- if ("missing" in found)
382
- throw new HarnessUnavailable(found.missing.message, acp && fixOf(acp.gooseFacts, found.missing));
383
- if (!acp)
384
- throw new HarnessUnavailable("Goose's adapter is not installed beside this server");
385
- const facts = acp.gooseFacts;
386
- const provider = providerFor(facts.wire, env, needs.model, GOOSE_ID);
387
- // A person's Claude Code login is its CLI's alone (claude-login.ts): Goose's requests never go on it.
388
- if (provider.login)
389
- throw new HarnessUnavailable("Goose runs on a model key: Claude Code's login on this machine is its CLI's alone.", undefined, ["ANTHROPIC_API_KEY", "OPENROUTER_API_KEY"]);
390
- try {
391
- return acp.gooseAdapter({
392
- binary: found.binary, sha256: found.sha256, model: provider.modelId,
393
- provider: { origin: provider.origin, credential: provider.credential, ...(provider.auth ? { auth: provider.auth } : {}) },
394
- price: priceOf({ ...needs, model: provider.priceModel }), log: harnessLog(GOOSE_ID, env),
395
- ...(needs.confine ? { confine: needs.confine } : {}),
396
- });
397
- }
398
- catch (error) {
399
- throw new HarnessUnavailable(error.message, fixOf(facts, error));
400
- }
401
- }
402
- /** Cursor's adapter (its package's cursorAdapter, acp-package.ts), on the release its owner installed into the data's
403
- * harnesses directory (`agentrun harness install cursor`, harness-cursor.ts), its launcher and every file beside it the
404
- * pinned ones, and on its owner's Cursor API key (CURSOR_API_KEY), which the adapter reads by name from `env` at each
405
- * start and hands to Cursor's process alone. Its model is Cursor's, billed to the owner's Cursor plan: no proxy and no
406
- * price of ours; the run stops at the owner's turn and tool-call limits (cursorLimitsOf). `cursor/default` runs Cursor's
407
- * own default model. */
408
- export async function cursorOf(env, needs) {
409
- const [{ acpPackage }, { cursorMissing, cursorLimitsOf, CURSOR_DEFAULT_MODEL, CURSOR_ID, CURSOR_KEY, CURSOR_PROVIDER }] = await Promise.all([import("./acp-package.js"), import("./harness-cursor.js")]);
410
- const acp = acpPackage();
411
- // What no key fixes is said first, as gooseOf does: the release, checked off the event loop.
412
- const found = await cursorMissing(env);
413
- if ("missing" in found)
414
- throw new HarnessUnavailable(found.missing.message, acp && fixOf(acp.cursorFacts, found.missing));
415
- if (!acp)
416
- throw new HarnessUnavailable("Cursor's adapter is not installed beside this server");
417
- const facts = acp.cursorFacts;
418
- if (needs.model.provider !== CURSOR_PROVIDER)
419
- throw new HarnessUnavailable(`${facts.label} runs Cursor's models, named ${CURSOR_PROVIDER}/<model-id>; the run's model is ${needs.model.provider}/${needs.model.modelId}.`);
420
- if (!env[CURSOR_KEY])
421
- throw new HarnessUnavailable(`${facts.label} runs on your Cursor API key, and ${CURSOR_KEY} is not set where AgentRun starts: set it there (it is handed to Cursor's runs alone), then restart AgentRun.`);
422
- let limits;
423
- try {
424
- limits = cursorLimitsOf(acp, env);
425
- }
426
- catch (error) {
427
- throw new HarnessUnavailable(error.message);
428
- }
429
- const model = needs.model.modelId === CURSOR_DEFAULT_MODEL ? undefined : needs.model.modelId;
430
- try {
431
- return acp.cursorAdapter({
432
- binary: found.binary, limits, env, log: harnessLog(CURSOR_ID, env),
433
- ...(model ? { model } : {}),
434
- ...(needs.confine ? { confine: needs.confine } : {}),
435
- });
436
- }
437
- catch (error) {
438
- throw new HarnessUnavailable(error.message, fixOf(facts, error));
439
- }
440
- }
441
372
  /** Why `harness` cannot run here, or undefined when it can (its entry's refusal): its package and pins, its provider, and
442
373
  * the adapter's own check of the model `given` names (with none, a model of its wire's vendor: whether it runs here at
443
374
  * all). `atStart`: asked by the start's probe, whose offers hold until a restart, so a reason installing fixes ends
@@ -1,11 +1,12 @@
1
- import { type Store } from "./store/index.js";
1
+ import { type PurgeKept, type Store } from "./store/index.js";
2
2
  /** The delete of an agent's learning: the server's is the learning module's deleteLearning over the agent's learning
3
3
  * folder (learn/delete.ts). Idempotent; refuses with LearningInFlight while learning work of the agent is in flight. */
4
4
  export type DeleteLearning = (store: Store, agentId: string) => Promise<unknown>;
5
- /** A point of a delete a test may stop it at (AgentDeleteHost.at): after step 1, after step 2, in step 3 between a
6
- * trigger's removal upstream and its settings', between its settings' and its row's, and in step 3 once its triggers
7
- * and the agent's first run are gone. */
8
- export type AgentDeleteStep = "after_step_1" | "after_step_2" | "in_step_3_trigger" | "in_step_3_trigger_settings" | "in_step_3";
5
+ /** A point of a delete a test may stop it at (AgentDeleteHost.at). An agent's: after step 1, after step 2, in step 3
6
+ * between a trigger's removal upstream and its settings', between its settings' and its row's, and in step 3 once its
7
+ * triggers and the agent's first run are gone (a purge's: after its learning, then the same). A run's: once the runs
8
+ * made from it are purged, and once its own things outside its rows are gone (its rows kept). */
9
+ export type AgentDeleteStep = "after_step_1" | "after_step_2" | "in_step_3_trigger" | "in_step_3_trigger_settings" | "in_step_3" | "run_made_from_gone" | "run_forgotten";
9
10
  /** What a delete does outside the store's own rows, as the server does it. */
10
11
  export interface AgentDeleteHost {
11
12
  readonly store: Store;
@@ -32,19 +33,41 @@ export interface AgentDeleteHost {
32
33
  removeDisk(agentId: string): Promise<void>;
33
34
  /** A final run's things outside its rows: its folders (its own folder on an Archil disk its launch named, read from its
34
35
  * launch record, which goes with its rows after; an ApiError (503 unavailable) while that folder is not deleted
35
- * there), its settings, the answers kept under its idempotency keys. */
36
- forgetRun(agentId: string, runId: string): Promise<void>;
36
+ * there), its settings, the answers kept under its idempotency keys. `alone`: its agent's Archil disk stays (a run's
37
+ * purge, or its agent's), so its own folder on that disk is deleted there too; with an external agent's delete that
38
+ * disk went whole. */
39
+ forgetRun(agentId: string, runId: string, alone: boolean): Promise<void>;
37
40
  /** The agent's things outside its rows: its folders, its settings, the answers kept under its idempotency keys. */
38
41
  forgetAgent(agentId: string): Promise<void>;
39
- /** How long step 1 waits for the agent's runs to be final, and how often it reads them meanwhile. */
42
+ /** The runs made from run `runId` (store runs.madeFrom, and its audit's shadow run), by id, whether there or not. */
43
+ madeFrom(runId: string): Promise<string[]>;
44
+ /** What agent `agentId`'s learning copied from run `runId`, gone: the grades it keeps of the run dropped, its promotion
45
+ * records' disagreements naming the run blanked, their decisions, numbers and run ids kept (learn/promote.ts
46
+ * forgetRunCopies). */
47
+ forgetCopies(agentId: string, runId: string): Promise<void>;
48
+ /** What run `runId`'s spend reads from its journal, read before its purge removes it (store-reads/cap.ts). */
49
+ kept(runId: string): Promise<PurgeKept>;
50
+ /** Whether run `runId`'s turn is over (it reads idle, a paused workflow aside): its runner writes it final next. */
51
+ turnOver(runId: string): Promise<boolean>;
52
+ /** How long step 1 waits for the agent's runs to be final (a purge: for a run whose turn is over), and how often it reads
53
+ * them meanwhile. */
40
54
  readonly waitMs: number;
41
55
  readonly pollMs: number;
42
- /** A test's seam: awaited at each step's point, so a throw there stops the delete as a crash would. */
43
- at?(step: AgentDeleteStep, agentId: string): void | Promise<void>;
56
+ /** A test's seam: awaited at each step's point with the agent's id (a run's step: the run's), so a throw there stops
57
+ * the delete as a crash would. */
58
+ at?(step: AgentDeleteStep, id: string): void | Promise<void>;
44
59
  }
45
60
  /** Deletes agent `agentId` (another system's, as the route checked) in the three steps above. Throws ApiError
46
61
  * runs_in_flight while a run of it is not final by the wait's end, learning_busy while its learning refuses. */
47
62
  export declare function deleteExternalAgent(host: AgentDeleteHost, agentId: string): Promise<void>;
63
+ /** Purges archived agent `agentId`, made here (as the route checked), as the header says: 409 run_not_final, nothing
64
+ * purged, while a run of it is live; learning_busy while its learning refuses. */
65
+ export declare function purgeAgent(host: AgentDeleteHost, agentId: string): Promise<void>;
66
+ /** The setting that marks agent `agentId`'s purge begun and not finished (purgeAgent). */
67
+ export declare const purgingKey: (agentId: string) => string;
68
+ /** Purges run `runId` with every run made from it, as the header says. 404 not_found when it is not there; 409
69
+ * run_not_final, nothing purged, while it or a run made from it is live. A purged run is no work. */
70
+ export declare function purgeRun(host: AgentDeleteHost, runId: string): Promise<void>;
48
71
  /** One delete of an agent at a time: a second DELETE of the same agent waits for the first, then finds it gone (404) or
49
72
  * finishes what the first left. */
50
73
  export declare function oneAtATime(): <T>(agentId: string, work: () => Promise<T>) => Promise<T>;
@@ -1,7 +1,31 @@
1
1
  // DELETE /v2/agents/{agent_id}: an agent another system owns (made by an inline run, POST /runs with `external`) deleted
2
- // whole, for a host that must delete what it sent. An agent made here is archived instead (409 agent_not_external).
2
+ // whole, for a host that must delete what it sent (deleteExternalAgent). An agent made here is purged once it is archived
3
+ // (purgeAgent; 409 agent_not_archived before). DELETE /v2/runs/{run_id}: one run purged (purgeRun), with the runs made
4
+ // from it. An owner must be able to delete what a run read; what it cost stays in every total. So a purge keeps each
5
+ // run's row, and an agent's, as a tombstone, and removes everything else of it.
3
6
  //
4
- // In order, each step finished before the next:
7
+ // A run's purge (purgeRun), only once it is not live (409 run_not_final otherwise, nothing purged: live is not final, or
8
+ // held by a runner; a run that ended and can take a follow-up is not live), nor any run made from it: first each run made
9
+ // from it (the replay runs of its input, its audit's shadow run, a learning run its kept learning names; each one's own
10
+ // such runs before it), then the grades its agent keeps of it and the content its promotion records copied from it (each
11
+ // disagreement's input and answers, learn/promote.ts forgetRunCopies), then the run, each by purgeOne: the figures its spend's
12
+ // readers read from its journal (kept on the tombstone, PurgeKept), its folders (its own folder on the agent's Archil disk
13
+ // it resolved to, and on a disk its launch named), settings and kept answers, then its rows (store runs.purge, which sets
14
+ // its purge time last). A replay of its input or an audit's shadow made by a claim (in a runner, maybe another process)
15
+ // after the DELETE read the runs made from it is found by the store's purge, under the run's row lock: 409 run_not_final
16
+ // naming it, the run kept for the next DELETE, which purges it first (RunsMadeFromLeft); one made once the run is purged
17
+ // is refused at its create, nothing written (RunPurged). A DELETE stopped part way finds the run not purged yet and the
18
+ // next DELETE finishes it; a DELETE of a purged run is 204 again, and every other route of it is 410 purged with its
19
+ // tombstone.
20
+ //
21
+ // An archived agent made here (purgeAgent), by the same rule: 409 run_not_final while a run of it is live. Then its
22
+ // learning, its things (triggers, sign-ins, its own computer, its disk), each of its runs by purgeOne (the runs made from
23
+ // it first, as a run's purge does them), its folders, settings and kept answers, and its rows (store agents.purge: its
24
+ // revisions' content, its name and description blanked, its purge time last). Each step is idempotent, so a DELETE stopped part way is finished by the next. Archived, the agent
25
+ // takes no new run and no trigger fires it; a run that reached it anyway keeps it unpurged (the store refuses), for the
26
+ // next DELETE.
27
+ //
28
+ // Another system's agent (deleteExternalAgent), in order, each step finished before the next:
5
29
  // 1. The agent refuses new runs, as a mark in the store that outlives a restart: its archive time, which only this
6
30
  // delete writes on an agent another system owns (its archive route is refused), set by the trigger engine with its
7
31
  // triggers off in the same commit. From that commit a person's run, an inline run, a trigger's firing, an SDK run and
@@ -27,7 +51,7 @@
27
51
  // same 503, and the next DELETE removes that trigger as it removes the others.
28
52
  import { ApiError } from "./errors.js";
29
53
  import { LearningInFlight } from "./learn/delete.js";
30
- import { FINAL_STATES, TriggersLeft } from "./store/index.js";
54
+ import { FINAL_STATES, RunsMadeFromLeft, StoreConstraint, TriggersLeft } from "./store/index.js";
31
55
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
32
56
  const isFinal = (state) => FINAL_STATES.includes(state);
33
57
  /** Deletes agent `agentId` (another system's, as the route checked) in the three steps above. Throws ApiError
@@ -37,7 +61,151 @@ export async function deleteExternalAgent(host, agentId) {
37
61
  await host.refuse(agentId);
38
62
  await stopRuns(host, agentId);
39
63
  await host.at?.("after_step_1", agentId);
40
- // 2. Its learning. Its refusal while learning work is in flight is learning_busy; any other failure is the server's own.
64
+ // 2. Its learning.
65
+ await learningGone(host, agentId);
66
+ await host.at?.("after_step_2", agentId);
67
+ // 3. Its things, then its rows; the agent's row last.
68
+ await thingsGone(host, agentId);
69
+ let first = true;
70
+ for (const run of await host.store.runs.every(agentId)) {
71
+ await host.forgetRun(agentId, run.id, false);
72
+ await host.store.runs.remove(run.id);
73
+ if (first)
74
+ await host.at?.("in_step_3", agentId);
75
+ first = false;
76
+ }
77
+ await host.forgetAgent(agentId);
78
+ try {
79
+ await host.store.agents.remove(agentId);
80
+ }
81
+ catch (error) {
82
+ throw triggersLeft(error, agentId);
83
+ }
84
+ }
85
+ /** Purges archived agent `agentId`, made here (as the route checked), as the header says: 409 run_not_final, nothing
86
+ * purged, while a run of it is live; learning_busy while its learning refuses. */
87
+ export async function purgeAgent(host, agentId) {
88
+ const live = await liveOf(host, (await host.store.runs.every(agentId)).filter((run) => run.purgedAt === null));
89
+ if (live.length)
90
+ throw liveRuns(`The agent ${agentId} has ${live.length === 1 ? "a run" : "runs"} that ${live.length === 1 ? "has" : "have"} not ended (${live.join(", ")}): cancel ${live.length === 1 ? "it" : "them"} (POST /v2/runs/{run_id}/cancel), then send the DELETE again. Nothing was purged.`, live);
91
+ // Marked before anything goes, and kept until its tombstone is written: a purge stopped part way leaves the agent
92
+ // refusing an unarchive and every write (server.ts agentWrite) until a DELETE finishes it.
93
+ await host.store.settings.put(purgingKey(agentId), true);
94
+ await learningGone(host, agentId);
95
+ await host.at?.("after_step_2", agentId);
96
+ await thingsGone(host, agentId);
97
+ let first = true;
98
+ for (const run of await host.store.runs.every(agentId)) {
99
+ if (run.purgedAt !== null)
100
+ continue;
101
+ // The runs made from it first, each one's own before it, as purgeRun does: the store refuses a run's purge while one
102
+ // made from it (an audit's shadow, a replay, each started after it) is not purged. Its disk went whole above, each
103
+ // of its runs' folders there with it; a run of another agent keeps that agent's disk.
104
+ for (const one of await madeFromAll(host, run.id))
105
+ await purgeOneOrRefuse(host, one.agentId, one.id, agentId, one.agentId !== agentId);
106
+ // A later run of the list may be gone as one made from an earlier.
107
+ if ((await host.store.runs.get(run.id))?.purgedAt !== null)
108
+ continue;
109
+ await purgeOneOrRefuse(host, agentId, run.id, agentId, false);
110
+ if (first)
111
+ await host.at?.("in_step_3", agentId);
112
+ first = false;
113
+ }
114
+ await host.forgetAgent(agentId);
115
+ try {
116
+ await host.store.agents.purge(agentId);
117
+ }
118
+ catch (error) {
119
+ if (error instanceof StoreConstraint)
120
+ throw liveRuns(`The agent ${agentId} has a run started while it was being purged (${error.message}): send the DELETE again once it has ended. Its runs purged so far stay purged.`, []);
121
+ throw triggersLeft(error, agentId);
122
+ }
123
+ // Its tombstone refuses every write from here (410 purged).
124
+ await host.store.settings.remove(purgingKey(agentId));
125
+ }
126
+ /** The setting that marks agent `agentId`'s purge begun and not finished (purgeAgent). */
127
+ export const purgingKey = (agentId) => `agent.purging.${agentId}`;
128
+ /** Purges run `runId` with every run made from it, as the header says. 404 not_found when it is not there; 409
129
+ * run_not_final, nothing purged, while it or a run made from it is live. A purged run is no work. */
130
+ export async function purgeRun(host, runId) {
131
+ const run = await host.store.runs.get(runId);
132
+ if (!run)
133
+ throw new ApiError("not_found", `no run ${runId}`);
134
+ if (run.purgedAt !== null)
135
+ return;
136
+ const made = await madeFromAll(host, runId);
137
+ const live = await liveOf(host, [run, ...made]);
138
+ if (live.length)
139
+ throw notFinal(runId, live);
140
+ for (const one of made)
141
+ await purgeOneOrRefuse(host, one.agentId, one.id, runId, true);
142
+ await host.at?.("run_made_from_gone", runId);
143
+ await host.forgetCopies(run.agentId, runId);
144
+ await purgeOneOrRefuse(host, run.agentId, runId, runId, true);
145
+ }
146
+ /** The one per-run step of both purges: the figures its spend's readers read from its journal, its things outside its
147
+ * rows, then its rows (a tombstone). Its store's refusal of a run gone live again since it was read (a follow-up opened
148
+ * it) is 409 run_not_final, as a run read live is (`purged`: the run or agent the DELETE names; `alone`: its agent's disk
149
+ * stays, AgentDeleteHost.forgetRun). */
150
+ async function purgeOneOrRefuse(host, agentId, runId, purged, alone) {
151
+ const kept = await host.kept(runId);
152
+ await host.forgetRun(agentId, runId, alone);
153
+ await host.at?.("run_forgotten", runId);
154
+ try {
155
+ await host.store.runs.purge(runId, kept);
156
+ }
157
+ catch (error) {
158
+ // A replay or shadow made from it after the runs made from it were read: named, for the next DELETE to purge first.
159
+ if (error instanceof RunsMadeFromLeft)
160
+ throw notFinal(purged, error.runs);
161
+ if (error instanceof StoreConstraint)
162
+ throw notFinal(purged, [runId]);
163
+ throw error;
164
+ }
165
+ }
166
+ /** Every run made from run `runId` that is there and not purged, each one's own before it (deepest first), never `runId`. */
167
+ async function madeFromAll(host, runId, seen = new Set([runId])) {
168
+ const out = [];
169
+ for (const id of await host.madeFrom(runId)) {
170
+ if (seen.has(id))
171
+ continue;
172
+ seen.add(id);
173
+ const row = await host.store.runs.get(id);
174
+ if (!row || row.purgedAt !== null)
175
+ continue;
176
+ out.push(...(await madeFromAll(host, id, seen)), { id, agentId: row.agentId, state: row.state, runner: row.runner });
177
+ }
178
+ return out;
179
+ }
180
+ /** Live: not final, or held by a runner. A run that ended and can take a follow-up (it reads idle) is not. */
181
+ const isLive = (run) => !isFinal(run.state) || run.runner !== null;
182
+ /** Of `runs`, the ids of the live ones. A run whose turn is over (it reads idle: a person's stop, or its turn's end) is
183
+ * written final by its runner a moment after it reads so, so while every live run is such a one, each is read again
184
+ * every host.pollMs, for host.waitMs at most, until it is final and let go. A live run whose turn is not over makes the
185
+ * answer at once, and so does one still live at the end. */
186
+ async function liveOf(host, runs) {
187
+ const deadline = Date.now() + host.waitMs;
188
+ let live = runs.filter(isLive).map((run) => run.id);
189
+ for (;;) {
190
+ if (!live.length)
191
+ return live;
192
+ for (const id of live)
193
+ if (!(await host.turnOver(id)))
194
+ return live;
195
+ if (Date.now() >= deadline)
196
+ return live;
197
+ await sleep(host.pollMs);
198
+ const rows = await Promise.all(live.map((id) => host.store.runs.get(id)));
199
+ live = rows.filter((row) => row !== undefined && row.purgedAt === null && isLive(row)).map((row) => row.id);
200
+ }
201
+ }
202
+ const liveRuns = (message, runs) => new ApiError("run_not_final", message, { details: { runs: [...runs] } });
203
+ const notFinal = (runId, live) => liveRuns(live.length === 1 && live[0] === runId
204
+ ? `The run ${runId} has not ended: cancel it first (POST /v2/runs/${runId}/cancel), then send the DELETE again. Nothing was purged.`
205
+ : `${runId} has ${live.length === 1 ? "a run" : "runs"} that ${live.length === 1 ? "has" : "have"} not ended (${live.join(", ")}): send the DELETE again once ${live.length === 1 ? "it has" : "they have"} ended. Runs purged so far stay purged.`, live);
206
+ /** An agent's learning deleted (step 2 of a delete, the first of a purge). Its refusal while learning work is in flight is
207
+ * learning_busy; any other failure is the server's own. */
208
+ async function learningGone(host, agentId) {
41
209
  try {
42
210
  await host.deleteLearning(host.store, agentId);
43
211
  }
@@ -46,10 +214,12 @@ export async function deleteExternalAgent(host, agentId) {
46
214
  throw error;
47
215
  throw new ApiError("learning_busy", `The agent ${agentId}'s learning could not be deleted yet (${error.message}). The agent starts no run meanwhile: send the DELETE again later to finish it.`, { details: { runs: [...error.runs] }, retry_after_ms: 5_000 });
48
216
  }
49
- await host.at?.("after_step_2", agentId);
50
- // 3. Its things, then its rows; the agent's row last.
217
+ }
218
+ /** An agent's things outside the store's rows: its triggers through the trigger engine (each one's registration upstream
219
+ * first, then its settings, then its row: the row names what is left to remove until each is gone), its saved sign-ins,
220
+ * its own computer, its Archil disk. */
221
+ async function thingsGone(host, agentId) {
51
222
  for (const trigger of await host.store.triggers.list(agentId)) {
52
- // Upstream first, then its settings, then its row: the row names what is left to remove until each is gone.
53
223
  await host.removeTriggerThere(trigger.id);
54
224
  await host.at?.("in_step_3_trigger", agentId);
55
225
  await host.removeTriggerSettings(trigger.id);
@@ -59,25 +229,13 @@ export async function deleteExternalAgent(host, agentId) {
59
229
  await host.forgetSignIns(agentId);
60
230
  await host.removeOwnComputer(agentId);
61
231
  await host.removeDisk(agentId);
62
- let first = true;
63
- for (const run of await host.store.runs.every(agentId)) {
64
- await host.forgetRun(agentId, run.id);
65
- await host.store.runs.remove(run.id);
66
- if (first)
67
- await host.at?.("in_step_3", agentId);
68
- first = false;
69
- }
70
- await host.forgetAgent(agentId);
71
- try {
72
- await host.store.agents.remove(agentId);
73
- }
74
- catch (error) {
75
- // A trigger that reached the agent after the listing above (the store refuses one once the agent is marked; this is
76
- // its backstop): the agent is kept, refusing, for the next DELETE to remove it upstream, its settings, then its row.
77
- if (!(error instanceof TriggersLeft))
78
- throw error;
79
- throw new ApiError("unavailable", `The agent ${agentId} has ${error.triggerIds.length === 1 ? "a trigger" : "triggers"} made while it was being deleted (${error.triggerIds.join(", ")}), not removed yet. It starts no run meanwhile: send the DELETE again to finish it.`, { details: { triggers: error.triggerIds }, retry_after_ms: 5_000 });
80
- }
232
+ }
233
+ /** A trigger that reached the agent after its delete listed them (the store refuses one once the agent is marked; this is
234
+ * its backstop): the agent is kept for the next DELETE to remove it upstream, its settings, then its row. */
235
+ function triggersLeft(error, agentId) {
236
+ if (!(error instanceof TriggersLeft))
237
+ return error;
238
+ return new ApiError("unavailable", `The agent ${agentId} has ${error.triggerIds.length === 1 ? "a trigger" : "triggers"} made while it was being deleted (${error.triggerIds.join(", ")}), not removed yet. It starts no run meanwhile: send the DELETE again to finish it.`, { details: { triggers: error.triggerIds }, retry_after_ms: 5_000 });
81
239
  }
82
240
  /** Step 1's second half: each run of the agent not final cancelled once, then read again until every one is final. A run's
83
241
  * end may queue its learning run, so the runs are listed again on each read. A run this server cannot end, or one still
@@ -70,6 +70,8 @@ export declare function createAgent(store: AgentsStore, { definition, skills, no
70
70
  export declare function makeRevision(definition: Json, files: Record<string, string>, note: string | undefined): NewRevision & {
71
71
  note?: string;
72
72
  };
73
+ /** Runs a write's last read and its commit in the agent's delete turn (server.ts agentWrite). */
74
+ export type InTurn = <T>(work: () => Promise<T>) => Promise<T>;
73
75
  /** An edit: a new revision of the agent, made current. Without `skills` the current revision's skill files carry over. An
74
76
  * edit that is the current revision writes nothing, so a PUT sent twice makes one revision. The agent keeps its id and name
75
77
  * from its creation (a changed one is input_invalid). Its description is a label: an edit that names a new one makes a
@@ -83,13 +85,15 @@ export declare function makeRevision(definition: Json, files: Record<string, str
83
85
  * revision it does not follow. `contract`: an edit that always makes a new revision, even one equal to the current.
84
86
  * `template`: the package an apply with agent_id wrote it from, kept on the revision (getAgent's `template`).
85
87
  * `fromPackage`: the definition is a whole package's (an apply with agent_id), so what it leaves out is not carried over
86
- * (editOn). */
87
- export declare function commitAgent(store: AgentsStore, read: AgentEntry, { definition, skills, note }: DefinitionBody, { ifCurrent, check, contract, template, fromPackage }?: {
88
+ * (editOn). `inTurn`: where the agent is read again and the revision written (the server's agentWrite, which refuses a
89
+ * purged agent, or one whose purge stopped part way); the check runs outside it. */
90
+ export declare function commitAgent(store: AgentsStore, read: AgentEntry, { definition, skills, note }: DefinitionBody, { ifCurrent, check, contract, template, fromPackage, inTurn }?: {
88
91
  ifCurrent?: string | null;
89
92
  check?: SaveCheck;
90
93
  contract?: boolean;
91
94
  template?: TemplatePackage;
92
95
  fromPackage?: boolean;
96
+ inTurn?: InTurn;
93
97
  }): Promise<AgentEntry>;
94
98
  /** Makes `revisionId`, one of the agent's own, its current one (POST /agents/{id}/current). */
95
99
  export declare function setCurrentRevision(store: AgentsStore, entry: AgentEntry, revisionId: string): Promise<AgentEntry>;
@@ -6,6 +6,7 @@
6
6
  //
7
7
  // The run counts an agent view shows (runs.count, runs.live) are E3's run reads, not this module's; agentView takes them.
8
8
  import { randomBytes } from "node:crypto";
9
+ import { purgedAgent } from "./agents.js";
9
10
  import { agentLink } from "./console-links.js";
10
11
  import { approvalsOf } from "./approvals.js";
11
12
  import { ApiError, invalid } from "./errors.js";
@@ -241,8 +242,9 @@ const EDIT_TRIES = 5;
241
242
  * revision it does not follow. `contract`: an edit that always makes a new revision, even one equal to the current.
242
243
  * `template`: the package an apply with agent_id wrote it from, kept on the revision (getAgent's `template`).
243
244
  * `fromPackage`: the definition is a whole package's (an apply with agent_id), so what it leaves out is not carried over
244
- * (editOn). */
245
- export async function commitAgent(store, read, { definition, skills, note }, { ifCurrent, check, contract = false, template, fromPackage = false } = {}) {
245
+ * (editOn). `inTurn`: where the agent is read again and the revision written (the server's agentWrite, which refuses a
246
+ * purged agent, or one whose purge stopped part way); the check runs outside it. */
247
+ export async function commitAgent(store, read, { definition, skills, note }, { ifCurrent, check, contract = false, template, fromPackage = false, inTurn } = {}) {
246
248
  const stale = () => new ApiError("precondition_failed", "the agent's current revision moved since the If-Match it was read at: read the agent again");
247
249
  const held = (entry) => {
248
250
  if (ifCurrent !== undefined && (entry.revision?.id ?? null) !== ifCurrent)
@@ -250,6 +252,9 @@ export async function commitAgent(store, read, { definition, skills, note }, { i
250
252
  return entry;
251
253
  };
252
254
  let entry = (await getAgent(store, read.agent.id)) ?? read;
255
+ // Purged since the request read it: 410 before anything is checked (the commit's turn and the store refuse it too).
256
+ if (entry.agent.purgedAt !== null)
257
+ throw purgedAgent(entry.agent);
253
258
  refuseExternal(entry.agent);
254
259
  held(entry);
255
260
  const { agent } = entry;
@@ -270,8 +275,13 @@ export async function commitAgent(store, read, { definition, skills, note }, { i
270
275
  const edit = template ? { ...made, package: template } : made;
271
276
  const revision = stamped(edit, await check?.(edit, entry.revision));
272
277
  const base = entry.revision?.id ?? null;
273
- const now = held((await getAgent(store, agent.id)) ?? entry);
274
- if ((now.revision?.id ?? null) === base) {
278
+ // The agent read again and the revision written in `inTurn` (the server's agent delete turn): the check above, which
279
+ // may wait on a server's listing, runs outside it, so edits of one agent are checked at once and a DELETE never waits
280
+ // on a check.
281
+ const landed = await (inTurn ?? ((work) => work()))(async () => {
282
+ const now = held((await getAgent(store, agent.id)) ?? entry);
283
+ if ((now.revision?.id ?? null) !== base)
284
+ return undefined;
275
285
  // A new description is a real edit: a revision, even with the body unchanged. The same one again writes nothing.
276
286
  const described = description !== undefined && description !== now.agent.description;
277
287
  if (!contract && !described && now.revision && sameRevision(now.revision, revision)) {
@@ -291,8 +301,11 @@ export async function commitAgent(store, read, { definition, skills, note }, { i
291
301
  catch (error) {
292
302
  if (!(error instanceof RevisionMoved))
293
303
  storeError(error);
304
+ return undefined;
294
305
  }
295
- }
306
+ });
307
+ if (landed)
308
+ return landed;
296
309
  // Moved while it was checked or written: with If-Match that is stale; without, built and checked again on it.
297
310
  if (ifCurrent !== undefined)
298
311
  throw stale();
package/dist/agents.d.ts CHANGED
@@ -16,9 +16,16 @@ export declare const homeBusy: () => ApiError;
16
16
  /** The answer to a run, a trigger or a write refused because its agent is being deleted (the store's AgentDeleting, read
17
17
  * in the transaction that would start or reopen the run or write the trigger; the server's own check for a write). */
18
18
  export declare const agentDeleting: (agentId: string) => ApiError;
19
+ /** 410 purged for a route of a purged agent (Agents.purge), or a write the store refused because it is (AgentPurged):
20
+ * its tombstone in the details. */
21
+ export declare const purgedAgent: (agent: {
22
+ id: string;
23
+ archivedAt: number | null;
24
+ purgedAt: number | null;
25
+ }) => ApiError;
19
26
  /** What a request's error answers, over HTTP and through an MCP tool alike (server.ts, mcp.ts dispatch): an ApiError as
20
27
  * it is; a busy store home_busy (409, retryable), never 500; a run of an agent being deleted agent_not_runnable (409);
21
- * anything else internal, its message kept. */
28
+ * a write to a purged agent purged (410); anything else internal, its message kept. */
22
29
  export declare const answerOf: (error: unknown) => ApiError;
23
30
  /** Whether a request's error goes to the server's log: every fault the server did not answer on purpose. A busy wait
24
31
  * is not one; a transaction past its deadline is (something held the store that long). */
package/dist/agents.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // (whenFree), then answered home_busy. The agents themselves are over the one store (agents-store.ts).
3
3
  import { ApiError } from "./errors.js";
4
4
  import { isObject } from "./validate.js";
5
- import { AgentDeleting, StoreBusy, StoreDeadline } from "./store/index.js";
5
+ import { AgentDeleting, AgentPurged, StoreBusy, StoreDeadline } from "./store/index.js";
6
6
  /** SQLITE_BUSY or SQLITE_LOCKED: another connection holds the database. */
7
7
  export const sqliteBusy = (error) => isObject(error) && error.code === "ERR_SQLITE_ERROR" && typeof error.errcode === "number" && [5, 6].includes(error.errcode & 0xff);
8
8
  /** How long a request waits for a busy agent store, step by step: short first, so a reader's overlap costs
@@ -36,10 +36,20 @@ export const homeBusy = () => new ApiError("home_busy", "the agent store is busy
36
36
  /** The answer to a run, a trigger or a write refused because its agent is being deleted (the store's AgentDeleting, read
37
37
  * in the transaction that would start or reopen the run or write the trigger; the server's own check for a write). */
38
38
  export const agentDeleting = (agentId) => new ApiError("agent_not_runnable", `The agent ${agentId} is being deleted (DELETE /v2/agents/${agentId}): it starts no run, opens none again and takes no new trigger or write. Send the DELETE again to finish it.`);
39
+ const isoOrNull = (ms) => (ms === null ? null : new Date(ms).toISOString());
40
+ /** 410 purged for a route of a purged agent (Agents.purge), or a write the store refused because it is (AgentPurged):
41
+ * its tombstone in the details. */
42
+ export const purgedAgent = (agent) => new ApiError("purged", `The agent ${agent.id} was purged: its definition, learning and runs' content are gone, and its runs' cost stays in every total.`, {
43
+ details: { agent_id: agent.id, archived_at: isoOrNull(agent.archivedAt), purged_at: isoOrNull(agent.purgedAt) },
44
+ });
39
45
  /** What a request's error answers, over HTTP and through an MCP tool alike (server.ts, mcp.ts dispatch): an ApiError as
40
46
  * it is; a busy store home_busy (409, retryable), never 500; a run of an agent being deleted agent_not_runnable (409);
41
- * anything else internal, its message kept. */
42
- export const answerOf = (error) => error instanceof ApiError ? error : storeBusy(error) ? homeBusy() : error instanceof AgentDeleting ? agentDeleting(error.agentId) : new ApiError("internal", error?.message ?? String(error));
47
+ * a write to a purged agent purged (410); anything else internal, its message kept. */
48
+ export const answerOf = (error) => error instanceof ApiError ? error
49
+ : storeBusy(error) ? homeBusy()
50
+ : error instanceof AgentDeleting ? agentDeleting(error.agentId)
51
+ : error instanceof AgentPurged ? purgedAgent({ id: error.agentId, archivedAt: error.archivedAt, purgedAt: error.purgedAt })
52
+ : new ApiError("internal", error?.message ?? String(error));
43
53
  /** Whether a request's error goes to the server's log: every fault the server did not answer on purpose. A busy wait
44
54
  * is not one; a transaction past its deadline is (something held the store that long). */
45
- export const logged = (error) => !(error instanceof ApiError) && !(error instanceof AgentDeleting) && (!storeBusy(error) || error instanceof StoreDeadline);
55
+ export const logged = (error) => !(error instanceof ApiError) && !(error instanceof AgentDeleting) && !(error instanceof AgentPurged) && (!storeBusy(error) || error instanceof StoreDeadline);
@@ -53,4 +53,14 @@ export declare function answerAsServed(output: string, schema: unknown): {
53
53
  } | {
54
54
  why: string;
55
55
  };
56
+ /** The output-schema annotation naming the top-level fields of an answer that its agent's next run reads back: a list of
57
+ * the root's property names (a scheduled watch's `seen`, a digest's `open_urgent`). The runtime reads it alone: when a
58
+ * trigger's last completed result is too large to hand whole, its next run is handed those fields
59
+ * (trigger-targets.ts previousResultOf). Never a tool's schema keyword: dsl submitParameters leaves it out. */
60
+ export declare const X_CARRIED = "x-carried";
61
+ /** Why `schema`'s `x-carried` is not a list of unique names of the root's `properties`; undefined when it is, or absent. */
62
+ export declare function carriedProblem(schema: Record<string, unknown>): string | undefined;
63
+ /** The fields `schema` names in `x-carried`, read by the save's rule (carriedProblem): undefined for none, or for one the
64
+ * save would refuse, so its run gets the too-large line. */
65
+ export declare function carriedFields(schema: unknown): readonly string[] | undefined;
56
66
  export {};
@@ -138,3 +138,26 @@ export function answerAsServed(output, schema) {
138
138
  const problems = compiled.check(shapes.find(isObject) ?? shapes[0]);
139
139
  return { why: `its answer does not meet the agent's output schema: ${problems.slice(0, 3).join("; ")}` };
140
140
  }
141
+ /** The output-schema annotation naming the top-level fields of an answer that its agent's next run reads back: a list of
142
+ * the root's property names (a scheduled watch's `seen`, a digest's `open_urgent`). The runtime reads it alone: when a
143
+ * trigger's last completed result is too large to hand whole, its next run is handed those fields
144
+ * (trigger-targets.ts previousResultOf). Never a tool's schema keyword: dsl submitParameters leaves it out. */
145
+ export const X_CARRIED = "x-carried";
146
+ /** Why `schema`'s `x-carried` is not a list of unique names of the root's `properties`; undefined when it is, or absent. */
147
+ export function carriedProblem(schema) {
148
+ const carried = schema[X_CARRIED];
149
+ if (carried === undefined)
150
+ return undefined;
151
+ if (!Array.isArray(carried) || !carried.every((name) => typeof name === "string" && name !== ""))
152
+ return "is a list of the names of the root's properties";
153
+ if (new Set(carried).size !== carried.length)
154
+ return "names a property twice";
155
+ const properties = isObject(schema.properties) ? schema.properties : {};
156
+ const unknown = carried.filter((name) => !Object.hasOwn(properties, name));
157
+ return unknown.length ? `names ${unknown.map((name) => JSON.stringify(name)).join(", ")}, which the root's properties have no field for` : undefined;
158
+ }
159
+ /** The fields `schema` names in `x-carried`, read by the save's rule (carriedProblem): undefined for none, or for one the
160
+ * save would refuse, so its run gets the too-large line. */
161
+ export function carriedFields(schema) {
162
+ return isObject(schema) && !carriedProblem(schema) ? schema[X_CARRIED] : undefined;
163
+ }