@parcha/agentrun-serve 0.1.0-beta.34 → 0.1.0-beta.35

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 (227) hide show
  1. package/CHANGELOG.md +135 -0
  2. package/README.md +84 -16
  3. package/dist/adapters.d.ts +3 -0
  4. package/dist/adapters.js +7 -0
  5. package/dist/agent-rows.d.ts +1 -0
  6. package/dist/agents-store.js +17 -2
  7. package/dist/archil-settings.d.ts +11 -1
  8. package/dist/archil-settings.js +10 -0
  9. package/dist/bash-read-only.d.ts +13 -0
  10. package/dist/bash-read-only.js +77 -0
  11. package/dist/browser-cost.d.ts +2 -2
  12. package/dist/browser-cost.js +6 -4
  13. package/dist/budget.d.ts +0 -5
  14. package/dist/budget.js +0 -5
  15. package/dist/cap.d.ts +6 -3
  16. package/dist/cap.js +7 -4
  17. package/dist/cli.js +32 -5
  18. package/dist/computer-keys.d.ts +20 -10
  19. package/dist/computer-keys.js +36 -57
  20. package/dist/computer-setting.d.ts +6 -5
  21. package/dist/computer-setting.js +54 -26
  22. package/dist/computers.d.ts +9 -4
  23. package/dist/computers.js +4 -2
  24. package/dist/console/assets/index-B7NKTU8E.css +1 -0
  25. package/dist/console/assets/index-CXZMgJE7.js +550 -0
  26. package/dist/console/index.html +2 -2
  27. package/dist/content-filter.d.ts +7 -0
  28. package/dist/content-filter.js +23 -0
  29. package/dist/decision-cap.d.ts +7 -29
  30. package/dist/decision-cap.js +3 -94
  31. package/dist/errors.d.ts +1 -0
  32. package/dist/errors.js +3 -0
  33. package/dist/explain.js +3 -1
  34. package/dist/github-connection.js +25 -7
  35. package/dist/github-faux.d.ts +26 -0
  36. package/dist/github-faux.js +76 -0
  37. package/dist/github.d.ts +6 -2
  38. package/dist/github.js +5 -3
  39. package/dist/graph-served.d.ts +5 -3
  40. package/dist/graph-served.js +14 -6
  41. package/dist/graph-view.js +5 -2
  42. package/dist/harness-opencode/harness.js +0 -1
  43. package/dist/harness-opencode/host/policy.js +2 -2
  44. package/dist/index.d.ts +1 -0
  45. package/dist/index.js +1 -0
  46. package/dist/learn/check.d.ts +3 -1
  47. package/dist/learn/check.js +3 -3
  48. package/dist/learn/folder.d.ts +6 -3
  49. package/dist/learn/folder.js +7 -16
  50. package/dist/learn/grade.d.ts +4 -1
  51. package/dist/learn/grade.js +43 -5
  52. package/dist/learn/index.d.ts +2 -2
  53. package/dist/learn/index.js +2 -2
  54. package/dist/learn/learning.sh +1 -14
  55. package/dist/learn/notes.d.ts +14 -3
  56. package/dist/learn/notes.js +16 -6
  57. package/dist/learn/reflect.js +5 -3
  58. package/dist/learn/skills.d.ts +48 -5
  59. package/dist/learn/skills.js +97 -21
  60. package/dist/learned-nodes.d.ts +14 -0
  61. package/dist/learned-nodes.js +8 -0
  62. package/dist/learned-workflow.d.ts +9 -5
  63. package/dist/learned-workflow.js +53 -9
  64. package/dist/learning-routes.d.ts +41 -0
  65. package/dist/learning-routes.js +94 -26
  66. package/dist/learning-run.d.ts +7 -5
  67. package/dist/learning-run.js +9 -6
  68. package/dist/learning.d.ts +0 -22
  69. package/dist/learning.js +0 -16
  70. package/dist/llm.d.ts +4 -1
  71. package/dist/llm.js +4 -2
  72. package/dist/mcp-gateway.d.ts +6 -0
  73. package/dist/mcp-gateway.js +11 -1
  74. package/dist/mcp-servers-store.d.ts +12 -12
  75. package/dist/model.d.ts +3 -0
  76. package/dist/model.js +8 -0
  77. package/dist/openapi.js +37 -13
  78. package/dist/paid-calls.js +1 -1
  79. package/dist/pause.d.ts +2 -19
  80. package/dist/pause.js +5 -74
  81. package/dist/port-models.d.ts +10 -3
  82. package/dist/port-models.js +26 -6
  83. package/dist/propose.d.ts +2 -0
  84. package/dist/propose.js +1 -10
  85. package/dist/run-launch.d.ts +5 -3
  86. package/dist/run-launch.js +6 -5
  87. package/dist/run-learning-served.d.ts +11 -0
  88. package/dist/run-reads-over-store.d.ts +4 -2
  89. package/dist/run-reads-over-store.js +10 -8
  90. package/dist/run-timeline-served.js +12 -2
  91. package/dist/run-view.d.ts +30 -14
  92. package/dist/run-view.js +60 -32
  93. package/dist/runnable.d.ts +4 -1
  94. package/dist/runnable.js +14 -2
  95. package/dist/runner/adapter-loop.d.ts +30 -4
  96. package/dist/runner/adapter-loop.js +253 -29
  97. package/dist/runner/adapter-run-spec.d.ts +21 -0
  98. package/dist/runner/adapter-run-spec.js +104 -28
  99. package/dist/runner/adapters/pi.d.ts +29 -1
  100. package/dist/runner/adapters/pi.js +95 -23
  101. package/dist/runner/beside.d.ts +8 -0
  102. package/dist/runner/beside.js +18 -0
  103. package/dist/runner/claim-secrets.d.ts +6 -0
  104. package/dist/runner/claim-secrets.js +15 -1
  105. package/dist/runner/cli-run-spec.d.ts +3 -0
  106. package/dist/runner/cli-run-spec.js +123 -34
  107. package/dist/runner/conformance/harness.d.ts +1 -0
  108. package/dist/runner/conformance/harness.js +5 -5
  109. package/dist/runner/github-app.d.ts +7 -2
  110. package/dist/runner/github-app.js +46 -15
  111. package/dist/runner/harness-loops.d.ts +6 -1
  112. package/dist/runner/harness-loops.js +23 -0
  113. package/dist/runner/journal-kinds.d.ts +38 -2
  114. package/dist/runner/journal-kinds.js +23 -0
  115. package/dist/runner/learning-end.js +88 -16
  116. package/dist/runner/learning-loop.d.ts +2 -0
  117. package/dist/runner/learning-loop.js +13 -5
  118. package/dist/runner/learning-seed.d.ts +6 -0
  119. package/dist/runner/learning-seed.js +6 -0
  120. package/dist/runner/loop-contract.d.ts +4 -0
  121. package/dist/runner/main.d.ts +9 -4
  122. package/dist/runner/main.js +26 -11
  123. package/dist/runner/mcp-claim.d.ts +3 -0
  124. package/dist/runner/mcp-claim.js +6 -1
  125. package/dist/runner/mcp-github.d.ts +11 -2
  126. package/dist/runner/mcp-github.js +55 -4
  127. package/dist/runner/mcp-run.js +1 -0
  128. package/dist/runner/metrics.d.ts +14 -1
  129. package/dist/runner/metrics.js +72 -1
  130. package/dist/runner/model-route.d.ts +3 -0
  131. package/dist/runner/model-route.js +1 -1
  132. package/dist/runner/runner.js +90 -8
  133. package/dist/runner/spec-holds.d.ts +7 -2
  134. package/dist/runner/spec-holds.js +4 -3
  135. package/dist/runner/workflow-host.d.ts +7 -2
  136. package/dist/runner/workflow-host.js +3 -1
  137. package/dist/runner/workflow-loop.d.ts +4 -1
  138. package/dist/runner/workflow-loop.js +8 -2
  139. package/dist/runner/workflow-spec.d.ts +3 -0
  140. package/dist/runner/workflow-spec.js +156 -78
  141. package/dist/runs-over-store.d.ts +7 -1
  142. package/dist/runs-over-store.js +42 -11
  143. package/dist/seal-key.d.ts +0 -2
  144. package/dist/seal-key.js +0 -2
  145. package/dist/server-lock.js +4 -5
  146. package/dist/server.d.ts +21 -18
  147. package/dist/server.js +183 -34
  148. package/dist/stop-signals.d.ts +4 -2
  149. package/dist/stop-signals.js +5 -3
  150. package/dist/store/agent-body.d.ts +5 -1
  151. package/dist/store/agent-body.js +11 -5
  152. package/dist/store/deadline.d.ts +18 -0
  153. package/dist/store/deadline.js +45 -0
  154. package/dist/store/postgres/connection.d.ts +4 -0
  155. package/dist/store/postgres/connection.js +55 -9
  156. package/dist/store/sqlite/connection.js +3 -38
  157. package/dist/store-reads/journal.js +39 -4
  158. package/dist/store-reads/learning.d.ts +58 -2
  159. package/dist/store-reads/learning.js +172 -7
  160. package/dist/store-view.d.ts +15 -1
  161. package/dist/store-view.js +45 -12
  162. package/dist/templates.d.ts +9 -4
  163. package/dist/templates.js +14 -9
  164. package/dist/timeline/timeline.d.ts +8 -0
  165. package/dist/tool-budget.d.ts +18 -0
  166. package/dist/tool-budget.js +50 -0
  167. package/dist/tool-gate.d.ts +6 -2
  168. package/dist/tool-gate.js +8 -5
  169. package/dist/tool-plane.d.ts +9 -10
  170. package/dist/tools.d.ts +37 -7
  171. package/dist/tools.js +73 -12
  172. package/dist/uploads.d.ts +28 -5
  173. package/dist/uploads.js +82 -9
  174. package/dist/usage.d.ts +1 -47
  175. package/dist/usage.js +3 -82
  176. package/dist/validate.d.ts +2 -0
  177. package/dist/validate.js +11 -1
  178. package/dist/workspace/archil-claim.d.ts +2 -2
  179. package/dist/workspace/archil-claim.js +4 -3
  180. package/dist/workspace/archil-disk.d.ts +10 -1
  181. package/dist/workspace/archil-disk.js +4 -0
  182. package/dist/workspace/archil-exec.d.ts +12 -2
  183. package/dist/workspace/archil-exec.js +16 -0
  184. package/dist/workspace/archil.d.ts +2 -2
  185. package/dist/workspace/archil.js +25 -5
  186. package/dist/workspace/attach.js +2 -0
  187. package/dist/workspace/computer-deps.d.ts +9 -10
  188. package/dist/workspace/computer-deps.js +53 -40
  189. package/dist/workspace/computer-for-claim.d.ts +5 -3
  190. package/dist/workspace/computer-for-claim.js +28 -16
  191. package/dist/workspace/computer-ledger.d.ts +1 -8
  192. package/dist/workspace/computer-ledger.js +0 -3
  193. package/dist/workspace/computer-providers.d.ts +5 -3
  194. package/dist/workspace/computer-providers.js +11 -9
  195. package/dist/workspace/hands.d.ts +5 -2
  196. package/dist/workspace/hands.js +4 -3
  197. package/dist/workspace/index.d.ts +3 -3
  198. package/dist/workspace/index.js +1 -1
  199. package/dist/workspace/local.d.ts +3 -0
  200. package/dist/workspace/local.js +9 -0
  201. package/dist/workspace/paths.js +3 -2
  202. package/dist/workspace/pi-env.d.ts +4 -0
  203. package/dist/workspace/pi-env.js +3 -2
  204. package/dist/workspace/resolve-computer.d.ts +8 -3
  205. package/dist/workspace/resolve-computer.js +28 -11
  206. package/dist/workspace/run-tools.d.ts +2 -0
  207. package/dist/workspace/run-tools.js +9 -3
  208. package/dist/workspace/workspace.d.ts +5 -0
  209. package/dist/workspace.d.ts +0 -3
  210. package/dist/workspace.js +1 -14
  211. package/package.json +14 -14
  212. package/skills/agentrun-serve/SKILL.md +1 -1
  213. package/templates/README.md +2 -2
  214. package/templates/code-review/evals/mentions-defused/case.yaml +15 -0
  215. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +254 -0
  216. package/templates/code-review/evals/mentions-defused/graders/no-pings.md +16 -0
  217. package/templates/code-review/evals/mentions-defused/graders/posted-a-review.md +5 -0
  218. package/templates/code-review/evals/mentions-defused/graders/schema.md +5 -0
  219. package/templates/code-review/evals/mentions-defused/prompt.md +10 -0
  220. package/templates/kyb/evals/clean-public-company/graders/no-opensanctions.md +5 -0
  221. package/templates/kyb/evals/opensanctions-on/case.yaml +5 -0
  222. package/templates/kyb/evals/opensanctions-on/graders/licence-and-evidence.md +18 -0
  223. package/templates/kyb/evals/opensanctions-on/graders/schema.md +5 -0
  224. package/templates/kyb/evals/opensanctions-on/prompt.md +11 -0
  225. package/templates/release-notes/agent.md +11 -0
  226. package/dist/console/assets/index-RPHGlXmM.js +0 -540
  227. package/dist/console/assets/index-opTN5Naq.css +0 -1
