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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/CHANGELOG.md +185 -0
  2. package/README.md +236 -30
  3. package/dist/adapters.js +1 -1
  4. package/dist/agent-delete.d.ts +13 -2
  5. package/dist/agent-delete.js +14 -5
  6. package/dist/agents-store.d.ts +5 -1
  7. package/dist/agents-store.js +17 -7
  8. package/dist/api-only.d.ts +6 -3
  9. package/dist/api-only.js +8 -5
  10. package/dist/archil-routes.d.ts +1 -0
  11. package/dist/archil-routes.js +28 -2
  12. package/dist/capacity.d.ts +50 -0
  13. package/dist/capacity.js +49 -0
  14. package/dist/cli-learning/claude-wire.d.ts +41 -0
  15. package/dist/cli-learning/claude-wire.js +258 -0
  16. package/dist/cli-learning/cli.d.ts +11 -0
  17. package/dist/cli-learning/cli.js +241 -0
  18. package/dist/cli-learning/codex-worktree.d.ts +10 -0
  19. package/dist/cli-learning/codex-worktree.js +119 -0
  20. package/dist/cli-learning/connections.d.ts +62 -0
  21. package/dist/cli-learning/connections.js +87 -0
  22. package/dist/cli-learning/entry.d.ts +1 -0
  23. package/dist/cli-learning/entry.js +4 -0
  24. package/dist/cli-learning/evidence.d.ts +78 -0
  25. package/dist/cli-learning/evidence.js +492 -0
  26. package/dist/cli-learning/hook.d.ts +33 -0
  27. package/dist/cli-learning/hook.js +544 -0
  28. package/dist/cli-learning/install.d.ts +33 -0
  29. package/dist/cli-learning/install.js +335 -0
  30. package/dist/cli-learning/observation-proof.d.ts +14 -0
  31. package/dist/cli-learning/observation-proof.js +10 -0
  32. package/dist/cli-learning/policy.d.ts +48 -0
  33. package/dist/cli-learning/policy.js +363 -0
  34. package/dist/cli-learning/schema.d.ts +16 -0
  35. package/dist/cli-learning/schema.js +27 -0
  36. package/dist/cli-learning/state.d.ts +23 -0
  37. package/dist/cli-learning/state.js +61 -0
  38. package/dist/cli.js +24 -2
  39. package/dist/computer-setting.d.ts +8 -0
  40. package/dist/computer-setting.js +11 -0
  41. package/dist/computers.d.ts +6 -2
  42. package/dist/computers.js +2 -2
  43. package/dist/console/assets/index-B-D0EM3j.js +733 -0
  44. package/dist/console/assets/{index-D0mr9wfZ.css → index-DlQepP2J.css} +1 -1
  45. package/dist/console/index.html +2 -2
  46. package/dist/email/email-faux.d.ts +3 -1
  47. package/dist/email/email-faux.js +3 -2
  48. package/dist/email/routes.js +22 -12
  49. package/dist/fal-price.d.ts +76 -0
  50. package/dist/fal-price.js +368 -0
  51. package/dist/harness-install.d.ts +6 -2
  52. package/dist/harness-install.js +40 -8
  53. package/dist/harness.d.ts +1 -1
  54. package/dist/harness.js +2 -2
  55. package/dist/learn/commit.d.ts +5 -0
  56. package/dist/learn/commit.js +4 -1
  57. package/dist/learn/compile.d.ts +13 -5
  58. package/dist/learn/compile.js +24 -7
  59. package/dist/learn/delete.d.ts +12 -6
  60. package/dist/learn/delete.js +17 -11
  61. package/dist/learn/folder.d.ts +11 -0
  62. package/dist/learn/folder.js +20 -3
  63. package/dist/learn/learning-of.d.ts +8 -0
  64. package/dist/learn/learning-of.js +8 -0
  65. package/dist/learn/learning.sh +14 -1
  66. package/dist/learn/promote.d.ts +51 -7
  67. package/dist/learn/promote.js +51 -8
  68. package/dist/learn/secrets.js +14 -3
  69. package/dist/learning-reset.d.ts +18 -0
  70. package/dist/learning-reset.js +115 -0
  71. package/dist/learning-routes.d.ts +1 -1
  72. package/dist/learning-words.d.ts +6 -1
  73. package/dist/learning-words.js +6 -1
  74. package/dist/learning.d.ts +8 -6
  75. package/dist/learning.js +5 -4
  76. package/dist/llms.txt +1 -0
  77. package/dist/mcp-gateway.d.ts +39 -2
  78. package/dist/mcp-gateway.js +41 -10
  79. package/dist/mcp-pin-first.js +3 -2
  80. package/dist/mcp-private-hosts.d.ts +24 -3
  81. package/dist/mcp-private-hosts.js +53 -3
  82. package/dist/mcp-servers-store.d.ts +1 -0
  83. package/dist/mcp-servers-store.js +2 -1
  84. package/dist/media-duration.d.ts +2 -0
  85. package/dist/media-duration.js +136 -0
  86. package/dist/model-gateway.d.ts +2 -0
  87. package/dist/model-gateway.js +3 -1
  88. package/dist/native/runtimes.d.ts +2 -0
  89. package/dist/native/runtimes.js +2 -0
  90. package/dist/observation/learning.d.ts +32 -0
  91. package/dist/observation/learning.js +66 -0
  92. package/dist/observation/observer.d.ts +8 -1
  93. package/dist/observation/observer.js +89 -9
  94. package/dist/observation/schema.js +12 -4
  95. package/dist/observation/usage-identity.d.ts +9 -0
  96. package/dist/observation/usage-identity.js +11 -0
  97. package/dist/openapi.js +133 -24
  98. package/dist/provider.d.ts +8 -0
  99. package/dist/provider.js +14 -2
  100. package/dist/refusal-words.d.ts +0 -3
  101. package/dist/refusal-words.js +0 -3
  102. package/dist/request-metadata.d.ts +20 -0
  103. package/dist/request-metadata.js +24 -0
  104. package/dist/run-launch.d.ts +27 -4
  105. package/dist/run-launch.js +18 -3
  106. package/dist/run-learning-served.d.ts +2 -2
  107. package/dist/run-usage.d.ts +48 -4
  108. package/dist/run-usage.js +156 -39
  109. package/dist/run-view.d.ts +2 -0
  110. package/dist/run-view.js +8 -7
  111. package/dist/runner/adapter-loop.d.ts +3 -1
  112. package/dist/runner/adapter-loop.js +41 -35
  113. package/dist/runner/adapter-run-spec.d.ts +1 -1
  114. package/dist/runner/adapter-run-spec.js +15 -15
  115. package/dist/runner/audit.d.ts +8 -3
  116. package/dist/runner/audit.js +21 -6
  117. package/dist/runner/beside.d.ts +13 -0
  118. package/dist/runner/beside.js +27 -8
  119. package/dist/runner/claim-secrets.d.ts +2 -1
  120. package/dist/runner/claim-secrets.js +5 -3
  121. package/dist/runner/cli-run-spec.d.ts +1 -1
  122. package/dist/runner/cli-run-spec.js +14 -13
  123. package/dist/runner/conformance/harness.js +4 -2
  124. package/dist/runner/disk-free.d.ts +44 -0
  125. package/dist/runner/disk-free.js +96 -0
  126. package/dist/runner/dispatch.js +4 -2
  127. package/dist/runner/feedback-round.d.ts +12 -8
  128. package/dist/runner/feedback-round.js +16 -30
  129. package/dist/runner/harness-loops.js +8 -3
  130. package/dist/runner/journal-kinds.d.ts +4 -1
  131. package/dist/runner/learning-end.d.ts +2 -1
  132. package/dist/runner/learning-end.js +51 -22
  133. package/dist/runner/main.d.ts +17 -6
  134. package/dist/runner/main.js +187 -45
  135. package/dist/runner/mcp-claim.js +1 -1
  136. package/dist/runner/mcp-run.d.ts +9 -0
  137. package/dist/runner/mcp-run.js +16 -1
  138. package/dist/runner/model-route.js +7 -4
  139. package/dist/runner/presence.d.ts +11 -2
  140. package/dist/runner/presence.js +31 -3
  141. package/dist/runner/promotion.d.ts +40 -21
  142. package/dist/runner/promotion.js +130 -59
  143. package/dist/runner/run-child-host.d.ts +12 -15
  144. package/dist/runner/run-child-host.js +52 -112
  145. package/dist/runner/run-errors.js +2 -0
  146. package/dist/runner/runner-check.d.ts +51 -0
  147. package/dist/runner/runner-check.js +206 -0
  148. package/dist/runner/runner-metrics.d.ts +19 -0
  149. package/dist/runner/runner-metrics.js +49 -0
  150. package/dist/runner/runner.d.ts +37 -0
  151. package/dist/runner/runner.js +58 -6
  152. package/dist/runner/sdk-loop.d.ts +2 -2
  153. package/dist/runner/sdk-loop.js +37 -25
  154. package/dist/runner/store-port.d.ts +3 -0
  155. package/dist/runner/workflow-spec.js +3 -3
  156. package/dist/runs-over-store.d.ts +13 -3
  157. package/dist/runs-over-store.js +71 -16
  158. package/dist/sdk/check.d.ts +6 -5
  159. package/dist/sdk/check.js +17 -16
  160. package/dist/sdk/runs.d.ts +22 -2
  161. package/dist/sdk/runs.js +167 -82
  162. package/dist/server.d.ts +3 -0
  163. package/dist/server.js +230 -43
  164. package/dist/skills/agentrun-serve/SKILL.md +52 -7
  165. package/dist/start-switches.js +2 -0
  166. package/dist/stats.d.ts +4 -0
  167. package/dist/stats.js +1 -1
  168. package/dist/store/agent-body.d.ts +16 -0
  169. package/dist/store/agent-body.js +20 -3
  170. package/dist/store/dialect.d.ts +2 -0
  171. package/dist/store/dialect.js +1 -0
  172. package/dist/store/index.d.ts +3 -3
  173. package/dist/store/index.js +2 -2
  174. package/dist/store/journal/storage.d.ts +2 -0
  175. package/dist/store/journal/storage.js +2 -1
  176. package/dist/store/postgres/connection.d.ts +5 -2
  177. package/dist/store/postgres/connection.js +19 -7
  178. package/dist/store/postgres/dialect.js +1 -0
  179. package/dist/store/postgres/migrate.d.ts +30 -0
  180. package/dist/store/postgres/migrate.js +72 -5
  181. package/dist/store/postgres/migration-lint.d.ts +8 -0
  182. package/dist/store/postgres/migration-lint.js +119 -0
  183. package/dist/store/postgres/migrations/0024_runner_capacity.sql +28 -0
  184. package/dist/store/postgres/migrations/0025_run_attempts.sql +27 -0
  185. package/dist/store/postgres/migrations/0026_run_disk.sql +23 -0
  186. package/dist/store/postgres/store.d.ts +8 -3
  187. package/dist/store/postgres/store.js +31 -11
  188. package/dist/store/schema.d.ts +32 -2
  189. package/dist/store/schema.js +74 -5
  190. package/dist/store/sqlite/run-launch.d.ts +31 -1
  191. package/dist/store/sqlite/run-launch.js +111 -2
  192. package/dist/store/sqlite/run-patch.d.ts +2 -1
  193. package/dist/store/sqlite/run-patch.js +4 -3
  194. package/dist/store/sqlite/store.d.ts +17 -0
  195. package/dist/store/sqlite/store.js +226 -37
  196. package/dist/store/store-schema.d.ts +34 -0
  197. package/dist/store/store-schema.js +125 -0
  198. package/dist/store/store.d.ts +120 -5
  199. package/dist/store/store.js +13 -0
  200. package/dist/store-reads/analytics.d.ts +3 -2
  201. package/dist/store-reads/analytics.js +20 -8
  202. package/dist/store-reads/learning.d.ts +12 -8
  203. package/dist/store-reads/learning.js +33 -24
  204. package/dist/store-reads/loop.d.ts +4 -3
  205. package/dist/store-reads/loop.js +7 -5
  206. package/dist/store-view.d.ts +4 -3
  207. package/dist/store-view.js +11 -7
  208. package/dist/template-eval.js +4 -4
  209. package/dist/templates.d.ts +6 -2
  210. package/dist/templates.js +7 -5
  211. package/dist/timeline/labels.js +1 -1
  212. package/dist/tool-gate.d.ts +4 -2
  213. package/dist/tools.js +1 -1
  214. package/dist/unified-usage.d.ts +24 -0
  215. package/dist/unified-usage.js +400 -0
  216. package/dist/uploads-archil.d.ts +100 -0
  217. package/dist/uploads-archil.js +431 -0
  218. package/dist/uploads.d.ts +52 -1
  219. package/dist/uploads.js +186 -108
  220. package/dist/validate.js +5 -1
  221. package/dist/web-save.d.ts +3 -0
  222. package/dist/web-save.js +17 -2
  223. package/dist/workspace/archil-disk.d.ts +6 -5
  224. package/dist/workspace/archil-disk.js +27 -12
  225. package/dist/workspace/archil-exec.js +1 -1
  226. package/dist/workspace/archil.js +4 -3
  227. package/dist/workspace/revision-skills.js +24 -11
  228. package/dist/workspace/synced-folder.d.ts +3 -3
  229. package/dist/workspace/synced-folder.js +7 -6
  230. package/package.json +10 -10
  231. package/skills/agentrun-serve/SKILL.md +52 -7
  232. package/dist/console/assets/index-D7G6o-1E.js +0 -720
