@parcha/agentrun-serve 0.1.0-beta.40 → 0.1.0-beta.41

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 (126) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/README.md +78 -15
  3. package/dist/api-only.d.ts +3 -1
  4. package/dist/api-only.js +4 -2
  5. package/dist/api-token.d.ts +30 -0
  6. package/dist/api-token.js +89 -0
  7. package/dist/cli.js +19 -5
  8. package/dist/composio-made.d.ts +54 -0
  9. package/dist/composio-made.js +83 -0
  10. package/dist/composio-preset.d.ts +16 -8
  11. package/dist/composio-preset.js +106 -43
  12. package/dist/composio-triggers.d.ts +7 -2
  13. package/dist/composio-triggers.js +13 -7
  14. package/dist/computer-attach.d.ts +29 -11
  15. package/dist/computer-attach.js +141 -47
  16. package/dist/computer-keys.d.ts +4 -0
  17. package/dist/computer-keys.js +5 -0
  18. package/dist/computers.d.ts +11 -1
  19. package/dist/computers.js +21 -12
  20. package/dist/console/assets/{index-B8Zn1Iqn.css → index-C3gNPz58.css} +1 -1
  21. package/dist/console/assets/index-COGhx_2Z.js +711 -0
  22. package/dist/console/index.html +2 -2
  23. package/dist/decisions.js +9 -2
  24. package/dist/eval-feed.d.ts +26 -0
  25. package/dist/eval-feed.js +68 -0
  26. package/dist/eval-mailbox.d.ts +4 -1
  27. package/dist/eval-mailbox.js +11 -3
  28. package/dist/exa-keyless.d.ts +1 -1
  29. package/dist/exa-keyless.js +1 -1
  30. package/dist/feed/feed-faux.d.ts +62 -0
  31. package/dist/feed/feed-faux.js +123 -0
  32. package/dist/feed/fetch.d.ts +41 -0
  33. package/dist/feed/fetch.js +128 -0
  34. package/dist/feed/parse.d.ts +41 -0
  35. package/dist/feed/parse.js +300 -0
  36. package/dist/learn/check.d.ts +3 -1
  37. package/dist/learn/check.js +57 -2
  38. package/dist/learn/compile.js +1 -1
  39. package/dist/learned-nodes.d.ts +21 -4
  40. package/dist/learned-nodes.js +21 -8
  41. package/dist/learned-workflow.d.ts +3 -3
  42. package/dist/learned-workflow.js +14 -5
  43. package/dist/mcp-oauth.d.ts +15 -1
  44. package/dist/mcp-oauth.js +39 -5
  45. package/dist/mcp-pin-first.d.ts +4 -2
  46. package/dist/mcp-pin-first.js +4 -3
  47. package/dist/mcp-servers-store.d.ts +58 -5
  48. package/dist/mcp-servers-store.js +136 -17
  49. package/dist/mcp.d.ts +2 -2
  50. package/dist/mcp.js +2 -2
  51. package/dist/observation/http.d.ts +4 -1
  52. package/dist/observation/http.js +5 -4
  53. package/dist/openapi.js +46 -12
  54. package/dist/print.d.ts +6 -3
  55. package/dist/print.js +4 -2
  56. package/dist/run-labels.d.ts +23 -0
  57. package/dist/run-labels.js +79 -0
  58. package/dist/run-secrets.js +12 -4
  59. package/dist/runner/adapter-loop.js +91 -10
  60. package/dist/runner/adapter-run-spec.d.ts +4 -0
  61. package/dist/runner/adapter-run-spec.js +38 -31
  62. package/dist/runner/beside.d.ts +6 -3
  63. package/dist/runner/beside.js +9 -7
  64. package/dist/runner/cli-run-spec.js +32 -26
  65. package/dist/runner/conformance/harness.js +69 -14
  66. package/dist/runner/conformance/subject.d.ts +4 -1
  67. package/dist/runner/main.d.ts +1 -1
  68. package/dist/runner/main.js +2 -2
  69. package/dist/runner/mcp-claim.d.ts +3 -0
  70. package/dist/runner/mcp-claim.js +1 -1
  71. package/dist/runner/mcp-run.d.ts +4 -0
  72. package/dist/runner/mcp-run.js +5 -3
  73. package/dist/runner/model-route.d.ts +4 -2
  74. package/dist/runner/model-route.js +8 -8
  75. package/dist/runner/promotion.d.ts +8 -0
  76. package/dist/runner/promotion.js +43 -1
  77. package/dist/runner/workflow-first.d.ts +6 -5
  78. package/dist/runner/workflow-first.js +9 -7
  79. package/dist/runs-over-store.js +5 -2
  80. package/dist/sdk/runs.d.ts +7 -1
  81. package/dist/sdk/runs.js +19 -6
  82. package/dist/secret-cut.js +3 -1
  83. package/dist/secrets.js +3 -1
  84. package/dist/server.d.ts +27 -2
  85. package/dist/server.js +168 -50
  86. package/dist/store/dialect.d.ts +3 -0
  87. package/dist/store/dialect.js +1 -0
  88. package/dist/store/index.d.ts +1 -1
  89. package/dist/store/postgres/dialect.js +1 -0
  90. package/dist/store/postgres/migrations/0015_run_labels.sql +5 -0
  91. package/dist/store/postgres/migrations/0016_minted_tokens.sql +21 -0
  92. package/dist/store/schema.d.ts +9 -0
  93. package/dist/store/schema.js +26 -2
  94. package/dist/store/sqlite/connection.js +11 -3
  95. package/dist/store/sqlite/run-patch.d.ts +2 -1
  96. package/dist/store/sqlite/run-patch.js +3 -2
  97. package/dist/store/sqlite/store.js +64 -10
  98. package/dist/store/store.d.ts +38 -1
  99. package/dist/store-reads/journal.js +2 -1
  100. package/dist/store-reads/learning.js +6 -1
  101. package/dist/store-reads/runs.d.ts +4 -3
  102. package/dist/store-reads/runs.js +3 -2
  103. package/dist/store-view.js +4 -2
  104. package/dist/template-eval.d.ts +4 -0
  105. package/dist/template-eval.js +127 -50
  106. package/dist/templates.d.ts +10 -0
  107. package/dist/templates.js +75 -17
  108. package/dist/timeline/origin.d.ts +1 -1
  109. package/dist/timeline/origin.js +2 -2
  110. package/dist/trigger-adapter.d.ts +9 -4
  111. package/dist/trigger-adapters.js +2 -1
  112. package/dist/trigger-feed.d.ts +12 -0
  113. package/dist/trigger-feed.js +371 -0
  114. package/dist/triggers.d.ts +2 -1
  115. package/dist/triggers.js +23 -5
  116. package/dist/webhooks.js +9 -5
  117. package/dist/workspace/computer-deps.d.ts +5 -1
  118. package/dist/workspace/computer-deps.js +2 -2
  119. package/dist/workspace/index.d.ts +1 -0
  120. package/dist/workspace/index.js +2 -0
  121. package/dist/workspace/resolve-computer.d.ts +32 -3
  122. package/dist/workspace/resolve-computer.js +47 -9
  123. package/launcher/agentrun-serve +6 -1
  124. package/package.json +10 -9
  125. package/templates/README.md +27 -2
  126. package/dist/console/assets/index-Jbxjcmdp.js +0 -705