package/dist/server.d.ts CHANGED
@@ -69,6 +69,10 @@ export type ServeOptions = {
69
69
  /** With `faux` only: a module whose default export gives the `browser` tool's `{ provider, driver }` (the tests' fake
70
70
  * backend), in place of Browserbase's or Kernel's. */
71
71
  fauxBrowser?: string;
72
+ /** With `faux` only: a fake GitHub App, connected at the start, its API in this process on loopback (github-faux.ts),
73
+ * so the console's GitHub flows run with nothing sent to GitHub. Its webhook secret is kept beside the data
74
+ * (FAUX_GITHUB_FILE) for a test's signed delivery. Refused on a data directory another GitHub App is connected in. */
75
+ fauxGitHub?: boolean;
72
76
  /** With `faux` only: a module whose default export is the fetch the check of a Kernel key goes through (the tests'
73
77
  * fake), in place of Kernel's API. */
74
78
  fauxKernel?: string;
@@ -139,8 +143,7 @@ export type ServeOptions = {
139
143
  * the CLI says a first build in words, as it starts and as it ends. */
140
144
  onBoxImage?: (state: ImageState) => void;
141
145
  /** The lines a person reads about a stop on this data root: this server's, as its close begins and runs' processes are
142
- * left to finish their turn, and this start's, when it waits for a server that is stopping (server-lock.ts). Default:
143
- * standard error, after `agentrun-serve: `. */
146
+ * left to finish their turn. Default: standard error, after `agentrun-serve: `. */
144
147
  notice?: (line: string) => void;
145
148
  /** A test's seam: awaited by a stop between its mark and its abort, so a test can hold a stop in flight there. */
146
149
  beforeAbort?: (runId: string) => Promise<void> | void;
@@ -303,14 +306,14 @@ export declare function readingOf(base: NodeJS.ProcessEnv, maxRuns: number, stor
303
306
  * web tool, what it resolves to on each harness under this server's tool settings; `key`, the tool key that unlocks
304
307
  * it (tool-keys.ts), when one does. */
305
308
  tools: ({
306
- providers?: ("auto" | "native" | "parallel" | "browserbase" | "kernel" | "off" | "exa-keyless" | "chrome")[] | undefined;
309
+ providers?: ("auto" | "native" | "parallel" | "off" | "kernel" | "browserbase" | "exa-keyless" | "chrome")[] | undefined;
307
310
  provider?: string | undefined;
308
311
  default_provider?: "auto" | "kernel" | undefined;
309
312
  resolves?: Record<"opencode" | "codex" | "pi" | "claude-agent", import("./tool-plane.js").Resolution> | undefined;
310
313
  why?: Record<"opencode" | "codex" | "pi" | "claude-agent", string> | undefined;
311
- permission: "deny" | "ask" | "allow";
312
- default_permission: "deny" | "ask" | "allow";
313
- permissions: ("deny" | "ask" | "allow")[];
314
+ permission: "deny" | "allow" | "ask";
315
+ default_permission: "deny" | "allow" | "ask";
316
+ permissions: ("deny" | "allow" | "ask")[];
314
317
  harnesses: ("opencode" | "codex" | "pi" | "claude-agent")[];
315
318
  missing?: string[] | undefined;
316
319
  reason?: string | undefined;
@@ -324,14 +327,14 @@ export declare function readingOf(base: NodeJS.ProcessEnv, maxRuns: number, stor
324
327
  summary: string;
325
328
  } | {
326
329
  key: string | undefined;
327
- providers?: ("auto" | "native" | "parallel" | "browserbase" | "kernel" | "off" | "exa-keyless" | "chrome")[] | undefined;
330
+ providers?: ("auto" | "native" | "parallel" | "off" | "kernel" | "browserbase" | "exa-keyless" | "chrome")[] | undefined;
328
331
  provider?: string | undefined;
329
332
  default_provider?: "auto" | "kernel" | undefined;
330
333
  resolves?: Record<"opencode" | "codex" | "pi" | "claude-agent", import("./tool-plane.js").Resolution> | undefined;
331
334
  why?: Record<"opencode" | "codex" | "pi" | "claude-agent", string> | undefined;
332
- permission: "deny" | "ask" | "allow";
333
- default_permission: "deny" | "ask" | "allow";
334
- permissions: ("deny" | "ask" | "allow")[];
335
+ permission: "deny" | "allow" | "ask";
336
+ default_permission: "deny" | "allow" | "ask";
337
+ permissions: ("deny" | "allow" | "ask")[];
335
338
  harnesses: ("opencode" | "codex" | "pi" | "claude-agent")[];
336
339
  missing?: string[] | undefined;
337
340
  reason?: string | undefined;
@@ -561,14 +564,14 @@ export declare function capabilities(env?: NodeJS.ProcessEnv, maxRuns?: number,
561
564
  * web tool, what it resolves to on each harness under this server's tool settings; `key`, the tool key that unlocks
562
565
  * it (tool-keys.ts), when one does. */
563
566
  tools: ({
564
- providers?: ("auto" | "native" | "parallel" | "browserbase" | "kernel" | "off" | "exa-keyless" | "chrome")[] | undefined;
567
+ providers?: ("auto" | "native" | "parallel" | "off" | "kernel" | "browserbase" | "exa-keyless" | "chrome")[] | undefined;
565
568
  provider?: string | undefined;
566
569
  default_provider?: "auto" | "kernel" | undefined;
567
570
  resolves?: Record<"opencode" | "codex" | "pi" | "claude-agent", import("./tool-plane.js").Resolution> | undefined;
568
571
  why?: Record<"opencode" | "codex" | "pi" | "claude-agent", string> | undefined;
569
- permission: "deny" | "ask" | "allow";
570
- default_permission: "deny" | "ask" | "allow";
571
- permissions: ("deny" | "ask" | "allow")[];
572
+ permission: "deny" | "allow" | "ask";
573
+ default_permission: "deny" | "allow" | "ask";
574
+ permissions: ("deny" | "allow" | "ask")[];
572
575
  harnesses: ("opencode" | "codex" | "pi" | "claude-agent")[];
573
576
  missing?: string[] | undefined;
574
577
  reason?: string | undefined;
@@ -582,14 +585,14 @@ export declare function capabilities(env?: NodeJS.ProcessEnv, maxRuns?: number,
582
585
  summary: string;
583
586
  } | {
584
587
  key: string | undefined;
585
- providers?: ("auto" | "native" | "parallel" | "browserbase" | "kernel" | "off" | "exa-keyless" | "chrome")[] | undefined;
588
+ providers?: ("auto" | "native" | "parallel" | "off" | "kernel" | "browserbase" | "exa-keyless" | "chrome")[] | undefined;
586
589
  provider?: string | undefined;
587
590
  default_provider?: "auto" | "kernel" | undefined;
588
591
  resolves?: Record<"opencode" | "codex" | "pi" | "claude-agent", import("./tool-plane.js").Resolution> | undefined;
589
592
  why?: Record<"opencode" | "codex" | "pi" | "claude-agent", string> | undefined;
590
- permission: "deny" | "ask" | "allow";
591
- default_permission: "deny" | "ask" | "allow";
592
- permissions: ("deny" | "ask" | "allow")[];
593
+ permission: "deny" | "allow" | "ask";
594
+ default_permission: "deny" | "allow" | "ask";
595
+ permissions: ("deny" | "allow" | "ask")[];
593
596
  harnesses: ("opencode" | "codex" | "pi" | "claude-agent")[];
594
597
  missing?: string[] | undefined;
595
598
  reason?: string | undefined;
package/dist/server.js CHANGED
@@ -32,7 +32,7 @@ import { healthOf, hostMemory, maxRunsOf, MIN_FREE_MIB, runsThatFit } from "./ho
32
32
  import { IMPORT_ASKED } from "./import.js";
33
33
  import { answerStoreCall } from "./import-proxy.js";
34
34
  import { gradeModelOf, LEARNING_LABEL, learningBudgetOf, learningOf, seedOf } from "./learning.js";
35
- import { agentLearning, learningLog, learningNotes, noteBody, pendingCount, readNote, secretsShown, sendNote, statusesOf, writeNote } from "./learning-routes.js";
35
+ import { agentLearning, learningLog, learningNotes, noteBody, pendingCount, promotable, readNote, secretsShown, sendNote, statusesOf, writeNote } from "./learning-routes.js";
36
36
  import { answerLlms, MCP_PATH, mcpEndpoint } from "./mcp.js";
37
37
  import { openapiDocument, servedOpenapi, UNSUPPORTED } from "./openapi.js";
38
38
  import { boxAvailability, boxesLine, defaultPlaceOf, NEW_AGENT_TOOLS, newAgentPlace, noBoxReason, placesOf } from "./place.js";
@@ -46,7 +46,7 @@ import { browserHandBack, handBackTarget } from "./browser-commands.js";
46
46
  import { computerView } from "./computer-view.js";
47
47
  import { durationMs, logLine } from "./print.js";
48
48
  import { approve, archiveRun, cancel, message, pause as pauseRunOverStore, raiseCap, resume as resumeRunOverStore, startInline, startRun, stop as stopRunOverStore } from "./runs-over-store.js";
49
- import { momentOverStore, summaryOverStore, timelineOverStore, viewOverStore, withheldOverStore } from "./store-view.js";
49
+ import { factsOverStore, momentOverStore, summaryOverStore, timelineOverStore, viewOverStore, withheldOverStore } from "./store-view.js";
50
50
  import { HELD_WAITS } from "./runner/journal-kinds.js";
51
51
  import { servedTimelineRows } from "./run-timeline-served.js";
52
52
  import { servedRunDiff, servedRunLearning } from "./run-learning-served.js";
@@ -62,7 +62,7 @@ import { watchRun } from "./live/stream.js";
62
62
  import { stats as statsOverStore } from "./store-reads/stats.js";
63
63
  import { analytics as analyticsOverStore } from "./store-reads/analytics.js";
64
64
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
65
- import { openStore } from "./store/index.js";
65
+ import { openStore, StoreOwned, storeTarget } from "./store/index.js";
66
66
  import { answerOf, logged } from "./agents.js";
67
67
  import { FINAL_STATES } from "./store/store.js";
68
68
  import { runModelRef } from "./model.js";
@@ -83,6 +83,8 @@ import { blockersOf, CODE_NODES_ENV, issueOf, MCP_HARNESSES, NOT_SET_UP } from "
83
83
  import { hostSecrets, SECRET_NAMES, secret, withSecrets } from "./secrets.js";
84
84
  import { isSecretWriteOperation, SECRET_WRITE_REFUSAL, secretsWritableFields, secretWriterFacts, writesSecretFor, writesSecretsAllowed } from "./secret-writes.js";
85
85
  import { bootSealKey, withSealKey } from "./seal-key.js";
86
+ import { ServerLockHeldError, takeServerLock } from "./server-lock.js";
87
+ import { DRAIN_TIMEOUT } from "./runner/beside.js";
86
88
  import { analyticsFilter, analyticsView, statsView } from "./stats.js";
87
89
  import { agentLearningOverStore, learningCountsOverStore, learningSpendOverStore } from "./store-reads/learning.js";
88
90
  import { keyOf, SEAL_KEY_ENV, TOOL_FIELDS } from "./tool-keys.js";
@@ -100,6 +102,7 @@ import { templateApplied, templateTriggerSecret, templateWebhookSecrets, trigger
100
102
  import { openServerSecretsOverStore } from "./server-secrets-store.js";
101
103
  import { HOOK_TOLERANCE_S } from "./standard-webhooks.js";
102
104
  import { GitHubConnect, GitHubConnection, INSTALLED_PATH, startedHere as gitHubStartedHere, stateCookie } from "./github-connection.js";
105
+ import { FAUX_GITHUB, FAUX_GITHUB_FILE, startFauxGitHub } from "./github-faux.js";
103
106
  import { GITHUB_API } from "./github.js";
104
107
  import { HookCut, receivePush } from "./push-handler.js";
105
108
  import { TRIGGER_ADAPTERS } from "./trigger-adapters.js";
@@ -107,11 +110,11 @@ import { webhook } from "./trigger-webhook.js";
107
110
  import { SCHEME_NAMES } from "./trigger-signatures.js";
108
111
  import { permissionFrom } from "./tool-gate.js";
109
112
  import { CATCHUP_WINDOW_S, FAILURES_TO_PAUSE, HISTORY_KEPT, MIN_EVERY_S, PAYLOAD_KEPT_BYTES, SOURCE_KINDS, TARGET_KINDS, Triggers } from "./triggers.js";
110
- import { applyBodyOf, compiled, GITHUB_TRIGGER_UNCONNECTED, githubTriggerWords, madeTriggerIssues, packageModel, packageView, readPackages } from "./templates.js";
113
+ import { applyBodyOf, compiled, githubTriggerUnconnected, githubTriggerWords, madeTriggerIssues, packageModel, packageView, readPackages } from "./templates.js";
111
114
  import { checkDefinitionBody, DEFAULT_INPUT_SCHEMA, definitionBodyIssues, EXTERNAL_NAME, ID, IDEMPOTENCY_TTL_S, inputIssues, isObject, stable, unknownFields } from "./validate.js";
112
115
  import { agentTools, browserKeyRow, isUnavailable, keptVendor, recheckPlane, settingsIssues, whyUnavailable, withDefaults } from "./tool-plane.js";
113
116
  import { toolSettingsOverStore } from "./tool-settings-store.js";
114
- import { writeApprovers } from "./server-approvers.js";
117
+ import { readApprovers, writeApprovers } from "./server-approvers.js";
115
118
  import { MAX_FILES_PER_RUN, MAX_UPLOAD_BYTES, Uploads, UPLOADS_DIR } from "./uploads.js";
116
119
  import { entryAt, listFiles, sendFile as sendWorkspaceFile, viewOf } from "./run-files.js";
117
120
  import { COMPUTER_ROUTES, computerHoldOf, computerRoute } from "./computer-routes.js";
@@ -125,7 +128,6 @@ import { runComputerField } from "./run-computer.js";
125
128
  import { writesHeld } from "./workspace.js";
126
129
  import { agentHomeFolder, claimKinds, computerProviderFactories, computerProviderMakers, computerReadiness, dockerHostAddressesOf, isWorkspaceError, localWorkspace, runShellOf, serverRunWorkspace, storeLedger } from "./workspace/index.js";
127
130
  import { keyReader } from "./key-meta.js";
128
- // server-lock.ts is gone: the store's EXCLUSIVE connection is the one-server lock (StoreOwned refuses a second server).
129
131
  export const CONTRACT = "agentrun.v2/0";
130
132
  /** A process's flags for a worker of it: without --input-type and the code string given with -e, --eval, -p or --print. */
131
133
  const workerArgs = (args) => args.filter((arg, i) => !arg.startsWith("--input-type") && !/^(?:-e|--eval|-p|--print)(?:=|$)/.test(arg) && !/^(?:-e|--eval|-p|--print)$/.test(args[i - 1] ?? ""));
@@ -305,6 +307,7 @@ export const ROUTES = [
305
307
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/retire$/, name: "retireLearningFile" },
306
308
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/approve$/, name: "approveLearningFile" },
307
309
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/restore$/, name: "restoreLearningFile" },
310
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/promote$/, name: "promoteLearnedWorkflow" },
308
311
  { method: "GET", pattern: /^\/runs\/([^/]+)\/learning$/, name: "getRunLearning" },
309
312
  { method: "GET", pattern: /^\/runs\/([^/]+)\/learning\/diff$/, name: "getRunLearningDiff" },
310
313
  ];
@@ -564,9 +567,9 @@ export async function startServe(options) {
564
567
  const minFreeBytes = options.minFreeBytes ?? minFreeMib * 2 ** 20;
565
568
  // The template packages, each checked whole (templates.ts readPackage): a broken one stops the start.
566
569
  const templates = readPackages(options.templates);
567
- // One server per data root is the store's own EXCLUSIVE lock (StoreOwned), taken when startHolding opens the store; a
568
- // data directory an earlier version wrote is refused there too (StoreFromEarlierVersion), in words, to start fresh. No
569
- // server.lock, no oldHomes/oldLayout checks, no migration.
570
+ // One server per data root: the store's owner lock (StoreOwned), then the data root's own (server-lock.ts), both taken
571
+ // when startHolding opens the store; a data directory an earlier version wrote is refused there too
572
+ // (StoreFromEarlierVersion), in words, to start fresh. No oldHomes/oldLayout checks, no migration.
570
573
  // What a start that fails stops: the webhook deliveries it began, which would write the next server's outbox, and the
571
574
  // store handle it opened.
572
575
  const stops = [];
@@ -579,6 +582,27 @@ export async function startServe(options) {
579
582
  throw error;
580
583
  }
581
584
  }
585
+ /** How much longer than its drain timeout a start waits for the server it replaces (a redeploy, a restart that starts the
586
+ * new server before the old one has exited): the old one's close, after its runs' drain. */
587
+ const START_WAIT_MARGIN_MS = 30_000;
588
+ /** `take()`, tried again every 250 ms while `held(error)` says the server this one replaces still holds what it takes, up
589
+ * to `until` (epoch ms); `waiting` is told this wait's `until` once, as it begins. Past `until`, or on any other error,
590
+ * it throws. */
591
+ async function whileReplaced(take, held, until, waiting) {
592
+ let told = false;
593
+ for (;;) {
594
+ try {
595
+ return await take();
596
+ }
597
+ catch (error) {
598
+ if (!held(error) || Date.now() >= until)
599
+ throw error;
600
+ if (!told)
601
+ (told = true), waiting(until);
602
+ await new Promise((resolve) => setTimeout(resolve, 250));
603
+ }
604
+ }
605
+ }
582
606
  async function startHolding(options, data, checked, stops) {
583
607
  const { maxRuns, minFreeBytes, learning, learningBudget, boxAllow, templates } = checked;
584
608
  /** What an agent's view says of its learning: how many learned items wait for its owner's OK, for an agent that learns
@@ -590,14 +614,6 @@ async function startHolding(options, data, checked, stops) {
590
614
  const pending = await pendingCount(data, entry.agent.id);
591
615
  return pending === undefined ? undefined : { pending };
592
616
  };
593
- const tokenFile = options.token === undefined ? join(data, TOKEN_FILE) : null;
594
- const stored = options.token === undefined ? await tokenIn(tokenFile) : undefined;
595
- const token = options.token ?? stored.token;
596
- // Given a token (AGENTRUN_TOKEN), a .token an earlier start made holds one this server refuses: it goes, so nothing
597
- // (a person told the token is there, a CLI that reads it) takes a dead token from it. A later start without one makes a
598
- // new file and token.
599
- if (options.token !== undefined)
600
- await rm(join(data, TOKEN_FILE), { force: true });
601
617
  const log = options.log;
602
618
  const quiet = process.env.AGENTRUN_LOG === "quiet";
603
619
  const authFailed = (route, reason) => log?.(logLine("auth_failed", { route, reason }));
@@ -612,17 +628,49 @@ async function startHolding(options, data, checked, stops) {
612
628
  let triggerSettings = new Map();
613
629
  const base = { ...withoutFaux(process.env), [DATA_ENV]: data, ...(options.allowCodeNodes ? { [CODE_NODES_ENV]: "1" } : {}), ...(options.faux ? { [FAUX_ENV]: resolve(options.faux) } : {}), ...(options.harnessTable ? { [HARNESS_TABLE_ENV]: resolve(options.harnessTable) } : {}) };
614
630
  // The one store (module A), opened here as this data root's single owner, before the settings layers that read it: its
615
- // EXCLUSIVE lock is the one-server lock (no server-lock.ts), and it refuses a data directory an earlier version wrote, in
616
- // words, to start fresh (no oldHomes/oldLayout checks, no migration). Every agent, run, setting and sign-in is a row; the
631
+ // owner lock holds the store to this server (the data root's own lock follows), and it refuses a data directory an
632
+ // earlier version wrote, in words, to start fresh (no oldHomes/oldLayout checks, no migration). Every agent, run, setting and sign-in is a row; the
617
633
  // server writes and reads rows, and a runner (its own process, sharing only this store) runs every run.
618
- // On Postgres when this process's AGENTRUN_STORE_URL secret names one (store/open.ts), its owner lock the one-server lock.
634
+ // On Postgres when this process's AGENTRUN_STORE_URL secret names one (store/open.ts).
619
635
  // A server deploying while the old one still holds the schema waits for it (said once), never exits at once.
620
- const store = await openStore({
636
+ // The server this one replaces may still be stopping (a redeploy, a restart that starts this one before the old one has
637
+ // exited): its close comes after its runs' drain, so this start waits for as long as its own drain timeout and a
638
+ // margin, saying so once, before it refuses. On Postgres the store's owner lock waits on its own (store/open.ts); on
639
+ // SQLite the store file's owner lock is waited for here, and the data root's lock below on either.
640
+ const replacedDrainMs = durationMs(options.drainTimeout ?? DRAIN_TIMEOUT) ?? 0;
641
+ const replacedUntil = Date.now() + replacedDrainMs + START_WAIT_MARGIN_MS;
642
+ const sayReplaced = noticeOf(options);
643
+ let replacedTold = false;
644
+ const waitingForReplaced = (until) => {
645
+ if (replacedTold)
646
+ return;
647
+ replacedTold = true;
648
+ sayReplaced(`another server holds this data root: waiting up to ${Math.max(1, Math.ceil((until - Date.now()) / 1000))} s for the previous server to stop`);
649
+ };
650
+ const onSqlite = storeTarget(data).kind === "sqlite";
651
+ const store = await whileReplaced(() => openStore({
621
652
  dataDir: data, role: "server",
622
653
  warn: (message) => void process.stderr.write(`agentrun-serve: ${message}\n`),
623
654
  ...(options.onStoreLost ? { onOwnerLost: options.onStoreLost } : {}),
624
- });
655
+ }), (error) => onSqlite && error instanceof StoreOwned, replacedUntil, waitingForReplaced);
625
656
  stops.push(() => store.close());
657
+ // The data root's own lock, once the store is held (so a deploy on Postgres waits at the store's owner lock first): the
658
+ // store's lock holds one store, but the data root also holds what the server writes beside it (its token, its seal key,
659
+ // uploads, harness installs, learning folders), which two servers on two stores (two Postgres schemas, or SQLite and
660
+ // Postgres) would share. The lock is SQLite's EXCLUSIVE lock (server-lock.ts): the kernel drops it when its process
661
+ // dies, so a crashed server never leaves it held.
662
+ // Its wait runs from when the store was held at the earliest, since a store on Postgres may have been waited for first.
663
+ const dataLock = await whileReplaced(() => takeServerLock(data), (error) => error instanceof ServerLockHeldError, Math.max(replacedUntil, Date.now() + START_WAIT_MARGIN_MS), waitingForReplaced);
664
+ stops.push(async () => dataLock.release());
665
+ // The token, once both locks are held: a start the locks refuse reads, makes and removes nothing in the data root.
666
+ const tokenFile = options.token === undefined ? join(data, TOKEN_FILE) : null;
667
+ const stored = options.token === undefined ? await tokenIn(tokenFile) : undefined;
668
+ const token = options.token ?? stored.token;
669
+ // Given a token (AGENTRUN_TOKEN), a .token an earlier start made holds one this server refuses: it goes, so nothing
670
+ // (a person told the token is there, a CLI that reads it) takes a dead token from it. A later start without one makes a
671
+ // new file and token.
672
+ if (options.token !== undefined)
673
+ await rm(join(data, TOKEN_FILE), { force: true });
626
674
  // No start without a seal key (seal-key.ts), checked against the store before anything reads it: the one handed over,
627
675
  // else the one in the data directory beside the store, made at the first start with only its path printed. A store whose
628
676
  // secrets another key sealed is refused, in words, and no key is made over them. Every secret here is kept under it;
@@ -881,11 +929,13 @@ async function startHolding(options, data, checked, stops) {
881
929
  * box's start-time answer stands. A box the start did not make keeps its reason ("start Docker, then restart
882
930
  * AgentRun"): the start's checks of Docker (Docker elsewhere, this server's paths, host addresses, its network) ran
883
931
  * without it, so a daemon that answers later is not taken. Else the box's start-time answer (boxOffers), with its
884
- * reason, which says how to fix it. */
932
+ * reason, which says how to fix it. The provider whose computers run on this machine's container engine is the one
933
+ * whose descriptor declares `local`. */
885
934
  const dockerDaemon = dockerDaemonCheck({ env });
886
935
  const dockerAnswers = async (provider) => {
887
936
  const box = boxAvailability(boxOffers).find((one) => one.id === provider);
888
- if (provider === "docker" && !fauxBox && enabledBoxes(env).has("docker")) {
937
+ const local = COMPUTER_PROVIDERS.find((one) => one.id === provider)?.local === true;
938
+ if (local && !fauxBox && enabledBoxes(env).has(provider)) {
889
939
  const daemon = await dockerDaemon();
890
940
  if (!daemon.up || box?.available)
891
941
  return daemon;
@@ -972,6 +1022,13 @@ async function startHolding(options, data, checked, stops) {
972
1022
  const swept = await uploads.sweep();
973
1023
  if (swept > 0)
974
1024
  log?.(logLine("uploads_swept", { removed: swept }));
1025
+ // A run's hold of its files goes at its claim, once they are in its workspace; one that ended before any claim copied
1026
+ // them (cancelled while queued) leaves its hold, which goes here, as does one whose run is gone.
1027
+ for (const runId of await uploads.holders()) {
1028
+ const row = await store.runs.get(runId);
1029
+ if (!row || FINAL_STATES.includes(row.state))
1030
+ await uploads.release(runId);
1031
+ }
975
1032
  const documents = options.documents ?? process.env[DOCUMENTS_ENV];
976
1033
  if (documents !== undefined && !(await stat(documents).then((info) => info.isDirectory(), () => false)))
977
1034
  throw new Error(`the documents directory ${documents} is not a directory`);
@@ -1021,6 +1078,7 @@ async function startHolding(options, data, checked, stops) {
1021
1078
  told: (error) => told(error),
1022
1079
  runnable,
1023
1080
  readyFiles: (ids) => uploads.readyFiles(ids),
1081
+ files: { hold: (runId, ids) => uploads.hold(runId, ids), release: (runId) => uploads.release(runId) },
1024
1082
  fallbackPlace: (kind, tools) => fallbackPlace(kind, tools),
1025
1083
  workflowTitle,
1026
1084
  serverSecrets,
@@ -1080,7 +1138,7 @@ async function startHolding(options, data, checked, stops) {
1080
1138
  const runReadsDeps = {
1081
1139
  runWorkspace: (_store, runId) => serverRunWorkspace(store, runId, { data, sealKey }),
1082
1140
  env,
1083
- runView: (_store, runId) => viewOverStore(store, runId, viewDepsFor(ownOriginOf())),
1141
+ runFacts: (_store, runId) => factsOverStore(store, runId, viewDepsFor(ownOriginOf())),
1084
1142
  withheld: (_store, runId) => withheldOverStore(store, runId, viewDepsFor(ownOriginOf())),
1085
1143
  cutValues: (_store, runId) => runCutValues({ serverSecrets, signIns }, store, runId),
1086
1144
  context: ctx,
@@ -1189,7 +1247,20 @@ async function startHolding(options, data, checked, stops) {
1189
1247
  // Connect GitHub: the server's one GitHub App, in the store's trigger_settings (adapter github, scope server), where the
1190
1248
  // runner reads it per claim (runner/github-app.ts).
1191
1249
  const github = new GitHubConnection(triggerSettings.get("github"));
1192
- const githubConnect = new GitHubConnect(github, { ...(options.publicUrl ? { publicUrl: options.publicUrl.replace(/\/+$/, "") } : {}), api: options.githubApi ?? GITHUB_API, say: (fields) => log?.(logLine("github", fields)) });
1250
+ // --faux-github (with --faux only): the fake App is connected afresh at each start, its API in this process.
1251
+ const was = options.faux && options.fauxGitHub ? github.view() : undefined;
1252
+ if (was && was.slug !== FAUX_GITHUB.slug)
1253
+ throw new Error(`--faux-github connects a fake GitHub App, and this data directory has the GitHub App ${was.slug} connected: use a scratch data directory.`);
1254
+ const fauxGitHub = options.faux && options.fauxGitHub ? await startFauxGitHub() : undefined;
1255
+ if (fauxGitHub) {
1256
+ stops.push(() => fauxGitHub.close());
1257
+ if (was)
1258
+ await github.remove();
1259
+ await github.save(fauxGitHub.app);
1260
+ await github.setInstallations([{ id: FAUX_GITHUB.installation, account: FAUX_GITHUB.account }]);
1261
+ await writeFile(join(data, FAUX_GITHUB_FILE), `${JSON.stringify({ webhook_secret: fauxGitHub.app.webhookSecret, installation: FAUX_GITHUB.installation, account: FAUX_GITHUB.account, repositories: FAUX_GITHUB.repositories })}\n`, { mode: 0o600 });
1262
+ }
1263
+ const githubConnect = new GitHubConnect(github, { ...(options.publicUrl ? { publicUrl: options.publicUrl.replace(/\/+$/, "") } : {}), api: fauxGitHub?.url ?? options.githubApi ?? GITHUB_API, say: (fields) => log?.(logLine("github", fields)) });
1193
1264
  /** The connection a GitHub template or the console reads: the App's id, slug and installations, never a secret. */
1194
1265
  const githubConnection = () => github.view();
1195
1266
  /** What applying a template reads of the server (templates.ts TemplatesDeps). */
@@ -1351,16 +1422,24 @@ async function startHolding(options, data, checked, stops) {
1351
1422
  return value;
1352
1423
  }
1353
1424
  /** The tools a learned draft of agent `id` may name, as a run's merge reads them (learning-run.ts draftTools): its
1354
- * current revision's, those the gate allows under the server's settings and the agent's own. */
1355
- async function learnedDraftToolsOf(id) {
1356
- const revision = (await needAgent(id)).revision;
1425
+ * current revision's, those the gate allows under the server's settings and the agent's own. `entry`: the agent as the
1426
+ * caller already read it, so what it checks and what it copies are one revision's (a promotion). */
1427
+ async function learnedDraftToolsOf(id, entry) {
1428
+ const revision = (entry ?? (await needAgent(id))).revision;
1357
1429
  if (revision?.kind !== "agentic")
1358
- return { tools: [], gated: {} };
1359
- const [{ learnedDraftTools }, { permissionOf }] = await Promise.all([import("./tools.js"), import("./tool-gate.js")]);
1430
+ return { tools: [], gated: {}, deniedBy: {} };
1431
+ const [{ learnedDraftTools, mcpGrantsListed }, { permissionFrom }, { learnedAskFits }] = await Promise.all([import("./tools.js"), import("./tool-gate.js"), import("./learned-workflow.js")]);
1360
1432
  const server = settings.get();
1361
1433
  // The revision row's body is the agentic body JSON (store-backed RevisionRow types it as unknown).
1362
1434
  const body = revision.body;
1363
- return learnedDraftTools(body.tools ?? [], (name) => permissionOf(name, server, (body.toolSettings ?? {}), body.approvals === "never" ? "never" : "ask"));
1435
+ // A server's wildcard grant read as the tools its server lists now (tools.ts mcpGrantsListed, LS-07).
1436
+ const rows = (body.tools ?? []).some((name) => /^mcp:[^/]+\/\*$/.test(name)) ? await store.mcp.servers().catch(() => []) : [];
1437
+ const listed = new Map(rows.map((row) => [row.name, (row.tools ?? []).flatMap((tool) => (typeof tool?.name === "string" ? [tool.name] : []))]));
1438
+ const gate = (name) => permissionFrom(name, server, (body.toolSettings ?? {}), body.approvals === "never" ? "never" : "ask");
1439
+ // `deniedBy`: where each deny was set (the agent's tool settings, the server's), which a refused draft's words name.
1440
+ const { tools, gated, deniedBy, asked } = learnedDraftTools(mcpGrantsListed(body.tools ?? [], (name) => listed.get(name) ?? []), (name) => gate(name).permission, undefined, (name) => gate(name).from, { mcp: true, approvers: await readApprovers(store.settings) });
1441
+ // #2424's card rule (learnedAskFits): a restored draft whose ask-set MCP tools would not all show is refused.
1442
+ return { tools, gated, deniedBy, ask: { asked, fits: learnedAskFits } };
1364
1443
  }
1365
1444
  async function needAgent(id) {
1366
1445
  const entry = ID.test(id) ? await agents.get(id) : null;
@@ -1514,6 +1593,52 @@ async function startHolding(options, data, checked, stops) {
1514
1593
  const entry = await agents.create(definition, async (revision) => void (warnings = await saveable(revision)), "place" in fresh ? { place: fresh.place, tools: NEW_AGENT_TOOLS } : undefined);
1515
1594
  return { entry, warnings };
1516
1595
  }
1596
+ /** Agent `source`'s learned workflow `raw` made into a workflow agent of its own, as POST /agents makes one
1597
+ * (createAgentOf: the definition's checks, the workflow's validation and what this host refuses of it). Only an active
1598
+ * one, checked again as a restore checks it (learning-routes.ts promotable). Its revision is a workflow revision of the
1599
+ * learned workflow.json, its tools those its call nodes call (each one the source agent has and its gate allows), and
1600
+ * the source's policy as it is now: its own tool settings, its approvals and its default cap, never more. Named
1601
+ * `body.name`, else the workflow's own; its id is the workflow's name, with -2, -3 and on past an agent's id or name
1602
+ * already here. The learned workflow stays where it is, unchanged. */
1603
+ async function promoteOf(source, raw, body) {
1604
+ const extra = unknownFields(body, ["name"]);
1605
+ if (body.name !== undefined && (typeof body.name !== "string" || body.name.trim() === "" || body.name.length > 200))
1606
+ extra.push({ field: "name", reason: "wrong_type", message: "name is the new agent's name: text of 1 to 200 characters" });
1607
+ if (extra.length)
1608
+ throw invalid(extra);
1609
+ const id = source.agent.id;
1610
+ const learned = await promotable(data, id, raw, { refuse: await learningValues(id), draftTools: () => learnedDraftToolsOf(id, source) });
1611
+ // Its policy from the same read of the source as the tools checked above: one revision's, whatever is saved meanwhile.
1612
+ const policy = (source.revision?.body ?? {});
1613
+ const promoted = (agentId) => ({
1614
+ id: agentId,
1615
+ name: typeof body.name === "string" ? body.name.trim() : agentId,
1616
+ ...(learned.description ? { description: learned.description } : {}),
1617
+ workflow: learned.workflow,
1618
+ tools: learned.calls,
1619
+ ...(policy.toolSettings ? { tool_settings: policy.toolSettings } : {}),
1620
+ ...(policy.approvals === "never" ? { approvals: "never" } : {}),
1621
+ ...(policy.maxCostUsd !== undefined ? { max_cost_usd: policy.maxCostUsd } : {}),
1622
+ ...(policy.capMode !== undefined ? { cap_mode: policy.capMode } : {}),
1623
+ });
1624
+ const note = `Made from the learned workflow ${learned.name} of agent ${id}.`;
1625
+ // Another promotion (or a create) may take the id between the read and the write: the next one is tried.
1626
+ for (let tries = 0;; tries++) {
1627
+ const all = [...(await agents.list()), ...(await agents.list({ archived: true }))];
1628
+ const taken = new Set(all.flatMap((entry) => [entry.agent.id, entry.agent.name]));
1629
+ let n = 1;
1630
+ while (taken.has(n === 1 ? learned.name : `${learned.name}-${n}`))
1631
+ n++;
1632
+ const agentId = n === 1 ? learned.name : `${learned.name}-${n}`;
1633
+ try {
1634
+ return await createAgentOf({ definition: promoted(agentId), note });
1635
+ }
1636
+ catch (error) {
1637
+ if (!(error instanceof ApiError && error.code === "agent_exists") || tries >= 4)
1638
+ throw error;
1639
+ }
1640
+ }
1641
+ }
1517
1642
  /** A template package applied: its parameters and the owner's grants checked (422), then the secrets and required MCP
1518
1643
  * servers it names (409, nothing made; an MCP server it can do without is skipped, with a warning), then its
1519
1644
  * agent made as POST /agents makes one, its MCP tools at the owner's own settings save those granted, set to allow (a
@@ -1609,7 +1734,7 @@ async function startHolding(options, data, checked, stops) {
1609
1734
  const hooks = made.triggers.flatMap((trigger, i) => (isObject(trigger.source) && trigger.source.kind === "webhook" ? [templateTriggerSecret(i)] : []));
1610
1735
  // Each github trigger: what it runs on, when made (a note, never a lack); skipped, what to do about it.
1611
1736
  const githubTriggers = made.triggers.flatMap((trigger, i) => (isObject(trigger.source) && trigger.source.kind === "github"
1612
- ? [unconnected.has(i) ? { field: `triggers.${i}`, reason: NOT_SET_UP, message: GITHUB_TRIGGER_UNCONNECTED } : { field: `triggers.${i}`, reason: "not_an_option", message: githubTriggerWords(pkg.name, trigger.source) }]
1737
+ ? [unconnected.has(i) ? { field: `triggers.${i}`, reason: NOT_SET_UP, message: githubTriggerUnconnected(pkg.name, trigger.source) } : { field: `triggers.${i}`, reason: "not_an_option", message: githubTriggerWords(pkg.name, trigger.source) }]
1613
1738
  : []));
1614
1739
  // Each trigger it made, a webhook trigger's with its secret's metadata; the values go back beside the answer, never in it
1615
1740
  // (the route adds them to the first answer to the owner's session, after the Idempotency-Key's record is written).
@@ -2324,6 +2449,12 @@ async function startHolding(options, data, checked, stops) {
2324
2449
  authFailed(`/v2${path}`, "approve_without_session");
2325
2450
  throw new ApiError("forbidden", owner ? "Approving a note takes the owner's password sign-in in the console, never a token." : "Approving a note takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
2326
2451
  }
2452
+ // Making a learned workflow an agent of its own gives it runs of its own, outside any agentic run's turn: the owner's
2453
+ // click alone, the same session as an approval.
2454
+ if (found.name === "promoteLearnedWorkflow" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
2455
+ authFailed(`/v2${path}`, "promote_without_session");
2456
+ throw new ApiError("forbidden", owner ? "Making a learned workflow an agent takes the owner's password sign-in in the console, never a token." : "Making a learned workflow an agent takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
2457
+ }
2327
2458
  // A run's live computer view is a full-control credential for its computer: the owner's signed-in page alone, as
2328
2459
  // approving a note is (never a token a run, an MCP client or a script may hold).
2329
2460
  if ((found.name === "getRunBrowser" || found.name === "handBackRunBrowser" || found.name === "getRunComputer") && !byOwnerSession(req) && req.headers.authorization !== undefined) {
@@ -2513,7 +2644,11 @@ async function startHolding(options, data, checked, stops) {
2513
2644
  return send(res, answer.status, answer.body, answer.headers);
2514
2645
  }
2515
2646
  case "raiseRunCap": {
2516
- const run = await needRun(id);
2647
+ // The run is read once its body is in, right before the raise row is written: the pause the answer names
2648
+ // (raiseFollowUpId) is the one the run stands at when its runner takes that row, never one an earlier raise ended
2649
+ // while this body was on its way.
2650
+ if (!ID.test(id) || !(await store.runs.get(id)))
2651
+ throw new ApiError("not_found", `no run ${id}`);
2517
2652
  const body = await bodyOf(req);
2518
2653
  const extra = unknownFields(body, ["max_cost_usd"]);
2519
2654
  if (extra.length)
@@ -2521,6 +2656,7 @@ async function startHolding(options, data, checked, stops) {
2521
2656
  const cap = body.max_cost_usd;
2522
2657
  if (!(typeof cap === "number" && Number.isFinite(cap) && cap > 0))
2523
2658
  throw invalid([{ field: "max_cost_usd", reason: cap === undefined ? "missing" : "wrong_type", message: "max_cost_usd is a number above 0" }]);
2659
+ const run = await needRun(id);
2524
2660
  const now = run.maxCostUsd;
2525
2661
  if (now === undefined)
2526
2662
  throw invalid([{ field: "max_cost_usd", reason: "not_allowed", message: "This run has no cap to raise: a cap is named when a run starts." }]);
@@ -2920,6 +3056,16 @@ async function startHolding(options, data, checked, stops) {
2920
3056
  const located = written.status === 201 && shown.name(written.file) === written.file;
2921
3057
  return sendNote(res, written.status, { ...written, text: shown.text(written.text) }, located ? { location: `/v2/agents/${encodeURIComponent(id)}/learning/files/${written.file}` } : {});
2922
3058
  }
3059
+ case "promoteLearnedWorkflow": {
3060
+ // The source read once the body is in, as it is then: what promoteOf checks and what it copies are that one read.
3061
+ const body = await bodyOf(req);
3062
+ const source = await needAgent(id);
3063
+ const answer = await idempotent(req, `/agents/${id}/learning/workflows/${second}/promote`, body, async () => {
3064
+ const { entry, warnings } = await promoteOf(source, second, body);
3065
+ return { status: 201, body: { ...agentView(entry, linkOrigin(req), await agentExtra(entry)), warnings }, headers: { location: `/v2/agents/${entry.agent.id}`, etag: etagOf(entry) } };
3066
+ });
3067
+ return send(res, answer.status, answer.body, answer.headers);
3068
+ }
2923
3069
  case "getRunLearning": {
2924
3070
  const run = await needRun(id);
2925
3071
  // The run's learning view over the store (learning-1's runLearningOverStore): its end, the notes it was given and its seed
@@ -3352,8 +3498,11 @@ async function startHolding(options, data, checked, stops) {
3352
3498
  await new Promise((done) => (server.close(done), server.closeAllConnections()));
3353
3499
  await mcpStopped;
3354
3500
  await githubStopped;
3501
+ // --faux-github's fake GitHub API, once nothing asks it anything.
3502
+ await fauxGitHub?.close();
3355
3503
  // The store's EXCLUSIVE lock is the one-server lock: closing it releases it for the next server.
3356
3504
  await store.close();
3505
+ dataLock.release();
3357
3506
  seal.release();
3358
3507
  }
3359
3508
  return {
@@ -15,8 +15,10 @@ export type StopDeps = {
15
15
  export declare const REPEAT_MS = 1000;
16
16
  /** How long past its runs' drain bound a stop may take before it stops at once. */
17
17
  export declare const DEADLINE_MARGIN_MS = 15000;
18
- /** The handler for SIGINT and SIGTERM. It exits once: 0 when the close ends, 130 when it stops at once. */
18
+ /** The handler for SIGINT and SIGTERM. It exits once: 0 when the close ends, 130 when it stops at once. `askedAt`: when
19
+ * the stop was asked, when earlier than this call (a signal during the start, cli.ts), so a second signal is timed from
20
+ * the first. */
19
21
  export declare function stopOnSignals(deps: StopDeps, { repeatMs, marginMs }?: {
20
22
  repeatMs?: number | undefined;
21
23
  marginMs?: number | undefined;
22
- }): () => void;
24
+ }): (askedAt?: number) => void;
@@ -7,7 +7,9 @@
7
7
  export const REPEAT_MS = 1_000;
8
8
  /** How long past its runs' drain bound a stop may take before it stops at once. */
9
9
  export const DEADLINE_MARGIN_MS = 15_000;
10
- /** The handler for SIGINT and SIGTERM. It exits once: 0 when the close ends, 130 when it stops at once. */
10
+ /** The handler for SIGINT and SIGTERM. It exits once: 0 when the close ends, 130 when it stops at once. `askedAt`: when
11
+ * the stop was asked, when earlier than this call (a signal during the start, cli.ts), so a second signal is timed from
12
+ * the first. */
11
13
  export function stopOnSignals(deps, { repeatMs = REPEAT_MS, marginMs = DEADLINE_MARGIN_MS } = {}) {
12
14
  const now = deps.now ?? Date.now;
13
15
  const setTimer = deps.setTimer ?? ((run, ms) => void setTimeout(run, ms).unref());
@@ -25,13 +27,13 @@ export function stopOnSignals(deps, { repeatMs = REPEAT_MS, marginMs = DEADLINE_
25
27
  const { runs } = deps.stopping();
26
28
  end(130, `${why}; runs resume on the next start${runs > 0 ? ` (${runs} ${runs === 1 ? "was" : "were"} running)` : ""}`);
27
29
  };
28
- return () => {
30
+ return (askedAt) => {
29
31
  if (stopAt !== undefined) {
30
32
  if (now() - stopAt >= repeatMs)
31
33
  stopNow("stopping now");
32
34
  return;
33
35
  }
34
- stopAt = now();
36
+ stopAt = askedAt ?? now();
35
37
  setTimer(() => stopNow("the stop passed its deadline, stopping now"), deps.stopping().boundMs + marginMs);
36
38
  void deps.close().then(() => end(0));
37
39
  };
@@ -27,10 +27,12 @@ export type RevisionPlace = {
27
27
  box?: string;
28
28
  };
29
29
  /** A revision's computer (computer-setting.ts): its kind and the provider that serves it, ids its host knows, and a
30
- * sandbox's GPUs, a type its provider names and how many; `place` is its v2 view. */
30
+ * sandbox's GPUs, a type its provider names and how many; `place` is its v2 view. `image`: one the provider offers for
31
+ * the kind, absent for its default. */
31
32
  export type RevisionComputer = {
32
33
  kind: string;
33
34
  provider?: string;
35
+ image?: string;
34
36
  gpu?: {
35
37
  type: string;
36
38
  count: number;
@@ -56,6 +58,7 @@ export type AgenticBody = {
56
58
  capMode?: string;
57
59
  approvals?: "ask" | "never";
58
60
  outputSchema?: Record<string, unknown>;
61
+ maxToolCalls?: number;
59
62
  };
60
63
  export type WorkflowBody = {
61
64
  workflow: Record<string, unknown>;
@@ -88,6 +91,7 @@ export type RevisionBodyInput = {
88
91
  capMode?: string;
89
92
  approvals?: "ask" | "never";
90
93
  outputSchema?: Record<string, unknown>;
94
+ maxToolCalls?: number;
91
95
  } | {
92
96
  kind: "workflow";
93
97
  workflow: unknown;