package/dist/sdk/runs.js CHANGED
@@ -3,22 +3,30 @@
3
3
  import { createHash, createHmac, timingSafeEqual } from "node:crypto";
4
4
  import { inspectWorkflow, resolveSchemaForWorkflow } from "@parcha/agentrun-dsl";
5
5
  import { ApiError } from "../errors.js";
6
- import { canonical, isObject } from "../store/agent-body.js";
6
+ import { canonical, isObject, cliLearningOf, learningSettingForBody } from "../store/agent-body.js";
7
7
  import { uuidv7 } from "../agents-store.js";
8
8
  import { launchBody } from "../run-launch.js";
9
9
  import { learningStartFor } from "../runs-over-store.js";
10
- import { chooseWorkflows, learningFolderOf, seedAt, secretsShown } from "../learning.js";
10
+ import { chooseWorkflows, learningFolderOf, seedAt, secretsShown, withAgentRepo } from "../learning.js";
11
11
  import { INSTRUCTION_EVIDENCE_BYTES } from "../native/instructions.js";
12
+ import { CLI_POLICY_BYTES } from "../cli-learning/policy.js";
12
13
  import { refuseWhileNoRunner } from "../runner/presence.js";
13
14
  import { secretRedactor } from "../runner/redact.js";
14
15
  import { redactedOutput } from "../key-refusal.js";