@@ -0,0 +1,83 @@
1
+ // What the Composio preset made on Composio for a saved server beyond its MCP server (whose id the server's address
2
+ // names): the auth config it found or made, and the connected accounts it found ACTIVE or its connect links started,
3
+ // each marked whether this server made it (`made`). Recorded when the preset saves the server, one row of store.settings
4
+ // per server (composioMadeKey), bound to the server row it was written for (`of`, the row's created_at, which a save over
5
+ // the row keeps) as its source record is (mcp-sources.ts); read when the server is deleted. The delete removes what was
6
+ // made that no other saved server uses (cleanupOf), and passes what another one uses to that one's record, so the last
7
+ // of them to go removes it. What this server didn't make (an auth config or an account the owner had already, or one no
8
+ // record says it made, as for a server saved before this was recorded) is never removed. A save over the server does the
9
+ // same with what the record it replaces made that the new one no longer stands on (droppedOf).
10
+ import { isObject } from "./validate.js";
11
+ /** The store.settings key a server's record lives under. */
12
+ export const composioMadeKey = (name) => `mcp.composio/${name}`;
13
+ /** The settings value a record is stored as, bound to the server row it was written for. */
14
+ export const storedMade = (made, row) => ({ ...made, of: row.createdAt });
15
+ const ID = /^[A-Za-z0-9_.-]{1,128}$/;
16
+ const thingOf = (value) => (isObject(value) && typeof value.id === "string" && ID.test(value.id) && typeof value.made === "boolean" ? { id: value.id, made: value.made } : undefined);
17
+ /** A stored record read for the row created at `createdAt`; undefined when there is none, it was written for another row,
18
+ * or it is not one (then nothing beyond the MCP server is removed). */
19
+ export function recordedMade(value, createdAt) {
20
+ if (!isObject(value) || createdAt === undefined || value.of !== createdAt || typeof value.user !== "string" || !Array.isArray(value.accounts))
21
+ return undefined;
22
+ const config = value.auth_config === null ? null : thingOf(value.auth_config);
23
+ const accounts = value.accounts.map(thingOf);
24
+ if (config === undefined || accounts.some((account) => !account))
25
+ return undefined;
26
+ return { user: value.user, auth_config: config, accounts: accounts };
27
+ }
28
+ /** Whether `other` stands on `mine`'s account: under the same auth config, as the same user (Composio's MCP server picks
29
+ * the account by the two). */
30
+ const sharesAccounts = (mine, other) => mine.auth_config !== null && other.auth_config?.id === mine.auth_config.id && other.user === mine.user;
31
+ /** A record a save writes, from what the preset found and made (`found`): a thing it found that a record of the server
32
+ * saved before over this row (`was`) or of another saved server (`others`) says was made here stays made here; and the
33
+ * accounts the server saved before had made, under the same auth config and user, stay its own. */
34
+ export function madeToWrite(found, was, others) {
35
+ const all = [...(was ? [was] : []), ...others];
36
+ const madeHere = (id) => all.some((r) => r.auth_config?.id === id ? r.auth_config.made : false) || all.some((r) => r.accounts.some((a) => a.id === id && a.made));
37
+ const config = found.auth_config && { id: found.auth_config.id, made: found.auth_config.made || madeHere(found.auth_config.id) };
38
+ const accounts = found.accounts.map((a) => ({ id: a.id, made: a.made || madeHere(a.id) }));
39
+ const kept = was && sharesAccounts(found, was) ? was.accounts.filter((a) => a.made && !accounts.some((b) => b.id === a.id)) : [];
40
+ return { user: found.user, auth_config: config, accounts: [...accounts, ...kept] };
41
+ }
42
+ /** What a removed server's record leaves to do, with the records of the servers still saved (`others`, by name): each
43
+ * thing it made that none of them uses is removed; one another uses is kept and passed to that one (`handover`: its record
44
+ * as it is to be written, owning it); one it didn't make is kept. */
45
+ export function cleanupOf(mine, others, withConfig = true) {
46
+ const cleanup = { remove: [], kept: [] };
47
+ const handed = new Map();
48
+ const take = (name, record) => handed.get(name) ?? (handed.set(name, { ...record, accounts: [...record.accounts] }), handed.get(name));
49
+ for (const account of mine.accounts) {
50
+ const user = others.find(([, other]) => sharesAccounts(mine, other));
51
+ if (!account.made)
52
+ cleanup.kept.push({ kind: "account", id: account.id });
53
+ else if (user) {
54
+ cleanup.kept.push({ kind: "account", id: account.id, by: user[0] });
55
+ const record = take(user[0], user[1]);
56
+ record.accounts = [...record.accounts.filter((a) => a.id !== account.id), { id: account.id, made: true }];
57
+ }
58
+ else
59
+ cleanup.remove.push({ kind: "account", id: account.id });
60
+ }
61
+ if (mine.auth_config && withConfig) {
62
+ const config = mine.auth_config;
63
+ const user = others.find(([, other]) => other.auth_config?.id === config.id);
64
+ if (!config.made)
65
+ cleanup.kept.push({ kind: "auth_config", id: config.id });
66
+ else if (user) {
67
+ cleanup.kept.push({ kind: "auth_config", id: config.id, by: user[0] });
68
+ take(user[0], user[1]).auth_config = { id: config.id, made: true };
69
+ }
70
+ else
71
+ cleanup.remove.push({ kind: "auth_config", id: config.id });
72
+ }
73
+ return { cleanup, handover: [...handed] };
74
+ }
75
+ /** What a save over a server leaves to do at Composio, with the records of the other servers saved (`others`, by name):
76
+ * what the record it replaces (`was`) made that the one written now (`now`) no longer stands on, an account of another
77
+ * user or auth config, and an auth config of another toolkit, each removed or passed on as a delete's is (cleanupOf). */
78
+ export function droppedOf(was, now, others) {
79
+ const accounts = was.accounts.filter((account) => account.made && !now.accounts.some((kept) => kept.id === account.id));
80
+ // The auth config goes through only when this save stands on another one: its accounts are checked under it either way.
81
+ const config = was.auth_config !== null && was.auth_config.made && now.auth_config?.id !== was.auth_config.id;
82
+ return cleanupOf({ user: was.user, auth_config: was.auth_config, accounts }, others, config);
83
+ }
@@ -1,3 +1,4 @@
1
+ import type { Cleanup, ComposioMade } from "./composio-made.js";
1
2
  import { type Json } from "./validate.js";
