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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (322) hide show
  1. package/CHANGELOG.md +160 -1
  2. package/README.md +306 -36
  3. package/dist/adapters.js +1 -1
  4. package/dist/agent-delete.d.ts +14 -4
  5. package/dist/agent-delete.js +30 -58
  6. package/dist/agent-package.d.ts +71 -0
  7. package/dist/agent-package.js +345 -0
  8. package/dist/agents-store.d.ts +28 -18
  9. package/dist/agents-store.js +48 -34
  10. package/dist/api-only.d.ts +30 -8
  11. package/dist/api-only.js +40 -16
  12. package/dist/archil-routes.d.ts +1 -0
  13. package/dist/archil-routes.js +28 -2
  14. package/dist/claude-login.d.ts +1 -0
  15. package/dist/claude-login.js +1 -1
  16. package/dist/cli-learning/cli.d.ts +3 -0
  17. package/dist/cli-learning/cli.js +17 -3
  18. package/dist/cli-learning/connections.js +3 -2
  19. package/dist/cli-learning/schema.js +2 -1
  20. package/dist/cli.js +70 -7
  21. package/dist/composio-preset.d.ts +2 -1
  22. package/dist/composio-preset.js +4 -3
  23. package/dist/composio-triggers.d.ts +4 -0
  24. package/dist/composio-triggers.js +4 -1
  25. package/dist/computer-needs.d.ts +32 -0
  26. package/dist/computer-needs.js +80 -0
  27. package/dist/computer-setting.d.ts +9 -0
  28. package/dist/computer-setting.js +19 -1
  29. package/dist/computers.d.ts +6 -2
  30. package/dist/computers.js +2 -2
  31. package/dist/console/assets/index-BFgyZzF_.js +734 -0
  32. package/dist/console/assets/index-DbilxljH.css +1 -0
  33. package/dist/console/index.html +2 -2
  34. package/dist/console-links.d.ts +1 -0
  35. package/dist/console-links.js +2 -0
  36. package/dist/env-switch.d.ts +14 -0
  37. package/dist/env-switch.js +23 -0
  38. package/dist/errors.d.ts +1 -0
  39. package/dist/errors.js +3 -0
  40. package/dist/eval-previous.js +4 -3
  41. package/dist/fal-price.d.ts +76 -0
  42. package/dist/fal-price.js +365 -0
  43. package/dist/handed-secret.d.ts +4 -0
  44. package/dist/handed-secret.js +10 -0
  45. package/dist/harness-archive.d.ts +15 -5
  46. package/dist/harness-archive.js +71 -34
  47. package/dist/harness-check.d.ts +2 -1
  48. package/dist/harness-check.js +36 -95
  49. package/dist/harness-egress.d.ts +23 -0
  50. package/dist/harness-egress.js +69 -0
  51. package/dist/harness-recipe-entry.d.ts +71 -0
  52. package/dist/harness-recipe-entry.js +184 -0
  53. package/dist/harness-recipe.d.ts +73 -6
  54. package/dist/harness-recipe.js +185 -31
  55. package/dist/harness-sign-in.d.ts +29 -0
  56. package/dist/harness-sign-in.js +122 -0
  57. package/dist/harness-table.d.ts +21 -0
  58. package/dist/harness-table.js +58 -3
  59. package/dist/harness-zip.d.ts +6 -0
  60. package/dist/harness-zip.js +203 -0
  61. package/dist/ids.d.ts +11 -0
  62. package/dist/ids.js +36 -0
  63. package/dist/learn/commit.d.ts +19 -1
  64. package/dist/learn/commit.js +160 -2
  65. package/dist/learn/compile.d.ts +13 -5
  66. package/dist/learn/compile.js +46 -15
  67. package/dist/learn/delete.d.ts +12 -6
  68. package/dist/learn/delete.js +17 -11
  69. package/dist/learn/folder.d.ts +16 -0
  70. package/dist/learn/folder.js +30 -4
  71. package/dist/learn/learning-of.d.ts +8 -0
  72. package/dist/learn/learning-of.js +8 -0
  73. package/dist/learn/learning.sh +29 -4
  74. package/dist/learn/promote.d.ts +51 -7
  75. package/dist/learn/promote.js +51 -8
  76. package/dist/learn/secrets.js +30 -7
  77. package/dist/learning-reset.d.ts +18 -0
  78. package/dist/learning-reset.js +115 -0
  79. package/dist/learning-routes.d.ts +23 -11
  80. package/dist/learning-routes.js +110 -20
  81. package/dist/learning-words.d.ts +5 -0
  82. package/dist/learning-words.js +5 -0
  83. package/dist/learning.d.ts +15 -10
  84. package/dist/learning.js +14 -8
  85. package/dist/llms.txt +1 -0
  86. package/dist/mcp-gateway.d.ts +39 -2
  87. package/dist/mcp-gateway.js +56 -12
  88. package/dist/mcp-pin-first.js +1 -1
  89. package/dist/mcp-probe.d.ts +3 -0
  90. package/dist/mcp-probe.js +7 -2
  91. package/dist/mcp-resources.d.ts +44 -0
  92. package/dist/mcp-resources.js +100 -0
  93. package/dist/mcp-servers-store.d.ts +17 -12
  94. package/dist/mcp-servers-store.js +2 -1
  95. package/dist/media-duration.d.ts +2 -0
  96. package/dist/media-duration.js +136 -0
  97. package/dist/model.d.ts +4 -4
  98. package/dist/model.js +6 -6
  99. package/dist/native/cli.js +9 -2
  100. package/dist/native/connection.d.ts +2 -2
  101. package/dist/native/connection.js +5 -2
  102. package/dist/native/discovery.d.ts +2 -0
  103. package/dist/native/discovery.js +10 -6
  104. package/dist/native/remote-worker-bridge.js +36 -4
  105. package/dist/native/remote.d.ts +18 -1
  106. package/dist/native/remote.js +126 -37
  107. package/dist/native/schema.d.ts +6 -0
  108. package/dist/native/schema.js +31 -6
  109. package/dist/native/source-account.d.ts +13 -0
  110. package/dist/native/source-account.js +114 -0
  111. package/dist/native/source-capture-hooks.d.ts +5 -0
  112. package/dist/native/source-capture-hooks.js +102 -0
  113. package/dist/native/source-mcp-selection.d.ts +13 -0
  114. package/dist/native/source-mcp-selection.js +72 -0
  115. package/dist/native/source-runtime-tools.d.ts +19 -0
  116. package/dist/native/source-runtime-tools.js +103 -0
  117. package/dist/native/source-snapshot-types.d.ts +138 -0
  118. package/dist/native/source-snapshot-types.js +12 -0
  119. package/dist/native/source-snapshot.d.ts +8 -0
  120. package/dist/native/source-snapshot.js +1201 -0
  121. package/dist/observation/learning.js +3 -2
  122. package/dist/openapi.js +211 -47
  123. package/dist/print.js +1 -1
  124. package/dist/provider.d.ts +8 -0
  125. package/dist/provider.js +14 -2
  126. package/dist/purged-workflow.d.ts +12 -0
  127. package/dist/purged-workflow.js +43 -0
  128. package/dist/refusal-words.d.ts +0 -3
  129. package/dist/refusal-words.js +0 -3
  130. package/dist/request-metadata.d.ts +20 -0
  131. package/dist/request-metadata.js +24 -0
  132. package/dist/run-keys.d.ts +46 -0
  133. package/dist/run-keys.js +109 -0
  134. package/dist/run-launch.d.ts +29 -5
  135. package/dist/run-launch.js +44 -4
  136. package/dist/run-learning-served.d.ts +2 -2
  137. package/dist/run-model-key.d.ts +2 -2
  138. package/dist/run-model-key.js +5 -5
  139. package/dist/run-secrets.d.ts +2 -0
  140. package/dist/run-secrets.js +7 -4
  141. package/dist/run-usage.d.ts +48 -4
  142. package/dist/run-usage.js +156 -39
  143. package/dist/run-view.d.ts +18 -1
  144. package/dist/run-view.js +28 -8
  145. package/dist/runner/adapter-loop.d.ts +14 -4
  146. package/dist/runner/adapter-loop.js +150 -31
  147. package/dist/runner/adapter-run-spec.d.ts +1 -1
  148. package/dist/runner/adapter-run-spec.js +35 -22
  149. package/dist/runner/audit.d.ts +10 -3
  150. package/dist/runner/audit.js +30 -7
  151. package/dist/runner/beside.js +2 -1
  152. package/dist/runner/claim-secrets.d.ts +31 -4
  153. package/dist/runner/claim-secrets.js +43 -7
  154. package/dist/runner/cli-run-spec.d.ts +1 -1
  155. package/dist/runner/cli-run-spec.js +32 -20
  156. package/dist/runner/conformance/harness.js +4 -2
  157. package/dist/runner/dispatch.js +4 -2
  158. package/dist/runner/harness-loops.d.ts +6 -0
  159. package/dist/runner/harness-loops.js +16 -3
  160. package/dist/runner/held.d.ts +4 -0
  161. package/dist/runner/journal-kinds.d.ts +5 -0
  162. package/dist/runner/learned-first.d.ts +2 -0
  163. package/dist/runner/learned-first.js +1 -1
  164. package/dist/runner/learning-end.d.ts +9 -3
  165. package/dist/runner/learning-end.js +66 -29
  166. package/dist/runner/learning-seed.d.ts +9 -3
  167. package/dist/runner/learning-seed.js +2 -2
  168. package/dist/runner/main.d.ts +1 -0
  169. package/dist/runner/main.js +20 -13
  170. package/dist/runner/mcp-claim.js +7 -2
  171. package/dist/runner/mcp-run.d.ts +12 -0
  172. package/dist/runner/mcp-run.js +14 -1
  173. package/dist/runner/model-route.js +7 -4
  174. package/dist/runner/monid-run.js +9 -11
  175. package/dist/runner/project-checkpoint.d.ts +35 -0
  176. package/dist/runner/project-checkpoint.js +116 -0
  177. package/dist/runner/project-drain.d.ts +8 -0
  178. package/dist/runner/project-drain.js +25 -0
  179. package/dist/runner/project-host.d.ts +10 -0
  180. package/dist/runner/project-host.js +52 -0
  181. package/dist/runner/promotion.d.ts +51 -24
  182. package/dist/runner/promotion.js +206 -78
  183. package/dist/runner/redact.d.ts +13 -0
  184. package/dist/runner/redact.js +67 -1
  185. package/dist/runner/run-channel.d.ts +9 -0
  186. package/dist/runner/run-channel.js +15 -2
  187. package/dist/runner/run-child-host.d.ts +8 -4
  188. package/dist/runner/run-child-host.js +174 -42
  189. package/dist/runner/run-errors.js +2 -2
  190. package/dist/runner/runner-check.js +5 -2
  191. package/dist/runner/runner.js +41 -12
  192. package/dist/runner/sdk-loop.d.ts +2 -2
  193. package/dist/runner/sdk-loop.js +3 -3
  194. package/dist/runner/store-port.d.ts +3 -0
  195. package/dist/runner/store-secrets.js +7 -3
  196. package/dist/runner/workflow-first.d.ts +4 -0
  197. package/dist/runner/workflow-first.js +13 -0
  198. package/dist/runner/workflow-loop.d.ts +2 -1
  199. package/dist/runner/workflow-loop.js +2 -1
  200. package/dist/runner/workflow-spec.js +4 -4
  201. package/dist/runs-over-store.d.ts +39 -8
  202. package/dist/runs-over-store.js +147 -32
  203. package/dist/sdk/check.d.ts +6 -5
  204. package/dist/sdk/check.js +17 -16
  205. package/dist/sdk/runs.d.ts +11 -1
  206. package/dist/sdk/runs.js +185 -78
  207. package/dist/sdk/schema.js +12 -2
  208. package/dist/sdk/workflows.d.ts +1 -1
  209. package/dist/server.d.ts +68 -32
  210. package/dist/server.js +678 -124
  211. package/dist/skills/agentrun-serve/SKILL.md +2 -1
  212. package/dist/source-sync/adoption.d.ts +15 -0
  213. package/dist/source-sync/adoption.js +36 -0
  214. package/dist/source-sync/auxiliary.d.ts +23 -0
  215. package/dist/source-sync/auxiliary.js +64 -0
  216. package/dist/source-sync/capture-git.d.ts +5 -0
  217. package/dist/source-sync/capture-git.js +272 -0
  218. package/dist/source-sync/capture-project.d.ts +53 -0
  219. package/dist/source-sync/capture-project.js +206 -0
  220. package/dist/source-sync/capture-refusal.d.ts +7 -0
  221. package/dist/source-sync/capture-refusal.js +16 -0
  222. package/dist/source-sync/capture.d.ts +11 -0
  223. package/dist/source-sync/capture.js +22 -0
  224. package/dist/source-sync/checkpoint-gate.d.ts +21 -0
  225. package/dist/source-sync/checkpoint-gate.js +52 -0
  226. package/dist/source-sync/checkpoints.d.ts +66 -0
  227. package/dist/source-sync/checkpoints.js +168 -0
  228. package/dist/source-sync/claim.d.ts +11 -0
  229. package/dist/source-sync/claim.js +48 -0
  230. package/dist/source-sync/destination.d.ts +47 -0
  231. package/dist/source-sync/destination.js +239 -0
  232. package/dist/source-sync/io.d.ts +15 -0
  233. package/dist/source-sync/io.js +52 -0
  234. package/dist/source-sync/local.d.ts +43 -0
  235. package/dist/source-sync/local.js +229 -0
  236. package/dist/source-sync/prepare.d.ts +59 -0
  237. package/dist/source-sync/prepare.js +93 -0
  238. package/dist/source-sync/projects.d.ts +61 -0
  239. package/dist/source-sync/projects.js +130 -0
  240. package/dist/source-sync/registry.d.ts +95 -0
  241. package/dist/source-sync/registry.js +226 -0
  242. package/dist/source-sync/service.d.ts +33 -0
  243. package/dist/source-sync/service.js +118 -0
  244. package/dist/source-sync/skill-edits.d.ts +12 -0
  245. package/dist/source-sync/skill-edits.js +122 -0
  246. package/dist/source-sync/snapshots.d.ts +48 -0
  247. package/dist/source-sync/snapshots.js +448 -0
  248. package/dist/source-sync/types.d.ts +9 -0
  249. package/dist/source-sync/types.js +14 -0
  250. package/dist/source-sync/workspace.d.ts +66 -0
  251. package/dist/source-sync/workspace.js +273 -0
  252. package/dist/store/agent-body.d.ts +8 -0
  253. package/dist/store/agent-body.js +20 -6
  254. package/dist/store/index.d.ts +2 -2
  255. package/dist/store/index.js +1 -1
  256. package/dist/store/journal/storage.d.ts +2 -0
  257. package/dist/store/journal/storage.js +2 -1
  258. package/dist/store/postgres/migrations/0025_run_attempts.sql +27 -0
  259. package/dist/store/postgres/migrations/0026_run_disk.sql +23 -0
  260. package/dist/store/schema.d.ts +15 -1
  261. package/dist/store/schema.js +43 -4
  262. package/dist/store/seal.d.ts +5 -1
  263. package/dist/store/seal.js +12 -3
  264. package/dist/store/sqlite/project-checkpoints.d.ts +11 -0
  265. package/dist/store/sqlite/project-checkpoints.js +70 -0
  266. package/dist/store/sqlite/run-launch.d.ts +14 -0
  267. package/dist/store/sqlite/run-launch.js +58 -7
  268. package/dist/store/sqlite/run-patch.d.ts +2 -1
  269. package/dist/store/sqlite/run-patch.js +4 -3
  270. package/dist/store/sqlite/store.js +319 -153
  271. package/dist/store/store-schema.js +2 -2
  272. package/dist/store/store.d.ts +173 -33
  273. package/dist/store/store.js +14 -1
  274. package/dist/store-reads/learning.d.ts +12 -8
  275. package/dist/store-reads/learning.js +33 -24
  276. package/dist/store-reads/loop.d.ts +4 -3
  277. package/dist/store-reads/loop.js +7 -5
  278. package/dist/store-view.d.ts +3 -1
  279. package/dist/store-view.js +17 -5
  280. package/dist/template-eval.js +4 -4
  281. package/dist/template-import.d.ts +10 -2
  282. package/dist/template-import.js +116 -13
  283. package/dist/templates.d.ts +29 -5
  284. package/dist/templates.js +68 -14
  285. package/dist/timeline/index.d.ts +1 -1
  286. package/dist/timeline/index.js +1 -1
  287. package/dist/timeline/labels.js +1 -1
  288. package/dist/timeline/timeline.d.ts +5 -0
  289. package/dist/timeline/timeline.js +8 -0
  290. package/dist/tool-plane.d.ts +12 -12
  291. package/dist/tools.d.ts +8 -8
  292. package/dist/tools.js +1 -1
  293. package/dist/trigger-launch-hook.d.ts +47 -0
  294. package/dist/trigger-launch-hook.js +90 -0
  295. package/dist/trigger-targets.d.ts +14 -1
  296. package/dist/trigger-targets.js +20 -0
  297. package/dist/triggers.d.ts +54 -5
  298. package/dist/triggers.js +143 -8
  299. package/dist/uploads-archil.js +2 -1
  300. package/dist/uploads.d.ts +0 -3
  301. package/dist/uploads.js +2 -11
  302. package/dist/validate.js +4 -1
  303. package/dist/web-save.d.ts +3 -0
  304. package/dist/web-save.js +17 -2
  305. package/dist/workspace/archil-exec.js +1 -1
  306. package/dist/workspace/archil.js +1 -1
  307. package/dist/workspace/computer-for-claim.d.ts +2 -0
  308. package/dist/workspace/computer-for-claim.js +43 -0
  309. package/dist/workspace/paths.d.ts +6 -0
  310. package/dist/workspace/paths.js +6 -0
  311. package/dist/workspace/resolve-computer.d.ts +1 -0
  312. package/dist/workspace/revision-skills.js +24 -11
  313. package/dist/workspace/run-tools.d.ts +2 -0
  314. package/dist/workspace/run-tools.js +8 -0
  315. package/dist/workspace/synced-folder.d.ts +3 -3
  316. package/dist/workspace/synced-folder.js +7 -6
  317. package/launcher/agentrun-serve +1 -1
  318. package/package.json +10 -10
  319. package/skills/agentrun-serve/SKILL.md +2 -1
  320. package/templates/README.md +5 -2
  321. package/dist/console/assets/index-Bt1B51b7.js +0 -733
  322. package/dist/console/assets/index-sVftE9Ht.css +0 -1