15
16
  import { decodedStrings, draftProblems } from "../learn/workflow-draft.js";
16
17
  import { sdkWorkflowManifest, sdkDraftTools } from "./workflows.js";
17
- import { promotionOf, promotionsOf } from "../learn/promote.js";
18
+ import { promotionOf, promotionsOf, resetAtOf } from "../learn/promote.js";
18
19
  import { championTextOf, releaseSdkCheck, reserveSdkCheck } from "../runner/promotion.js";
19
20
  import { fits, workflowDigest } from "../runner/workflow-first.js";
20
21
  import { SDK_WORKFLOW_RUNTIMES, sdkBindingOf } from "./runtimes.js";
21
22
  export { SDK_RUNTIMES, isSdkRuntime } from "./runtimes.js";
23
+ /** Claude's begin snapshot is provisional; only its immutable same-window completion can establish policy. */
24
+ export function cliPolicyOf(launch, completion) {
25
+ const cli = launch.cli_learning;
26
+ if (!cli)
27
+ return undefined;
28
+ return cli.runtime === "claude-code-cli" ? completion?.source_policy ?? { instructions: "The current Claude prompt policy was not captured.", complete: false } : { instructions: cli.instructions, complete: cli.policy_complete };
29
+ }
22
30
  const keyOf = (id) => `sdk-run:${id}`;