2
3
  /** Another Composio than the real one, and its fetch: a test's fake (the same seam as `archilControl`). */
3
4
  export type ComposioControl = {
@@ -26,7 +27,9 @@ export declare function composioTools(body: unknown, control: ComposioControl, s
26
27
  * account left off, and the path ended in /mcp (Composio redirects the bare one, which the client refuses on purpose). */
27
28
  export declare function composioAddress(generated: string): string;
28
29
  /** PUT /settings/mcp-servers/{name}/composio: Composio makes the managed MCP server, `save` keeps it as a saved MCP server
29
- * (`{url, auth}`: the key a sealed header), and a toolkit that needs the person's account says where to connect it. */
30
+ * (`{url, auth}`: the key a sealed header), and a toolkit that needs the person's account says where to connect it.
31
+ * `save` gets what the server stands on there too (`stands`, composio-made.ts): the auth config found or made and the
32
+ * account found or started, each marked whether this save made it, for its delete to remove what was made. */
30
33
  export declare function composioSave<T extends {
31
34
  tools?: readonly {
32
35
  name: string;
@@ -40,22 +43,27 @@ export declare function composioSave<T extends {
40
43
  }, made: {
41
44
  source: "composio";
42
45
  toolkit: string | null;
43
- }) => Promise<T>, name: string, signal?: AbortSignal, savedUrl?: () => Promise<string | undefined>): Promise<{
46
+ }, stands: ComposioMade) => Promise<T>, name: string, signal?: AbortSignal, savedUrl?: () => Promise<string | undefined>): Promise<{
44
47
  server: T;
45
48
  connect_url?: string;
46
49
  not_served?: string[];
47
50
  }>;
48
51
  /** The Composio MCP server a saved preset address names (`/v3/mcp/<id>/mcp`, composioAddress): its id, or undefined. */
49
52
  export declare const composioServerId: (address: string) => string | undefined;
