@parcha/agentrun-serve 0.1.0-beta.46 → 0.1.0-beta.48

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 (292) hide show
  1. package/CHANGELOG.md +211 -1
  2. package/NOTICE +4 -0
  3. package/README.md +350 -53
  4. package/dist/acp-package.d.ts +53 -6
  5. package/dist/acp-package.js +3 -3
  6. package/dist/adapter-facts.d.ts +3 -4
  7. package/dist/adapter-facts.js +4 -4
  8. package/dist/adapters.d.ts +3 -5
  9. package/dist/adapters.js +1 -31
  10. package/dist/agents-store.d.ts +5 -3
  11. package/dist/agents-store.js +13 -8
  12. package/dist/answer-json.d.ts +10 -0
  13. package/dist/answer-json.js +24 -0
  14. package/dist/api-only.d.ts +11 -11
  15. package/dist/api-only.js +16 -11
  16. package/dist/archil-routes.js +2 -1
  17. package/dist/browser-live.d.ts +9 -4
  18. package/dist/browser-live.js +18 -5
  19. package/dist/cap.js +10 -2
  20. package/dist/chatgpt-plan.js +2 -1
  21. package/dist/cli.js +109 -41
  22. package/dist/composio-made.d.ts +19 -2
  23. package/dist/composio-made.js +17 -5
  24. package/dist/composio-preset.d.ts +42 -7
  25. package/dist/composio-preset.js +106 -70
  26. package/dist/composio-triggers.d.ts +9 -4
  27. package/dist/composio-triggers.js +20 -13
  28. package/dist/computer-attach.d.ts +11 -10
  29. package/dist/computer-attach.js +13 -14
  30. package/dist/computer-commands.d.ts +3 -0
  31. package/dist/computer-commands.js +3 -2
  32. package/dist/computer-lost.d.ts +4 -0
  33. package/dist/computer-lost.js +8 -3
  34. package/dist/computer-routes.d.ts +8 -5
  35. package/dist/computer-routes.js +7 -5
  36. package/dist/computer-setting.d.ts +2 -0
  37. package/dist/computer-setting.js +2 -0
  38. package/dist/computers.d.ts +14 -76
  39. package/dist/computers.js +24 -68
  40. package/dist/conformance.d.ts +4 -0
  41. package/dist/conformance.js +6 -0
  42. package/dist/console/assets/index-CTGegcKt.css +1 -0
  43. package/dist/console/assets/index-D1Se6mgG.js +715 -0
  44. package/dist/console/index.html +2 -2
  45. package/dist/cost-heal.d.ts +13 -0
  46. package/dist/cost-heal.js +27 -0
  47. package/dist/dial-relay.d.ts +6 -2
  48. package/dist/dial-relay.js +9 -12
  49. package/dist/email/routes.js +2 -1
  50. package/dist/errors.d.ts +2 -0
  51. package/dist/errors.js +5 -0
  52. package/dist/exa-keyless.d.ts +1 -1
  53. package/dist/exa-keyless.js +1 -1
  54. package/dist/faux-computers.d.ts +2 -3
  55. package/dist/faux-computers.js +9 -31
  56. package/dist/github-connection.js +2 -1
  57. package/dist/harness-archive.d.ts +19 -2
  58. package/dist/harness-archive.js +49 -15
  59. package/dist/harness-check.d.ts +75 -0
  60. package/dist/harness-check.js +518 -0
  61. package/dist/harness-cursor.d.ts +28 -0
  62. package/dist/harness-cursor.js +42 -0
  63. package/dist/harness-goose.d.ts +4 -29
  64. package/dist/harness-goose.js +6 -86
  65. package/dist/harness-module.d.ts +4 -0
  66. package/dist/harness-module.js +1 -0
  67. package/dist/harness-owned.d.ts +52 -0
  68. package/dist/harness-owned.js +92 -0
  69. package/dist/harness-recipe.d.ts +127 -0
  70. package/dist/harness-recipe.js +335 -0
  71. package/dist/harness-table.d.ts +120 -5
  72. package/dist/harness-table.js +280 -6
  73. package/dist/harness.d.ts +2 -0
  74. package/dist/harness.js +5 -4
  75. package/dist/host-check.d.ts +6 -0
  76. package/dist/host-check.js +14 -0
  77. package/dist/host.d.ts +10 -3
  78. package/dist/host.js +17 -3
  79. package/dist/import-sources.d.ts +2 -0
  80. package/dist/import-sources.js +2 -0
  81. package/dist/import-summary.d.ts +15 -5
  82. package/dist/import-summary.js +24 -8
  83. package/dist/import.d.ts +24 -4
  84. package/dist/import.js +108 -26
  85. package/dist/key-refusal.d.ts +3 -1
  86. package/dist/key-refusal.js +26 -5
  87. package/dist/key-words.d.ts +1 -1
  88. package/dist/key-words.js +4 -4
  89. package/dist/learn/check.d.ts +3 -0
  90. package/dist/learn/check.js +31 -20
  91. package/dist/learn/compile.js +12 -5
  92. package/dist/learn/promote.d.ts +80 -2
  93. package/dist/learn/promote.js +95 -3
  94. package/dist/learn/secrets.d.ts +4 -0
  95. package/dist/learn/secrets.js +23 -0
  96. package/dist/learned-nodes.d.ts +4 -3
  97. package/dist/learned-workflow.js +4 -1
  98. package/dist/learning-cost.d.ts +6 -16
  99. package/dist/learning-cost.js +6 -12
  100. package/dist/learning-model.d.ts +18 -0
  101. package/dist/learning-model.js +77 -0
  102. package/dist/learning-words.d.ts +2 -0
  103. package/dist/learning-words.js +1 -1
  104. package/dist/listen-first.d.ts +10 -0
  105. package/dist/listen-first.js +25 -1
  106. package/dist/llms.txt +2 -1
  107. package/dist/mcp-gateway.d.ts +2 -1
  108. package/dist/mcp-gateway.js +31 -15
  109. package/dist/mcp-probe.d.ts +18 -6
  110. package/dist/mcp-probe.js +41 -8
  111. package/dist/mcp-secret-writes.d.ts +8 -0
  112. package/dist/mcp-secret-writes.js +104 -4
  113. package/dist/mcp-servers-store.d.ts +11 -5
  114. package/dist/mcp-servers-store.js +46 -20
  115. package/dist/model-form.d.ts +2 -1
  116. package/dist/model-form.js +30 -16
  117. package/dist/model-gateway.d.ts +113 -0
  118. package/dist/model-gateway.js +433 -0
  119. package/dist/model.d.ts +5 -3
  120. package/dist/model.js +26 -18
  121. package/dist/monid.js +1 -1
  122. package/dist/native/binding.d.ts +4 -0
  123. package/dist/native/binding.js +9 -0
  124. package/dist/native/cli.d.ts +3 -2
  125. package/dist/native/cli.js +6 -5
  126. package/dist/openapi.d.ts +2 -0
  127. package/dist/openapi.js +356 -43
  128. package/dist/owner.d.ts +4 -2
  129. package/dist/owner.js +10 -4
  130. package/dist/page.d.ts +9 -0
  131. package/dist/page.js +10 -2
  132. package/dist/port-models.js +17 -10
  133. package/dist/provider.d.ts +3 -3
  134. package/dist/provider.js +12 -3
  135. package/dist/public-address.d.ts +28 -0
  136. package/dist/public-address.js +62 -0
  137. package/dist/run-launch.d.ts +1 -1
  138. package/dist/run-launch.js +1 -1
  139. package/dist/run-secrets.d.ts +3 -2
  140. package/dist/run-secrets.js +7 -4
  141. package/dist/run-trace.js +6 -3
  142. package/dist/runner/adapter-loop.d.ts +14 -8
  143. package/dist/runner/adapter-loop.js +58 -24
  144. package/dist/runner/adapter-run-spec.d.ts +15 -2
  145. package/dist/runner/adapter-run-spec.js +48 -10
  146. package/dist/runner/adapters/index.d.ts +4 -2
  147. package/dist/runner/adapters/index.js +6 -26
  148. package/dist/runner/adapters/pi.d.ts +5 -2
  149. package/dist/runner/adapters/pi.js +7 -4
  150. package/dist/runner/audit.d.ts +7 -0
  151. package/dist/runner/audit.js +15 -6
  152. package/dist/runner/claim-secrets.js +5 -1
  153. package/dist/runner/cli-run-spec.js +22 -10
  154. package/dist/runner/compare-end.d.ts +43 -0
  155. package/dist/runner/compare-end.js +95 -0
  156. package/dist/runner/computer-journal.d.ts +3 -0
  157. package/dist/runner/computer-journal.js +22 -2
  158. package/dist/runner/conformance/host-tools.d.ts +4 -0
  159. package/dist/runner/conformance/host-tools.js +14 -0
  160. package/dist/runner/harness-loops.d.ts +6 -1
  161. package/dist/runner/harness-loops.js +94 -54
  162. package/dist/runner/held.d.ts +5 -4
  163. package/dist/runner/journal-kinds.d.ts +4 -1
  164. package/dist/runner/journal-kinds.js +3 -0
  165. package/dist/runner/loop-contract.d.ts +10 -0
  166. package/dist/runner/main.d.ts +5 -5
  167. package/dist/runner/main.js +62 -11
  168. package/dist/runner/mcp-claim.js +40 -12
  169. package/dist/runner/meta-tools.js +4 -2
  170. package/dist/runner/metrics.d.ts +26 -0
  171. package/dist/runner/metrics.js +44 -1
  172. package/dist/runner/presence.d.ts +44 -0
  173. package/dist/runner/presence.js +96 -0
  174. package/dist/runner/promotion.d.ts +70 -7
  175. package/dist/runner/promotion.js +178 -28
  176. package/dist/runner/run-child-host.js +40 -10
  177. package/dist/runner/runner.d.ts +5 -0
  178. package/dist/runner/runner.js +8 -0
  179. package/dist/runner/sdk-loop.js +25 -1
  180. package/dist/runner/store-port.d.ts +3 -0
  181. package/dist/runner/store-secrets.js +19 -7
  182. package/dist/runner/workflow-first.d.ts +5 -2
  183. package/dist/runner/workflow-first.js +6 -3
  184. package/dist/runner/workflow-spec.js +3 -2
  185. package/dist/runs-over-store.d.ts +7 -2
  186. package/dist/runs-over-store.js +12 -4
  187. package/dist/sdk/check.d.ts +31 -0
  188. package/dist/sdk/check.js +58 -0
  189. package/dist/sdk/runs.d.ts +11 -3
  190. package/dist/sdk/runs.js +90 -15
  191. package/dist/sdk/schema.js +12 -4
  192. package/dist/secret-writes.d.ts +16 -3
  193. package/dist/secret-writes.js +28 -3
  194. package/dist/server-secrets-store.js +5 -0
  195. package/dist/server.d.ts +34 -2
  196. package/dist/server.js +437 -90
  197. package/dist/sign-ins-secrets.js +4 -1
  198. package/dist/skills/agentrun-serve/SKILL.md +11 -0
  199. package/dist/slack-url.d.ts +5 -0
  200. package/dist/slack-url.js +11 -0
  201. package/dist/slack.d.ts +107 -0
  202. package/dist/slack.js +292 -0
  203. package/dist/start-switches.d.ts +28 -0
  204. package/dist/start-switches.js +37 -0
  205. package/dist/stats.d.ts +1 -1
  206. package/dist/stats.js +2 -1
  207. package/dist/stop-signals.d.ts +11 -0
  208. package/dist/stop-signals.js +22 -0
  209. package/dist/store/agent-body.d.ts +1 -1
  210. package/dist/store/agent-body.js +2 -2
  211. package/dist/store/index.d.ts +3 -3
  212. package/dist/store/index.js +1 -1
  213. package/dist/store/postgres/migrations/0020_runners.sql +18 -0
  214. package/dist/store/postgres/store.d.ts +1 -1
  215. package/dist/store/postgres/store.js +4 -2
  216. package/dist/store/schema.d.ts +13 -5
  217. package/dist/store/schema.js +20 -11
  218. package/dist/store/seal.d.ts +16 -4
  219. package/dist/store/sqlite/store.d.ts +1 -1
  220. package/dist/store/sqlite/store.js +112 -28
  221. package/dist/store/store.d.ts +78 -24
  222. package/dist/store/store.js +11 -0
  223. package/dist/store-reads/analytics.js +3 -2
  224. package/dist/store-reads/cap.d.ts +7 -0
  225. package/dist/store-reads/cap.js +11 -1
  226. package/dist/store-reads/journal.js +27 -1
  227. package/dist/store-reads/learning.d.ts +23 -2
  228. package/dist/store-reads/learning.js +29 -8
  229. package/dist/store-reads/runs.d.ts +9 -0
  230. package/dist/store-reads/runs.js +19 -6
  231. package/dist/store-reads/stats.d.ts +4 -1
  232. package/dist/store-reads/stats.js +15 -6
  233. package/dist/store-view.d.ts +125 -14
  234. package/dist/store-view.js +156 -21
  235. package/dist/telemetry.d.ts +7 -7
  236. package/dist/telemetry.js +38 -15
  237. package/dist/template-eval.js +5 -2
  238. package/dist/template-github-permissions.d.ts +5 -1
  239. package/dist/template-github-permissions.js +7 -3
  240. package/dist/timeline/index.d.ts +1 -1
  241. package/dist/timeline/index.js +1 -1
  242. package/dist/timeline/timeline.d.ts +8 -0
  243. package/dist/timeline/timeline.js +30 -0
  244. package/dist/tool-gate.d.ts +8 -4
  245. package/dist/tool-gate.js +6 -7
  246. package/dist/tool-keys-store.js +2 -2
  247. package/dist/tool-keys.js +2 -1
  248. package/dist/tool-plane.d.ts +4 -0
  249. package/dist/tool-plane.js +12 -12
  250. package/dist/trigger-adapter.d.ts +3 -4
  251. package/dist/trigger-adapter.js +2 -2
  252. package/dist/trigger-composio.js +3 -3
  253. package/dist/trigger-email.js +0 -2
  254. package/dist/trigger-feed.js +0 -2
  255. package/dist/trigger-schedule.js +3 -0
  256. package/dist/trigger-secrets-shown.d.ts +6 -3
  257. package/dist/trigger-secrets-shown.js +22 -13
  258. package/dist/trigger-targets.d.ts +12 -3
  259. package/dist/trigger-targets.js +90 -10
  260. package/dist/triggers.d.ts +2 -2
  261. package/dist/validate.js +5 -1
  262. package/dist/viewer-credential.d.ts +25 -0
  263. package/dist/viewer-credential.js +51 -0
  264. package/dist/webhooks.d.ts +82 -8
  265. package/dist/webhooks.js +128 -45
  266. package/dist/wires.d.ts +6 -1
  267. package/dist/wires.js +5 -0
  268. package/dist/workspace/attach.d.ts +3 -2
  269. package/dist/workspace/attach.js +2 -1
  270. package/dist/workspace/attached-computers.d.ts +6 -8
  271. package/dist/workspace/attached-computers.js +27 -24
  272. package/dist/workspace/computer-deps.d.ts +2 -3
  273. package/dist/workspace/computer-deps.js +3 -6
  274. package/dist/workspace/computer-for-claim.js +72 -96
  275. package/dist/workspace/computer-kept.d.ts +0 -7
  276. package/dist/workspace/computer-kept.js +0 -17
  277. package/dist/workspace/resolve-computer.d.ts +23 -14
  278. package/dist/workspace/resolve-computer.js +66 -61
  279. package/dist/workspace/synced-folder.d.ts +20 -15
  280. package/dist/workspace/synced-folder.js +33 -43
  281. package/launcher/agentrun-serve +4 -1
  282. package/package.json +18 -10
  283. package/skills/agentrun-serve/SKILL.md +11 -0
  284. package/templates/README.md +1 -1
  285. package/templates/code-review/agent.md +2 -3
  286. package/templates/code-review/evals/mentions-defused/case.yaml +0 -1
  287. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +0 -27
  288. package/templates/code-review/evals/other-repo/case.yaml +0 -1
  289. package/templates/code-review/evals/other-repo/fixtures/github-mcp.json +0 -18
  290. package/templates/code-review/evals/other-repo/graders/no-other-repo.md +1 -1
  291. package/dist/console/assets/index-C2MYaUBa.css +0 -1
  292. package/dist/console/assets/index-CZZeCReB.js +0 -701