@@ -0,0 +1,90 @@
1
+ // The launch hook: a server started with AGENTRUN_LAUNCH_HOOK_URL and AGENTRUN_LAUNCH_HOOK_SECRET hands each trigger firing
2
+ // that would start a run to the host behind it instead (triggers.ts drive), and starts no run of its own for it. The host
3
+ // starts the run through the API (POST /v2/agents/{agent_id}/runs with `trigger_firing` and its own model_key, keys and
4
+ // max_cost_usd: the firing's run, under its key, triggers.ts handedStart) and answers 2xx, before or after that start
5
+ // (after: within LAUNCH_HOOK_LATE_START_MS of that 2xx, the firing's start_by); any other answer, or none within
6
+ // LAUNCH_HOOK_TIMEOUT_MS, and the firing is skipped with why, unless the host started its run. Unset, nothing changes.
7
+ // Off this machine the hook is https: a firing's input can carry a person's data, and the signature proves who sent it,
8
+ // not that no one else read it.
9
+ // The POST is signed as the outbound webhook's messages are (standard-webhooks.ts): `webhook-id` (the firing's id, the
10
+ // same each time it is handed), `webhook-timestamp` (Unix seconds) and `webhook-signature: v1,<base64 HMAC-SHA256 of
11
+ // "{id}.{timestamp}.{body}">` under the secret's key, so a host checks it with any Standard Webhooks library.
12
+ import { fetch as undiciFetch } from "undici";
13
+ import { keyBytes, MIN_KEY_BYTES, SECRET_PREFIX, signatureOf } from "./standard-webhooks.js";
14
+ export const LAUNCH_HOOK_URL_ENV = "AGENTRUN_LAUNCH_HOOK_URL";
15
+ export const LAUNCH_HOOK_SECRET_ENV = "AGENTRUN_LAUNCH_HOOK_SECRET";
16
+ /** How long the host has to answer a firing, its connection included. */
17
+ export const LAUNCH_HOOK_TIMEOUT_MS = 10_000;
18
+ /** How long after its 2xx a host that answered without starting the firing's run may still start it (one start, under
19
+ * the firing: triggers.ts handedStart). From the answer, not from fired_at: a catch-up, a firing that waited on its
20
+ * trigger's max_active_runs, or one a stop cut short and the next start handed again reaches the host late, and its
21
+ * host gets the same 10 minutes as any. */
22
+ export const LAUNCH_HOOK_LATE_START_MS = 10 * 60_000;
23
+ /** A host this machine alone answers: localhost, 127.0.0.0/8 or ::1, as URL writes them (lower case, IPv4 in four parts,
24
+ * IPv6 in brackets and shortest form). */
25
+ const loopback = (hostname) => hostname === "localhost" || hostname === "[::1]" || /^127(\.\d{1,3}){3}$/.test(hostname);
26
+ /** The launch hook `given` sets (the URL from the environment, the secret as the server holds its own), or undefined when
27
+ * neither is set. Throws, in words that never hold the secret, when one is set without the other, the URL is not https
28
+ * (http only to loopback) or holds a user or password, or the secret is not a `whsec_` secret of MIN_KEY_BYTES or more. */
29
+ export function launchHookFrom(given) {
30
+ const url = given.url?.trim() || undefined;
31
+ const secret = given.secret?.trim() || undefined;
32
+ if (!url && !secret)
33
+ return undefined;
34
+ if (!secret)
35
+ throw new Error(`${LAUNCH_HOOK_URL_ENV} is set without ${LAUNCH_HOOK_SECRET_ENV}: the launch hook signs every firing it hands over. Set both, or neither.`);
36
+ if (!url)
37
+ throw new Error(`${LAUNCH_HOOK_SECRET_ENV} is set without ${LAUNCH_HOOK_URL_ENV}: the launch hook needs the host's URL. Set both, or neither.`);
38
+ let parsed;
39
+ try {
40
+ parsed = new URL(url);
41
+ }
42
+ catch {
43
+ throw new Error(`${LAUNCH_HOOK_URL_ENV} is not a URL: give the host's http or https address for firings.`);
44
+ }
45
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:")
46
+ throw new Error(`${LAUNCH_HOOK_URL_ENV} is an http or https address, not ${parsed.protocol}`);
47
+ if (parsed.protocol === "http:" && !loopback(parsed.hostname)) {
48
+ throw new Error(`${LAUNCH_HOOK_URL_ENV} is http to ${parsed.hostname}: a firing's input can carry a person's data, so a hook off this machine is https. Plain http is for 127.0.0.0/8, ::1 or localhost alone.`);
49
+ }
50
+ if (parsed.username || parsed.password)
51
+ throw new Error(`${LAUNCH_HOOK_URL_ENV} holds no user or password: the host checks the signature.`);
52
+ if (!secret.startsWith(SECRET_PREFIX))
53
+ throw new Error(`${LAUNCH_HOOK_SECRET_ENV} is a Standard Webhooks secret: ${SECRET_PREFIX} and its key in base64.`);
54
+ if (keyBytes(secret) < MIN_KEY_BYTES)
55
+ throw new Error(`${LAUNCH_HOOK_SECRET_ENV}'s key is shorter than ${MIN_KEY_BYTES} bytes: make one of 32 random bytes.`);
56
+ return { url, secret };
57
+ }
58
+ /** Where `hook` sends, for the start's banner: its origin alone, never a path or query that may hold a token. */
59
+ export const hookOrigin = (hook) => new URL(hook.url).origin;
60
+ /** `firing` handed to `hook`: one signed POST of it, within the hook's bound and cut by `stop`. A redirect is not followed. */
61
+ export async function handToHost(hook, firing, stop) {
62
+ const timeoutMs = hook.timeoutMs ?? LAUNCH_HOOK_TIMEOUT_MS;
63
+ const body = JSON.stringify(firing);
64
+ const timestamp = String(Math.floor(Date.now() / 1000));
65
+ const headers = {
66
+ "content-type": "application/json",
67
+ "user-agent": "agentrun-serve-launch-hook/1",
68
+ "webhook-id": firing.firing_id,
69
+ "webhook-timestamp": timestamp,
70
+ "webhook-signature": signatureOf(hook.secret, firing.firing_id, timestamp, body),
71
+ };
72
+ const signal = AbortSignal.any([AbortSignal.timeout(timeoutMs), stop]);
73
+ try {
74
+ const res = await undiciFetch(hook.url, { method: "POST", redirect: "manual", signal, headers, body });
75
+ // The answer's body is not read: the run the host started is found by the firing's key, never by what it says.
76
+ await res.body?.cancel().catch(() => undefined);
77
+ if (res.status >= 200 && res.status <= 299)
78
+ return { taken: true };
79
+ const said = res.status >= 300 && res.status < 400 ? `answered ${res.status}: a redirect is not followed` : `answered ${res.status}`;
80
+ return { skipped: `The launch hook ${said}, so the host did not take this firing.` };
81
+ }
82
+ catch (error) {
83
+ if (stop.aborted)
84
+ return { stopped: true };
85
+ if (error.name === "TimeoutError" || signal.aborted)
86
+ return { skipped: `The launch hook did not answer in ${timeoutMs / 1000} s, so the host did not take this firing.` };
87
+ const code = error.cause?.code;
88
+ return { skipped: `The launch hook was not reached${typeof code === "string" ? ` (${code})` : ""}, so the host did not take this firing.` };
89
+ }
90
+ }
@@ -1,10 +1,14 @@
1
- import { type InputIssue } from "./errors.js";
1
+ import { ApiError, type InputIssue } from "./errors.js";
2
2
  import { type RunMoment, type RunsStore, type StartDeps } from "./runs-over-store.js";
