@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/server.js CHANGED
@@ -1,3 +1,6 @@
1
+ import { CliLearningConnections } from "./cli-learning/connections.js";
2
+ import { ObservationLearning } from "./observation/learning.js";
3
+ import { cliLearningOf } from "./store/agent-body.js";
1
4
  import { maintainObservations, Observations } from './observation/observer.js';
2
5
  import { isObservationRoute, observationHttp } from './observation/http.js';
3
6
  import { SdkRuns, sdkOf, sdkRunSecret } from "./sdk/runs.js";
@@ -7,7 +10,7 @@ import { RemoteConnectors, verifyRemote, REMOTE_COMPLETION_BODY_BYTES } from './
7
10
  import { REMOTE_HISTORY_BODY_BYTES } from './native/history.js';
8
11
  import { nativeOf, nativeModelOverrides, nativeExecutionOverrides, NATIVE_MODEL_SETTINGS_UNSUPPORTED, NATIVE_EXECUTION_SETTINGS_UNSUPPORTED, NATIVE_TOOL_BUDGET_UNSUPPORTED, NATIVE_CAP_UNSUPPORTED } from "./native/binding.js";
9
12
  import { discoverNative } from "./native/discovery.js";
10
- import { isNativeRuntime } from "./native/runtimes.js";
13
+ import { isNativeRuntime, NATIVE_RUNTIME_FACTS } from "./native/runtimes.js";
11
14
  import { connectNative, launchNative, updateNative, verifyConnection } from "./native/connection.js";
12
15
  // The /v2 API over the agent store in a data directory: the contract agentrun.v2/0, served on loopback with a bearer
13
16
  // token.
@@ -16,6 +19,7 @@ import { chmod, lstat, mkdir, readFile, realpath, rename, stat, writeFile } from
16
19
  import { createServer } from "node:http";
17
20
  import proxyaddr from "proxy-addr";
18
21
  import { apiOnlyRefusal, servedApiOnly } from "./api-only.js";
22
+ import { capacityOverStore, capacityWindowOf } from "./capacity.js";
19
23
  import { carriedFields } from "./answer-json.js";
20
24
  import { dirname, join, relative, resolve, sep } from "node:path";
21
25
  import { pathToFileURL } from "node:url";
@@ -25,7 +29,7 @@ import { existsSync } from "node:fs";
25
29
  import { rm } from "node:fs/promises";
26
30
  import { homedir, hostname } from "node:os";
27
31
  import { pinFirst as pinFirstOf } from "./mcp-pin-first.js";
28
- import { agentRevision, agentRevisions, agentView, commitAgent, createAgent, etagOf, externalKey, getAgent, listAgents, makeRevision, refuseExternal, revisionView, setAgentArchived, setCurrentRevision } from "./agents-store.js";
32
+ import { agentRevision, agentRevisions, agentView, commitAgent, createAgent, etagOf, externalKey, getAgent, listAgents, makeRevision, ownedElsewhere, refuseExternal, revisionView, setAgentArchived, setCurrentRevision } from "./agents-store.js";
29
33
  import { WORKFLOW_ADAPTERS } from "./runner/workflow-adapters.js";
30
34
  import { DECISION_ADAPTER, decisionsOf, FAUX_JEV_ENV, FAUX_OPENROUTER_ENV, FAUX_PARALLEL_ENV, fauxFetch } from "./decisions.js";
31
35
  import { FAUX_WEB_ENV } from "./web-fetch-direct.js";
@@ -45,7 +49,7 @@ import { DEFAULT_PORT, healthOf, hostMemory, maxRunsOf, runsThatFit } from "./ho
45
49
  import { DEFAULT_HOST, elsewhereOf, listenOn, minFreeMibOf, takeOver, urlOf } from "./listen-first.js";
46
50
  import { IMPORT_ASKED, MAX_CANDIDATES } from "./import.js";
47
51
  import { answerStoreCall } from "./import-proxy.js";
48
- import { LEARNING_LABEL, learningFolderOf, secretsShown, learningOf, learnsOf, RUN_LEARNING_USE, seedOf } from "./learning.js";
52
+ import { LEARNING_LABEL, learningFolderOf, secretsShown, learningOf, learnsOf, RUN_LEARNING_USE, seedOf, withAgentRepo } from "./learning.js";
49
53
  import { askReplay, ReplayRefused, replayView } from "./runner/promotion.js";
50
54
  import { agentLearning, changeWorkflow, correctionsView, correctionsWrite, learningLog, pendingCount, readLearnedFile, sendText, statusesOf, textBody, workflowAtDigest, workflowRevisions } from "./learning-routes.js";
51
55
  import { answerLlms, MCP_PATH, mcpEndpoint } from "./mcp.js";