@@ -7,22 +7,41 @@
7
7
  // is never logged, echoed or put in an error.
8
8
  import { randomBytes } from "node:crypto";
9
9
  import { ApiError, invalid } from "./errors.js";
10
+ import { priceValid } from "./mcp-probe.js";
10
11
  import { MCP_SERVER_NAME } from "./tool-names.js";
11
12
  import { isObject } from "./validate.js";
12
13
  const BASE = "https://backend.composio.dev";
13
14
  /** The one Composio user a server's actions run as, unless the owner names another. */
14
15
  export const COMPOSIO_USER = "agentrun";
15
- const TOOLKIT = /^[a-z0-9][a-z0-9_-]{0,63}$/;
16
- const USER_ID = /^[A-Za-z0-9._@-]{1,128}$/;
16
+ /** A Composio toolkit's slug, as a save takes it once trimmed and lower-cased. */
17
+ export const COMPOSIO_TOOLKIT = /^[a-z0-9][a-z0-9_-]{0,63}$/;
18
+ const TOOLKIT = COMPOSIO_TOOLKIT;
19
+ /** A Composio user id, as a save's `user_id` and a run's binding (mcp_auth's composio_user_id) take it. */
20
+ export const COMPOSIO_USER_ID = /^[A-Za-z0-9._@-]{1,128}$/;
21
+ const USER_ID = COMPOSIO_USER_ID;
22
+ /** The `user_id` a save names for a per-run server, reserved for that and never a Composio user: the server keeps no user
23
+ * and no connected account, and each run names its own (mcp_auth.<server> = {composio_user_id, connected_account_id?}). */
24
+ export const COMPOSIO_PER_RUN = "per_run";
25
+ /** A Composio connected account's id, as a run's binding names one: Composio's are `ca_` and a short random id. At least
26
+ * 8 characters in all, so the run's redactors (which hold a value of 8 or more) hold every one. */
27
+ export const COMPOSIO_ACCOUNT_ID = /^ca_[A-Za-z0-9_-]{5,64}$/;
28
+ /** Where Composio's MCP address names the user and the connected account its calls run as. */
29
+ const ADDRESS_USER = "user_id";
30
+ const ADDRESS_ACCOUNT = "connected_account_id";
31
+ /** A Composio auth config's id, as its dashboard and API show it (`ac_` and a nanoid). */
32
+ export const COMPOSIO_AUTH_CONFIG_ID = /^ac_[A-Za-z0-9_-]{1,64}$/;
17
33
  const PAGE = 200;