3
3
  import type { Store } from "./store/index.js";
4
4
  import type { AgentEntry } from "./agents-store.js";
5
5
  import type { MessageOrigin } from "./timeline/index.js";
6
6
  import type { Json } from "./validate.js";
7
7
  import type { RunTrigger, Target } from "./triggers.js";
8
+ /** Why a trigger may not message a run on a harness recipe billed to its vendor's plan: the turn would run as that run
9
+ * does, on its owner's own sign-in, which runs only what a person starts (HARNESS.md#run-it), and a scheduled turn runs
10
+ * on keys saved for the harness, which no server saves yet (the claim's RECIPE_SIGN_IN_PERSON_ONLY, for a new run). */
11
+ export declare const RECIPE_MESSAGE_PERSON_ONLY = "The run is on a harness recipe billed to its vendor's plan, which runs on its owner's own sign-in only for what a person starts: a trigger's turn runs on keys saved for that harness, and this server saves no harness's keys yet. Message the run yourself, or target a run on a harness billed through this server's model proxy.";
8
12
  /** What the trigger target policy needs that lives elsewhere: the run-start leaves (StartDeps, shared with the create
9
13
  * route), the agent reads, and the run view that gives a run's live moment and its v2 status. */
10
14
  export interface TriggerTargetDeps {
@@ -19,6 +23,9 @@ export interface TriggerTargetDeps {
19
23
  /** A run's live moment, for a message's acceptance and a target's cap/kind check (the run view → RunMoment); undefined
20
24
  * for an unknown run. */
21
25
  momentOf(runId: string): Promise<RunMoment | undefined>;
26
+ /** Whether `harness` is a harness recipe billed to its vendor's plan in this server's table (harness-table.ts
27
+ * recipeHarness): a trigger never messages a run on one. Absent: none is. */
28
+ planRecipe?(harness: string): boolean;
22
29
  /** `work`, a write that may open run `runId` of agent `agentId` again, done in the agent's delete turn (server.ts
23
30
  * runWrite): never under a purge of the run, and 410 purged after one. */
24
31
  runWrite<T>(agentId: string, runId: string, work: () => Promise<T>): Promise<T>;
@@ -29,6 +36,11 @@ export interface TriggerTargetDeps {
29
36
  * fields the output schema it was checked against (its pinned revision's, never the agent's current one) names in
30
37
  * `x-carried` (answer-json.ts carriedFields), absent when it names none. */
31
38
  completedOutput(runId: string): Promise<CompletedOutput | undefined>;
39
+ /** Under the run-keys setting, the keys a run of `revision` owes when it carries none (run-keys.ts keysOwed); absent
40
+ * when the setting is off. */
41
+ keysOwed?(revision: object): InputIssue[];
42
+ /** The server has the launch hook: each start_run firing goes to the backend in front of it (trigger-launch-hook.ts). */
43
+ readonly hooked?: boolean;
32
44
  }
33
45
  /** The most bytes of a previous run's result a triggered run is handed, as JSON: past it, it is handed none, said so. */
34
46
  export declare const PREVIOUS_RESULT_MAX_BYTES: number;
@@ -66,6 +78,7 @@ export declare function previousHandover(runId: string, done: CompletedOutput):
66
78
  * adapter's sealed settings, the failed-firing webhook) stay server-wired. */
67
79
  export type TriggerTargets = {
68
80
  targetIssues(target: Target): Promise<InputIssue[]>;
81
+ targetRefusal(target: Target): Promise<ApiError | undefined>;
69
82
  start(target: Extract<Target, {
70
83
  kind: "start_run";
71
84
  }>, input: Json, origin: RunTrigger, from: MessageOrigin, title: string | undefined, previous: boolean): Promise<{
@@ -8,8 +8,13 @@ import { ApiError, unsupported } from "./errors.js";
8
8
  import { message, startRun, WAITS_ON_A_PERSON } from "./runs-over-store.js";
9
9
  import { runOfOrigin } from "./store-reads/runs.js";
10
10
  import { NATIVE_CAP_UNSUPPORTED, NATIVE_RUN_OVERRIDES_UNSUPPORTED, nativeOf, nativeRunOverrides } from "./native/binding.js";
11
+ import { firingsOwe, keysOwedRefusal } from "./run-keys.js";
11
12
  /** Why a trigger may not message a run with no cap (server.ts NO_CAP). */
12
13
  const NO_CAP = "The run has no spend cap: a trigger only messages a run with one, as every turn it drives is capped.";
14
+ /** Why a trigger may not message a run on a harness recipe billed to its vendor's plan: the turn would run as that run
15
+ * does, on its owner's own sign-in, which runs only what a person starts (HARNESS.md#run-it), and a scheduled turn runs
16
+ * on keys saved for the harness, which no server saves yet (the claim's RECIPE_SIGN_IN_PERSON_ONLY, for a new run). */
17
+ export const RECIPE_MESSAGE_PERSON_ONLY = "The run is on a harness recipe billed to its vendor's plan, which runs on its owner's own sign-in only for what a person starts: a trigger's turn runs on keys saved for that harness, and this server saves no harness's keys yet. Message the run yourself, or target a run on a harness billed through this server's model proxy.";
13
18
  /** The most of a trigger's firings, newest first, read for its last completed run. */
14
19
  const PREVIOUS_FIRINGS_READ = 20;
15
20
  /** The most bytes of a previous run's result a triggered run is handed, as JSON: past it, it is handed none, said so. */
@@ -110,6 +115,15 @@ function carriedEntryBytes(entry) {
110
115
  /** The trigger target policy over `store`, with its reads and the run-start leaves injected. */
111
116
  export function triggerTargets(store, deps) {
112
117
  return {
118
+ async targetRefusal(target) {
119
+ if (!deps.keysOwed)
120
+ return undefined;
121
+ // The revision a firing would open a turn of: the run's own for a message_run, the agent's current for a start_run.
122
+ const row = target.kind === "message_run" ? await store.runs.get(target.run_id) : undefined;
123
+ const revision = target.kind === "message_run" ? (row ? await store.agents.revision(row.revisionId) : undefined) : (await deps.getAgent(target.agent_id))?.revision;
124
+ const owed = revision ? deps.keysOwed(revision) : [];
125
+ return firingsOwe(owed, target.kind, deps.hooked === true) ? keysOwedRefusal(owed) : undefined;
126
+ },
113
127
  async targetIssues(target) {
114
128
  if (target.kind === "message_run") {
115
129
  const run = await deps.momentOf(target.run_id);
@@ -117,6 +131,8 @@ export function triggerTargets(store, deps) {
117
131
  return [{ field: "target.run_id", reason: "not_found", message: `no run ${target.run_id}` }];
118
132
  if (run.kind === "workflow")
119
133
  return [{ field: "target.run_id", reason: "not_allowed", message: "A workflow run takes no messages here." }];
134
+ if (run.harness !== undefined && deps.planRecipe?.(run.harness))
135
+ return [{ field: "target.run_id", reason: "not_allowed", message: RECIPE_MESSAGE_PERSON_ONLY }];
120
136
  return run.maxCostUsd === undefined ? [{ field: "target.run_id", reason: "not_allowed", message: NO_CAP }] : [];
121
137
  }
122
138
  const entry = await deps.getAgent(target.agent_id);
@@ -164,6 +180,10 @@ export function triggerTargets(store, deps) {
164
180
  throw new ApiError("not_found", `There is no run ${target.run_id}.`);
165
181
  if (run.kind === "workflow")
166
182
  throw unsupported("messages.steer_workflow_runs", "A workflow run takes no messages here.");
183
+ // Never a turn on a plan-billed recipe (its owner's own sign-in, a person's alone): checked again at each firing, as
184
+ // the server may since have been started with that recipe; skipped in words, never queued.
185
+ if (run.harness !== undefined && deps.planRecipe?.(run.harness))
186
+ return { skipped: RECIPE_MESSAGE_PERSON_ONLY };
167
187
  // Never an uncapped turn, nor an answer to a person's question, an approval or a budget pause: a run that waits on its
168
188
  // person is told nothing by a trigger (skipped, never queued behind the person).
169
189
  if (run.maxCostUsd === undefined)
@@ -2,6 +2,7 @@ import { type MessageOrigin } from "./timeline/index.js";
2
2
  import { ApiError, type InputIssue } from "./errors.js";
3
3
  import { type FiringRow, type Store } from "./store/index.js";
4
4
  import { type Source, type TriggerAdapter } from "./trigger-adapter.js";
5
+ import { type LaunchHook } from "./trigger-launch-hook.js";
5
6
  import { type Json } from "./validate.js";
6
7
  export { MAX_EVERY_S, MIN_EVERY_S } from "./trigger-schedule.js";
7
8
  /** The firings each trigger keeps in its history, newest first; a firing still due is never dropped, nor a failure whose
@@ -14,6 +15,8 @@ export declare const DUE_KEPT = 20;
14
15
  export declare const SOURCE_KINDS: readonly string[];
15
16
  export declare const TARGET_KINDS: readonly ["start_run", "message_run"];
16
17
  export declare const FIRING_STATUSES: readonly ["due", "started", "sent", "skipped", "failed", "missed"];
18
+ /** A firing the launch hook's host took (a 2xx) without starting its run here under the firing (RunCreate trigger_firing). */
19
+ export declare const HANDED_NO_RUN = "Handed to the host by the launch hook, which started no run here for it.";
17
20
  /** The most of a webhook's payload a firing passes on: the rest is cut, at a character's start (trigger-adapter.ts). */
18
21
  /** How late a missed time may be and still fire once, by default: an hour. */
19
22
  export declare const CATCHUP_WINDOW_S = 3600;
@@ -119,6 +122,9 @@ export type TriggerDeps = {
119
122
  credentials?(kind: string): Promise<unknown>;
120
123
  /** What keeps a target from starting runs here, by field (its agent, its kind, its input). */
121
124
  targetIssues(target: Target): Promise<InputIssue[]>;
125
+ /** The refusal of a trigger aimed at `target` whose firings could never start or message a run that has what it needs
126
+ * (run-keys.ts firingsOwe), once its fields read; undefined, or no such dep, when there is none. */
127
+ targetRefusal?(target: Target): Promise<ApiError | undefined>;
122
128
  /** Starts the target's run with `input`, as POST /agents/{id}/runs would, under `origin`, titled `title` (its
123
129
  * trigger's, never its input's); its first message is the trigger's (`from`, never the person's); ApiError when
124
130
  * refused. */
@@ -168,6 +174,9 @@ export type TriggerDeps = {
168
174
  publicUrl?: string;
169
175
  /** What source `kind`'s sender keeps of its triggers, when it is set up from here (TriggerUpstream); none for the rest. */
170
176
  upstream?(kind: string): TriggerUpstream | undefined;
177
+ /** The launch hook (AGENTRUN_LAUNCH_HOOK_URL): set, a firing that would start a run here is handed to the host
178
+ * instead (trigger-launch-hook.ts); a message_run firing starts no run and is sent here as ever. */
179
+ launchHook?: LaunchHook;
171
180
  };
172
181
  export declare const firingKey: (by: string, triggerId: string, what: string) => string;
173
182
  /** What is wrong with a POST /triggers body by itself, as create refuses it with the sources of `adapters`, all but the
@@ -208,10 +217,13 @@ export declare class Triggers {
208
217
  /** Each polled trigger's count of turn-ons: a poll that sees it changed keeps nothing, its cursor read before. */
209
218
  private readonly restarts;
210
219
  private closed;
220
+ /** Aborted by close: a firing being handed to the host is cut short and left due. */
221
+ private readonly stopping;
211
222
  constructor(deps: TriggerDeps);
212
223
  /** At the server's start: every enabled trigger whose source no longer reads turned off, each failure's trigger.failed
213
- * queued that is not yet, every firing an earlier server left due driven again (its origin key makes a run it already
214
- * started the same run), the times missed while it was down recorded, and the timer armed. */
224
+ * queued that is not yet, each sent firing whose host's run is in the store started with it (relink), every firing an
225
+ * earlier server left due driven again (its origin key makes a run it already started the same run), the times missed
226
+ * while it was down recorded, and the timer armed. */
215
227
  start(): Promise<void>;
216
228
  close(): void;
217
229
  list(): Promise<{
@@ -230,6 +242,7 @@ export declare class Triggers {
230
242
  created_at: string;
231
243
  updated_at: string;
232
244
  last_firing: {
245
+ start_by?: string | undefined;
233
246
  attempts?: number | undefined;
234
247
  retry_at?: string | undefined;
235
248
  catch_up?: boolean | undefined;
@@ -269,6 +282,7 @@ export declare class Triggers {
269
282
  created_at: string;
270
283
  updated_at: string;
271
284
  last_firing: {
285
+ start_by?: string | undefined;
272
286
  attempts?: number | undefined;
273
287
  retry_at?: string | undefined;
274
288
  catch_up?: boolean | undefined;
@@ -294,6 +308,7 @@ export declare class Triggers {
294
308
  }>;
295
309
  firings(id: string): Promise<{
296
310
  firings: {
311
+ start_by?: string | undefined;
297
312
  attempts?: number | undefined;
298
313
  retry_at?: string | undefined;
299
314
  catch_up?: boolean | undefined;
@@ -327,6 +342,7 @@ export declare class Triggers {
327
342
  created_at: string;
328
343
  updated_at: string;
329
344
  last_firing: {
345
+ start_by?: string | undefined;
330
346
  attempts?: number | undefined;
331
347
  retry_at?: string | undefined;
332
348
  catch_up?: boolean | undefined;
@@ -386,9 +402,13 @@ export declare class Triggers {
386
402
  id: string;
387
403
  name: string;
388
404
  }[]>;
389
- /** Agent `agentId` unarchived: none of its triggers turns on again. The triggers its archive turned off that are off
390
- * still, by name: each is turned on by a PATCH. */
391
- agentUnarchived(agentId: string): Promise<{
405
+ /** Agent `agentId` unarchived: none of its triggers turns on again, but those its archive turned off whose source
406
+ * `turnOn` takes, each turned on as a PATCH with enabled true does (an API-only server's with the launch hook, which
407
+ * serves no trigger route: api-only.ts). The triggers its archive turned off that are off still, by name: each is
408
+ * turned on by a PATCH. One `turnOn` takes that can't be on (a schedule with no time left), or that its first check
409
+ * turns off again, is named: what is off is read from the store after the turn-ons, never taken from whether one
410
+ * resolved. */
411
+ agentUnarchived(agentId: string, turnOn?: (source: Source) => boolean): Promise<{
392
412
  id: string;
393
413
  name: string;
394
414
  }[]>;
@@ -437,6 +457,7 @@ export declare class Triggers {
437
457
  created_at: string;
438
458
  updated_at: string;
439
459
  last_firing: {
460
+ start_by?: string | undefined;
440
461
  attempts?: number | undefined;
441
462
  retry_at?: string | undefined;
442
463
  catch_up?: boolean | undefined;
@@ -561,6 +582,33 @@ export declare class Triggers {
561
582
  /** A target refused the firing: a busy server's answer is a failed try under the table; any other (a refusal, a thrown
562
583
  * error) fails the firing at once. Both count toward the streak. */
563
584
  private answered;
585
+ /** A start_run firing handed to the host by the launch hook, never started here. The run the host started for it
586
+ * (handedStart: under the firing's key) makes it started, as a run started here would, whatever the hook answered;
587
+ * else a 2xx makes it sent, with no run (its attrs kept for a run the host starts late: handedRan) and its startBy
588
+ * LAUNCH_HOOK_LATE_START_MS after that answer, and any other answer or none skipped with why. The server's stop leaves
589
+ * it due, so the next start hands it again under the same webhook-id (or finds the run the host started). */
590
+ private handed;
591
+ /** The run the host starts through the API for a firing the launch hook handed it (RunCreate `trigger_firing`): the
592
+ * firing's key (the run's origin key, so the firing finds it), and the trigger, input origin and title its own start
593
+ * would give the run; or the run already started under that key. Refused, in words, unless this server has the hook and
594
+ * the firing, of a start_run trigger on `agentId`, is due (being handed over) or one its host took with no run, up to
595
+ * its startBy (the host may answer first and start the run after). */
596
+ handedStart(given: unknown, agentId: string): Promise<{
597
+ run_id: string;
598
+ } | {
599
+ key: string;
600
+ trigger: RunTrigger;
601
+ from: MessageOrigin;
602
+ title: string;
603
+ }>;
604
+ /** Run `runId`, which the host started for firing `key` (handedStart), started: one whose host answered first (sent,
605
+ * with no run) is made started here, as handed() makes it when the run came first, so the overlap check and
606
+ * max_active_runs count it. A firing still being handed is left to handed(), which reads its run after the answer. */
607
+ handedRan(triggerId: string, key: string, runId: string): Promise<void>;
608
+ /** Each sent firing whose host's run is in the store under its key, though the server stopped before the firing was
609
+ * started with it (a late start writes the run, then handedRan): started with that run, so the overlap check and
610
+ * max_active_runs count it. */
611
+ private relink;
564
612
  private started;
565
613
  /** A failed firing: one more in its trigger's streak, the trigger turned off at FAILURES_TO_PAUSE, and trigger.failed
566
614
  * queued (after the firing is written: a start finds one not yet queued and queues it, under the same webhook-id). */
@@ -632,6 +680,7 @@ export interface TriggerOwn {
632
680
  readonly onAgent?: string;
633
681
  }
634
682
  declare function firingView(firing: FiringRow): {
683
+ start_by?: string | undefined;
635
684
  attempts?: number | undefined;
636
685
  retry_at?: string | undefined;
637
686
  catch_up?: boolean | undefined;
package/dist/triggers.js CHANGED
@@ -21,14 +21,18 @@
21
21
  // late timer does not drift. Of the times that came while the server was down, or its timer late past LATE_MS, the
22
22
  // latest fires if it is within the trigger's catch-up window and the rest are one `missed` row; the schedule goes on from
23
23
  // now. A failed firing queues a trigger.failed webhook message.
24
+ // With the launch hook set (trigger-launch-hook.ts), a firing that would start a run goes the same way up to the start,
25
+ // then is handed to the host instead: sent when the host takes it, skipped with why when it does not.
24
26
  import { createHash, randomBytes } from "node:crypto";
25
27
  import { TRIGGER_LABELS } from "./timeline/index.js";
26
28
  import { agentDeleting, purgedAgent } from "./agents.js";
29
+ import { ownedElsewhere } from "./agents-store.js";
27
30
  import { ApiError, invalid } from "./errors.js";
28
31
  import { EFFORTS } from "./model.js";
29
32
  import { AgentArchived, StoreConstraint, TriggerFull } from "./store/index.js";
30
33
  import { carriesPrevious, PAYLOAD_KEPT_BYTES, second, validZone } from "./trigger-adapter.js";
31
34
  import { TRIGGER_ADAPTERS } from "./trigger-adapters.js";
35
+ import { handToHost, LAUNCH_HOOK_LATE_START_MS } from "./trigger-launch-hook.js";
32
36
  import { MAX_EVERY_S } from "./trigger-schedule.js";
33
37
  import { ID, IDEMPOTENCY_TTL_S, isObject, unknownFields } from "./validate.js";
34
38
  export { MAX_EVERY_S, MIN_EVERY_S } from "./trigger-schedule.js";
@@ -44,6 +48,8 @@ const FULL_RETRY_S = 30;
44
48
  export const SOURCE_KINDS = TRIGGER_ADAPTERS.map((a) => a.id);
45
49
  export const TARGET_KINDS = ["start_run", "message_run"];
46
50
  export const FIRING_STATUSES = ["due", "started", "sent", "skipped", "failed", "missed"];
51
+ /** A firing the launch hook's host took (a 2xx) without starting its run here under the firing (RunCreate trigger_firing). */
52
+ export const HANDED_NO_RUN = "Handed to the host by the launch hook, which started no run here for it.";
47
53
  /** The most of a webhook's payload a firing passes on: the rest is cut, at a character's start (trigger-adapter.ts). */
48
54
  /** How late a missed time may be and still fire once, by default: an hour. */
49
55
  export const CATCHUP_WINDOW_S = 3600;
@@ -239,6 +245,8 @@ export class Triggers {
239
245
  /** Each polled trigger's count of turn-ons: a poll that sees it changed keeps nothing, its cursor read before. */
240
246
  restarts = new Map();
241
247
  closed = false;
248
+ /** Aborted by close: a firing being handed to the host is cut short and left due. */
249
+ stopping = new AbortController();
242
250
  constructor(deps) {
243
251
  this.deps = deps;
244
252
  this.store = deps.store;
@@ -254,15 +262,18 @@ export class Triggers {
254
262
  throw new Error(`two trigger sources claim the id ${twice.id}${twice.push ? `, and its hook /v2/hooks/${twice.id}` : ""}: one source each`);
255
263
  }
256
264
  /** At the server's start: every enabled trigger whose source no longer reads turned off, each failure's trigger.failed
257
- * queued that is not yet, every firing an earlier server left due driven again (its origin key makes a run it already
258
- * started the same run), the times missed while it was down recorded, and the timer armed. */
265
+ * queued that is not yet, each sent firing whose host's run is in the store started with it (relink), every firing an
266
+ * earlier server left due driven again (its origin key makes a run it already started the same run), the times missed
267
+ * while it was down recorded, and the timer armed. */
259
268
  async start() {
260
269
  const now = this.clock.now();
261
270
  await this.offUnreadable((await this.all()).filter((t) => t.enabled && this.problem(t.source)), now);
271
+ await this.relink();
262
272
  await this.tick();
263
273
  }
264
274
  close() {
265
275
  this.closed = true;
276
+ this.stopping.abort();
266
277
  this.timer?.clear();
267
278
  this.timer = undefined;
268
279
  }
@@ -284,6 +295,9 @@ export class Triggers {
284
295
  issues.push(...(await this.deps.targetIssues(this.given(typeof body.name === "string" ? body.name.trim() : `trg_${"0".repeat(24)}`, source, target, now))));
285
296
  if (issues.length || !source || !target)
286
297
  throw invalid(issues);
298
+ const refused = await this.deps.targetRefusal?.(target);
299
+ if (refused)
300
+ throw refused;
287
301
  const agentId = await this.agentOf(target);
288
302
  const id = `trg_${randomBytes(12).toString("hex")}`;
289
303
  const enabled = body.enabled !== false;
@@ -388,11 +402,20 @@ export class Triggers {
388
402
  await this.offThere((await Promise.all(off.map((t) => this.find(t.id)))).filter((t) => t !== undefined));
389
403
  return off;
390
404
  }
391
- /** Agent `agentId` unarchived: none of its triggers turns on again. The triggers its archive turned off that are off
392
- * still, by name: each is turned on by a PATCH. */
393
- async agentUnarchived(agentId) {
405
+ /** Agent `agentId` unarchived: none of its triggers turns on again, but those its archive turned off whose source
406
+ * `turnOn` takes, each turned on as a PATCH with enabled true does (an API-only server's with the launch hook, which
407
+ * serves no trigger route: api-only.ts). The triggers its archive turned off that are off still, by name: each is
408
+ * turned on by a PATCH. One `turnOn` takes that can't be on (a schedule with no time left), or that its first check
409
+ * turns off again, is named: what is off is read from the store after the turn-ons, never taken from whether one
410
+ * resolved. */
411
+ async agentUnarchived(agentId, turnOn = () => false) {
394
412
  await this.store.agents.archive(agentId, false);
395
- return (await this.store.triggers.list(agentId)).filter((t) => !t.enabled && reasonOf(t.disabled) === "agent_archived").map((t) => ({ id: t.id, name: t.name }));
413
+ const off = (await this.store.triggers.list(agentId)).map(asTrigger).filter((t) => !t.enabled && reasonOf(t.disabled) === "agent_archived");
414
+ for (const t of off)
415
+ if (turnOn(t.source))
416
+ await this.update(t.id, { enabled: true }, { onAgent: agentId }).catch(() => undefined);
417
+ const ids = new Set(off.map((t) => t.id));
418
+ return (await this.store.triggers.list(agentId)).filter((t) => ids.has(t.id) && !t.enabled).map((t) => ({ id: t.id, name: t.name }));
396
419
  }
397
420
  /** Refused (409 agent_archived) when agent `agentId` is archived: a trigger made on, turned on or aimed at it. */
398
421
  async needAgentOn(agentId) {
@@ -407,7 +430,7 @@ export class Triggers {
407
430
  const agent = await this.store.agents.get(agentId);
408
431
  if (agent?.purgedAt != null)
409
432
  throw purgedAgent(agent);
410
- if (agent?.archivedAt != null && agent.externalRef != null)
433
+ if (agent?.archivedAt != null && ownedElsewhere(agent))
411
434
  throw agentDeleting(agentId);
412
435
  }
413
436
  /** The store's refusal of a trigger left on for an archived agent (an archive that committed past needAgentOn) as the
@@ -494,6 +517,9 @@ export class Triggers {
494
517
  issues.push(...(await this.deps.targetIssues(this.given(typeof body.name === "string" ? body.name.trim() : was.name, source ?? was.source, target, this.clock.now()))));
495
518
  if (issues.length || (body.source !== undefined && !source) || (body.target !== undefined && !target))
496
519
  throw invalid(issues);
520
+ const refused = target ? await this.deps.targetRefusal?.(target) : undefined;
521
+ if (refused)
522
+ throw refused;
497
523
  const trigger = await this.need(id, own.onAgent);
498
524
  if (source && source.kind !== trigger.source.kind)
499
525
  throw invalid([{ field: "source.kind", reason: "not_allowed", message: "A trigger's source kind is fixed: make a new trigger for another." }]);
@@ -977,6 +1003,8 @@ export class Triggers {
977
1003
  return;
978
1004
  if (now.target.kind === "message_run")
979
1005
  return void (await this.send(now, firing));
1006
+ if (this.deps.launchHook)
1007
+ return void (await this.handed(now, firing, this.deps.launchHook));
980
1008
  let started;
981
1009
  try {
982
1010
  const attrs = firing.attrs;
@@ -1104,6 +1132,112 @@ export class Triggers {
1104
1132
  return this.failedTry(triggerId, key, error);
1105
1133
  await this.failed(triggerId, key, errorOf(error), runId);
1106
1134
  }
1135
+ /** A start_run firing handed to the host by the launch hook, never started here. The run the host started for it
1136
+ * (handedStart: under the firing's key) makes it started, as a run started here would, whatever the hook answered;
1137
+ * else a 2xx makes it sent, with no run (its attrs kept for a run the host starts late: handedRan) and its startBy
1138
+ * LAUNCH_HOOK_LATE_START_MS after that answer, and any other answer or none skipped with why. The server's stop leaves
1139
+ * it due, so the next start hands it again under the same webhook-id (or finds the run the host started). */
1140
+ async handed(trigger, firing, hook) {
1141
+ if (trigger.target.kind !== "start_run")
1142
+ return;
1143
+ const agentId = trigger.target.agent_id;
1144
+ const sent = {
1145
+ firing_id: firing.key, trigger_id: trigger.id, agent_id: agentId, revision_id: (await this.store.agents.get(agentId))?.currentRevision ?? null,
1146
+ input: this.inputOf(trigger, firing), fired_at: second(firing.nominalAt),
1147
+ };
1148
+ const handed = await handToHost(hook, sent, this.stopping.signal);
1149
+ if (this.closed || "stopped" in handed)
1150
+ return;
1151
+ const linked = await this.deps.runOf(firing.key);
1152
+ if (this.closed)
1153
+ return;
1154
+ if (linked)
1155
+ return void (await this.started(trigger.id, firing.key, linked.run_id));
1156
+ if ("skipped" in handed) {
1157
+ await this.store.triggers.settle(trigger.id, firing.key, { status: "skipped", reason: handed.skipped });
1158
+ this.deps.say({ condition: "trigger_hook_skipped", trigger: trigger.id, firing: firing.key });
1159
+ return;
1160
+ }
1161
+ await this.store.triggers.settle(trigger.id, firing.key, { status: "sent", reason: HANDED_NO_RUN, keepAttrs: true, startBy: this.clock.now() + LAUNCH_HOOK_LATE_START_MS }, { reset: true });
1162
+ // The host may start the run right after its answer: one it started between the read above and this write found the
1163
+ // firing still due (handedRan left it), so it is read again here.
1164
+ const after = await this.deps.runOf(firing.key);
1165
+ if (this.closed)
1166
+ return;
1167
+ if (after)
1168
+ return void (await this.started(trigger.id, firing.key, after.run_id));
1169
+ this.deps.say({ condition: "trigger_handed", trigger: trigger.id, firing: firing.key });
1170
+ }
1171
+ /** The run the host starts through the API for a firing the launch hook handed it (RunCreate `trigger_firing`): the
1172
+ * firing's key (the run's origin key, so the firing finds it), and the trigger, input origin and title its own start
1173
+ * would give the run; or the run already started under that key. Refused, in words, unless this server has the hook and
1174
+ * the firing, of a start_run trigger on `agentId`, is due (being handed over) or one its host took with no run, up to
1175
+ * its startBy (the host may answer first and start the run after). */
1176
+ async handedStart(given, agentId) {
1177
+ const refused = (reason, message, field = "trigger_firing") => invalid([{ field, reason, message }]);
1178
+ if (!this.deps.launchHook)
1179
+ throw refused("not_allowed", "This server has no launch hook: a run starts as a trigger firing's only when the hook handed that firing to its host.");
1180
+ if (!isObject(given))
1181
+ throw refused("wrong_type", "trigger_firing is { trigger_id, firing_id }, as the launch hook sent them.");
1182
+ const extra = unknownFields(given, ["trigger_id", "firing_id"]);
1183
+ if (extra.length)
1184
+ throw invalid(extra.map((issue) => ({ ...issue, field: `trigger_firing.${issue.field}` })));
1185
+ const { trigger_id: triggerId, firing_id: key } = given;
1186
+ if (typeof triggerId !== "string" || !ID.test(triggerId))
1187
+ throw refused("wrong_type", "trigger_id is the trigger's id, as the launch hook sent it.", "trigger_firing.trigger_id");
1188
+ if (typeof key !== "string" || !/^fir_[0-9a-f]{32}$/.test(key))
1189
+ throw refused("wrong_type", "firing_id is the firing's id, as the launch hook sent it.", "trigger_firing.firing_id");
1190
+ const trigger = await this.find(triggerId);
1191
+ if (!trigger || trigger.target.kind !== "start_run" || trigger.target.agent_id !== agentId)
1192
+ throw refused("not_found", `This agent has no trigger ${triggerId} that starts its runs.`, "trigger_firing.trigger_id");
1193
+ const firing = await this.store.triggers.firing(triggerId, key);
1194
+ if (!firing)
1195
+ throw refused("not_found", `Trigger ${triggerId} has no firing ${key}.`, "trigger_firing.firing_id");
1196
+ // The run already under its key is its run. A stop between that run's write and handedRan left the firing sent with
1197
+ // no run, so a repeated start starts the firing with it.
1198
+ const prior = await this.deps.runOf(key);
1199
+ if (prior) {
1200
+ await this.handedRan(triggerId, key, prior.run_id);
1201
+ return prior;
1202
+ }
1203
+ const minutes = LAUNCH_HOOK_LATE_START_MS / 60_000;
1204
+ const taken = firing.status === "sent" && firing.runId === null && firing.reason === HANDED_NO_RUN;
1205
+ if (taken && (firing.startBy === null || this.clock.now() > firing.startBy)) {
1206
+ const until = firing.startBy === null ? "" : ` (start_by ${iso(firing.startBy)})`;
1207
+ throw refused("not_due", `Firing ${key}'s host answered without starting its run, and the ${minutes} minutes after its host answered in which it may still start it have passed${until}.`, "trigger_firing.firing_id");
1208
+ }
1209
+ if (firing.status !== "due" && !taken) {
1210
+ throw refused("not_due", `Firing ${key} is ${firing.status}${firing.reason ? ` (${firing.reason})` : ""}: a run starts only for a firing the launch hook is handing over, or one its host took within ${minutes} minutes of its answer.`, "trigger_firing.firing_id");
1211
+ }
1212
+ const attrs = firing.attrs;
1213
+ return { key, trigger: { id: triggerId, firing_key: key, name: trigger.name, ...(attrs && Object.keys(attrs).length ? { attrs } : {}) }, from: this.originOf(trigger), title: this.titleOf(trigger, firing) };
1214
+ }
1215
+ /** Run `runId`, which the host started for firing `key` (handedStart), started: one whose host answered first (sent,
1216
+ * with no run) is made started here, as handed() makes it when the run came first, so the overlap check and
1217
+ * max_active_runs count it. A firing still being handed is left to handed(), which reads its run after the answer. */
1218
+ async handedRan(triggerId, key, runId) {
1219
+ const firing = await this.store.triggers.firing(triggerId, key);
1220
+ if (firing?.status === "sent" && firing.runId === null && firing.reason === HANDED_NO_RUN)
1221
+ await this.started(triggerId, key, runId);
1222
+ }
1223
+ /** Each sent firing whose host's run is in the store under its key, though the server stopped before the firing was
1224
+ * started with it (a late start writes the run, then handedRan): started with that run, so the overlap check and
1225
+ * max_active_runs count it. */
1226
+ async relink() {
1227
+ for (const trigger of await this.all()) {
1228
+ if (trigger.target.kind !== "start_run")
1229
+ continue;
1230
+ for (const firing of await this.store.triggers.firings(trigger.id)) {
1231
+ if (firing.status !== "sent" || firing.runId !== null)
1232
+ continue;
1233
+ const run = await this.deps.runOf(firing.key);
1234
+ if (this.closed)
1235
+ return;
1236
+ if (run)
1237
+ await this.handedRan(trigger.id, firing.key, run.run_id);
1238
+ }
1239
+ }
1240
+ }
1107
1241
  async started(triggerId, key, runId) {
1108
1242
  await this.store.triggers.settle(triggerId, key, { status: "started", runId }, { reset: true });
1109
1243
  this.deps.say({ condition: "trigger_fired", trigger: triggerId, firing: key, run: runId });
@@ -1183,7 +1317,7 @@ export class Triggers {
1183
1317
  * most SEEN_KEPT of them; past it the oldest go, said once each time the cap is reached. */
1184
1318
  async prune(trigger) {
1185
1319
  const cap = this.deps.seenKept ?? SEEN_KEPT;
1186
- const over = await this.store.triggers.prune(trigger.id, { history: HISTORY_KEPT, dayMs: DAY_MS, keepByKey: (by) => by === "manual" || eventful(adapterIn(this.adapters, by)), kept: cap });
1320
+ const over = await this.store.triggers.prune(trigger.id, { history: HISTORY_KEPT, dayMs: DAY_MS, keepByKey: (by) => by === "manual" || eventful(adapterIn(this.adapters, by)), kept: cap, now: this.clock.now() });
1187
1321
  if (over > 0) {
1188
1322
  if (!this.seenFull.has(trigger.id))
1189
1323
  this.deps.say({ condition: "trigger_seen_full", trigger: trigger.id, kept: cap });
@@ -1352,6 +1486,7 @@ function firingView(firing) {
1352
1486
  return {
1353
1487
  key: firing.key, by: firing.by, nominal_at: second(firing.nominalAt), status: firing.status, at: iso(firing.at), run_id: firing.runId, reason: firing.reason, error: firing.error,
1354
1488
  ...(firing.count !== null ? { count: firing.count } : {}), ...(firing.catchUp ? { catch_up: true } : {}), ...(firing.retryAt !== null ? { attempts: firing.attempts, retry_at: iso(firing.retryAt) } : {}),
1489
+ ...(firing.startBy !== null ? { start_by: iso(firing.startBy) } : {}),
1355
1490
  };
1356
1491
  }
1357
1492
  /** A payload tag's attributes from its source's `attrs`, each ` name="value"`: a name of lowercase letters, digits, `_` and
@@ -32,7 +32,8 @@ import { archilWorkspace } from "./workspace/archil.js";
32
32
  import { agentDirName, runKey } from "./workspace/paths.js";
33
33
  import { runDiskOf } from "./workspace/run-disk.js";
34
34
  import { isWorkspaceError, WorkspaceError } from "./workspace/index.js";
35
- import { answerOf, copyFilesInto, INPUTS_DIR, isUploadedFile, MAX_FILES_PER_RUN, MAX_UPLOAD_BYTES, mismatchOf, pathProblem, readyFilesOf, reservation, sentInOneCall, slots, uuidv7, } from "./uploads.js";
35
+ import { answerOf, copyFilesInto, INPUTS_DIR, isUploadedFile, MAX_FILES_PER_RUN, MAX_UPLOAD_BYTES, mismatchOf, pathProblem, readyFilesOf, reservation, sentInOneCall, slots, } from "./uploads.js";
36
+ import { uuidv7 } from "./ids.js";
36
37
  /** The folder of the uploads disk the files are kept under. */
37
38
  export const UPLOADS_KEY = "files";
38
39
  const RECORD = "file.json";
package/dist/uploads.d.ts CHANGED
@@ -51,9 +51,6 @@ export type UploadedFile = {
51
51
  created_at: string;
52
52
  expires_at: null;
53
53
  };
54
- /** A UUIDv7, the form of the agent store's agent and run ids: 48 bits of Unix milliseconds, then random bits, so ids
55
- * sort by creation time. The store mints its own inside it and exports no minter. */
56
- export declare function uuidv7(now?: number): string;
57
54
  /** Why `path` is not the contract's FilePathString (relative, `/` between segments, no empty segment and none that starts
58
55
  * with `.`, no backslash or NUL, at most 1024 characters), or a segment is longer than a name on disk; undefined when it
59
56
  * is one. */