50
- /** What the answer to a delete says when the Composio MCP server could not be removed: where to remove it by hand. */
51
- export declare const composioNote: (name: string) => {
53
+ /** What the answer to a delete says when this server could not ask Composio at all (the saved key does not open here, or
54
+ * the address names no Composio server): all of it is left there, to remove by hand. `mcp`: the MCP server left, by its
55
+ * id when known (true: the one it made; false: none). `over`: a save over a server, which says what it keeps too. */
56
+ export declare const composioNote: (name: string, cleanup?: Cleanup, mcp?: string | boolean, over?: boolean) => {
52
57
  removed: false;
53
58
  note: string;
54
59
  };
55
60
  /** Deleting a preset server: the Composio MCP server `id` it made is deleted as `key` (the saved credential, held for this
56
- * call only). Composio's 404 is "already gone"; a refusal, or no answer, is `removed: false` with what to do by hand, for
57
- * the delete of our own row to go on regardless. */
58
- export declare function composioForget(control: ComposioControl, key: string, id: string, name: string, signal?: AbortSignal): Promise<{
61
+ * call only), then what `cleanup` says this server made for it and nothing else uses (composio-made.ts: its connected
62
+ * accounts, then their auth config). Composio's 404 is "already gone"; a refusal, or no answer, leaves that one there and
63
+ * says so, for the delete of our own row to go on regardless. The answer says in words what went, what stays and why.
64
+ * A save over a server does the same with what the save before made that it left (ComposioDropped); no `id` when the
65
+ * row still names the MCP server it named. */
66
+ export declare function composioForget(control: ComposioControl, key: string, id: string | undefined, name: string, signal?: AbortSignal, cleanup?: Cleanup): Promise<{
59
67
  removed: boolean;
60
- note?: string;
68
+ note: string;
61
69
  }>;
@@ -116,7 +116,9 @@ export function composioAddress(generated) {
116
116
  return url.href;
117
117
  }
118
118
  /** PUT /settings/mcp-servers/{name}/composio: Composio makes the managed MCP server, `save` keeps it as a saved MCP server
119
- * (`{url, auth}`: the key a sealed header), and a toolkit that needs the person's account says where to connect it. */
119
+ * (`{url, auth}`: the key a sealed header), and a toolkit that needs the person's account says where to connect it.
120
+ * `save` gets what the server stands on there too (`stands`, composio-made.ts): the auth config found or made and the
121
+ * account found or started, each marked whether this save made it, for its delete to remove what was made. */
120
122
  export async function composioSave(body, control, save, name, signal, savedUrl) {
121
123
  const { key, toolkit, rest } = head(body);
122
124
  const tools = Array.isArray(rest.tools) ? rest.tools : [];
@@ -129,51 +131,70 @@ export async function composioSave(body, control, save, name, signal, savedUrl)
129
131
  if (issues.length)
130
132
  throw invalid(issues);
131
133
  const ask = asking(control, key, signal);
132
- const kit = await ask("reading the toolkit", "GET", `/api/v3/toolkits/${encodeURIComponent(toolkit)}`, undefined, notFound(toolkit));
133
- const noAuth = needsNoAuth(kit);
134
- let authConfig;
135
- if (!noAuth) {
136
- const configs = await ask("finding the toolkit's auth config", "GET", `/api/v3/auth_configs?toolkit_slug=${encodeURIComponent(toolkit)}`);
137
- const managed = (Array.isArray(configs.items) ? configs.items : []).find((c) => isObject(c) && c.is_composio_managed === true && c.status !== "DISABLED" && text(c.id));
138
- authConfig = managed ? text(managed.id) : undefined;
139
- if (!authConfig) {
140
- 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" } });
141
- authConfig = isObject(made.auth_config) ? text(made.auth_config.id) : "";
142
- if (!authConfig)
143
- throw new ApiError("upstream_failed", "Composio made no auth config: nothing was saved.");
144
- }
145
- }
146
- const made = await ask("making the MCP server", "POST", "/api/v3.1/mcp/servers/custom", {
147
- name: `ar-${name.slice(0, 18)}-${randomBytes(3).toString("hex")}`, toolkits: [toolkit], ...(authConfig ? { auth_config_ids: [authConfig] } : {}), allowed_tools: tools, managed_auth_via_composio: true,
148
- });
149
- const id = text(made.id);
150
- if (!id)
151
- throw new ApiError("upstream_failed", "Composio made no MCP server: nothing was saved.");
152
- // From here a failure deletes the server Composio just made, so a failed save leaves nothing in the person's account
153
- // (best effort: the save's own error is the one answered). Not when the local entry was written before the save failed
154
- // (its flush, say): `savedUrl` reads the name's saved address, and one that is this server's keeps it.
134
+ // What this save made at Composio. A failure removes it all again (the MCP server, the account its connect link started,
135
+ // then the auth config), so a failed save leaves nothing it made in the person's account, and never removes what it
136
+ // found there. The save's own error is the one answered, saying what is left when Composio refuses a removal too. Not
137
+ // when the local entry was written before the save failed (its flush, say): `savedUrl` reads the name's saved address,
138
+ // and one that is this server's keeps it all.
139
+ const madeHere = [];
155
140
  let url;
156
141
  try {
142
+ const kit = await ask("reading the toolkit", "GET", `/api/v3/toolkits/${encodeURIComponent(toolkit)}`, undefined, notFound(toolkit));
143
+ const noAuth = needsNoAuth(kit);
144
+ let authConfig;
145
+ let madeConfig = false;
146
+ if (!noAuth) {
147
+ const configs = await ask("finding the toolkit's auth config", "GET", `/api/v3/auth_configs?toolkit_slug=${encodeURIComponent(toolkit)}`);
148
+ const managed = (Array.isArray(configs.items) ? configs.items : []).find((c) => isObject(c) && c.is_composio_managed === true && c.status !== "DISABLED" && text(c.id));
149
+ authConfig = managed ? text(managed.id) : undefined;
150
+ if (!authConfig) {
151
+ 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" } });
152
+ authConfig = isObject(made.auth_config) ? text(made.auth_config.id) : "";
153
+ if (!authConfig)
154
+ throw new ApiError("upstream_failed", "Composio made no auth config: nothing was saved.");
155
+ madeConfig = true;
156
+ madeHere.push({ kind: "auth_config", id: authConfig });
157
+ }
158
+ }
159
+ const made = await ask("making the MCP server", "POST", "/api/v3.1/mcp/servers/custom", {
160
+ name: `ar-${name.slice(0, 18)}-${randomBytes(3).toString("hex")}`, toolkits: [toolkit], ...(authConfig ? { auth_config_ids: [authConfig] } : {}), allowed_tools: tools, managed_auth_via_composio: true,
161
+ });
162
+ const id = text(made.id);
163
+ if (!id)
164
+ throw new ApiError("upstream_failed", "Composio made no MCP server: nothing was saved.");
165
+ madeHere.push({ kind: "mcp", id });
157
166
  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 });
158
167
  const address = Array.isArray(generated.user_ids_url) ? text(generated.user_ids_url[0]) : "";
159
168
  if (!address)
160
169
  throw new ApiError("upstream_failed", "Composio gave no address for the MCP server: nothing was saved.");
161
170
  let connect;
171
+ const accounts = [];
162
172
  if (authConfig) {
163
173
  // Only an account under this server's auth config serves it: one ACTIVE under another config (a custom one) doesn't.
164
- const accounts = await ask("checking the connected account", "GET", `/api/v3/connected_accounts?user_ids=${encodeURIComponent(user)}&toolkit_slugs=${encodeURIComponent(toolkit)}&auth_config_ids=${encodeURIComponent(authConfig)}`);
165
- if (!(Array.isArray(accounts.items) ? accounts.items : []).some((a) => isObject(a) && a.status === "ACTIVE" && isObject(a.auth_config) && a.auth_config.id === authConfig)) {
174
+ 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)}`);
175
+ const active = (Array.isArray(listed.items) ? listed.items : []).find((a) => isObject(a) && a.status === "ACTIVE" && isObject(a.auth_config) && a.auth_config.id === authConfig);
176
+ if (active) {
177
+ if (text(active.id))
178
+ accounts.push({ id: text(active.id), made: false });
179
+ }
180
+ else {
181
+ // The link starts the connected account it connects (connected_account_id): this save's, removed with the server.
166
182
  const link = await ask("making the connect link", "POST", "/api/v3/connected_accounts/link", { auth_config_id: authConfig, user_id: user });
167
183
  connect = text(link.redirect_url) || undefined;
184
+ if (text(link.connected_account_id)) {
185
+ accounts.push({ id: text(link.connected_account_id), made: true });
186
+ madeHere.push({ kind: "account", id: text(link.connected_account_id) });
187
+ }
168
188
  }
169
189
  }
190
+ const stands = { user, auth_config: authConfig ? { id: authConfig, made: madeConfig } : null, accounts };
170
191
  url = composioAddress(address);
171
192
  // Saved as what it is, a Composio server of this toolkit: a template that needs the toolkit maps to it, whatever its
172
193
  // name. A slug no template can name (mcp:<toolkit>/<tool>: no `_`) is saved as a Composio server of no toolkit.
173
194
  // Composio leaves out an action it does not serve, and a server that serves none of the picked ones lists no tools at
174
195
  // all: its MCP answers the listing "Method not found" (JSON-RPC -32601). Only that answer says "none served", in words
175
196
  // naming the picked actions; any other failure (no DNS, a timeout, an HTTP 500) stays the 424 it is.
176
- const server = await save({ url, auth: { type: "headers", headers: { "x-api-key": key } } }, { source: "composio", toolkit: MCP_SERVER_NAME.test(toolkit) ? toolkit : null }).catch((error) => {
197
+ 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) => {
177
198
  if (!(error instanceof ApiError) || error.code !== "upstream_failed" || error.extra.details?.rpc_code !== METHOD_NOT_FOUND)
178
199
  throw error;
179
200
  throw invalid([issue("tools", "not_served", `Composio's ${toolkit} server doesn't serve ${tools.join(", ")}: pick another action.`)]);
@@ -187,9 +208,35 @@ export async function composioSave(body, control, save, name, signal, savedUrl)
187
208
  catch (error) {
188
209
  if (url && savedUrl && (await savedUrl().catch(() => undefined)) === url)
189
210
  throw error;
190
- await ask("deleting the MCP server it made", "DELETE", `/api/v3.1/mcp/${encodeURIComponent(id)}`).catch(() => undefined);
191
- throw error;
211
+ const left = await removing(ask, [...madeHere].sort((a, b) => ORDER[a.kind] - ORDER[b.kind]), []);
212
+ if (!left.length || !(error instanceof ApiError))
213
+ throw error;
214
+ // In its message, and in its details too when it was refused on a field (422 input_invalid): a page that shows the
215
+ // fields' words in place of the message still says what is left at Composio.
216
+ const note = said(name, [], [], left).note;
217
+ throw new ApiError(error.code, `${error.message} ${note}`, error.extra.fields?.length ? { ...error.extra, details: { ...error.extra.details, composio: note } } : error.extra, error.headers);
218
+ }
219
+ }
220
+ /** The order things are removed in: the MCP server, then the accounts, then the auth config they are under. */
221
+ const ORDER = { mcp: 0, account: 1, auth_config: 2 };
222
+ /** Removes `things` at Composio in order, each named in `removed` once gone (Composio's 404: already gone); answers
223
+ * those it could not remove, named. */
224
+ async function removing(ask, things, removed) {
225
+ const left = [];
226
+ for (const thing of things) {
227
+ const path = thing.kind === "mcp" ? `/api/v3.1/mcp/${encodeURIComponent(thing.id)}` : thing.kind === "account" ? `/api/v3/connected_accounts/${encodeURIComponent(thing.id)}` : `/api/v3/auth_configs/${encodeURIComponent(thing.id)}`;
228
+ try {
229
+ await ask(`deleting ${named(thing)}`, "DELETE", path, undefined, "gone");
230
+ removed.push(named(thing, true));
231
+ }
232
+ catch (error) {
233
+ if (error instanceof ApiError && error.extra.fields?.[0]?.reason === "not_found")
234
+ removed.push(named(thing, true));
235
+ else
236
+ left.push(named(thing));
237
+ }
192
238
  }
239
+ return left;
193
240
  }
194
241
  /** JSON-RPC's "Method not found": what a Composio MCP server with none of the picked actions answers a tool listing. */
195
242
  const METHOD_NOT_FOUND = -32601;
@@ -204,19 +251,35 @@ export const composioServerId = (address) => {
204
251
  return undefined;
205
252
  }
206
253
  };
207
- /** What the answer to a delete says when the Composio MCP server could not be removed: where to remove it by hand. */
208
- export const composioNote = (name) => ({ removed: false, note: `Remove ${name} in Composio yourself: ${DASHBOARD}` });
254
+ /** A thing at Composio as the words name it; `removed`: as a removal names it (an account its connect link with it). */
255
+ 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)" : ""}`;
256
+ /** "a", "a and b", "a, b and c". */
257
+ const listed = (items) => (items.length < 2 ? items.join("") : `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`);
258
+ /** What a delete's answer says it did at Composio, in words: what it removed, what it kept and why (another saved server
259
+ * uses it, or this server didn't make it), and what is left, with where to remove that by hand. `removed`: nothing is
260
+ * left there. */
261
+ function said(name, removed, kept, left) {
262
+ const parts = [];
263
+ if (removed.length)
264
+ parts.push(`Removed in Composio: ${listed(removed)}.`);
265
+ if (kept.length)
266
+ parts.push(`${parts.length ? "Kept there" : "Kept in Composio"}: ${kept.map((thing) => `${named(thing)}, which ${thing.by ? `${thing.by} uses too` : "AgentRun didn't make"}`).join("; ")}.`);
267
+ if (left.length)
268
+ parts.push(`${parts.length ? "Left there" : "Left in Composio"}: ${listed(left)}. Remove what is left of ${name} in Composio yourself: ${DASHBOARD}`);
269
+ return { removed: left.length === 0, note: parts.join(" ") };
270
+ }
271
+ /** What the answer to a delete says when this server could not ask Composio at all (the saved key does not open here, or
272
+ * the address names no Composio server): all of it is left there, to remove by hand. `mcp`: the MCP server left, by its
273
+ * id when known (true: the one it made; false: none). `over`: a save over a server, which says what it keeps too. */
274
+ export const composioNote = (name, cleanup, mcp = true, over = false) => ({ removed: false, note: said(name, [], over ? cleanup?.kept ?? [] : [], [`${listed([...(typeof mcp === "string" ? [named({ kind: "mcp", id: mcp })] : mcp ? ["the MCP server it made"] : []), ...(cleanup?.remove ?? []).map((thing) => named(thing))])} (the saved key doesn't open here)`]).note });
209
275
  /** Deleting a preset server: the Composio MCP server `id` it made is deleted as `key` (the saved credential, held for this
210
- * call only). Composio's 404 is "already gone"; a refusal, or no answer, is `removed: false` with what to do by hand, for
211
- * the delete of our own row to go on regardless. */
212
- export async function composioForget(control, key, id, name, signal) {
213
- try {
214
- await asking(control, key, signal)("deleting the MCP server it made", "DELETE", `/api/v3.1/mcp/${encodeURIComponent(id)}`, undefined, "gone");
215
- return { removed: true };
216
- }
217
- catch (error) {
218
- if (error instanceof ApiError && error.extra.fields?.[0]?.reason === "not_found")
219
- return { removed: true };
220
- return composioNote(name);
221
- }
276
+ * call only), then what `cleanup` says this server made for it and nothing else uses (composio-made.ts: its connected
277
+ * accounts, then their auth config). Composio's 404 is "already gone"; a refusal, or no answer, leaves that one there and
278
+ * says so, for the delete of our own row to go on regardless. The answer says in words what went, what stays and why.
279
+ * A save over a server does the same with what the save before made that it left (ComposioDropped); no `id` when the
280
+ * row still names the MCP server it named. */
281
+ export async function composioForget(control, key, id, name, signal, cleanup) {
282
+ const removed = [];
283
+ const left = await removing(asking(control, key, signal, "it is still there"), [...(id ? [{ kind: "mcp", id }] : []), ...(cleanup?.remove ?? [])], removed);
284
+ return said(name, removed, cleanup?.kept ?? [], left);
222
285
  }
@@ -78,8 +78,13 @@ export declare class ComposioTriggers implements TriggerUpstream {
78
78
  * delete take its project's turn, so a create still making its first trigger is saved, and counted, before the check;
79
79
  * any other server (no Composio key) is deleted with no turn and nothing asked of Composio. */
80
80
  deleting<T>(name: string, remove: () => Promise<T>): Promise<T>;
81
- /** The triggers that use saved server `name`: a server that has any is not deleted (refused, naming them). */
82
- inUse(name: string): Promise<void>;
81
+ /** `step` in the turn of saved server `name`'s Composio project, when it is a Composio server (its key opens): a create
82
+ * still making its first trigger on it is saved, and counted, before `step` reads who uses it. Any other server's runs
83
+ * at once. A save that moves the server off what its triggers stand on checks inUse in it (server.ts saveMcpServer). */
84
+ inTurnOf<T>(name: string, step: () => Promise<T>): Promise<T>;
85
+ /** The triggers that use saved server `name`: a server that has any is not deleted, nor saved off what they stand on
86
+ * (`then`: what to do once they are gone), refused, naming them. */
87
+ inUse(name: string, then?: string): Promise<void>;
83
88
  /** `step` run once the steps queued before it for the project of key `key` are done (failed or not), and before any
84
89
  * queued after it. The key is digested, never kept as it is. */
85
90
  private serial;
@@ -237,18 +237,24 @@ export class ComposioTriggers {
237
237
  * delete take its project's turn, so a create still making its first trigger is saved, and counted, before the check;
238
238
  * any other server (no Composio key) is deleted with no turn and nothing asked of Composio. */
239
239
  async deleting(name, remove) {
240
- const credential = await this.deps.credential(name, "route").catch(() => undefined);
241
- const checked = async () => {
240
+ return this.inTurnOf(name, async () => {
242
241
  await this.inUse(name);
243
242
  return remove();
244
- };
245
- return credential ? this.serial(credential.key, checked) : checked();
243
+ });
244
+ }
245
+ /** `step` in the turn of saved server `name`'s Composio project, when it is a Composio server (its key opens): a create
246
+ * still making its first trigger on it is saved, and counted, before `step` reads who uses it. Any other server's runs
247
+ * at once. A save that moves the server off what its triggers stand on checks inUse in it (server.ts saveMcpServer). */
248
+ async inTurnOf(name, step) {
249
+ const credential = await this.deps.credential(name, "route").catch(() => undefined);
250
+ return credential ? this.serial(credential.key, step) : step();
246
251
  }
247
- /** The triggers that use saved server `name`: a server that has any is not deleted (refused, naming them). */
248
- async inUse(name) {
252
+ /** The triggers that use saved server `name`: a server that has any is not deleted, nor saved off what they stand on
253
+ * (`then`: what to do once they are gone), refused, naming them. */
254
+ async inUse(name, then = "then the server") {
249
255
  const using = (await this.deps.holders()).filter((h) => h.source.server === name);
250
256
  if (using.length)
251
- throw new ApiError("composio_in_use", `${name} has Composio triggers: ${using.map((h) => h.name).join(", ")}. Delete ${using.length > 1 ? "them" : "it"} first, then the server.`, { details: { triggers: using.map((h) => ({ id: h.id, name: h.name })) } });
257
+ throw new ApiError("composio_in_use", `${name} has Composio triggers: ${using.map((h) => h.name).join(", ")}. Delete ${using.length > 1 ? "them" : "it"} first, ${then}.`, { details: { triggers: using.map((h) => ({ id: h.id, name: h.name })) } });
252
258
  }
253
259
  // ---- its steps ---------------------------------------------------------------------------------------------------------
254
260
  /** `step` run once the steps queued before it for the project of key `key` are done (failed or not), and before any
@@ -1,14 +1,16 @@
1
1
  import type { IncomingMessage } from "node:http";
2
2
  import type { Duplex } from "node:stream";
3
- import { type AttachHub, type AttachSocket, type HelloResult } from "@parcha/agentrun-computer";
3
+ import { type AttachHub, type AttachSocket, type HelloResult, type MachineTokens } from "@parcha/agentrun-computer";
4
4
  import { type WebSocket } from "ws";
5
- import type { PairedComputerRow, PairedComputers } from "./store/index.js";
5
+ import type { MintedTokens, PairedComputerRow, PairedComputers } from "./store/index.js";
6
6
  /** The characters of a pairing code: no 0, O, 1 or I, so a person reads it off a screen without a doubt. */
7
7
  export declare const PAIRING_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
8
8
  /** A computer's token starts with this, so a secret scanner knows one. */
9
9
  export declare const ATTACH_TOKEN_PREFIX = "art_";
10
10
  /** Pair tries a source address makes in a minute; the next waits. */
11
11
  export declare const PAIR_TRIES_PER_MINUTE = 10;
12
+ /** Daemon fetches a minted machine's token makes in a minute (GET /v2/computers/daemon); the next is 429. */
13
+ export declare const DAEMON_FETCHES_PER_MINUTE = 10;
12
14
  /** The longest name a person gives a computer, in characters. */
13
15
  export declare const PAIRED_NAME_MAX = 100;
14
16
  /** What the store keeps of a secret: its SHA-256, in hex. */
@@ -21,22 +23,29 @@ export declare function pairingCodeOf(typed: unknown): string | undefined;
21
23
  export declare const newPairedId: (pick?: (below: number) => number) => string;
22
24
  /** A new computer token: ATTACH_TOKEN_PREFIX and 32 random bytes. */
23
25
  export declare const newAttachToken: () => string;
26
+ /** A new hosted machine's token: ATTACH_TOKEN_PREFIX and 32 random bytes in hex, which goes in the machine's env. */
27
+ export declare const newMintedToken: () => string;
24
28
  /** `reason` cut to what a close frame holds (123 bytes of UTF-8), never inside a character. */
25
29
  export declare function closeReason(reason: string): string;
26
- /** The pair route's limit: PAIR_TRIES_PER_MINUTE tries a minute by source address (peerKey: an IPv6 one by its /64). */
27
- export declare class PairTries {
30
+ /** A limit of `perMinute` tries a minute by key: the pair route's by source address (`keyOf` peerKey: an IPv6 one by its
31
+ * /64), the daemon route's by the minted token's machine. */
32
+ export declare class MinuteLimit {
28
33
  #private;
34
+ private readonly perMinute;
35
+ private readonly keyOf;
29
36
  private readonly now;
30
- private readonly peers;
31
- constructor(now?: () => number, peers?: number);
32
- /** Counts a try from `address`: ok, or how long until the next is let in. */
33
- allow(address: string): {
37
+ private readonly keys;
38
+ constructor(perMinute: number, keyOf?: (key: string) => string, now?: () => number, keys?: number);
39
+ /** Counts a try by `key`: ok, or how long until the next is let in. */
40
+ allow(given: string): {
34
41
  ok: true;
35
42
  } | {
36
43
  ok: false;
37
44
  retryAfterMs: number;
38
45
  };
39
46
  }
47
+ /** The pair route's limit: PAIR_TRIES_PER_MINUTE tries a minute by source address. */
48
+ export declare const pairTries: (now?: () => number, keys?: number) => MinuteLimit;
40
49
  /** POST /v2/computers/pair's body checked: its code in its one form, the name, and the driver's hello; or input_invalid
41
50
  * naming each field that is wrong. The protocol version is the caller's next check (pairRefusal), not this one's. */
42
51
  export declare function pairBodyOf(body: unknown): {
@@ -81,9 +90,10 @@ export type PairedView = {
81
90
  /** The pairing (createPairing's id) whose code paired it. */
82
91
  pairing: string;
83
92
  created_at: string;
93
+ /** Its last hello: the live socket's while it is attached (never null while online), else the last one kept. */
84
94
  seen_at: string | null;
85
95
  };
86
- export declare function pairedView(row: PairedComputerRow, hub: Pick<AttachHub, "online" | "hello" | "claimed" | "deadline">, serves: readonly string[]): PairedView;
96
+ export declare function pairedView(row: PairedComputerRow, hub: Pick<AttachHub, "online" | "since" | "hello" | "claimed" | "deadline">, serves: readonly string[]): PairedView;
87
97
  /** How the socket's liveness is timed: ATTACH_HEARTBEAT_MS and ATTACH_IDLE_MS, unless a test gives its own. */
88
98
  export type AttachTiming = {
89
99
  readonly heartbeatMs: number;
@@ -96,10 +106,15 @@ export declare function attachSocketOf(ws: WebSocket, timing?: AttachTiming): At
96
106
  export interface AttachRoutesOptions {
97
107
  readonly store: {
98
108
  readonly pairedComputers: PairedComputers;
109
+ readonly mintedTokens: MintedTokens;
99
110
  };
100
111
  readonly hub: AttachHub;
101
- /** Told each event worth a line: a computer paired, attached, refused at its hello, removed. Never a code or a token. */
112
+ /** Told each event worth a line: a computer paired, attached, refused at its hello, removed; a machine's token minted
113
+ * or revoked. Never a code or a token, nor a token's hash. */
102
114
  readonly log?: (event: string, fields: Record<string, string>) => void;
115
+ /** An API-only server's (api-only.ts): the socket takes a hosted machine's minted token alone, and a paired computer's
116
+ * (the console's) is 401 as one it does not know. */
117
+ readonly machinesOnly?: boolean;
103
118
  /** The socket's liveness timing: the protocol's unless a test gives its own. */
104
119
  readonly timing?: AttachTiming;
105
120
  readonly now?: () => number;
@@ -107,7 +122,8 @@ export interface AttachRoutesOptions {
107
122
  * watches the raw socket to see how a driver answers a close, a drop and a frame it must refuse. */
108
123
  readonly onSocket?: (computer: string, ws: WebSocket) => void;
109
124
  }
110
- /** The pairing routes and the attach socket over one store and one hub. */
125
+ /** The pairing routes, the attach socket and the daemon route over one store and one hub, and the tokens a dial
126
+ * provider mints. */
111
127
  export declare function createAttachRoutes(options: AttachRoutesOptions): {
112
128
  createPairing: () => Promise<{
113
129
  id: string;
@@ -121,5 +137,7 @@ export declare function createAttachRoutes(options: AttachRoutesOptions): {
121
137
  remove: (id: string) => Promise<void>;
122
138
  upgrade: (req: IncomingMessage, socket: Duplex, head: Buffer, deny: (status: string, words?: string, headers?: Record<string, string>) => void) => void;
123
139
  close: () => Promise<void>;
140
+ machineTokens: MachineTokens;
141
+ daemon: (authorization: string | undefined, arch: string | null) => Promise<string>;
124
142
  };
125
143
  export type AttachRoutes = ReturnType<typeof createAttachRoutes>;