@@ -93,6 +97,7 @@ import { openStore, openRunLaunch, sealRunLaunch, StoreLaunchMissing, StoreOwned
93
97
  import { agentDeleting, answerOf, logged, purgedAgent } from "./agents.js";
94
98
  import { keepGrade } from "./runner/feedback-round.js";
95
99
  import { gradeRow, notAuditableOf } from "./runner/audit.js";
100
+ import { namedDisksOf } from "./learn/learning-of.js";
96
101
  import { auditsOffWords, auditWriterOf, isShadowRun, readAudits, servingLinesOf, shadowRunId } from "./learn/audit.js";
97
102
  import { auditLoopOf, COMPILE_AFTER_MAX } from "./learning-setting.js";
98
103
  import { FINAL_STATES, RUN_CHANGES_PAGE } from "./store/store.js";
@@ -117,9 +122,12 @@ import { modelGatewayRoute, readSavedGateway, withSavedGateway } from "./model-g
117
122
  import { CLAUDE_LOGIN_ROUTES, ClaudeLoginRefused, claudeLoginOf, claudeLoginRouteOff, claudeLoginSwitchedOff, claudeLoginSetting, claudeLoginView, dropRefusedLogin, envAtPlace, LOGIN_HARNESS, loginOf, startLoginHere, turnOffClaudeLogin, turnOnClaudeLogin, whyNotOneOwner, withClaudeLogin } from "./claude-login.js";
118
123
  import { bootSealKey, parametersDigest, withSealKey } from "./seal-key.js";
119
124
  import { ServerLockHeldError, takeServerLock } from "./server-lock.js";
125
+ import { recordDataRoot } from "./runner/disk-free.js";
126
+ import { recordRunEnv, runFacingNames } from "./runner/runner-check.js";
120
127
  import { DRAIN_TIMEOUT } from "./runner/beside.js";
121
128
  import { analyticsFilter, analyticsView, statsView } from "./stats.js";
122
129
  import { joinedBasis } from "./runner/metrics.js";
130
+ import { unifiedUsage } from "./unified-usage.js";
123
131
  import { agentLoopOverStore } from "./store-reads/loop.js";
124
132
  import { printable } from "./learn/index.js";
125
133
  import { agentCostOverStore, agentLearningOverStore, costStopOverStore, learningCountsOverStore, learningSpendOverStore, runAllInOverStore, runLearningEnd } from "./store-reads/learning.js";
@@ -168,6 +176,7 @@ import { wakeAnsweredBySetting } from "./settings-wake.js";
168
176
  import { toolSettingsOverStore } from "./tool-settings-store.js";
169
177
  import { readApprovers, writeApprovers } from "./server-approvers.js";
170
178
  import { MAX_FILES_PER_RUN, MAX_UPLOAD_BYTES, Uploads, UPLOADS_DIR } from "./uploads.js";
179
+ import { archilUploads, runKeepsUploads, UPLOAD_RETENTION_ENV, UPLOAD_SWEEP_EVERY_MS, uploadRetentionMs } from "./uploads-archil.js";
171
180
  import { entryAt, listFiles, sendFile as sendWorkspaceFile, viewOf } from "./run-files.js";
172
181
  import { recordingsOf, recordingsWorkspace } from "./run-recordings.js";
173
182
  import { recordingsFolder } from "./workspace/paths.js";
@@ -190,7 +199,8 @@ import { computerOfPlace } from "./computer-setting.js";
190
199
  import { computerCapabilities, createComputerRoutes, folderModeOf, hostCommandRefusals, settingsComputerRoute } from "./computers.js";
191
200
  import { fauxComputers } from "./faux-computers.js";
192
201
  import { writesHeld } from "./workspace.js";
193
- import { deleteExternalAgent, oneAtATime, purgeAgent, purgeRun, purgingKey } from "./agent-delete.js";
202
+ import { deleteExternalAgent, oneAtATime, purgeAgent, purgedAgain, purgeRun, purgingKey } from "./agent-delete.js";
203
+ import { resetLearning } from "./learning-reset.js";
194
204
  import { agentComputerHoldKey } from "./workspace/agent-computer.js";
195
205
  import { sdkRunKey } from "./sdk/runs.js";
196
206
  import { waitEndedKey } from "./browser-wait-ended.js";
@@ -292,6 +302,13 @@ export const ROUTES = [
292
302
  { method: "POST", pattern: /^\/connectors\/([^/]+)\/poll$/, name: "pollRemoteConnector" },
293
303
  { method: "POST", pattern: /^\/connectors\/([^/]+)\/commands\/([^/]+)\/events$/, name: "remoteCommandEvents" },
294
304
  { method: "POST", pattern: /^\/connectors\/([^/]+)\/commands\/([^/]+)\/complete$/, name: "completeRemoteCommand" },
305
+ { method: "POST", pattern: /^\/cli-learning\/connections$/, name: "enrollCliLearning" },
306
+ { method: "GET", pattern: /^\/cli-learning\/connections$/, name: "listCliLearning" },
307
+ { method: "DELETE", pattern: /^\/cli-learning\/connections\/([^/]+)$/, name: "revokeCliLearning" },
308
+ { method: "POST", pattern: /^\/cli-learning\/connections\/([^/]+)\/runs$/, name: "startCliLearningRun" },
309
+ { method: "GET", pattern: /^\/cli-learning\/runs\/([^/]+)$/, name: "getCliLearningRun" },
310
+ { method: "POST", pattern: /^\/cli-learning\/runs\/([^/]+)\/events$/, name: "cliLearningEvents" },
311
+ { method: "POST", pattern: /^\/cli-learning\/runs\/([^/]+)\/complete$/, name: "completeCliLearningRun" },
295
312
  { method: "POST", pattern: /^\/agents\/([^/]+)\/sdk-runs$/, name: "startSdkRun" },
296
313
  { method: "GET", pattern: /^\/sdk-runs\/([^/]+)$/, name: "getSdkRun" },
297
314
  { method: "POST", pattern: /^\/sdk-runs\/([^/]+)\/events$/, name: "sdkRunEvents" },
@@ -391,6 +408,8 @@ export const ROUTES = [
391
408
  { method: "POST", pattern: /^\/quotes$/, name: "createQuote", capability: "quotes" },
392
409
  { method: "GET", pattern: /^\/usage$/, name: "getUsage" },
393
410
  { method: "GET", pattern: /^\/stats$/, name: "getStats" },
411
+ // The runs waiting and held, the live runners and their free slots, and the recent hand-backs (capacity.ts).
412
+ { method: "GET", pattern: /^\/capacity$/, name: "getCapacity" },
394
413
  { method: "GET", pattern: /^\/settings\/tool-keys$/, name: "listToolKeys" },
395
414
  { method: "PUT", pattern: /^\/settings\/tool-keys\/([^/]+)$/, name: "saveToolKey" },
396
415
  { method: "DELETE", pattern: /^\/settings\/tool-keys\/([^/]+)$/, name: "deleteToolKey" },
@@ -477,6 +496,8 @@ export const ROUTES = [
477
496
  // Answered before routing (mcp.ts), with the token only: listed here for the document.
478
497
  { method: "POST", pattern: /^\/mcp$/, name: "callMcp" },
479
498
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning$/, name: "getAgentLearning" },
499
+ // The agent's learning reset, the agent and its runs kept (learning-reset.ts).
500
+ { method: "DELETE", pattern: /^\/agents\/([^/]+)\/learning$/, name: "deleteAgentLearning" },
480
501
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/cost$/, name: "getLearningCost" },
481
502
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/promotions$/, name: "listLearningPromotions" },
482
503
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/audits$/, name: "listLearningAudits" },
@@ -946,6 +967,11 @@ async function startHolding(options, data, checked, stops) {
946
967
  // there is no keeping one in the clear.
947
968
  const seal = await bootSealKey(store, data);
948
969
  stops.push(async () => seal.release());
970
+ // What a runner apart reads to tell its disk from this server's, and its environment's gaps (runner/disk-free.ts,
971
+ // runner/runner-check.ts): this data root's id, and the names (never the values) of the run-facing environment this
972
+ // server holds, each said in the store at every start, replacing the last start's.
973
+ await recordDataRoot(store, data);
974
+ await recordRunEnv(store, runFacingNames((name) => secret(name) ?? base[name], Object.keys(base)));
949
975
  // Its runners on other hosts (AGENTRUN_RUNNER_HOSTS): a viewer's row naming one of their hosts is dialled there, with
950
976
  // the proxy's proof under the seal key (live-reach.ts); any other host is never dialled. A hosted machine a runner in a
951
977
  // process of its own made is relayed to that runner's attach listener the same way (dial-relay.ts).
@@ -1399,6 +1425,31 @@ async function startHolding(options, data, checked, stops) {
1399
1425
  if (!row || FINAL_STATES.includes(row.state))
1400
1426
  await uploads.release(runId);
1401
1427
  }
1428
+ // Mode 2 (uploads-archil.ts): the uploads on this server's own Archil disk, and each run's placed in its folder at its
1429
+ // start, so its runner reads no upload. Mode 1 keeps them in this data directory (uploads above), as before.
1430
+ const archilFiles = archilUploads({ store, sealKey, env: withSecrets(process.env, "own"), ...(options.archilControl ? { control: options.archilControl } : {}) });
1431
+ /** Where the files routes find uploads now: the uploads disk in Mode 2, else this data directory. `make`: an upload,
1432
+ * which makes the uploads disk when there is none. */
1433
+ const uploadsHere = async (make = false) => (await archilFiles.here(make)) ?? uploads;
1434
+ const uploadRetention = uploadRetentionMs(options.uploadRetention ?? process.env[UPLOAD_RETENTION_ENV]);
1435
+ if (uploadRetention !== undefined) {
1436
+ // An uploaded file no run names, older than the retention, is deleted from the uploads disk (Mode 2 only): once an
1437
+ // hour, each sweep after the last one ends.
1438
+ let sweeping = Promise.resolve();
1439
+ const sweepUploads = () => {
1440
+ sweeping = sweeping.then(async () => {
1441
+ const removed = await archilFiles.sweep(uploadRetention, runKeepsUploads(store));
1442
+ if (removed.length)
1443
+ log?.(logLine("uploads_expired", { removed: removed.length }));
1444
+ }).catch((error) => void log?.(logLine("uploads_sweep_failed", { why: String(error?.message ?? error).slice(0, 300) })));
1445
+ };
1446
+ const uploadsTimer = setInterval(sweepUploads, UPLOAD_SWEEP_EVERY_MS);
1447
+ uploadsTimer.unref();
1448
+ stops.push(async () => {
1449
+ clearInterval(uploadsTimer);
1450
+ await sweeping;
1451
+ });
1452
+ }
1402
1453
  const documents = options.documents ?? process.env[DOCUMENTS_ENV];
1403
1454
  if (documents !== undefined && !(await stat(documents).then((info) => info.isDirectory(), () => false)))
1404
1455
  throw new Error(`the documents directory ${documents} is not a directory`);
@@ -1451,7 +1502,7 @@ async function startHolding(options, data, checked, stops) {
1451
1502
  // no box relay here — a runner (its own process, sharing only this store) claims and runs every run. The leaves a start
1452
1503
  // needs that live in this request layer are gathered once as StartDeps; the run's model is resolved once, now (the runner
1453
1504
  // reads launch.model alone).
1454
- const modelOf = (_entry, revision) => nativeOf(revision.body) ? Promise.resolve(undefined) : runModelRef(env, revision);
1505
+ const modelOf = (_entry, revision) => (nativeOf(revision.body) || cliLearningOf(revision.body)) ? Promise.resolve(undefined) : runModelRef(env, revision);
1455
1506
  // Why no runner here can take a run, while every runner there refused to claim (runner/presence.ts): read from the
1456
1507
  // store at each start, capabilities and health answer, so a runner in another process (or on another host over one
1457
1508
  // Postgres) counts as the one beside this server does, and a runner that can claim, once there, clears it at once.
@@ -1487,8 +1538,8 @@ async function startHolding(options, data, checked, stops) {
1487
1538
  told: (error) => told(error),
1488
1539
  runnable,
1489
1540
  pinFirst: (revision) => pinFirst(revision),
1490
- readyFiles: (ids) => uploads.readyFiles(ids),
1491
- files: { hold: (runId, ids) => uploads.hold(runId, ids), release: (runId) => uploads.release(runId) },
1541
+ readyFiles: async (ids) => (await uploadsHere()).readyFiles(ids),
1542
+ files: { hold: (runId, ids) => uploads.hold(runId, ids), release: (runId) => uploads.release(runId), place: (runId, agentId, launch) => archilFiles.place(runId, agentId, launch) },
1492
1543
  fallbackPlace: (kind, tools) => fallbackPlace(kind, tools),
1493
1544
  // The run's Archil disk for its launch record (run-launch.ts archilDisk): the body's, else its agent's when it has one.
1494
1545
  // A disk the body names is read at Archil once, before the run is made (archil-routes.ts checkLaunchDisk): one that is
@@ -1569,7 +1620,7 @@ async function startHolding(options, data, checked, stops) {
1569
1620
  // (liveViewerLink, the one the runner's browser tool wrote under its claim), opened with the server's seal key. The
1570
1621
  // timeline route keeps its own stub (store-reads journal + SSE) until E2c's timeline lands.
1571
1622
  const runReadsDeps = {
1572
- runWorkspace: (_store, runId) => serverRunWorkspace(store, runId, { data, sealKey, env: withSecrets(process.env, "own") }),
1623
+ runWorkspace: (_store, runId) => serverRunWorkspace(store, runId, { data, sealKey, env: withSecrets(process.env, "own"), ...(options.archilControl?.makeDisk ? { makeDisk: options.archilControl.makeDisk } : {}) }),
1573
1624
  recordings: async (_store, runId) => {
1574
1625
  const run = await store.runs.get(runId);
1575
1626
  return run ? recordingsWorkspace(recordingsFolder(data, run.agentId, runId)) : null;
@@ -2271,11 +2322,42 @@ async function startHolding(options, data, checked, stops) {
2271
2322
  throw new ApiError("unavailable", `${error.message.replace(/[.\s]*$/, "")}. ${again}`, { retry_after_ms: 5_000 });
2272
2323
  }
2273
2324
  };
2325
+ /** The Archil disks agent `agentId`'s learning folder may be on: a Mode 2 run's end writes it on the disk its claim
2326
+ * mounted (workspace/learning-workspace.ts, at learningKey), the agent's stored disk (named here only for
2327
+ * `agentDisk`) or one a launch named (kind "launch", a customer's: each run's disk, learn/learning-of.ts namedDisksOf,
2328
+ * read off its row, so a purged run whose launch is gone still names it). A run's kept disk, or a launch's kind
2329
+ * "agent", is the agent's own disk, mounted only while it is still the stored one (workspace/run-disk.ts runDiskOf):
2330
+ * one no longer stored was removed at Archil, its folder with it. */
2331
+ const learningDisksOf = async (agentId, agentDisk) => {
2332
+ const disks = new Set();
2333
+ const stored = agentDisk ? await agentDiskOf(store, agentId) : undefined;
2334
+ if (stored)
2335
+ disks.add(stored.diskId);
2336
+ for (const disk of await namedDisksOf(store, agentId))
2337
+ disks.add(disk);
2338
+ return [...disks];
2339
+ };
2340
+ /** Step 2 of DELETE /agents/{id}, and DELETE /agents/{id}/learning: the learning module's delete over the agent's
2341
+ * learning folder on this server's disk, as the learning routes open it (learningFolderOf), which deleteLearning ends
2342
+ * in its finally, and over its folder on each Archil disk a launch of its runs named and, for a reset (`agentDisk`),
2343
+ * on its own disk, which the agent's delete removes whole in step 3 (archil-routes.ts removeLearningFolder; Archil
2344
+ * off or refusing is 503 unavailable, nothing here deleted, for the next call). */
2345
+ const learningDelete = options.deleteLearning ?? ((given, agentId, { keepResetLedger = false, agentDisk = false } = {}) => deleteLearning(given, agentId, learningFolderOf(data, agentId), {
2346
+ keepResetLedger,
2347
+ elsewhere: async () => {
2348
+ for (const diskId of await learningDisksOf(agentId, agentDisk)) {
2349
+ try {
2350
+ await archil.removeLearningFolder(agentId, diskId);
2351
+ }
2352
+ catch (error) {
2353
+ if (!(error instanceof ApiError && ["unavailable", "upstream_failed"].includes(error.code)))
2354
+ throw error;
2355
+ throw new ApiError("unavailable", `${error.message.replace(/[.\s]*$/, "")}. The agent's learning folder on this server and its learning records are kept: send the DELETE again once it can be reached.`, { retry_after_ms: 5_000 });
2356
+ }
2357
+ }
2358
+ },
2359
+ }));
2274
2360
  /** What DELETE /agents/{id} does outside the store's rows, on this server (agent-delete.ts AgentDeleteHost). */
2275
- /** Step 2 of DELETE /agents/{id}: the learning module's delete over the agent's learning folder on this server's disk,
2276
- * as the learning routes open it (learningFolderOf), which deleteLearning ends in its finally. A learning folder on
2277
- * the agent's Archil disk goes with that disk in step 3. */
2278
- const learningDelete = options.deleteLearning ?? ((given, agentId) => deleteLearning(given, agentId, learningFolderOf(data, agentId)));
2279
2361
  const agentDeleteHost = {
2280
2362
  store,
2281
2363
  deleteLearning: learningDelete,
@@ -2327,8 +2409,11 @@ async function startHolding(options, data, checked, stops) {
2327
2409
  // DELETE. A run on its agent's own disk: with its agent's delete that disk went whole (removeDisk), its folder with
2328
2410
  // it; deleted alone, its folder there is deleted, the disk kept, read from its disk setting, which goes after.
2329
2411
  const launched = await store.runs.launch(runId).then((row) => readLaunchBody(row.body)?.archilDisk, (error) => (error instanceof StoreLaunchMissing ? undefined : Promise.reject(error)));
2330
- if (launched?.kind === "launch")
2412
+ // The agent's learning folder there too: a Mode 2 end wrote the run's diff and correction in it, and nothing reads it.
2413
+ if (launched?.kind === "launch") {
2331
2414
  await notYetWith(() => archil.removeRunFolder(agentId, runId, launched.diskId), ["unavailable", "upstream_failed"], again);
2415
+ await notYetWith(() => archil.removeLearningFolder(agentId, launched.diskId), ["unavailable", "upstream_failed"], again);
2416
+ }
2332
2417
  else if (alone) {
2333
2418
  const own = launched?.diskId ?? (await runDiskKept(store, runId));
2334
2419
  if (own)
@@ -2374,6 +2459,16 @@ async function startHolding(options, data, checked, stops) {
2374
2459
  pollMs: 200,
2375
2460
  ...(options.agentDeleteAt ? { at: options.agentDeleteAt } : {}),
2376
2461
  };
2462
+ /** What DELETE /agents/{id}/learning does outside the learning module (learning-reset.ts): the agent delete's learning
2463
+ * step, cancel path and wait, and the agent's learning queue, where a run's start reads its seed. */
2464
+ const learningResetHost = {
2465
+ store,
2466
+ deleteLearning: learningDelete,
2467
+ cancel: agentDeleteHost.cancel,
2468
+ inQueue: (agentId, work) => withAgentRepo(data, agentId, work),
2469
+ waitMs: agentDeleteHost.waitMs,
2470
+ pollMs: agentDeleteHost.pollMs,
2471
+ };
2377
2472
  // A run's live moment from the store (store-view momentOf), for the one acceptance each act a run takes reads. The run
2378
2473
  // routes read from the store + the run view now, not a live Run.
2379
2474
  async function needRun(id) {
@@ -2482,6 +2577,8 @@ async function startHolding(options, data, checked, stops) {
2482
2577
  * does not have yet. `capped`: the run has a spend cap, which a web tool's resolution reads (tool-plane.ts). `price`:
2483
2578
  * what prices an OpenRouter decision model under that cap; a start's reads OpenRouter's catalog (decisionPrice). */
2484
2579
  async function runnable(revision, place, { capped = false, price = decisionPrice } = {}) {
2580
+ if (cliLearningOf(revision.body))
2581
+ throw new ApiError("agent_not_runnable", "Continue in the original CLI session; this connection records learning without launching its tools.");
2485
2582
  if (sdkOf(revision.body))
2486
2583
  throw new ApiError("agent_not_runnable", "This agent runs in its backend SDK. Call its SDK wrapper to start a task; AgentRun does not launch its tools or credentials.");
2487
2584
  const native = nativeOf(revision.body);
@@ -2614,7 +2711,7 @@ async function startHolding(options, data, checked, stops) {
2614
2711
  return undefined;
2615
2712
  try {
2616
2713
  return mcpPinOf(granted, { server: (name) => { const kept = carried.get(name); if (kept)
2617
- return kept; const listing = listings.get(name); return listing && { url: listing.url, tools: listing.tools.map(boundTool), prices: listing.prices }; } });
2714
+ return kept; const listing = listings.get(name); return listing && { url: listing.url, tools: listing.tools.map(boundTool), prices: listing.prices, toolkit: listing.toolkit }; } });
2618
2715
  }
2619
2716
  catch (error) {
2620
2717
  throw invalid([{ field: "definition.tools", reason: "not_an_option", message: error.message }]);
@@ -2647,7 +2744,7 @@ async function startHolding(options, data, checked, stops) {
2647
2744
  throw invalid(execution.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_EXECUTION_SETTINGS_UNSUPPORTED })));
2648
2745
  return { warnings: [], stamp: {} };
2649
2746
  }
2650
- if (sdkOf(body))
2747
+ if (cliLearningOf(body) || sdkOf(body))
2651
2748
  return { warnings: [], stamp: {} };
2652
2749
  // An agent on a harness that installs on first use starts its install, if it is not in yet: its first run waits for less.
2653
2750
  const harnessId = revision.kind === "agentic" ? harnessOfBody(body) : undefined;
@@ -2980,7 +3077,10 @@ async function startHolding(options, data, checked, stops) {
2980
3077
  // (catchup_window_s and max_active_runs the package leaves out back to their defaults, as a fresh apply makes them); a new name is made; one the package
2981
3078
  // marked and no longer lists is removed (`removing`). Each trigger the apply makes or keeps is marked as the package's; each write to one the agent had is made only while it
2982
3079
  // is still the agent's: one a PATCH moved away meanwhile is neither changed nor removed, and its name is made anew.
2983
- const ids = [];
3080
+ // Each trigger it made or kept, in the package's order, as it stands after its write: the answer's triggers (its id,
3081
+ // its name, its kind, and whether it is on).
3082
+ const answered = [];
3083
+ const list = (view) => answered.push({ trigger_id: view.id, name: view.name, kind: view.source.kind, enabled: view.enabled });
2984
3084
  // The triggers this apply made (never one it changed in place): what a refusal's undo removes.
2985
3085
  const madeNow = [];
2986
3086
  // Each webhook trigger's signing secret, minted as it is made: handed back in the apply's first answer alone, as POST
@@ -3014,8 +3114,9 @@ async function startHolding(options, data, checked, stops) {
3014
3114
  // The package's settings whole: one its version leaves out goes back to what a fresh apply makes (POST
3015
3115
  // /triggers' default), never kept from the version before. PATCH reads null as no cap.
3016
3116
  const patch = { ...sent, catchup_window_s: sent.catchup_window_s ?? CATCHUP_WINDOW_S, max_active_runs: sent.max_active_runs ?? null };
3017
- if (await triggers.update(was.id, source ? { ...patch, source } : patch, own).then(() => true, movedAway)) {
3018
- ids.push(was.id);
3117
+ const changed = await triggers.update(was.id, source ? { ...patch, source } : patch, own).catch(movedAway);
3118
+ if (changed) {
3119
+ list(changed);
3019
3120
  continue;
3020
3121
  }
3021
3122
  was = undefined;
@@ -3030,8 +3131,9 @@ async function startHolding(options, data, checked, stops) {
3030
3131
  was = undefined;
3031
3132
  else if (isObject(left) && isObject(left.composio) && left.composio.done === false)
3032
3133
  throw new ApiError("upstream_failed", `The ${pkg.name} template's trigger ${String(trigger.name).trim()} changed, so its old Composio trigger instance must go before the new one is made, and Composio didn't delete it: the new one was not made, and the old trigger is kept here as it was. ${String(left.composio.note ?? "")} Then apply again.`.trim());
3033
- const { id: madeId, secret } = await triggers.create(was && !was.enabled ? { ...aimed, enabled: false } : aimed, { templateId: pkg.id });
3034
- ids.push(madeId);
3134
+ const created = await triggers.create(was && !was.enabled ? { ...aimed, enabled: false } : aimed, { templateId: pkg.id });
3135
+ const { id: madeId, secret } = created;
3136
+ list(created);
3035
3137
  madeNow.push(madeId);
3036
3138
  if (secret)
3037
3139
  secrets.push({ trigger_id: madeId, secret });
@@ -3095,7 +3197,10 @@ async function startHolding(options, data, checked, stops) {
3095
3197
  const minted = new Map(secrets.map(({ trigger_id, secret }) => [trigger_id, secret]));
3096
3198
  // Which saved server each MCP need runs on (null: none here, said under mcp.<toolkit>).
3097
3199
  const used = Object.fromEntries(mapped.map(({ need, server }) => [need.toolkit, server]));
3098
- const applied = { template: pkg.id, version: pkg.version, agent_id: entry.agent.id, revision_version: entry.version, servers: used, trigger_ids: ids, ...templateWebhookSecrets([...minted.keys()], new Date().toISOString()), warnings: [...skipped, ...kept, ...modelWarnings, ...computerWarnings, ...unpinned, ...warnings, ...hooks, ...githubTriggers, ...composioSkipped, ...feedsSkipped, ...leftThere, ...appShort, ...twins] };
3200
+ // What the apply did to the agent: made it, wrote a new revision, or wrote none (an update whose package and
3201
+ // parameters the current revision already holds: commitAgent keeps that revision).
3202
+ const agentChange = !onto ? "made" : entry.revision?.id === onto.revision?.id ? "unchanged" : "updated";
3203
+ const applied = { template: pkg.id, version: pkg.version, agent_id: entry.agent.id, revision_version: entry.version, agent_change: agentChange, servers: used, triggers: answered, ...templateWebhookSecrets([...minted.keys()], new Date().toISOString()), warnings: [...skipped, ...kept, ...modelWarnings, ...computerWarnings, ...unpinned, ...warnings, ...hooks, ...githubTriggers, ...composioSkipped, ...feedsSkipped, ...leftThere, ...appShort, ...twins] };
3099
3204
  return { applied, minted, updated: onto !== undefined };
3100
3205
  }
3101
3206
  /** A run create's issues told from the input this server checks (explain.ts): an agentic run's input schema in force
@@ -3264,6 +3369,8 @@ async function startHolding(options, data, checked, stops) {
3264
3369
  * (runs-over-store startInline). The answer is POST /agents/{agent_id}/runs' own: 202 and the run. */
3265
3370
  async function createInlineRun(req) {
3266
3371
  const { body, handed } = handedLaunchSecrets(await bodyOf(req));
3372
+ if (isObject(body.definition) && body.definition.cli_learning !== undefined)
3373
+ throw new ApiError("input_invalid", "CLI learning references are registered only through /cli-learning/connections on the source machine.");
3267
3374
  if (isObject(body.definition) && body.definition.native !== undefined)
3268
3375
  throw new ApiError("input_invalid", "Native references are registered only through /native/connect on the source machine; an inline definition cannot create one.");
3269
3376
  const { external, definition, skills, note, revision: pinned, ...run } = body;
@@ -3916,7 +4023,11 @@ async function startHolding(options, data, checked, stops) {
3916
4023
  // runner_refused: why no runner here can take a run, in their words, while every runner there refused to claim
3917
4024
  // (runner/presence.ts); null while one can, or none is there yet.
3918
4025
  const runnerRefused = (await refusedNow().catch(() => undefined)) ?? null;
3919
- return send(res, 200, { ...answer, runner_refused: runnerRefused, features: { ...answer.features, computers: await computerCapabilities(computersOf()), triggers: { ...answer.features.triggers, public_url: Boolean(options.publicUrl) } } });
4026
+ // store_schema: the store's version and runner floor now, beside this build's (Store.schemaState), for a deploy's
4027
+ // skew check; left out when the store cannot say (a read that failed).
4028
+ const state = await store.schemaState?.().catch(() => undefined);
4029
+ const storeSchema = state ? { store_schema: { version: state.version, runner_floor: state.runnerFloor, known: state.known } } : {};
4030
+ return send(res, 200, { ...answer, ...storeSchema, runner_refused: runnerRefused, features: { ...answer.features, computers: await computerCapabilities(computersOf()), triggers: { ...answer.features.triggers, public_url: Boolean(options.publicUrl) } } });
3920
4031
  }
3921
4032
  if (found.name === "getOpenapi")
3922
4033
  return send(res, 200, servedOpenapi(openapi, req.socket.localPort));
@@ -4028,13 +4139,13 @@ async function startHolding(options, data, checked, stops) {
4028
4139
  authFailed(`/v2${path}`, "approve_without_session");
4029
4140
  throw new ApiError("forbidden", owner ? "Answering a tool call's approval takes the owner's password sign-in in the console, never a token." : "Answering a tool call's approval takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
4030
4141
  }
4031
- // Purging a run or an agent, or deleting another system's agent, cannot be undone: the owner's session or the API
4032
- // token. A console session counts as the owner's only where it does for a secret (secret-writes.ts: accounts off on a
4033
- // loopback-bound server); bound off loopback with accounts off, whoever opened the console is no owner. With no
4034
- // credential at all it is 401, as every route is.
4035
- if ((found.name === "deleteRun" || found.name === "deleteAgent") && byConsoleSession(req) && !writesSecretsAllowed(req, { accounts: owner !== undefined, loopbackBound: isLoopback(host) })) {
4142
+ // Purging a run or an agent, deleting another system's agent, or resetting an agent's learning cannot be undone: the
4143
+ // owner's session or the API token. A console session counts as the owner's only where it does for a secret
4144
+ // (secret-writes.ts: accounts off on a loopback-bound server); bound off loopback with accounts off, whoever opened the
4145
+ // console is no owner. With no credential at all it is 401, as every route is.
4146
+ if ((found.name === "deleteRun" || found.name === "deleteAgent" || found.name === "deleteAgentLearning") && byConsoleSession(req) && !writesSecretsAllowed(req, { accounts: owner !== undefined, loopbackBound: isLoopback(host) })) {
4036
4147
  authFailed(`/v2${path}`, "delete_without_owner");
4037
- throw new ApiError("forbidden", "Deleting a run or an agent takes the owner's session (the password sign-in, or the console on a server bound to loopback) or the API token.");
4148
+ throw new ApiError("forbidden", "Deleting a run or an agent, or resetting an agent's learning, takes the owner's session (the password sign-in, or the console on a server bound to loopback) or the API token.");
4038
4149
  }
4039
4150
  // Saving, replacing or removing a secret (secret-writes.ts): the one check. Who may is mayWriteSecrets' alone (the
4040
4151
  // owner's session); which writes are secret is each plane's registered predicate, read from the body, so a token's
@@ -4094,6 +4205,48 @@ async function startHolding(options, data, checked, stops) {
4094
4205
  const commandId = decodeURIComponent(parts[2]);
4095
4206
  return send(res, 200, found.name === "remoteCommandEvents" ? await broker.events(connectorId, commandId, body) : await broker.complete(connectorId, commandId, body));
4096
4207
  }
4208
+ if (found.name === "startCliLearningRun") {
4209
+ if (options.apiOnly || options.publicUrl || !isLoopback(host) || !isLoopback(req.socket.remoteAddress ?? ""))
4210
+ throw new ApiError("forbidden", "CLI learning runs require the enrolled local source server.");
4211
+ const connectionId = decodeURIComponent(found.pattern.exec(path)[1]);
4212
+ const broker = new CliLearningConnections(store, sdkSecret);
4213
+ const connection = await broker.authenticate(connectionId, String(req.headers.authorization ?? "").replace(/^Bearer /, ""));
4214
+ if (!req.headers["idempotency-key"])
4215
+ throw new ApiError("bad_request", "A CLI prompt window requires Idempotency-Key.");
4216
+ const body = await bodyOf(req);
4217
+ if (Object.keys(body).some(key => !["session_id", "turn_id", "input", "instructions", "policy_complete", "model"].includes(key)) || typeof body.session_id !== "string" || !body.session_id || body.session_id.length > 256 || typeof body.turn_id !== "string" || !body.turn_id || body.turn_id.length > 256 || typeof body.policy_complete !== "boolean")
4218
+ throw new ApiError("input_invalid", "Supply session_id, turn_id, input, instructions, and explicit policy_complete.");
4219
+ const entry = await needAgent(connection.agent_id);
4220
+ const runtime = NATIVE_RUNTIME_FACTS[connection.runtime].captureRuntime;
4221
+ const sdk = new SdkRuns(store, data, sdkSecret, () => [...serverSecrets(), broker.token(connection)], [], "cli");
4222
+ const input = { runtime, input: body.input, instructions: body.instructions, ...(body.model !== undefined ? { model: body.model } : {}) };
4223
+ const key = `cli-window:${connectionId}:${connection.generation}:${createHash("sha256").update(`${body.session_id}\0${body.turn_id}`).digest("hex")}`;
4224
+ const fingerprint = createHash("sha256").update(stable(body)).digest("hex");
4225
+ const answer = await idempotent(req, `${path}:${connection.generation}`, body, async () => ({ status: 201, body: await sdk.start(entry, input, startDeps, { key, fingerprint }, { check: async () => { } }, linkOrigin(req), { runtime, connection_id: connectionId, connection_generation: connection.generation, session_id: body.session_id, turn_id: body.turn_id, instructions: String(body.instructions ?? ""), policy_complete: body.policy_complete }) }));
4226
+ const receipt = await sdk.receipt(answer.body.run_id, linkOrigin(req));
4227
+ await broker.recordWindow(connectionId, connection.generation, receipt.run_id, body.session_id);
4228
+ return send(res, answer.status, receipt, answer.headers);
4229
+ }
4230
+ if (["getCliLearningRun", "cliLearningEvents", "completeCliLearningRun"].includes(found.name)) {
4231
+ const runId = decodeURIComponent(found.pattern.exec(path)[1]);
4232
+ const authentication = new SdkRuns(store, data, sdkSecret, serverSecrets, [], "cli");
4233
+ await authentication.authenticate(runId, String(req.headers.authorization ?? "").replace(/^Bearer /, ""));
4234
+ const launch = (await store.runs.launch(runId)).body;
4235
+ if (!launch.cli_learning)
4236
+ throw new ApiError("not_found", "This is not a CLI learning prompt window.");
4237
+ const connection = await new CliLearningConnections(store, sdkSecret).get(launch.cli_learning.connection_id);
4238
+ if (!connection.active || connection.generation !== launch.cli_learning.connection_generation)
4239
+ throw new ApiError("unauthenticated", "The CLI learning connection was disconnected.");
4240
+ const sdk = new SdkRuns(store, data, sdkSecret, () => [...serverSecrets(), new CliLearningConnections(store, sdkSecret).token(connection)], [], "cli");
4241
+ if (found.name === "cliLearningEvents")
4242
+ return send(res, 200, await sdk.events(runId, await bodyOf(req)));
4243
+ if (found.name === "completeCliLearningRun") {
4244
+ const result = await sdk.complete(runId, await bodyOf(req));
4245
+ await new CliLearningConnections(store, sdkSecret).recordWindow(connection.connection_id, connection.generation, runId, launch.cli_learning.session_id);
4246
+ return send(res, 200, result);
4247
+ }
4248
+ return send(res, 200, { ...await sdk.status(runId), learning: await servedRunLearning({ serverSecrets, signIns, statuses }, store, runId) });
4249
+ }
4097
4250
  if (["getSdkRun", "sdkRunEvents", "completeSdkRun"].includes(found.name)) {
4098
4251
  const runId = decodeURIComponent(found.pattern.exec(path)[1]);
4099
4252
  const sdk = new SdkRuns(store, data, sdkSecret, serverSecrets, tokens.map((entry) => entry.token));
@@ -4110,7 +4263,7 @@ async function startHolding(options, data, checked, stops) {
4110
4263
  }
4111
4264
  if (found.capability)
4112
4265
  throw unsupported(found.capability, UNSUPPORTED[found.capability]);
4113
- if (["discoverNative", "connectNative"].includes(found.name) && (options.apiOnly || options.publicUrl || !isLoopback(host)))
4266
+ if (["discoverNative", "connectNative", "enrollCliLearning"].includes(found.name) && (options.apiOnly || options.publicUrl || !isLoopback(host)))
4114
4267
  throw new ApiError("forbidden", "Native connections require AgentRun on the source machine, bound to loopback without a public URL. A hosted browser cannot discover your laptop.");
4115
4268
  const [, first, second] = found.pattern.exec(path);
4116
4269
  const id = first ? decodeURIComponent(first) : "";
@@ -4129,6 +4282,13 @@ async function startHolding(options, data, checked, stops) {
4129
4282
  }
4130
4283
  }
4131
4284
  switch (found.name) {
4285
+ case "enrollCliLearning": {
4286
+ if (!isLoopback(req.socket.remoteAddress ?? ""))
4287
+ throw new ApiError("forbidden", "CLI learning enrollment must come from the local source machine.");
4288
+ return send(res, 201, await new CliLearningConnections(store, sdkSecret).enroll(await bodyOf(req)));
4289
+ }
4290
+ case "listCliLearning": return send(res, 200, await new CliLearningConnections(store, sdkSecret).list());
4291
+ case "revokeCliLearning": return send(res, 200, await new CliLearningConnections(store, sdkSecret).revoke(id));
4132
4292
  case "startSdkRun": {
4133
4293
  if (!req.headers["idempotency-key"])
4134
4294
  throw new ApiError("bad_request", "An SDK run requires Idempotency-Key so a retried start never duplicates execution.");
@@ -4157,7 +4317,7 @@ async function startHolding(options, data, checked, stops) {
4157
4317
  const days = Number(url.searchParams.get("days") ?? 30);
4158
4318
  if (!Number.isInteger(days) || days < 1 || days > 31)
4159
4319
  throw new ApiError("input_invalid", "Choose an observation window from 1 to 31 days.");
4160
- return send(res, 200, await new Observations(store).snapshot(days, url.searchParams.get("session_id") ?? undefined));
4320
+ return send(res, 200, await new Observations(store, Date.now, new ObservationLearning(store, new CliLearningConnections(store, sdkSecret), learning !== "off")).snapshot(days, url.searchParams.get("session_id") ?? undefined));
4161
4321
  }
4162
4322
  case "listRemoteConnectors": return send(res, 200, await new RemoteConnectors(store).list());
4163
4323
  case "enrollRemoteConnector": return send(res, 200, await new RemoteConnectors(store).enroll(await bodyOf(req)));
@@ -4196,6 +4356,8 @@ async function startHolding(options, data, checked, stops) {
4196
4356
  }
4197
4357
  case "createAgent": {
4198
4358
  const body = await bodyOf(req);
4359
+ if (isObject(body.definition) && body.definition.cli_learning !== undefined)
4360
+ throw new ApiError("input_invalid", "CLI learning references are registered only through /cli-learning/connections on the source machine.");
4199
4361
  if (isObject(body.definition) && body.definition.native !== undefined)
4200
4362
  throw new ApiError("input_invalid", "Native references are registered only through /native/connect on the source machine.");
4201
4363
  const answer = await idempotent(req, "/agents", body, async () => {
@@ -4242,6 +4404,9 @@ async function startHolding(options, data, checked, stops) {
4242
4404
  // contract's is the definition itself, and takes the contract's preconditions: If-Match, and a version past the
4243
4405
  // current one.
4244
4406
  const contract = !("definition" in body);
4407
+ const cliEdit = contract ? body.cli_learning : isObject(body.definition) ? body.definition.cli_learning : undefined;
4408
+ if (cliEdit !== undefined && stable(cliEdit) !== stable(cliLearningOf(entry.revision?.body)))
4409
+ throw new ApiError("input_invalid", "CLI learning bindings are changed only through their enrollment endpoints.");
4245
4410
  const nativeEdit = contract ? body.native : isObject(body.definition) ? body.definition.native : undefined;
4246
4411
  if (nativeEdit !== undefined && stable(nativeEdit) !== stable(nativeOf(entry.revision?.body)))
4247
4412
  throw new ApiError("input_invalid", "Native references are changed only through the native connection endpoints. Normal edits retain the existing reference.");
@@ -4289,6 +4454,8 @@ async function startHolding(options, data, checked, stops) {
4289
4454
  const candidate = await agents.revision(id, revision);
4290
4455
  if (!candidate)
4291
4456
  throw invalid([{ field: "revision", reason: "not_an_option", message: `${revision} is not a revision of the agent ${id}` }]);
4457
+ if (stable(cliLearningOf(candidate.revision.body)) !== stable(cliLearningOf(entry.revision?.body)))
4458
+ throw new ApiError("input_invalid", "A revision restore cannot change the enrolled CLI learning connection.");
4292
4459
  if (stable(nativeOf(candidate.revision.body)) !== stable(nativeOf(entry.revision?.body)))
4293
4460
  throw new ApiError("input_invalid", "This revision changes the native connection. Reconnect or verify through the native connection controls; ordinary revision restore cannot change its source or connection state.");
4294
4461
  if (nativeOf(candidate.revision.body)) {
@@ -4310,8 +4477,8 @@ async function startHolding(options, data, checked, stops) {
4310
4477
  await deleteInTurn(id, async () => {
4311
4478
  const { agent } = await needAgent(id);
4312
4479
  if (agent.purgedAt !== null)
4313
- return;
4314
- if (agent.externalRef !== null)
4480
+ return purgedAgain(agentDeleteHost, id);
4481
+ if (ownedElsewhere(agent))
4315
4482
  return deleteExternalAgent(agentDeleteHost, id);
4316
4483
  if (agent.archivedAt === null)
4317
4484
  throw new ApiError("agent_not_archived", `The agent ${id} is not archived: archive it first (POST /v2/agents/${id}/archive), which stops new runs and turns its triggers off, then send the DELETE again. Nothing was purged.`);
@@ -4437,6 +4604,13 @@ async function startHolding(options, data, checked, stops) {
4437
4604
  const row = ID.test(id) ? await store.runs.get(id) : undefined;
4438
4605
  if (!row)
4439
4606
  throw new ApiError("not_found", `no run ${id}`);
4607
+ // API-only (api-only.ts): a run of an agent another system owns alone, for the backend whose inline runs made it,
4608
+ // as it deletes that agent; a run of an agent made here is the profile's refusal, in its words, as before.
4609
+ if (options.apiOnly) {
4610
+ const agent = await store.agents.get(row.agentId);
4611
+ if (!agent || !ownedElsewhere(agent))
4612
+ throw new ApiError("not_found", apiOnlyRefusal(`/v2${path}`));
4613
+ }
4440
4614
  await deleteInTurn(row.agentId, () => purgeRun(agentDeleteHost, id));
4441
4615
  res.writeHead(204, { "cache-control": "no-store", "x-content-type-options": "nosniff" });
4442
4616
  return void res.end();
@@ -4487,7 +4661,7 @@ async function startHolding(options, data, checked, stops) {
4487
4661
  throw invalid([{ field: "label", reason: "wrong_type", message: `label is a string of at most ${LABEL_MAX} characters: the grade's words` }]);
4488
4662
  // A run that reads ended while it still learns from that end (its look-back: store-view.ts lookingBackEnd) is graded
4489
4663
  // once that ends: its row is not ended yet, and the round a grade opens reopens only an ended run.
4490
- if (!FINAL_STATES.includes(row.state) && (await lookingBackEnd(store, row.id)))
4664
+ if (!FINAL_STATES.includes(row.state) && (await lookingBackEnd(store, row)))
4491
4665
  throw new ApiError("run_learning", "The run is still learning from its answer: grade it once that ends.");
4492
4666
  if (!FINAL_STATES.includes(row.state))
4493
4667
  throw invalid([{ field: "run_id", reason: "not_allowed", message: "A run is graded once it has ended." }]);
@@ -4770,8 +4944,9 @@ async function startHolding(options, data, checked, stops) {
4770
4944
  case "createFile": {
4771
4945
  // A `path` in the query, or a body that is not JSON: the file sent in one call, its bytes the body. Else the
4772
4946
  // contract's JSON reservation, its bytes sent after with PUT /files/{file_id}.
4947
+ const kept = await uploadsHere(true);
4773
4948
  if (url.searchParams.has("path") || !isJson(req)) {
4774
- const received = await uploads.take(url.searchParams, req.headers["content-type"], req);
4949
+ const received = await kept.take(url.searchParams, req.headers["content-type"], req);
4775
4950
  try {
4776
4951
  const answer = await idempotent(req, "/files", received.fingerprint, async () => ({ status: 201, body: await received.commit() }));
4777
4952
  return send(res, answer.status, answer.body, answer.headers);
@@ -4781,36 +4956,39 @@ async function startHolding(options, data, checked, stops) {
4781
4956
  }
4782
4957
  }
4783
4958
  const body = await bodyOf(req);
4784
- const answer = await idempotent(req, "/files", body, async () => ({ status: 201, body: await uploads.reserve(body) }));
4959
+ const answer = await idempotent(req, "/files", body, async () => ({ status: 201, body: await kept.reserve(body) }));
4785
4960
  return send(res, answer.status, answer.body, answer.headers);
4786
4961
  }
4787
4962
  case "uploadFile":
4788
- return send(res, 200, await uploads.receive(id, req));
4963
+ return send(res, 200, await (await uploadsHere()).receive(id, req));
4789
4964
  case "listFiles": {
4965
+ const kept = await uploadsHere();
4790
4966
  // This server's own: its uploads, newest first, a page at a time, so an id is never lost with the answer that gave it.
4791
4967
  const limit = limitOf(url.searchParams.get("limit"));
4792
4968
  const offset = cursorOf(url.searchParams.get("cursor"));
4793
- const ids = await uploads.ids();
4794
- const files = (await Promise.all(ids.slice(offset, offset + limit).map((fileId) => uploads.get(fileId)))).filter((file) => file !== null);
4969
+ const ids = await kept.ids();
4970
+ const files = (await Promise.all(ids.slice(offset, offset + limit).map((fileId) => kept.get(fileId)))).filter((file) => file !== null);
4795
4971
  return send(res, 200, { files, next_cursor: nextCursor(offset + limit, ids.length) });
4796
4972
  }
4797
4973
  case "getFile": {
4798
- const file = await uploads.get(id);
4974
+ const file = await (await uploadsHere()).get(id);
4799
4975
  if (!file)
4800
4976
  throw new ApiError("not_found", `no file ${id}: GET /v2/files lists the files this server keeps`);
4801
4977
  return send(res, 200, file);
4802
4978
  }
4803
4979
  case "deleteFile":
4804
- await uploads.remove(id);
4980
+ await (await uploadsHere()).remove(id);
4805
4981
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
4806
4982
  case "getUsage":
4807
4983
  return send(res, 200, await usage(url));
4984
+ case "getCapacity":
4985
+ return send(res, 200, await capacityOverStore(store.runners, capacityWindowOf(url)));
4808
4986
  case "getStats": {
4809
4987
  const filter = analyticsFilter(url);
4810
4988
  // The store's counts and cost sums (store-reads/stats), the runs' metrics summed (store-reads/analytics), and the
4811
4989
  // runs over the store for the learning counts. No in-process pending set and no held Runs: the runner writes a
4812
4990
  // run's end to the store before it lets it go.
4813
- const [s, a] = await Promise.all([statsOverStore(store), analyticsOverStore(store, { ...filter })]);
4991
+ const [s, a, tokens] = await Promise.all([statsOverStore(store), analyticsOverStore(store, { ...filter }), unifiedUsage(store, filter)]);
4814
4992
  // Each running row's status over the store (viewOverStore), for the active/needs_input/unknown buckets.
4815
4993
  const vd = viewDepsFor(ownOriginOf());
4816
4994
  const runningStatus = new Map();
@@ -4819,7 +4997,7 @@ async function startHolding(options, data, checked, stops) {
4819
4997
  // How the runs that tried to learn fared, over the store (learning-1's learningCountsOverStore): the same figures the
4820
4998
  // ledger gave, run for run; no held run's learning from memory.
4821
4999
  const learning = await learningCountsOverStore(store, filter);
4822
- return send(res, 200, { ...statsView(s, (id) => runningStatus.get(id)), analytics: analyticsView(a, filter), learning });
5000
+ return send(res, 200, { ...statsView(s, (id) => runningStatus.get(id)), analytics: { ...analyticsView(a, filter), usage: tokens }, learning });
4823
5001
  }
4824
5002
  case "listToolKeys":
4825
5003
  // The offers the server holds, not capabilities': a model key's row names the harnesses its key would run too.
@@ -5180,6 +5358,15 @@ async function startHolding(options, data, checked, stops) {
5180
5358
  const written = await agentWrite(id, () => correctionsWrite(data, id, { text, ifMatch: typeof req.headers["if-match"] === "string" ? req.headers["if-match"] : undefined, refuse }));
5181
5359
  return send(res, 200, written, { etag: written.etag });
5182
5360
  }
5361
+ case "deleteAgentLearning": {
5362
+ // The agent's learning reset (learning-reset.ts), a write to its learning: in its delete turn (agentWrite), which
5363
+ // reads the agent there (404 unknown) and refuses one being deleted.
5364
+ await agentWrite(id, () => resetLearning(learningResetHost, id));
5365
+ // A run's list row that read a workflow of the agent's says what the folder says now, at the next list.
5366
+ await lister.learningChanged(id);
5367
+ res.writeHead(204, { "cache-control": "no-store", "x-content-type-options": "nosniff" });
5368
+ return void res.end();
5369
+ }
5183
5370
  case "listLearnedWorkflowRevisions":
5184
5371
  await needAgent(id);
5185
5372
  return send(res, 200, await workflowRevisions(data, id, second, url.searchParams, await learningShown(id)));
@@ -5525,7 +5712,7 @@ async function startHolding(options, data, checked, stops) {
5525
5712
  if (answerPage(req, res, raw, { token, authFailed, console: options.console, takesBytes, ...(owner ? { owner } : {}), ...(consoleSessions ? { sessions: consoleSessions } : {}), ...(options.publicUrl ? { publicUrl: options.publicUrl } : {}) }))
5526
5713
  return;
5527
5714
  if (isObservationRoute(raw))
5528
- return void observationHttp(req, res, url, new Observations(store), (header) => bearer(header, req)).catch(fail);
5715
+ return void observationHttp(req, res, url, new Observations(store, Date.now, new ObservationLearning(store, new CliLearningConnections(store, sdkSecret), learning !== "off")), (header) => bearer(header, req)).catch(fail);
5529
5716
  if (!raw.startsWith("/v2/"))
5530
5717
  return fail(new ApiError("not_found", `no route ${raw}; the API is under /v2`));
5531
5718
  // A run's id needs no decoding: one that is not an id as sent (a stray or malformed escape) is no run's, and is never