18
34
  const MAX_PAGES = 10;
19
35
  const MAX_TOOLS = 500;
36
+ /** The longest action slug a save takes: Composio's are far shorter. */
37
+ const MAX_SLUG = 128;
20
38
  const WAIT_MS = 20_000;
21
39
  const text = (value) => (typeof value === "string" ? value : "");
22
40
  const issue = (field, reason, message) => ({ field, reason, message });
23
41
  /** A Composio call as `key`: its JSON answer, or an error in words that name `step` and never the key nor a `sealed`
24
42
  * value (a trigger's sealed config), and end with `outcome`, what the failure left (a save's: nothing was saved). A call
25
- * with sealed values in play passes on none of Composio's words. */
43
+ * with sealed values in play passes on none of Composio's words. Composio's 404 is `missing` when given: the words of a
44
+ * toolkit it has not, or the refusal on another field. */
26
45
  export function asking(control, key, signal, outcome = "nothing was saved", sealed = []) {
27
46
  const base = (control.baseUrl ?? BASE).replace(/\/+$/, "");
28
47
  const send = control.fetch ?? fetch;
@@ -64,7 +83,7 @@ export function asking(control, key, signal, outcome = "nothing was saved", seal
64
83
  if (res.status === 401 || res.status === 403)
65
84
  throw invalid([issue("api_key", "refused", `Composio refused the API key while ${step}: check it in Composio's dashboard.`)]);
66
85
  if (res.status === 404 && missing)
67
- throw invalid([issue("toolkit", "not_found", missing)]);
86
+ throw invalid([typeof missing === "string" ? issue("toolkit", "not_found", missing) : missing]);
68
87
  if (res.status >= 400 && res.status < 500 && withheld)
69
88
  throw invalid([issue("body", "refused", `Composio refused the request while ${step} (HTTP ${res.status}): ${outcome}. Its answer is withheld because the request carried a sealed value.`)]);
70
89
  if (res.status >= 400 && res.status < 500)
@@ -121,70 +140,75 @@ export async function composioTools(body, control, signal) {
121
140
  const { tools } = await toolkitTools(ask, toolkit);
122
141
  return { toolkit, no_auth: needsNoAuth(kit), tools };
123
142
  }
124
- /** Edit distance (Levenshtein). */
125
- function distance(a, b) {
126
- let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
127
- for (let i = 1; i <= a.length; i++) {
128
- const row = [i];
129
- for (let j = 1; j <= b.length; j++)
130
- row[j] = Math.min(prev[j] + 1, row[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
131
- prev = row;
132
- }
133
- return prev[b.length];
134
- }
135
- /** The listed slug a missing one most likely means, when one is obvious: the same slug in another case, the one listed
136
- * slug that only adds or drops a trailing _WORD, else the one within a typo's reach (an edit distance of at most
137
- * max(2, length/10)). */
138
- function likelySlug(slug, listed) {
143
+ /** The listed slug a missing one means when it is that slug in another case (linear_list_issues for LINEAR_LIST_ISSUES). */
144
+ const likelySlug = (slug, slugs) => {
139
145
  const want = slug.toUpperCase();
140
- const same = listed.find((s) => s.toUpperCase() === want);
141
- if (same)
142
- return same;
143
- const extended = listed.filter((s) => s.toUpperCase().startsWith(`${want}_`) || want.startsWith(`${s.toUpperCase()}_`)).sort((a, b) => a.length - b.length);
144
- if (extended.length === 1 || (extended.length > 1 && extended[0].length < extended[1].length))
145
- return extended[0];
146
- const reach = Math.max(2, Math.floor(want.length / 10));
147
- let best;
148
- let tie = false;
149
- for (const s of listed) {
150
- // An edit distance is at least the length difference: a slug that far off is skipped before the O(n·m) distance, so a
151
- // huge pasted value against a big toolkit costs one length compare per action.
152
- if (Math.abs(s.length - want.length) > reach)
153
- continue;
154
- const d = distance(want, s.toUpperCase());
155
- if (d > reach)
156
- continue;
157
- if (!best || d < best.d)
158
- [best, tie] = [{ slug: s, d }, false];
159
- else if (d === best.d)
160
- tie = true;
161
- }
162
- return best && !tie ? best.slug : undefined;
146
+ return slugs.find((s) => s.toUpperCase() === want);
147
+ };
148
+ /** The toolkit's Composio-managed auth config not disabled, the one a save that names none stands on: none, if Composio
149
+ * has none for it yet. */
150
+ export async function managedConfig(ask, toolkit) {
151
+ const configs = await ask("finding the toolkit's auth config", "GET", `/api/v3/auth_configs?toolkit_slug=${encodeURIComponent(toolkit)}`);
152
+ const managed = (Array.isArray(configs.items) ? configs.items : []).find((c) => isObject(c) && c.is_composio_managed === true && c.status !== "DISABLED" && text(c.id));
153
+ return isObject(managed) ? text(managed.id) : undefined;
163
154
  }
164
155
  /** The address Composio's generate answers, made one this server's client can use: the helper actions that connect an
165
- * account left off, and the path ended in /mcp (Composio redirects the bare one, which the client refuses on purpose). */
166
- export function composioAddress(generated) {
156
+ * account left off, and the path ended in /mcp (Composio redirects the bare one, which the client refuses on purpose).
157
+ * `perRun`: with no user and no connected account in it either, for each run to name its own (composioRunAddress). */
158
+ export function composioAddress(generated, perRun = false) {
167
159
  const url = new URL(generated);
168
160
  url.searchParams.delete("include_composio_helper_actions");
161
+ if (perRun)
162
+ for (const name of [ADDRESS_USER, ADDRESS_ACCOUNT])
163
+ url.searchParams.delete(name);
169
164
  const path = url.pathname.replace(/\/+$/, "");
170
165
  url.pathname = path.endsWith("/mcp") ? path : `${path}/mcp`;
171
166
  return url.href;
172
167
  }
168
+ /** The Composio user a per-run server's tools are listed as (its save, refresh, preview and an agent's save): Composio's
169
+ * MCP endpoint refuses an address that names no user, its listing too, and any user lists the server's tools. Outside
170
+ * COMPOSIO_USER_ID (the ~), so no save and no run's binding can name it: never stored, never used for a call. */
171
+ export const COMPOSIO_LISTING_USER = "agentrun~tool-listing";
172
+ /** The address a per-run Composio server's tools are listed at: its saved one (no user, no account) as
173
+ * COMPOSIO_LISTING_USER. */
174
+ export function composioListingAddress(saved) {
175
+ const url = new URL(saved.href);
176
+ url.searchParams.set(ADDRESS_USER, COMPOSIO_LISTING_USER);
177
+ return url;
178
+ }
179
+ /** What a run's requests to a per-run Composio server add to its saved address: the Composio user and, when the run's
180
+ * binding names one, the connected account its calls run as (Composio's MCP endpoint reads both from the query). */
181
+ export const composioRunQuery = (binding) => ({ [ADDRESS_USER]: binding.user_id, ...(binding.connected_account_id ? { [ADDRESS_ACCOUNT]: binding.connected_account_id } : {}) });
173
182
  /** PUT /settings/mcp-servers/{name}/composio: Composio makes the managed MCP server, `save` keeps it as a saved MCP server
174
- * (`{url, auth}`: the key a sealed header), and a toolkit that needs the person's account says where to connect it.
175
- * `save` gets what the server stands on there too (`stands`, composio-made.ts): the auth config found or made and the
176
- * account found or started, each marked whether this save made it, for its delete to remove what was made. */
183
+ * (`{url, auth}`: the key a sealed header; `prices`, each granted action at `price_usd` when the body names one), and a
184
+ * toolkit that needs the person's account says where to connect it. The auth config is the body's `auth_config_id` (one
185
+ * the owner has, a custom OAuth app's say: read first, and refused unless it is this toolkit's and enabled), else the
186
+ * toolkit's Composio-managed one, found or made. `save` gets what the server stands on there too (`stands`,
187
+ * composio-made.ts): the auth config found or made and the account found or started, each marked whether this save made
188
+ * it, for its delete to remove what was made. */
177
189
  export async function composioSave(body, control, save, name, signal, savedUrl) {
178
190
  const { key, toolkit, rest } = head(body);
179
191
  const tools = Array.isArray(rest.tools) ? rest.tools : [];
180
192
  const user = rest.user_id === undefined ? COMPOSIO_USER : typeof rest.user_id === "string" ? rest.user_id : "";
193
+ const price = rest.price_usd;
194
+ const ownConfig = rest.auth_config_id === undefined ? undefined : typeof rest.auth_config_id === "string" ? rest.auth_config_id : "";
181
195
  const issues = [];
182
- if (!tools.length || tools.length > MAX_TOOLS || !tools.every((t) => typeof t === "string" && t))
183
- issues.push(issue("tools", "invalid", `Send the slugs of the actions to grant: 1 to ${MAX_TOOLS} of them.`));
196
+ if (!tools.length || tools.length > MAX_TOOLS || !tools.every((t) => typeof t === "string" && t && t.length <= MAX_SLUG))
197
+ issues.push(issue("tools", "invalid", `Send the slugs of the actions to grant: 1 to ${MAX_TOOLS} of them, each at most ${MAX_SLUG} characters.`));
184
198
  if (!USER_ID.test(user))
185
- issues.push(issue("user_id", "invalid", "A user_id is letters, digits and . _ @ - (at most 128)."));
199
+ issues.push(issue("user_id", "invalid", `A user_id is letters, digits and . _ @ - (at most 128), or "${COMPOSIO_PER_RUN}" for a server each run names its own account for.`));
200
+ if (price !== undefined && !priceValid(price))
201
+ issues.push(issue("price_usd", "invalid", "price_usd is what each call of the server's actions costs, in USD: a finite number, 0 or more."));
202
+ if (ownConfig !== undefined && !COMPOSIO_AUTH_CONFIG_ID.test(ownConfig))
203
+ issues.push(issue("auth_config_id", "invalid", "An auth_config_id is the id Composio shows for an auth config: ac_ then letters, digits, _ and - (at most 64 after ac_)."));
186
204
  if (issues.length)
187
205
  throw invalid(issues);
206
+ // A per-run server: no user, no account, no connect link here; each run names its own (mcp_auth).
207
+ const perRun = user === COMPOSIO_PER_RUN;
208
+ // Every granted action at the one price, saved as the server's prices: each call is held and booked as any priced MCP
209
+ // call (mcp-gateway.ts). None named: the server's prices as they stand, for the actions it still lists (a server saved
210
+ // with none: "not metered").
211
+ const prices = priceValid(price) ? Object.fromEntries([...new Set(tools)].map((slug) => [slug, price])) : undefined;
188
212
  const ask = asking(control, key, signal);
189
213
  // What this save made at Composio. A failure removes it all again (the MCP server, the account its connect link started,
190
214
  // then the auth config), so a failed save leaves nothing it made in the person's account, and never removes what it
@@ -199,24 +223,33 @@ export async function composioSave(body, control, save, name, signal, savedUrl)
199
223
  // allowing a slug it doesn't have, which then serves nothing under that name. A list longer than MAX_PAGES refuses
200
224
  // nothing on what it didn't read; the check after the save (not_served) still names an action left out.
201
225
  const offered = await toolkitTools(ask, toolkit);
202
- const known = new Set(offered.tools.map((tool) => tool.slug));
203
- const unknown = offered.complete ? [...new Set(tools)].filter((slug) => !known.has(slug)) : [];
226
+ const slugs = offered.tools.map((tool) => tool.slug);
227
+ const unknown = offered.complete ? [...new Set(tools)].filter((slug) => !slugs.includes(slug)) : [];
204
228
  if (unknown.length) {
205
- // A slug past 128 characters is named by its first 64 and its length, so the refusal never carries a pasted megabyte back.
206
229
  const names = unknown.map((slug) => {
207
- const likely = likelySlug(slug, [...known]);
208
- const shown = slug.length > 128 ? `${slug.slice(0, 64)}… (${slug.length} characters)` : slug;
209
- return likely ? `${shown} (did you mean ${likely}?)` : shown;
230
+ const likely = likelySlug(slug, slugs);
231
+ return likely ? `${slug} (did you mean ${likely}?)` : slug;
210
232
  });
211
- throw invalid([issue("tools", "not_found", `Composio's ${toolkit} toolkit has no action ${names.length < 2 ? names.join("") : `${names.slice(0, -1).join(", ")} or ${names.at(-1)}`}: pick from its list (POST /settings/mcp-servers/composio/tools). Nothing was saved.`)]);
233
+ throw invalid([issue("tools", "not_found", `Composio's ${toolkit} toolkit has no action ${listed(names, "or")}: pick from its list (POST /settings/mcp-servers/composio/tools). Nothing was saved.`)]);
212
234
  }
213
235
  const noAuth = needsNoAuth(kit);
236
+ if (noAuth && ownConfig)
237
+ throw invalid([issue("auth_config_id", "not_allowed", `Composio's ${toolkit} toolkit needs no account, so no auth config: send no auth_config_id. Nothing was saved.`)]);
214
238
  let authConfig;
215
239
  let madeConfig = false;
216
- if (!noAuth) {
217
- const configs = await ask("finding the toolkit's auth config", "GET", `/api/v3/auth_configs?toolkit_slug=${encodeURIComponent(toolkit)}`);
218
- const managed = (Array.isArray(configs.items) ? configs.items : []).find((c) => isObject(c) && c.is_composio_managed === true && c.status !== "DISABLED" && text(c.id));
219
- authConfig = managed ? text(managed.id) : undefined;
240
+ if (ownConfig) {
241
+ // The owner's own auth config (a custom OAuth app's): the server and its connect link are made against it, as it is.
242
+ // Read first, so one Composio doesn't know, of another toolkit, or disabled is refused before anything is made.
243
+ const config = await ask("reading the auth config", "GET", `/api/v3/auth_configs/${encodeURIComponent(ownConfig)}`, undefined, issue("auth_config_id", "not_found", `Composio has no auth config ${ownConfig} in this key's project: use the id its dashboard shows for one of the ${toolkit} toolkit's. Nothing was saved.`));
244
+ const of = isObject(config.toolkit) ? text(config.toolkit.slug).toLowerCase() : "";
245
+ if (of !== toolkit)
246
+ throw invalid([issue("auth_config_id", "wrong_toolkit", `The auth config ${ownConfig} is ${of ? `the ${of} toolkit's` : "no toolkit's Composio names"}, not ${toolkit}'s: use one of ${toolkit}'s. Nothing was saved.`)]);
247
+ if (config.status === "DISABLED")
248
+ throw invalid([issue("auth_config_id", "disabled", `The auth config ${ownConfig} is disabled in Composio: enable it there, or use another. Nothing was saved.`)]);
249
+ authConfig = ownConfig;
250
+ }
251
+ else if (!noAuth) {
252
+ authConfig = await managedConfig(ask, toolkit);
220
253
  if (!authConfig) {
221
254
  const made = await ask("making the toolkit's auth config", "POST", "/api/v3/auth_configs", { toolkit: { slug: toolkit }, auth_config: { type: "use_composio_managed_auth" } });
222
255
  authConfig = isObject(made.auth_config) ? text(made.auth_config.id) : "";
@@ -233,13 +266,15 @@ export async function composioSave(body, control, save, name, signal, savedUrl)
233
266
  if (!id)
234
267
  throw new ApiError("upstream_failed", "Composio made no MCP server: nothing was saved.");
235
268
  madeHere.push({ kind: "mcp", id });
236
- const generated = await ask("making the MCP server's address", "POST", "/api/v3.1/mcp/servers/generate", { mcp_server_id: id, user_ids: [user], managed_auth_by_composio: true });
269
+ // A per-run server's address is generated as the default user's (the one answer shape known, user_ids_url), then
270
+ // saved with no user and no account in it (composioAddress): generating an address makes nothing at Composio.
271
+ const generated = await ask("making the MCP server's address", "POST", "/api/v3.1/mcp/servers/generate", { mcp_server_id: id, user_ids: [perRun ? COMPOSIO_USER : user], managed_auth_by_composio: true });
237
272
  const address = Array.isArray(generated.user_ids_url) ? text(generated.user_ids_url[0]) : "";
238
273
  if (!address)
239
274
  throw new ApiError("upstream_failed", "Composio gave no address for the MCP server: nothing was saved.");
240
275
  let connect;
241
276
  const accounts = [];
242
- if (authConfig) {
277
+ if (authConfig && !perRun) {
243
278
  // Only an account under this server's auth config serves it: one ACTIVE under another config (a custom one) doesn't.
244
279
  const listed = await ask("checking the connected account", "GET", `/api/v3/connected_accounts?user_ids=${encodeURIComponent(user)}&toolkit_slugs=${encodeURIComponent(toolkit)}&auth_config_ids=${encodeURIComponent(authConfig)}`);
245
280
  const active = (Array.isArray(listed.items) ? listed.items : []).find((a) => isObject(a) && a.status === "ACTIVE" && isObject(a.auth_config) && a.auth_config.id === authConfig);
@@ -257,22 +292,23 @@ export async function composioSave(body, control, save, name, signal, savedUrl)
257
292
  }
258
293
  }
259
294
  }
260
- const stands = { user, auth_config: authConfig ? { id: authConfig, made: madeConfig } : null, accounts };
261
- url = composioAddress(address);
295
+ // One the owner named is theirs (`named`): never recorded as made here, whoever made it (composio-made.ts).
296
+ const stands = { user, auth_config: authConfig ? { id: authConfig, made: madeConfig, ...(ownConfig ? { named: true } : {}) } : null, accounts, ...(perRun ? { per_run: true } : {}) };
297
+ url = composioAddress(address, perRun);
262
298
  // Saved as what it is, a Composio server of this toolkit: a template that needs the toolkit maps to it, whatever its
263
299
  // name. A slug no template can name (mcp:<toolkit>/<tool>: no `_`) is saved as a Composio server of no toolkit.
264
300
  // Composio leaves out an action it does not serve, and a server that serves none of the picked ones lists no tools at
265
301
  // all: its MCP answers the listing "Method not found" (JSON-RPC -32601). Only that answer says "none served", in words
266
302
  // naming the picked actions; any other failure (no DNS, a timeout, an HTTP 500) stays the 424 it is.
267
- const server = await save({ url, auth: { type: "headers", headers: { "x-api-key": key } } }, { source: "composio", toolkit: MCP_SERVER_NAME.test(toolkit) ? toolkit : null }, stands).catch((error) => {
303
+ const server = await save({ url, auth: { type: "headers", headers: { "x-api-key": key } }, ...(prices ? { prices } : {}) }, { source: "composio", toolkit: MCP_SERVER_NAME.test(toolkit) ? toolkit : null }, stands).catch((error) => {
268
304
  if (!(error instanceof ApiError) || error.code !== "upstream_failed" || error.extra.details?.rpc_code !== METHOD_NOT_FOUND)
269
305
  throw error;
270
306
  throw invalid([issue("tools", "not_served", `Composio's ${toolkit} server doesn't serve ${tools.join(", ")}: pick another action.`)]);
271
307
  });
272
308
  // Composio's server can leave out an action it was allowed (HACKERNEWS_GET_FRONTPAGE, live 11-13): say which, so a grant
273
309
  // doesn't vanish without a word. A toolkit with no account yet still lists its actions, so this holds before the connect.
274
- const listed = new Set((server.tools ?? []).map((tool) => tool.name));
275
- const missing = tools.filter((slug) => !listed.has(slug));
310
+ const served = new Set((server.tools ?? []).map((tool) => tool.name));
311
+ const missing = tools.filter((slug) => !served.has(slug));
276
312
  return { server, ...(connect ? { connect_url: connect } : {}), ...(missing.length ? { not_served: missing } : {}) };
277
313
  }
278
314
  catch (error) {
@@ -323,8 +359,8 @@ export const composioServerId = (address) => {
323
359
  };
324
360
  /** A thing at Composio as the words name it; `removed`: as a removal names it (an account its connect link with it). */
325
361
  const named = (thing, removed = false) => thing.kind === "mcp" ? `the MCP server ${thing.id}` : thing.kind === "auth_config" ? `the auth config ${thing.id}` : `the connected account ${thing.id}${removed ? " (its connect link with it)" : ""}`;
326
- /** "a", "a and b", "a, b and c". */
327
- const listed = (items) => (items.length < 2 ? items.join("") : `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`);
362
+ /** "a", "a and b", "a, b and c" (or "a, b or c"). */
363
+ const listed = (items, word = "and") => (items.length < 2 ? items.join("") : `${items.slice(0, -1).join(", ")} ${word} ${items.at(-1)}`);
328
364
  /** What a delete's answer says it did at Composio, in words: what it removed, what it kept and why (another saved server
329
365
  * uses it, or this server didn't make it), and what is left, with where to remove that by hand. `removed`: nothing is
330
366
  * left there. */
@@ -2,11 +2,14 @@ import { type ComposioControl } from "./composio-preset.js";
2
2
  import type { Source } from "./trigger-adapter.js";
3
3
  import type { TriggerUpstream } from "./triggers.js";
4
4
  import { type Json } from "./validate.js";
5
- /** A saved Composio server's key, the Composio user its address names, and its toolkit. */
5
+ /** A saved Composio server's key, the Composio user its address names, its toolkit, and the auth config its save stands
6
+ * on (the managed one found or made, or the one auth_config_id named; none for a server saved before that was recorded,
7
+ * whose link is then under managedConfig's, or of a toolkit with no sign-in). */
6
8
  export type ComposioCredential = {
7
9
  key: string;
8
10
  user: string;
9
11
  toolkit: string;
12
+ auth_config?: string;
10
13
  };
11
14
  /** A trigger of kind composio, as the engine keeps it. */
12
15
  type Holder = {
@@ -27,7 +30,7 @@ export type ComposioTriggerDeps = {
27
30
  publicUrl?: string;
28
31
  /** The composio source's sealed settings: each hook's subscription secret. */
29
32
  sealed: Sealed;
30
- /** Saved server `name`'s key, user and toolkit; refused (thrown) when it is no Composio server: by the source's field at
33
+ /** Saved server `name`'s key, user, toolkit and auth config; refused (thrown) when it is no Composio server: by the source's field at
31
34
  * a trigger's create (`field`), as a 404 on its own routes (`route`). */
32
35
  credential(name: string, refusal: "field" | "route"): Promise<ComposioCredential>;
33
36
  /** Every trigger of kind composio, on or off. */
@@ -143,8 +146,10 @@ export declare class ComposioTriggers implements TriggerUpstream {
143
146
  /** The project's subscription for a trigger: made here if there is none (undone with `undo`), reused if it is this
144
147
  * server's, moved here only when `move`. Answers its hook. */
145
148
  private subscribe;
146
- /** The id of the one ACTIVE account the server's user has for its toolkit; none: refused, with the link to connect it;
147
- * several: refused, naming each with when it was connected, so the owner disconnects the ones it shouldn't run as. */
149
+ /** The id of the one ACTIVE account the server's user has for its toolkit, under the auth config the server's save stands
150
+ * on (as its MCP server serves only those; every config, for a server saved before that was recorded); none: refused,
151
+ * with the link to connect it under that config; several: refused, naming each with when it was connected, so the
152
+ * owner disconnects the ones it shouldn't run as. */
148
153
  private accountOf;
149
154
  }
150
155
  export {};
@@ -25,7 +25,7 @@
25
25
  // asked anything.
26
26
  import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
27
27
  import { ApiError, invalid } from "./errors.js";
28
- import { asking } from "./composio-preset.js";
28
+ import { asking, managedConfig } from "./composio-preset.js";
29
29
  import { COMPOSIO_HOOK, COMPOSIO_SECRET, CONFIG_SECRET, CONFIG_UNLISTED, configScope, configSecrets, MOVE_FIELD, SEALED_FIELD, SEALED_MASK, sealableValue, sealedConfigFields, sealedKept, sealedSchemaFields, shownSource } from "./trigger-composio.js";
30
30
  import { isObject } from "./validate.js";
31
31
  /** Where the owner does by hand what this server could not do on Composio. */
@@ -138,11 +138,14 @@ export class ComposioTriggers {
138
138
  undo.push(async () => this.leave(ask, instance, await this.leftWith(instance, id)));
139
139
  if (!enabled && (await this.leftWith(instance, id)) !== "keep")
140
140
  await ask("turning the trigger instance off", "PATCH", `/api/v3/trigger_instances/manage/${enc(instance)}`, { status: "disable" });
141
- // The saved server is still there, under the key this was made with: one deleted (or saved again with another
142
- // key) meanwhile is refused here, and what was made is undone, so no trigger names a server that is gone.
141
+ // The saved server is still there, under the key and on the auth config this was made with: one deleted (or saved
142
+ // again with another key, or onto another config, whose accounts the instance's isn't) meanwhile is refused here,
143
+ // and what was made is undone, so no trigger names a server that is gone or an account it doesn't serve.
143
144
  const now = await this.deps.credential(server, "field");
144
145
  if (now.key !== credential.key)
145
146
  throw invalid([{ field: "source.server", reason: "invalid", message: `${server} was saved again with another Composio key while this trigger was being made: nothing was saved, make it again.` }]);
147
+ if (now.auth_config !== credential.auth_config)
148
+ throw invalid([{ field: "source.server", reason: "invalid", message: `${server} was saved again on another auth config while this trigger was being made: nothing was saved, make it again.` }]);
146
149
  // Each credential of its config sealed, the trigger keeping the mask in its place: Composio's upsert above was the
147
150
  // one place it went.
148
151
  undo.push(async () => {
@@ -626,22 +629,26 @@ export class ComposioTriggers {
626
629
  this.deps.say({ condition: "composio_subscription_moved", from: sub.webhook_url, hook });
627
630
  return hook;
628
631
  }
629
- /** The id of the one ACTIVE account the server's user has for its toolkit; none: refused, with the link to connect it;
630
- * several: refused, naming each with when it was connected, so the owner disconnects the ones it shouldn't run as. */
632
+ /** The id of the one ACTIVE account the server's user has for its toolkit, under the auth config the server's save stands
633
+ * on (as its MCP server serves only those; every config, for a server saved before that was recorded); none: refused,
634
+ * with the link to connect it under that config; several: refused, naming each with when it was connected, so the
635
+ * owner disconnects the ones it shouldn't run as. */
631
636
  async accountOf(ask, credential, server) {
632
- const accounts = await ask("checking the connected account", "GET", `/api/v3/connected_accounts?user_ids=${enc(credential.user)}&toolkit_slugs=${enc(credential.toolkit)}&statuses=ACTIVE`);
633
- const active = (Array.isArray(accounts.items) ? accounts.items : []).filter((a) => isObject(a) && a.status === "ACTIVE" && !!text(a.id));
637
+ const config = credential.auth_config;
638
+ const accounts = await ask("checking the connected account", "GET", `/api/v3/connected_accounts?user_ids=${enc(credential.user)}&toolkit_slugs=${enc(credential.toolkit)}${config ? `&auth_config_ids=${enc(config)}` : ""}&statuses=ACTIVE`);
639
+ const active = (Array.isArray(accounts.items) ? accounts.items : []).filter((a) => isObject(a) && a.status === "ACTIVE" && !!text(a.id) && (!config || (isObject(a.auth_config) && a.auth_config.id === config)));
634
640
  if (active.length === 1)
635
641
  return text(active[0].id);
642
+ const under = config ? ` under auth config ${config}` : "";
636
643
  // Several: never one picked, which would run the trigger as an account the owner didn't choose, unseen.
637
644
  if (active.length > 1) {
638
645
  const listed = active.map((a) => ({ id: text(a.id), created_at: text(a.created_at) })).sort((a, b) => a.created_at.localeCompare(b.created_at) || a.id.localeCompare(b.id));
639
- throw new ApiError("composio_account_ambiguous", `${server}'s Composio user ${credential.user} has ${listed.length} connected ${credential.toolkit} accounts: ${listed.map((a) => `${a.id} (connected ${a.created_at || "at an unknown time"})`).join(", ")}. A trigger runs as one account: disconnect the ones it shouldn't run as in Composio, then make the trigger again.`, { details: { server, user_id: credential.user, accounts: listed } });
646
+ throw new ApiError("composio_account_ambiguous", `${server}'s Composio user ${credential.user} has ${listed.length} connected ${credential.toolkit} accounts${under}: ${listed.map((a) => `${a.id} (connected ${a.created_at || "at an unknown time"})`).join(", ")}. A trigger runs as one account: disconnect the ones it shouldn't run as in Composio, then make the trigger again.`, { details: { server, user_id: credential.user, accounts: listed } });
640
647
  }
641
- // The link is under the toolkit's Composio-managed auth config, the one the server's save made or found.
642
- const configs = await ask("finding the toolkit's auth config", "GET", `/api/v3/auth_configs?toolkit_slug=${enc(credential.toolkit)}`);
643
- const managed = (Array.isArray(configs.items) ? configs.items : []).find((c) => isObject(c) && c.is_composio_managed === true && c.status !== "DISABLED" && text(c.id));
644
- const link = isObject(managed) ? text((await ask("making the connect link", "POST", "/api/v3/connected_accounts/link", { auth_config_id: text(managed.id), user_id: credential.user })).redirect_url) : "";
645
- throw new ApiError("composio_not_connected", `${server}'s Composio user ${credential.user} has no connected ${credential.toolkit} account: connect it${link ? ` at ${link}` : " in Composio"}, then make the trigger again.`, { details: { server, user_id: credential.user, ...(link ? { connect_url: link } : {}) } });
648
+ // The link is under the server's auth config; for a server saved before that was recorded, under the one its save
649
+ // found or made (managedConfig, the preset's own finder).
650
+ const linkConfig = config || (await managedConfig(ask, credential.toolkit));
651
+ const link = linkConfig ? text((await ask("making the connect link", "POST", "/api/v3/connected_accounts/link", { auth_config_id: linkConfig, user_id: credential.user })).redirect_url) : "";
652
+ throw new ApiError("composio_not_connected", `${server}'s Composio user ${credential.user} has no connected ${credential.toolkit} account${under}: connect it${link ? ` at ${link}` : " in Composio"}, then make the trigger again.`, { details: { server, user_id: credential.user, ...(link ? { connect_url: link } : {}) } });
646
653
  }
647
654
  }
@@ -3,7 +3,7 @@ import type { Duplex } from "node:stream";
3
3
  import { type AttachHub, type AttachSocket, type HelloResult, type MachineTokens } from "@parcha/agentrun-computer";
4
4
  import { WebSocket } from "ws";
5
5
  import { type LiveReach } from "./live-reach.js";
6
- import type { MintedTokens, PairedComputerRow, PairedComputers, RunnerRelays } from "./store/index.js";
6
+ import type { MintedTokens, PairedComputerRow, PairedComputers, RunnerRow, Runners } from "./store/index.js";
7
7
  /** The characters of a pairing code: no 0, O, 1 or I, so a person reads it off a screen without a doubt. */
8
8
  export declare const PAIRING_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
9
9
  /** A computer's token starts with this, so a secret scanner knows one. */
@@ -22,10 +22,6 @@ export declare function newPairingCode(pick?: (below: number) => number): string
22
22
  export declare function pairingCodeOf(typed: unknown): string | undefined;
23
23
  /** A new paired computer's id: PAIRED_ID_PREFIX and 16 lowercase letters and digits. */
24
24
  export declare const newPairedId: (pick?: (below: number) => number) => string;
25
- /** A new computer token: ATTACH_TOKEN_PREFIX and 32 random bytes. */
26
- export declare const newAttachToken: () => string;
27
- /** A new hosted machine's token: ATTACH_TOKEN_PREFIX and 32 random bytes in hex, which goes in the machine's env. */
28
- export declare const newMintedToken: () => string;
29
25
  /** `reason` cut to what a close frame holds (123 bytes of UTF-8), never inside a character. */
30
26
  export declare function closeReason(reason: string): string;
31
27
  /** A limit of `perMinute` tries a minute by key: the pair route's by source address (`keyOf` peerKey: an IPv6 one by its
@@ -139,16 +135,21 @@ export interface AttachRoutesOptions {
139
135
  /** The server's relay of a dial whose token another runner minted: where each runner's attach listener answers, and
140
136
  * the hosts it may dial with the proxy's proof (live-reach.ts). Without it such a dial is refused 503. */
141
137
  readonly relay?: {
142
- readonly relays: Pick<RunnerRelays, "get">;
138
+ readonly runners: Pick<Runners, "live">;
143
139
  readonly reach: LiveReach;
144
140
  };
145
141
  }
146
142
  /** A request's Bearer token, or undefined. */
147
143
  export declare const bearerOf: (authorization: string | undefined) => string | undefined;
148
- /** How often a runner's attach listener says it is there (its runner_relays row's seen_at), and how long after its last
149
- * word the server takes it as gone. */
150
- export declare const RELAY_RENEW_MS = 10000;
151
- export declare const RELAY_STALE_MS: number;
144
+ /** A runner's row that says where its relay answers. */
145
+ export type RelayRow = RunnerRow & {
146
+ readonly host: string;
147
+ readonly port: number;
148
+ };
149
+ /** The runners whose relay takes dials now: their rows seen within PRESENCE_STALE_MS on the store's clock (Runners.live,
150
+ * the database's on Postgres), never one process's, that say where their relay answers. The server relays a dial only
151
+ * to one of these, and says a dial provider is served while one answers at a host it dials (server.ts relayed). */
152
+ export declare function liveRelays(runners: Pick<Runners, "live">): Promise<RelayRow[]>;
152
153
  /** How long the server waits for a runner's attach listener to take a relayed dial. */
153
154
  export declare const RELAY_CONNECT_MS = 10000;
154
155
  /** Two WebSockets joined frame by frame, each an attach socket with `timing` (attachSocketOf: its idle close, its binary
@@ -24,12 +24,13 @@
24
24
  // over MAX_LINE_BYTES, a binary frame, ATTACH_IDLE_MS of silence), joined frame by frame: a close of either closes the
25
25
  // other with its code.
26
26
  import { createHash, randomBytes, randomInt } from "node:crypto";
27
- import { ATTACH_CLOSE, ATTACH_HEARTBEAT_MS, ATTACH_IDLE_MS, ATTACH_PATH, ATTACH_SUBPROTOCOL, hostedDaemonPath, MAX_LINE_BYTES, mintedComputer, PAIRING_CODE_PATTERN, PAIRING_CODE_TTL_MS, PROTOCOL_VERSION, RUN_LABEL } from "@parcha/agentrun-computer";
27
+ import { ATTACH_CLOSE, ATTACH_HEARTBEAT_MS, ATTACH_IDLE_MS, ATTACH_PATH, ATTACH_SUBPROTOCOL, hostedDaemonPath, MAX_LINE_BYTES, mintedComputer, newMachineToken, PAIRING_CODE_PATTERN, PAIRING_CODE_TTL_MS, PROTOCOL_VERSION, RUN_LABEL } from "@parcha/agentrun-computer";
28
28
  import { WebSocket, WebSocketServer } from "ws";
29
29
  import { ApiError, invalid } from "./errors.js";
30
30
  import { dialHost, LIVE_PROOF_HEADER, relayProof } from "./live-reach.js";
31
31
  import { peerKey } from "./owner.js";
32
32
  import { registerNotSecretWrite } from "./secret-writes.js";
33
+ import { PRESENCE_STALE_MS } from "./runner/presence.js";
33
34
  import { pairedOf, PAIRED_ID_PREFIX, RUNNER_APART_WORDS, servesNoKind } from "./workspace/attached-computers.js";
34
35
  // Routes under /computers, where a provider's keys are a secret write (computers.ts): these three write none of the
35
36
  // owner's secrets, so the API token may call them as the console's session does.
@@ -70,10 +71,6 @@ export function pairingCodeOf(typed) {
70
71
  }
71
72
  /** A new paired computer's id: PAIRED_ID_PREFIX and 16 lowercase letters and digits. */
72
73
  export const newPairedId = (pick = randomInt) => `${PAIRED_ID_PREFIX}${Array.from({ length: 16 }, () => "abcdefghijkmnpqrstuvwxyz23456789"[pick(32)]).join("")}`;
73
- /** A new computer token: ATTACH_TOKEN_PREFIX and 32 random bytes. */
74
- export const newAttachToken = () => `${ATTACH_TOKEN_PREFIX}${randomBytes(32).toString("base64url")}`;
75
- /** A new hosted machine's token: ATTACH_TOKEN_PREFIX and 32 random bytes in hex, which goes in the machine's env. */
76
- export const newMintedToken = () => `${ATTACH_TOKEN_PREFIX}${randomBytes(32).toString("hex")}`;
77
74
  /** The computerd builds a minted machine fetches (GET /v2/computers/daemon?arch=), each at hostedDaemonPath: the file a
78
75
  * hosted provider uploads by default, so the route serves the bytes whose SHA-256 the provider puts in the machine's env. */
79
76
  const DAEMON_ARCHES = ["amd64", "arm64"];
@@ -274,10 +271,12 @@ export function attachSocketOf(ws, timing = { heartbeatMs: ATTACH_HEARTBEAT_MS,
274
271
  }
275
272
  /** A request's Bearer token, or undefined. */
276
273
  export const bearerOf = (authorization) => /^Bearer (\S+)$/.exec(String(authorization ?? ""))?.[1];
277
- /** How often a runner's attach listener says it is there (its runner_relays row's seen_at), and how long after its last
278
- * word the server takes it as gone. */
279
- export const RELAY_RENEW_MS = 10_000;
280
- export const RELAY_STALE_MS = 3 * RELAY_RENEW_MS;
274
+ /** The runners whose relay takes dials now: their rows seen within PRESENCE_STALE_MS on the store's clock (Runners.live,
275
+ * the database's on Postgres), never one process's, that say where their relay answers. The server relays a dial only
276
+ * to one of these, and says a dial provider is served while one answers at a host it dials (server.ts relayed). */
277
+ export async function liveRelays(runners) {
278
+ return (await runners.live(PRESENCE_STALE_MS)).filter((row) => row.host !== null && row.port !== null);
279
+ }
281
280
  /** How long the server waits for a runner's attach listener to take a relayed dial. */
282
281
  export const RELAY_CONNECT_MS = 10_000;
283
282
  /** A close code one side of a relay may send the other: its own, or 1001 for one a peer may not send (1005, 1006). */
@@ -337,7 +336,7 @@ export function createAttachRoutes(options) {
337
336
  if (unserved)
338
337
  throw invalid([{ field: "hello.groups", reason: "invalid", message: unserved }]);
339
338
  const id = newPairedId();
340
- const token = newAttachToken();
339
+ const token = newMachineToken();
341
340
  const made = await paired.pair(sha256Hex(code), { id, name, hello: hello, labels: {}, tokenSha256: sha256Hex(token) });
342
341
  if (!made)
343
342
  throw new ApiError("not_found", "no such pairing code: make a new one on the console's Computers page");
@@ -360,7 +359,7 @@ export function createAttachRoutes(options) {
360
359
  const until = expiresAt.getTime();
361
360
  if (!Number.isFinite(until))
362
361
  throw new TypeError(`a machine token's expiresAt is a time, not ${JSON.stringify(expiresAt)}`);
363
- const token = newMintedToken();
362
+ const token = newMachineToken();
364
363
  await minted.mint({ machine, tokenSha256: sha256Hex(token), kind, os, arch, expiresAt: until, ...(options.owner ?? {}), ...(run !== undefined ? { run } : {}) });
365
364
  log("machine_token_minted", { ...(run !== undefined ? { run } : {}), machine, kind, os, arch, expires_at: new Date(until).toISOString() });
366
365
  return token;
@@ -417,9 +416,9 @@ export function createAttachRoutes(options) {
417
416
  };
418
417
  if (options.relay === undefined)
419
418
  return refuse(`runner ${runner} made it, and this server relays no dial to a runner`);
420
- const at = await options.relay.relays.get(runner);
421
- if (at === undefined || at.seenAt < now() - RELAY_STALE_MS)
422
- return refuse(`runner ${runner}, which made it, is not running now (no attach listener of its has said it is there for ${RELAY_STALE_MS / 1000} s): its run makes a new machine at its next claim`);
419
+ const at = (await liveRelays(options.relay.runners)).find((row) => row.runner === runner);
420
+ if (at === undefined)
421
+ return refuse(`runner ${runner}, which made it, is not running now (no attach listener of its has said it is there for ${PRESENCE_STALE_MS / 1000} s): its run makes a new machine at its next claim`);
423
422
  if (at.incarnation !== row.incarnation)
424
423
  return refuse(`runner ${runner}, which made it, restarted since, and the machine was its earlier process's: its run makes a new machine at its next claim`);
425
424
  const host = dialHost(at.host, options.relay.reach);
@@ -25,6 +25,9 @@ export interface JournalEntry {
25
25
  readonly kind: string;
26
26
  readonly data: unknown;
27
27
  }
28
+ /** Who may drive, and how a take may end, as a journal entry (or a run's own process) may say them. */
29
+ export declare const STATES: readonly string[];
30
+ export declare const ENDS: readonly string[];
28
31
  /** The hold as the run's journal has it. */
29
32
  export type HoldRead = {
30
33
  /** Whether the run's computer is up (its last up entry). */
@@ -37,8 +37,9 @@ export const takeEndedWords = (computer, why) => why === "given" || why === "ans
37
37
  /** An ask already answered: 409, in the browser's route's words. */
38
38
  const answeredWords = (outcome) => outcome === "expired" ? "The agent's hand-over expired before this answer: the agent was told it expired." : `The agent's hand-over was already answered ${outcome}.`;
39
39
  const dataOf = (entry) => (entry.data && typeof entry.data === "object" ? entry.data : {});
40
- const STATES = ["agent", "pending", "person"];
41
- const ENDS = ["given", "answered", "idle", "away", "released"];
40
+ /** Who may drive, and how a take may end, as a journal entry (or a run's own process) may say them. */
41
+ export const STATES = ["agent", "pending", "person"];
42
+ export const ENDS = ["given", "answered", "idle", "away", "released"];
42
43
  const OUTCOMES = ["done", "cancelled", "expired"];
43
44
  /** The run's hold, from its journal's computer.hold entries. */
44
45
  export function holdIn(entries) {
@@ -2,6 +2,10 @@
2
2
  export declare const LOST_RECREATES = 2;
3
3
  /** The code a run past its new sandboxes fails with: the one a computer that cannot be had at the claim is refused with. */
4
4
  export declare const COMPUTER_UNAVAILABLE_CODE = "computer_unavailable";
5
+ /** The answer of the call in flight when its sandbox, `name`, was found lost, `why` the provider's words. Its code is
6
+ * gone, never not_found, so no caller reads it as a file or a program that is not there (a shell's fallback from bash
7
+ * to sh would send the command again, to the new sandbox). */
8
+ export declare const lostInCallWords: (name: string, why: string) => string;
5
9
  /** The Timeline's row once a new sandbox replaced a lost one: its name. */
6
10
  export declare const lostRecreatedWords: (name: string) => string;
7
11
  /** The run's end once its sandbox was lost again after `recreates` new ones (the claim's bound): the provider's words,
@@ -1,7 +1,8 @@
1
1
  // A run's sandbox that its provider lost mid-run (deleted by the vendor's own API or console, or gone with no why): the
2
- // claim starts a new one in its place at the next tool call (workspace/computer-for-claim.ts lostAware), up to
3
- // LOST_RECREATES times a claim. These are the words of both: the Timeline's row for a new one, and the run's end once the
4
- // claim has started as many as it may. That end's words begin with its code, so a reader of the run's summary serves it
2
+ // call in flight when the loss is confirmed fails and is never run again, and the claim starts a new one in its place at
3
+ // the next tool call (workspace/computer-for-claim.ts lostAware), up to LOST_RECREATES times a claim. These are the words
4
+ // of all three: the call the loss cut, the Timeline's row for a new one, and the run's end once the claim has started as
5
+ // many as it may. That end's words begin with its code, so a reader of the run's summary serves it
5
6
  // as the error computer_unavailable, its message the words after the code (store-view.ts errorOfRow), as a cap's end is
6
7
  // served as spend_cap_reached.
7
8
  /** How many new sandboxes a claim starts in place of ones its provider lost, by default. */
@@ -10,6 +11,10 @@ export const LOST_RECREATES = 2;
10
11
  export const COMPUTER_UNAVAILABLE_CODE = "computer_unavailable";
11
12
  /** How lostEnd's words begin, and only theirs. */
12
13
  const LOST_END = `${COMPUTER_UNAVAILABLE_CODE}: `;
14
+ /** The answer of the call in flight when its sandbox, `name`, was found lost, `why` the provider's words. Its code is
15
+ * gone, never not_found, so no caller reads it as a file or a program that is not there (a shell's fallback from bash
16
+ * to sh would send the command again, to the new sandbox). */
17
+ export const lostInCallWords = (name, why) => `the computer ${name} was lost while this call ran, and it was not run again: ${why.replace(/[.!?]+$/, "")}. A new computer starts at the next call.`;
13
18
  /** The Timeline's row once a new sandbox replaced a lost one: its name. */
14
19
  export const lostRecreatedWords = (name) => `Its computer was lost; started a new one (${name}).`;
15
20
  /** The run's end once its sandbox was lost again after `recreates` new ones (the claim's bound): the provider's words,