23
31
  /** The settings key an SDK run's record is kept under (the run's delete with its agent's: agent-delete.ts). */
24
32
  export const sdkRunKey = keyOf;
@@ -126,7 +134,7 @@ function checkToolParents(row, events) {
126
134
  /** The key a server signs its SDK runs' credentials with: derived from its seal key (seal-key.ts), which stays the
127
135
  * store's for its life, so adding, reordering or removing an API token (api-token.ts) never changes a run's credential. */
128
136
  export const sdkRunSecret = (sealKey) => createHmac("sha256", sealKey).update("agentrun sdk-run credentials").digest("base64url");
129
- const sign = (secret, runId) => `ar_sdk_${createHmac("sha256", secret).update(`sdk-run\0${runId}`).digest("base64url")}`;
137
+ const sign = (secret, runId, lane = "sdk") => `${lane === "cli" ? "ar_cli_run_" : "ar_sdk_"}${createHmac("sha256", secret).update(`${lane}-run\0${runId}`).digest("base64url")}`;
130
138
  const digest = (text) => createHash("sha256").update(text).digest();
131
139
  export class SdkRuns {
132
140
  store;
@@ -134,50 +142,61 @@ export class SdkRuns {
134
142
  secret;
135
143
  secrets;
136
144
  earlier;
145
+ lane;
137
146
  /** `earlier` are the keys credentials were once signed with (the server's API tokens, before `secret` was its seal
138
147
  * key's): a credential any of them signed is still taken, so a run started before an upgrade keeps its credential. */
139
- constructor(store, data, secret, secrets = () => [], earlier = []) {
148
+ constructor(store, data, secret, secrets = () => [], earlier = [], lane = "sdk") {
140
149
  this.store = store;
141
150
  this.data = data;
142
151
  this.secret = secret;
143
152
  this.secrets = secrets;
144
153
  this.earlier = earlier;
154
+ this.lane = lane;
145
155
  }
146
156
  token(runId) {
147
- return sign(this.secret, runId);
157
+ return sign(this.secret, runId, this.lane);
148
158
  }
149
159
  async authenticate(runId, token) {
150
160
  // Every key compared, on equal-length digests, with no early return.
151
161
  const given = digest(token);
152
162
  let ok = false;
153
163
  for (const key of [this.secret, ...this.earlier])
154
- ok = timingSafeEqual(given, digest(sign(key, runId))) || ok;
164
+ ok = timingSafeEqual(given, digest(sign(key, runId, this.lane))) || ok;
155
165
  if (!ok)
156
166
  throw new ApiError("unauthenticated", "This credential is scoped to a different SDK run.");
157
167
  await sdkInbox(this.store, runId);
158
168
  }
159
169
  clean(body, runId) {
160
- const redact = secretRedactor([...this.secrets(), ...(runId ? [this.secret, ...this.earlier].map((key) => sign(key, runId)) : [])]);
170
+ const redact = secretRedactor([...this.secrets(), ...(runId ? [this.secret, ...this.earlier].map((key) => sign(key, runId, this.lane)) : [])]);
161
171
  // Redact values structurally: a long string or encoded credential can be withheld whole,
162
172
  // so treating serialized JSON as prose could remove its delimiters and corrupt the envelope.
163
173
  return redactedOutput(body, redact.heldValues?.() ?? []);
164
174
  }
165
- async start(entry, body, deps, origin, compile, consoleOrigin) {
166
- only(body, ["runtime", "platform", "input", "instructions", "model", "workflow_tools", "workflow_adapters"]);
167
- const source = sdkBindingOf(body) ?? refuse("The SDK source needs a supported runtime; external requires a platform label of 1–80 characters without surrounding whitespace, controls or lone surrogates. Other runtimes do not take platform.");
168
- if (!SDK_WORKFLOW_RUNTIMES.includes(source.runtime) && (body.workflow_tools !== undefined || body.workflow_adapters !== undefined))
175
+ async start(entry, body, deps, origin, compile, consoleOrigin, cli) {
176
+ if (this.lane !== (cli ? "cli" : "sdk"))
177
+ refuse("The run must use its enrolled credential lane.");
178
+ only(body, cli ? ["runtime", "input", "instructions", "model"] : ["runtime", "platform", "input", "instructions", "model", "workflow_tools", "workflow_adapters"]);
179
+ const source = cli ? undefined : sdkBindingOf(body) ?? refuse("The SDK source needs a supported runtime; external requires a platform label of 1–80 characters without surrounding whitespace, controls or lone surrogates. Other runtimes do not take platform.");
180
+ if (source && !SDK_WORKFLOW_RUNTIMES.includes(source.runtime) && (body.workflow_tools !== undefined || body.workflow_adapters !== undefined))
169
181
  refuse("External runs receive owner corrections; workflow_tools and workflow_adapters require a backend workflow bridge.");
170
- const workflow = sdkWorkflowManifest(body.workflow_tools, body.workflow_adapters);
182
+ const workflow = cli ? undefined : sdkWorkflowManifest(body.workflow_tools, body.workflow_adapters);
171
183
  if (workflow && canonical(this.clean(workflow)) !== canonical(workflow))
172
184
  refuse("The workflow manifest contains a protected value; keep credentials in the backend.");
173
185
  const binding = sdkOf(entry.revision?.body);
174
- if (!binding || !entry.revision)
175
- throw new ApiError("agent_not_runnable", "This agent is not registered as a backend SDK agent.");
186
+ if (cli) {
187
+ if (cliLearningOf(entry.revision?.body)?.connection_id !== cli.connection_id)
188
+ refuse("CLI connection does not match the enrolled agent.");
189
+ if (body.runtime !== cli.runtime)
190
+ refuse("The CLI runtime must match the enrolled agent.");
191
+ }
192
+ else if (!binding || source.runtime !== binding.runtime || source.platform !== binding.platform) {
193
+ refuse("The SDK runtime and platform must match the registered agent.");
194
+ }
195
+ if (!entry.revision)
196
+ throw new ApiError("agent_not_runnable", "This agent has no current registered revision.");
176
197
  if (entry.agent.archivedAt !== null)
177
198
  throw new ApiError("agent_archived", "This SDK agent is archived.");
178
- if (source.runtime !== binding.runtime || source.platform !== binding.platform)
179
- refuse("The SDK runtime and platform must match the registered agent.");
180
- const input = text(body.input, "input"), instructions = text(body.instructions, "instructions");
199
+ const input = text(body.input, "input"), instructions = text(body.instructions, "instructions", cli ? CLI_POLICY_BYTES : TEXT_LIMIT);
181
200
  const model = body.model === undefined ? undefined : text(body.model, "model", 256);
182
201
  if (origin) {
183
202
  const known = await this.store.runOfOrigin(origin.key);
@@ -197,74 +216,102 @@ export class SdkRuns {
197
216
  // A runner keeps an SDK run's evidence and ends it: while every runner here refused to claim, the start is refused in
198
217
  // their words, as any start is (prepareLaunch), before the caller holds a receipt it would run on.
199
218
  await refuseWhileNoRunner(this.store.runners);
200
- const learning = await learningStartFor(deps, entry, pinned.revision, revisionBody, {
219
+ // A connected agent's run names no disk.
220
+ const learning = await learningStartFor(deps, entry, pinned.revision, { ...revisionBody, learning: learningSettingForBody(revisionBody) }, {
221
+ disk: null,
201
222
  noWorkflows: !workflow,
202
223
  ...(compile.model ? { model: compile.model } : {}),
203
224
  });
204
225
  if (learning) {
205
- if (Buffer.byteLength(instructions) > INSTRUCTION_EVIDENCE_BYTES)
206
- refuse("Original SDK instructions exceed the 64 KiB learning evidence limit. Keep learning off or provide a complete policy within that limit.");
207
- if (!learning.model)
226
+ if (Buffer.byteLength(instructions) > (cli ? CLI_POLICY_BYTES : INSTRUCTION_EVIDENCE_BYTES))
227
+ refuse(cli ? "Original CLI instructions exceed the 256 KiB evidence limit. Keep capture off or provide a complete policy within that limit." : "Original SDK instructions exceed the 64 KiB learning evidence limit. Keep learning off or provide a complete policy within that limit.");
228
+ if (!cli && !learning.model)
208
229
  throw new ApiError("agent_not_runnable", "Self-improving SDK runs need a server model and its model key to compile workflows. Configure the model or turn self-improving off.");
209
- await compile.check(learning.model);
230
+ if (!cli)
231
+ await compile.check(learning.model);
210
232
  if (learning.seedFailed)
211
233
  throw new ApiError("unavailable", "The learning seed could not be read. Retry after restoring the agent learning folder.");
212
234
  }
213
- const selected = learning && !learning.noWorkflows && workflow ? await this.selectedWorkflows(entry.agent.id, learning.seed, workflow) : { workflows: [], candidates: [] };
214
- const cleaned = this.clean({ instructions, ...(model ? { model } : {}) });
215
- const runId = uuidv7();
216
- const redacted = cleanedInput !== input || cleaned.instructions !== instructions;
217
- let task;
218
- try {
219
- task = JSON.parse(input);
220
- }
221
- catch { /* A prose task: the client resolves the draft's input from the turn. */ }
222
- // A turn is a check only when it can be one's baseline: no protected value in its task or policy, and an input the
223
- // draft takes. A JSON object task is the input, so it must fit (the managed check's own rule); a prose task's input
224
- // is resolved by the client from the turn's recorded tool inputs or the host's resolveCheckInput, and a turn it
225
- // cannot resolve is given back (releaseSdkCheck), never counted.
226
- const takes = (flow) => !redacted && (!isObject(task) || fits(flow, task, resolveSchemaForWorkflow));
227
- const checkDeps = { store: this.store, agentId: entry.agent.id, log: () => { }, shown: async () => secretsShown(this.secrets(), { local: true }) };
228
- const check = learning ? await reserveSdkCheck(checkDeps, { runId, revision: learning.seed, learning: revisionBody.learning, flows: selected.candidates, takes }) : undefined;
229
- // A shadow check needs the original agent's own answer, not an answer produced by its existing champion.
230
- const workflows = check ? [] : selected.workflows;
231
- const launch = {
232
- input: { content: cleanedInput },
233
- title: cleanedInput.trim().replace(/\s+/g, " ").slice(0, 80),
234
- place: { mode: "runner" },
235
- harness: "sdk",
236
- sdk: {
237
- ...binding,
238
- ...workflow,
239
- instructions: cleaned.instructions,
240
- ...(cleaned.model ? { model: cleaned.model } : {}),
241
- },
242
- ...(learning ? { learning: { ...learning, workflows: workflows.map((flow) => flow.name) } } : {}),
243
- };
244
- const now = Date.now();
245
- try {
246
- await this.store.settings.put(keyOf(runId), {
247
- run_id: runId,
248
- created_at: now,
249
- expires_at: now + 3_600_000,
250
- batches: [],
251
- learning_workflows: workflows,
252
- ...(check ? { learning_check: check } : {}),
253
- ...(redacted ? { check_redacted: true } : {}),
254
- });
255
- await this.store.runs.create({ id: runId, agentId: entry.agent.id, revisionId: entry.revision.id, ...(origin ? { origin } : {}) }, { body: launchBody(launch) });
256
- }
257
- catch (error) {
258
- await this.store.settings.remove(keyOf(runId));
259
- // The reservation comes first because the launch it is created with withholds the champion from a check's turn.
260
- // No turn ran, so the check waits for the next one, the release uncounted: never a hold of a draft never compared.
261
- if (check) {
262
- const record = promotionOf(await promotionsOf(this.store.settings, entry.agent.id).catch(() => []), check.workflow.name, check.digest);
263
- if (record?.decided === "replaying" && record.replay_id === check.id)
264
- await releaseSdkCheck(checkDeps, record, "its start could not be admitted", false).catch(() => undefined);
235
+ const revision = entry.revision;
236
+ const admit = async () => {
237
+ // The reset deletes the agent's learning in this queue after setting its watermark (learning-reset.ts): a seed
238
+ // read at or before it is of learning the reset deleted, so the start is refused, to start again on a new seed.
239
+ const reset = learning ? await resetAtOf(this.store.settings, entry.agent.id) : undefined;
240
+ if (learning && reset !== undefined && !(learning.seededAt !== undefined && learning.seededAt > reset))
241
+ throw new ApiError("unavailable", "The agent's learning was reset while this run started: start it again.", { retry_after_ms: 1_000 });
242
+ const selected = learning && !learning.noWorkflows && workflow ? await this.selectedWorkflows(entry.agent.id, learning.seed, workflow) : { workflows: [], candidates: [] };
243
+ const cleaned = this.clean({ instructions, ...(model ? { model } : {}) });
244
+ const runId = uuidv7();
245
+ const redacted = cleanedInput !== input || cleaned.instructions !== instructions;
246
+ let task;
247
+ try {
248
+ task = JSON.parse(input);
265
249
  }
266
- throw error;
267
- }
250
+ catch { /* A prose task: the client resolves the draft's input from the turn. */ }
251
+ // A turn is a check only when it can be one's baseline: no protected value in its task or policy, and an input the
252
+ // draft takes. A JSON object task is the input, so it must fit (the managed check's own rule); a prose task's input
253
+ // is resolved by the client from the turn's recorded tool inputs or the host's resolveCheckInput, and a turn it
254
+ // cannot resolve is given back (releaseSdkCheck), never counted.
255
+ const takes = (flow) => !redacted && (!isObject(task) || fits(flow, task, resolveSchemaForWorkflow));
256
+ const checkDeps = { store: this.store, agentId: entry.agent.id, log: () => { }, shown: async () => secretsShown(this.secrets(), { local: true }) };
257
+ const check = learning ? await reserveSdkCheck(checkDeps, { runId, revision: learning.seed, learning: revisionBody.learning, flows: selected.candidates, takes }) : undefined;
258
+ // A shadow check needs the original agent's own answer, not an answer produced by its existing champion.
259
+ const workflows = check ? [] : selected.workflows;
260
+ const launch = {
261
+ input: { content: cleanedInput },
262
+ title: cleanedInput.trim().replace(/\s+/g, " ").slice(0, 80),
263
+ place: { mode: "runner" },
264
+ ...(cli ? {
265
+ harness: "cli",
266
+ cli_learning: { ...cli, instructions: cleaned.instructions, policy_complete: cli.policy_complete && cleaned.instructions === instructions, ...(cleaned.model ? { model: cleaned.model } : {}) },
267
+ } : {
268
+ harness: "sdk",
269
+ sdk: { ...binding, ...workflow, instructions: cleaned.instructions, ...(cleaned.model ? { model: cleaned.model } : {}) },
270
+ }),
271
+ ...(learning ? { learning: { ...learning, workflows: workflows.map((flow) => flow.name) } } : {}),
272
+ };
273
+ const now = Date.now();
274
+ try {
275
+ await this.store.settings.put(keyOf(runId), {
276
+ run_id: runId,
277
+ created_at: now,
278
+ expires_at: now + (cli ? 86_400_000 : 3_600_000),
279
+ batches: [],
280
+ learning_workflows: workflows,
281
+ ...(check ? { learning_check: check } : {}),
282
+ ...(redacted ? { check_redacted: true } : {}),
283
+ ...(cli && cleanedInput !== input ? { evidence_incomplete: true } : {}),
284
+ });
285
+ await this.store.runs.create({ id: runId, agentId: entry.agent.id, revisionId: revision.id, ...(origin ? { origin } : {}) }, { body: launchBody(launch) });
286
+ }
287
+ catch (error) {
288
+ await this.store.settings.remove(keyOf(runId));
289
+ // The reservation comes first because the launch it is created with withholds the champion from a check's turn.
290
+ // No turn ran, so the check waits for the next one, the release uncounted: never a hold of a draft never compared.
291
+ if (check) {
292
+ const record = promotionOf(await promotionsOf(this.store.settings, entry.agent.id).catch(() => []), check.workflow.name, check.digest);
293
+ if (record?.decided === "replaying" && record.replay_id === check.id)
294
+ await releaseSdkCheck(checkDeps, record, "its start could not be admitted", false).catch(() => undefined);
295
+ }
296
+ // Two source hooks may admit the same immutable prompt window under different transport keys.
297
+ // The store's origin constraint chooses one; recover its receipt (the run it chose) without creating another run.
298
+ if (origin) {
299
+ const known = await this.store.runOfOrigin(origin.key);
300
+ if (known) {
301
+ if (known.fingerprint !== origin.fingerprint)
302
+ throw new ApiError("idempotency_mismatch", "The key was used with another SDK start.");
303
+ return known.runId;
304
+ }
305
+ }
306
+ throw error;
307
+ }
308
+ return runId;
309
+ };
310
+ // A learning start is admitted in its agent's learning queue (learning.ts withAgentRepo), the one a reset of the
311
+ // agent's learning deletes it in: either the reset comes first, and the seed read before it is refused above, or this
312
+ // run's row is made first, and the reset refuses while it goes (409 learning_busy). No check of a draft the reset
313
+ // deleted is reserved, and no run starts on it.
314
+ const runId = learning ? await withAgentRepo(this.data, entry.agent.id, admit) : await admit();
268
315
  return this.receipt(runId, consoleOrigin);
269
316
  }
270
317
  async receipt(runId, consoleOrigin) {
@@ -354,9 +401,16 @@ export class SdkRuns {
354
401
  refuse("Supply a positive sequence and at most 100 events.");
355
402
  if (Buffer.byteLength(JSON.stringify(body)) > BATCH_LIMIT)
356
403
  throw new ApiError("payload_too_large", "An SDK event batch exceeds 256 KB.");
404
+ const launch = (await this.store.runs.launch(runId)).body;
357
405
  const events = body.events.map((value) => {
358
406
  if (!isObject(value))
359
407
  return refuse("An SDK event must be an object.");
408
+ if (value.type === "message" && launch.cli_learning) {
409
+ only(value, ["type", "role", "text"]);
410
+ if (value.role !== "user" && value.role !== "assistant")
411
+ return refuse("A dialogue message role must be user or assistant.");
412
+ return { type: "message", role: value.role, text: text(value.text, "text") };
413
+ }
360
414
  if (value.type === "text") {
361
415
  only(value, ["type", "text"]);
362
416
  return { type: "text", text: text(value.text, "text") };
@@ -434,25 +488,56 @@ export class SdkRuns {
434
488
  for (const check of checks)
435
489
  if (!row.learning_check || check.id !== row.learning_check.id || check.digest !== row.learning_check.digest)
436
490
  refuse("The workflow check must name this SDK run's reserved candidate.");
437
- return { ...row, batches: [...row.batches, batch], ...(checkRedacted ? { check_redacted: true } : {}) };
491
+ return { ...row, batches: [...row.batches, batch], ...(checkRedacted ? { check_redacted: true, ...(launch.cli_learning ? { evidence_incomplete: true } : {}) } : {}) };
438
492
  }, EVIDENCE_LIMIT);
439
493
  return { accepted: true };
440
494
  }
441
495
  async complete(runId, body) {
442
- only(body, ["status", "answer", "error", "model", "session_id", "usage", "evidence_complete"]);
496
+ const launch = (await this.store.runs.launch(runId)).body;
497
+ only(body, ["status", "answer", "error", "model", "session_id", "usage", "evidence_complete", ...(launch.cli_learning ? ["seed_observed", "seed_revision"] : []), ...(launch.cli_learning?.runtime === "claude-code-cli" ? ["source_policy"] : [])]);
498
+ if (body.seed_observed !== undefined && typeof body.seed_observed !== "boolean")
499
+ refuse("seed_observed must be a boolean.");
500
+ if (body.seed_observed === true && (!launch.learning?.seed || !launch.learning.section.trim() || body.seed_revision !== launch.learning.seed))
501
+ refuse("An observed seed requires pinned owner corrections and the matching revision from this prompt window receipt.");
443
502
  if (body.evidence_complete !== undefined && typeof body.evidence_complete !== "boolean")
444
503
  refuse("evidence_complete must be a boolean.");
445
504
  if (!["completed", "failed", "cancelled"].includes(String(body.status)))
446
505
  refuse("SDK completion status is completed, failed or cancelled.");
447
- const completion = this.clean({
506
+ if (launch.cli_learning && body.session_id !== undefined && body.session_id !== launch.cli_learning.session_id)
507
+ refuse("The completion session_id must match this CLI prompt window.");
508
+ let sourcePolicy;
509
+ if (body.source_policy !== undefined) {
510
+ if (!isObject(body.source_policy))
511
+ refuse("source_policy must be the current Claude prompt snapshot.");
512
+ const policy = body.source_policy;
513
+ only(policy, ["instructions", "complete"]);
514
+ if (typeof policy.complete !== "boolean")
515
+ refuse("source_policy.complete must be explicit.");
516
+ const instructions = text(policy.instructions, "source_policy.instructions", CLI_POLICY_BYTES);
517
+ if (Buffer.byteLength(instructions) > CLI_POLICY_BYTES)
518
+ refuse("The CLI source policy exceeds 256 KiB; mark capture incomplete rather than truncating it.");
519
+ sourcePolicy = { instructions, complete: policy.complete };
520
+ }
521
+ const submitted = {
448
522
  status: body.status,
523
+ ...(sourcePolicy ? { source_policy: sourcePolicy } : {}),
449
524
  answer: text(body.answer, "answer"),
450
525
  ...(body.evidence_complete !== undefined ? { evidence_complete: body.evidence_complete } : {}),
526
+ ...(body.seed_observed !== undefined ? { seed_observed: body.seed_observed } : {}),
527
+ ...(body.seed_revision !== undefined ? { seed_revision: text(body.seed_revision, "seed_revision", 128) } : {}),
451
528
  ...(body.error !== undefined ? { error: text(body.error, "error", 8000) } : {}),
452
529
  ...(body.model !== undefined ? { model: text(body.model, "model", 256) } : {}),
453
530
  ...(body.session_id !== undefined ? { session_id: text(body.session_id, "session_id", 256) } : {}),
454
531
  ...(body.usage !== undefined ? { usage: usageOf(body.usage) } : {}),
455
- }, runId);
532
+ };
533
+ const completion = this.clean(submitted, runId);
534
+ // Source policy has its own completeness flag; redacted execution evidence cannot
535
+ // be represented as complete even when the source explicitly claimed it was.
536
+ const { source_policy: _submittedPolicy, ...submittedEvidence } = submitted;
537
+ const { source_policy: _cleanedPolicy, ...cleanedEvidence } = completion;
538
+ const evidenceIncomplete = !!launch.cli_learning && canonical(submittedEvidence) !== canonical(cleanedEvidence);
539
+ if (completion.source_policy && completion.source_policy.instructions !== sourcePolicy.instructions)
540
+ completion.source_policy.complete = false;
456
541
  const known = (await sdkInbox(this.store, runId)).completion;
457
542
  if (known) {
458
543
  if (canonical(known) !== canonical(completion))
@@ -467,7 +552,7 @@ export class SdkRuns {
467
552
  return row;
468
553
  }
469
554
  writableInbox(row);
470
- return { ...row, completion, ...(completion.answer !== body.answer ? { check_redacted: true } : {}) };
555
+ return { ...row, completion, ...(evidenceIncomplete ? { evidence_incomplete: true } : {}), ...(completion.answer !== body.answer ? { check_redacted: true } : {}) };
471
556
  });
472
557
  return { accepted: true };
473
558
  }
package/dist/server.d.ts CHANGED
@@ -92,6 +92,9 @@ export type ServeOptions = {
92
92
  * test's fakes, for the server's own Archil calls (a launch's disk read, the settings' test, an agent's disk removed,
93
93
  * a deleted agent's run folder removed from a disk its launch named). */
94
94
  archilControl?: ArchilRoutesOptions["control"];
95
+ /** How long an uploaded file no run names is kept on the uploads disk in Mode 2 (uploads-archil.ts): a duration such
96
+ * as 7d, or "off". Default AGENTRUN_UPLOAD_RETENTION, else 7d. */
97
+ uploadRetention?: string;
95
98
  /** Another Composio than the real one, and its fetch: a test's fake, for the Composio preset's calls (composio-preset.ts). */
96
99
  composioControl?: ComposioControl;
97
100
  /** With `faux` only: a module whose default export gives the `browser` tool's `{ provider, driver }` (the tests' fake