@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
package/dist/mcp-oauth.js CHANGED
@@ -74,6 +74,22 @@ export const systemNetwork = {
74
74
  }
75
75
  },
76
76
  };
77
+ /** The authorization endpoints, by host, that give a refresh token only when the sign-in asks for offline access in
78
+ * their own words, and the parameters that ask: Google's, which gives one only with access_type=offline, and on a
79
+ * sign-in again only with prompt=consent. The page the owner opens there carries them (askingOffline); any other
80
+ * authorization server's is the SDK's, unchanged. */
81
+ const OFFLINE_ACCESS = { "accounts.google.com": { access_type: "offline", prompt: "consent" } };
82
+ /** `url`, the authorization page the owner opens (the discovered authorization endpoint, as the SDK builds it), with
83
+ * what its host asks for a refresh token (OFFLINE_ACCESS), each once; any other host's, as it is. */
84
+ function askingOffline(url) {
85
+ const asks = Object.hasOwn(OFFLINE_ACCESS, url.hostname) ? OFFLINE_ACCESS[url.hostname] : undefined;
86
+ if (!asks)
87
+ return url;
88
+ const out = new URL(url);
89
+ for (const [key, value] of Object.entries(asks))
90
+ out.searchParams.set(key, value);
91
+ return out;
92
+ }
77
93
  /** A request the address check refused before anything was sent (checked's words): no try again reaches it. */
78
94
  export class EndpointRefused extends Error {
79
95
  name = "EndpointRefused";
@@ -168,7 +184,7 @@ function loopbackAllowed(url, mcpUrl, own) {
168
184
  * link-local, unspecified, multicast or broadcast, never this machine's (`network.local`) nor this server's own
169
185
  * (`reach.own`). Every address its name resolves to must pass, and the one dialled is one checked. An unlisted host
170
186
  * whose private addresses the list could allow is refused in words that name it and where to allow it. */
171
- async function checked(subject, url, signal, network, reach = {}) {
187
+ async function checked(subject, url, signal, network, reach = {}, plain = false) {
172
188
  let at;
173
189
  try {
174
190
  at = new URL(url);
@@ -202,15 +218,30 @@ async function checked(subject, url, signal, network, reach = {}) {
202
218
  const own = [...(network.local ?? localAddresses)(), ...(reach.own ?? []).map((one) => URL.parse(one)?.hostname.replace(/^\[|\]$/g, "") ?? "")];
203
219
  if (!inside.every((address) => privateAllowed(address, own)))
204
220
  return { refused: `${subject} is a private address; refused` };
221
+ // Plain http is for a public address alone: a private host, allowed or not, is read over https.
222
+ if (plain && at.protocol === "http:")
223
+ return { refused: `${subject} is a private address; refused` };
205
224
  const named = hostKey(at.hostname);
206
225
  // Allowing it helps only an https endpoint: a plain-http one keeps the private-address words.
207
226
  if (!(reach.allowed ?? []).includes(named))
208
227
  return { refused: at.protocol === "https:" ? `${subject} is on a private network, refused: an owner can allow ${named} in ${PRIVATE_HOSTS_PAGE}` : `${subject} is a private address; refused` };
209
228
  }
210
- if (at.protocol !== "https:")
229
+ if (at.protocol !== "https:" && !(plain && at.protocol === "http:"))
211
230
  return { refused: `${subject} is not https; refused` };
212
231
  return { address: addresses[0] };
213
232
  }
233
+ /** Where a feed trigger's read of `url` (feed/fetch.ts readFeed, each redirect again) may go, before anything is sent:
234
+ * `checked`'s rule, an MCP server's, with plain http allowed on a public address alone (a feed is public text, and many
235
+ * are served over http; a private host the owner allows, `reach.allowed`, is read over https). A URL on loopback as
236
+ * written where `reach.loopback` allows it (a local install, as for an MCP server) on any port but this server's own:
237
+ * `address` undefined, dialled as written. A URL that isn't http(s) is refused. */
238
+ export async function feedAt(url, signal, network, reach = {}) {
239
+ if (url.protocol !== "http:" && url.protocol !== "https:")
240
+ return { refused: `the feed at ${url.href.slice(0, 200)} is not http or https; refused` };
241
+ if (reach.loopback && loopbackAllowed(url, url.href, reach.own ?? []))
242
+ return { address: undefined };
243
+ return checked(`the feed at ${url.host}`, url.href, signal, network, reach, true);
244
+ }
214
245
  /** Where a request to the MCP server at `url` may go, before anything is sent to it: the preview, the save, the tools'
215
246
  * refresh and the sign-in on this server, and each request of a run's calls on the runner. The rule is `checked`'s, the
216
247
  * one an authorization server's endpoint is held to: a public https address; a private-network one only for a host the
@@ -301,12 +332,15 @@ export class McpSignIns {
301
332
  /** Whether this server is a local install (McpServersOverStore.attach): only then may a loopback MCP server's
302
333
  * authorization server be on loopback too. */
303
334
  loopback = false;
335
+ /** A runner's registry (mcp-pin-first.ts registryListing), which listens nowhere: the own addresses of the
336
+ * local-install server beside it (Serve.own), held to as this server's own are. Set by McpServersOverStore.attach. */
337
+ beside = [];
304
338
  /** This server's own local addresses, whose ports a loopback authorization server may never name: where it listens,
305
339
  * and its public address too when that is on loopback (a local https proxy on another port, in front of the
306
- * listener, reaches this server). */
340
+ * listener, reaches this server); on a runner, the server's beside it. */
307
341
  get own() {
308
342
  const base = URL.parse(this.base);
309
- return [this.listening, ...(base && LOOPBACK.test(base.hostname) ? [this.base] : [])].filter(Boolean);
343
+ return [this.listening, ...(base && LOOPBACK.test(base.hostname) ? [this.base] : []), ...this.beside].filter(Boolean);
310
344
  }
311
345
  /** CIMD only from a public https address: an authorization server must be able to fetch the document. */
312
346
  get metadataUrl() {
@@ -442,7 +476,7 @@ export class McpSignIns {
442
476
  saveClientInformation: (client) => void (entry.client = client),
443
477
  tokens: () => undefined,
444
478
  saveTokens: (tokens) => hooks.saved?.(tokens),
445
- redirectToAuthorization: (url) => hooks.redirect?.(url),
479
+ redirectToAuthorization: (url) => hooks.redirect?.(askingOffline(url)),
446
480
  saveCodeVerifier: (verifier) => void (entry.verifier = verifier),
447
481
  codeVerifier: () => entry.verifier ?? "",
448
482
  // Checked before anything discovery found is used: registration, the page the owner opens, the code exchange.
@@ -25,12 +25,14 @@ export declare function pinFirst(revision: {
25
25
  readonly mcpPin?: unknown;
26
26
  }, deps: PinFirstDeps): Promise<McpPin | undefined>;
27
27
  /** A runner's pinListing (PinFirstDeps): the owner's registry over the one store, opened with the runner's seal key (the
28
- * server's) on the first listing it is asked for, loopback allowed only for a runner beside a local install. `githubApp`:
28
+ * server's) on the first listing it is asked for, loopback allowed only for a runner beside a local install, never to
29
+ * that server's own ports (`own`, Serve.own). `githubApp`:
29
30
  * the run's GitHub App access (runner/mcp-github.ts), which lists a `github_app` server with a token of the run's
30
31
  * repository, metadata read alone, as a save lists it with one (github-connection.ts tokenForListing); without it such a
31
32
  * server can't be listed. `appOrigin`: a test's fake GitHub MCP (McpServersOverStore.appOrigin). */
32
- export declare function registryListing(store: Parameters<typeof mcpServersOverStore>[0], sealKey: Buffer, { loopback, network, githubApp, appOrigin }?: {
33
+ export declare function registryListing(store: Parameters<typeof mcpServersOverStore>[0], sealKey: Buffer, { loopback, own, network, githubApp, appOrigin }?: {
33
34
  loopback?: boolean;
35
+ own?: readonly string[];
34
36
  network?: OAuthNetwork;
35
37
  githubApp?: GithubAppAccess;
36
38
  appOrigin?: string;
@@ -63,11 +63,12 @@ export async function pinFirst(revision, deps) {
63
63
  return ((await deps.pinOnce(revision.id, pin)) ?? undefined);
64
64
  }
65
65
  /** A runner's pinListing (PinFirstDeps): the owner's registry over the one store, opened with the runner's seal key (the
66
- * server's) on the first listing it is asked for, loopback allowed only for a runner beside a local install. `githubApp`:
66
+ * server's) on the first listing it is asked for, loopback allowed only for a runner beside a local install, never to
67
+ * that server's own ports (`own`, Serve.own). `githubApp`:
67
68
  * the run's GitHub App access (runner/mcp-github.ts), which lists a `github_app` server with a token of the run's
68
69
  * repository, metadata read alone, as a save lists it with one (github-connection.ts tokenForListing); without it such a
69
70
  * server can't be listed. `appOrigin`: a test's fake GitHub MCP (McpServersOverStore.appOrigin). */
70
- export function registryListing(store, sealKey, { loopback = false, network, githubApp, appOrigin } = {}) {
71
+ export function registryListing(store, sealKey, { loopback = false, own = [], network, githubApp, appOrigin } = {}) {
71
72
  let registry;
72
73
  // The listing tokens minted and not yet revoked, and how many listings are under way: no one holds a listing token
73
74
  // after its listing (the claim's cleanup reaches only githubTokens' tokens), so once no listing is under way, each is
@@ -77,7 +78,7 @@ export function registryListing(store, sealKey, { loopback = false, network, git
77
78
  const open = async () => {
78
79
  const { version } = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
79
80
  const opened = mcpServersOverStore(store, { [SEAL_KEY_ENV]: sealKey.toString("base64") }, version, network);
80
- opened.attach("", "", loopback);
81
+ opened.attach("", "", loopback, own);
81
82
  if (appOrigin)
82
83
  opened.appOrigin = appOrigin;
83
84
  if (githubApp)
@@ -1,6 +1,7 @@
1
1
  import { type Listed, type McpPrices, type McpTool } from "./mcp-probe.js";
2
2
  import { type SecretMeta } from "./secret-writes.js";
3
3
  import { type ClientKind, type OAuthNetwork } from "./mcp-oauth.js";
4
+ import { type Cleanup, type ComposioMade } from "./composio-made.js";
4
5
  import { type RecordedRow, type SourceRecord } from "./mcp-sources.js";
5
6
  import { type ToolSettingsMap } from "./tool-plane.js";
6
7
  import { type McpCredentialMark, type Mcp, type McpOauth, type Settings, type Store } from "./store/index.js";
@@ -17,11 +18,32 @@ type McpServersStore = {
17
18
  * `unusable` when either can't be had (a key that does not open here, an address that names no server): the delete of
18
19
  * our row still stands, and the answer says to remove it in Composio by hand. Taken from the row actually removed, never
19
20
  * a row read before it, so a server saved again under the name meanwhile is not the one deleted on Composio. */
20
- export type ComposioHandle = {
21
+ export type ComposioHandle = ({
21
22
  id: string;
22
23
  key: string;
23
24
  } | {
24
25
  unusable: true;
26
+ }) & {
27
+ cleanup?: Cleanup;
28
+ };
29
+ /** What a save over a preset server leaves to do at Composio, with the key the server was saved with before, which made
30
+ * what it left; `unusable` when that key does not open here. `mcp`: the Composio MCP server the row named before, which
31
+ * the preset made and the row names no longer (a preset save over it makes a new one; an ordinary save moves it off
32
+ * Composio). `cleanup`: what that save had made there besides that this one no longer stands on (composio-made.ts
33
+ * droppedOf; all of it, as a delete's cleanupOf, for a row moved off Composio). */
34
+ export type ComposioDropped = ({
35
+ key: string;
36
+ } | {
37
+ unusable: true;
38
+ }) & {
39
+ cleanup: Cleanup;
40
+ mcp?: string;
41
+ };
42
+ /** A preset row's save guard (McpServersOverStore.save): `turn`, the Composio turns its write and cleanup take; `inUse`,
43
+ * refused while Composio triggers use the server (composio-triggers.ts inUse). */
44
+ export type SaveGuard = {
45
+ turn: <T>(work: () => Promise<T>) => Promise<T>;
46
+ inUse: () => Promise<void>;
25
47
  };
26
48
  export declare class McpServersOverStore {
27
49
  private readonly store;
@@ -55,8 +77,12 @@ export declare class McpServersOverStore {
55
77
  /** This server's address as a browser reaches it and where it listens (McpServers.attach). `local`: whether its
56
78
  * operator said this is a local install (ServeOptions.mcpLoopback, the CLI's AGENTRUN_MCP_ALLOW_LOOPBACK=1), the one kind
57
79
  * of server an MCP server's URL may be on loopback for. Never inferred from where it listens: a hosted container
58
- * listens on loopback behind its proxy too. Omitted, or never attached, it is not one. */
59
- attach(base: string, listening: string, local?: boolean): void;
80
+ * listens on loopback behind its proxy too. Omitted, or never attached, it is not one. `beside`: a runner's registry
81
+ * (registryListing), attached at no address of its own, is held to the own addresses of the server beside it. */
82
+ attach(base: string, listening: string, local?: boolean, beside?: readonly string[]): void;
83
+ /** This server's own addresses (McpSignIns.own): where it listens, and its public address when that is on loopback. A
84
+ * read on loopback, here or by the runner beside it (Serve.own), never goes to their ports. */
85
+ get own(): readonly string[];
60
86
  clientDocument(): {
61
87
  redirect_uris: string[];
62
88
  token_endpoint_auth_method?: string | undefined;
@@ -79,6 +105,18 @@ export declare class McpServersOverStore {
79
105
  };
80
106
  /** The origin the authorization server sends the browser back to. */
81
107
  get callbackOrigin(): string;
108
+ /** Where a server-side read of a URL may go (a feed's, a calendar's), as an MCP server's requests may: this server's
109
+ * network, its own addresses (never read), the private-network hosts the owner allows (read now, at each call), loopback
110
+ * only on a local install, and stopped with the server. */
111
+ outboundReach(): Promise<{
112
+ network: OAuthNetwork;
113
+ reach: {
114
+ own: readonly string[];
115
+ allowed: readonly string[];
116
+ loopback: boolean;
117
+ };
118
+ signal: AbortSignal;
119
+ }>;
82
120
  /** The server's own tool settings, set as the server starts. */
83
121
  toolSettings: () => ToolSettingsMap;
84
122
  close(boundMs?: number): Promise<void>;
@@ -195,8 +233,15 @@ export declare class McpServersOverStore {
195
233
  private signInNoted;
196
234
  /** PUT: preview, then keep the server with the tools listed. A body with no credential keeps the sealed one, while the
197
235
  * auth type and the URL's origin stay the same. `made`: what made the server, when that is the Composio preset (its
198
- * source and toolkit, recorded as they are). */
199
- save(name: string, body: Record<string, unknown>, stop?: AbortSignal, checkedAgainst?: McpCredentialMark, made?: SourceRecord): Promise<{
236
+ * source and toolkit, recorded as they are), and `stands`, what it stands on at Composio (composio-made.ts), recorded
237
+ * for its delete. `dropped` is told what a save over a preset server leaves to do there, once the row is written: the
238
+ * MCP server the save before made, when the row names it no longer, and what else that save made that this one no
239
+ * longer stands on (all of it, for an ordinary save that moves the row off Composio, as a delete), which another saved
240
+ * server's record now owns or the caller removes. `guard`, a preset row's: the turn its write and cleanup take, once
241
+ * the listing is done (never across it), and the check of the triggers that use it, made in that turn before a write
242
+ * that leaves what they stand on (an ordinary save moving the row off Composio, a preset save as another user or auth
243
+ * config): refused, nothing written. */
244
+ save(name: string, body: Record<string, unknown>, stop?: AbortSignal, checkedAgainst?: McpCredentialMark, made?: SourceRecord, stands?: ComposioMade, dropped?: (left: ComposioDropped) => void, guard?: SaveGuard): Promise<{
200
245
  listed_at: string;
201
246
  updated_at: string;
202
247
  secret: SecretMeta;
@@ -294,6 +339,14 @@ export declare class McpServersOverStore {
294
339
  remove(name: string, checkedAgainst?: McpCredentialMark): Promise<{
295
340
  composio?: ComposioHandle;
296
341
  }>;
342
+ /** Whether `name` is a Composio preset server now (auth headers, source composio): a save of it takes the Composio turn,
343
+ * since one that moves it off Composio removes there what the preset made for it. */
344
+ composioPreset(name: string): Promise<boolean>;
345
+ /** Writes each record a cleanup passes a thing to (composio-made.ts `handover`), for its own row of `others`. */
346
+ private handOver;
347
+ /** The saved servers' records of what they stand on at Composio (composio-made.ts), each read for its own row: name,
348
+ * record and the row's created_at. */
349
+ private composioRecords;
297
350
  /** POST .../{name}/oauth/start: `{url, scopes?, client_id?, client_secret?, toolkit?}`; answers the URL the owner opens.
298
351
  * Its toolkit, as a save's, is written for the server the sign-in saves. */
299
352
  oauthStart(name: string, body: Record<string, unknown>): Promise<{
@@ -15,6 +15,7 @@ import { checkPrivateHosts, privateOAuthHosts, savePrivateOAuthHosts } from "./m
15
15
  import { credentialMark } from "./mcp-secret-writes.js";
16
16
  import { secretMeta, secretName } from "./secret-writes.js";
17
17
  import { dialAt, issuerOf, LOOPBACK, MAX_PENDING, MCP_SETTINGS_PAGE, mcpServerAt, McpSignIns, reasonOf, SIGN_IN_AGAIN, systemNetwork } from "./mcp-oauth.js";
18
+ import { cleanupOf, composioMadeKey, droppedOf, madeToWrite, recordedMade, storedMade } from "./composio-made.js";
18
19
  import { COMPOSIO_USER, composioServerId } from "./composio-preset.js";
19
20
  import { mcpSourceKey, recordedForAnother, sourceOf, sourceToWrite, standInGiven, storedSource, toolkitGiven } from "./mcp-sources.js";
20
21
  import { SEAL_KEY_ENV, sealKeyOf } from "./tool-keys.js";
@@ -39,12 +40,15 @@ function changedMeanwhile(name, saved) {
39
40
  throw new ApiError("precondition_failed", `The MCP server ${name}'s credential changed while this save ran (another save, a sign-in or a removal): read it again, then save again.`);
40
41
  return saved;
41
42
  }
42
- function composioHandleOf(removed) {
43
+ function composioHandleOf(removed, cleanup) {
43
44
  const id = removed ? composioServerId(removed.url) : undefined;
44
- const open = removed?.opened;
45
+ const key = composioKeyOf(removed?.opened);
46
+ return { ...(id && key ? { id, key } : { unusable: true }), ...(cleanup ? { cleanup } : {}) };
47
+ }
48
+ /** The Composio key a preset row's opened credential holds (its x-api-key header); none when it does not open. */
49
+ function composioKeyOf(open) {
45
50
  const headers = open && "credential" in open && open.credential.type === "headers" ? open.credential.headers : undefined;
46
- const key = headers ? Object.entries(headers).find(([header]) => header.toLowerCase() === "x-api-key")?.[1] : undefined;
47
- return id && key ? { id, key } : { unusable: true };
51
+ return headers ? Object.entries(headers).find(([header]) => header.toLowerCase() === "x-api-key")?.[1] : undefined;
48
52
  }
49
53
  /** The sign-ins in flight over the store (store.mcpOauth): the sign-in's secret parts (the PKCE verifier and the OAuth
50
54
  * client, with its secret) sealed together by its state, the rest of its working state plain JSON the callback rebuilds.
@@ -121,13 +125,20 @@ export class McpServersOverStore {
121
125
  /** This server's address as a browser reaches it and where it listens (McpServers.attach). `local`: whether its
122
126
  * operator said this is a local install (ServeOptions.mcpLoopback, the CLI's AGENTRUN_MCP_ALLOW_LOOPBACK=1), the one kind
123
127
  * of server an MCP server's URL may be on loopback for. Never inferred from where it listens: a hosted container
124
- * listens on loopback behind its proxy too. Omitted, or never attached, it is not one. */
125
- attach(base, listening, local) {
128
+ * listens on loopback behind its proxy too. Omitted, or never attached, it is not one. `beside`: a runner's registry
129
+ * (registryListing), attached at no address of its own, is held to the own addresses of the server beside it. */
130
+ attach(base, listening, local, beside = []) {
126
131
  this.signIns.base = base.replace(/\/+$/, "");
127
132
  this.signIns.listening = listening.replace(/\/+$/, "");
133
+ this.signIns.beside = [...beside];
128
134
  this.loopback = local === true;
129
135
  this.signIns.loopback = this.loopback;
130
136
  }
137
+ /** This server's own addresses (McpSignIns.own): where it listens, and its public address when that is on loopback. A
138
+ * read on loopback, here or by the runner beside it (Serve.own), never goes to their ports. */
139
+ get own() {
140
+ return this.signIns.own;
141
+ }
131
142
  clientDocument() {
132
143
  return this.signIns.clientDocument();
133
144
  }
@@ -135,6 +146,12 @@ export class McpServersOverStore {
135
146
  get callbackOrigin() {
136
147
  return new URL(this.signIns.base).origin;
137
148
  }
149
+ /** Where a server-side read of a URL may go (a feed's, a calendar's), as an MCP server's requests may: this server's
150
+ * network, its own addresses (never read), the private-network hosts the owner allows (read now, at each call), loopback
151
+ * only on a local install, and stopped with the server. */
152
+ async outboundReach() {
153
+ return { network: this.network, reach: { own: this.signIns.own, allowed: await privateOAuthHosts(this.store), loopback: this.loopback }, signal: this.stopped.signal };
154
+ }
138
155
  /** The server's own tool settings, set as the server starts. */
139
156
  toolSettings = () => ({});
140
157
  async close(boundMs = 2_000) {
@@ -232,8 +249,15 @@ export class McpServersOverStore {
232
249
  }
233
250
  /** PUT: preview, then keep the server with the tools listed. A body with no credential keeps the sealed one, while the
234
251
  * auth type and the URL's origin stay the same. `made`: what made the server, when that is the Composio preset (its
235
- * source and toolkit, recorded as they are). */
236
- async save(name, body, stop, checkedAgainst, made) {
252
+ * source and toolkit, recorded as they are), and `stands`, what it stands on at Composio (composio-made.ts), recorded
253
+ * for its delete. `dropped` is told what a save over a preset server leaves to do there, once the row is written: the
254
+ * MCP server the save before made, when the row names it no longer, and what else that save made that this one no
255
+ * longer stands on (all of it, for an ordinary save that moves the row off Composio, as a delete), which another saved
256
+ * server's record now owns or the caller removes. `guard`, a preset row's: the turn its write and cleanup take, once
257
+ * the listing is done (never across it), and the check of the triggers that use it, made in that turn before a write
258
+ * that leaves what they stand on (an ordinary save moving the row off Composio, a preset save as another user or auth
259
+ * config): refused, nothing written. */
260
+ async save(name, body, stop, checkedAgainst, made, stands, dropped, guard) {
237
261
  nameOf(name);
238
262
  const was = await this.store.mcp.server(name);
239
263
  // Its URL as every read shows it (shownUrl), sent back unchanged: the saved one.
@@ -242,6 +266,8 @@ export class McpServersOverStore {
242
266
  // is now, checked before anything is listed; written once the server is, for the row it wrote.
243
267
  const sourceIssues = [];
244
268
  const wasSource = await this.sourceOf({ name, auth: auth.type, createdAt: was?.createdAt });
269
+ // Whether the row was a Composio preset server (auth headers, source composio), read before this save writes its own.
270
+ const wasPreset = was !== undefined && was.auth === "headers" && (await this.sourceOf(was)).source === "composio";
245
271
  // An ordinary save that moves a Composio preset row to another address makes it another service's server: it stops being
246
272
  // Composio's, whatever its path looks like, so its delete never sends the key it holds to Composio. It is url's, with the
247
273
  // toolkit the same save names, else none.
@@ -301,14 +327,70 @@ export class McpServersOverStore {
301
327
  ...(priced && Object.keys(priced).length ? { prices: priced } : {}),
302
328
  };
303
329
  };
304
- const saved = keeping
305
- // Re-applied only onto a row that still holds a credential of this auth type at this origin: never onto another one's.
306
- // It writes no credential column, so it never drops or replaces one.
307
- ? await this.rewriteKeeping(name, was, fields, "save", (fresh) => fresh.auth === auth.type && fresh.sealed !== null && new URL(fresh.url).origin === url.origin)
308
- // A new credential, or none: written only while the row's credential is still `against`, in the store's one statement.
309
- : changedMeanwhile(name, await saveMcpServerIfCredential(this.store, this.sealKey, { ...fields(was), ...(credential ? { credential } : {}) }, against, { githubMcpOrigin: this.appOrigin }));
310
- if (source)
311
- await this.store.settings.put(mcpSourceKey(name), storedSource(source, saved, !made && source === standIn));
330
+ // From here, in the guard's turn (a preset row's): what it stood on read, the triggers checked, the row written, and
331
+ // what it leaves at Composio counted.
332
+ const write = async () => {
333
+ if (guard && wasPreset) {
334
+ const stood = recordedMade(await this.store.settings.get(composioMadeKey(name)), was.createdAt);
335
+ if (moved || (made && stands && (!stood || stood.user !== stands.user || (stood.auth_config?.id ?? null) !== (stands.auth_config?.id ?? null))))
336
+ await guard.inUse();
337
+ }
338
+ const saved = keeping
339
+ // Re-applied only onto a row that still holds a credential of this auth type, at the address this save read: never
340
+ // onto another one's, nor over a row another save moved meanwhile (a Composio save over it, whose cleanup removed the
341
+ // MCP server at the address read; Composio's share an origin). It writes no credential column, so it never drops or
342
+ // replaces one.
343
+ ? await this.rewriteKeeping(name, was, fields, "save", (fresh) => fresh.auth === auth.type && fresh.sealed !== null && fresh.url === was.url)
344
+ // A new credential, or none: written only while the row's credential is still `against`, in the store's one statement.
345
+ : changedMeanwhile(name, await saveMcpServerIfCredential(this.store, this.sealKey, { ...fields(was), ...(credential ? { credential } : {}) }, against, { githubMcpOrigin: this.appOrigin }));
346
+ if (source)
347
+ await this.store.settings.put(mcpSourceKey(name), storedSource(source, saved, !made && source === standIn));
348
+ // The Composio MCP server the row named before, when the preset made it (the row was a preset server) and the row names
349
+ // it no longer: a preset save over it made a new one, or an ordinary save moved the row off Composio.
350
+ const madeBefore = wasPreset && (made || moved) ? composioServerId(was.url) : undefined;
351
+ const leftMcp = madeBefore !== undefined && madeBefore !== composioServerId(url.href) ? madeBefore : undefined;
352
+ let left;
353
+ // What it stands on at Composio: what the preset found and made, over what the server saved before over this row had
354
+ // made. A row moved off Composio stands on nothing there: its delete removes nothing at Composio.
355
+ if (made && stands) {
356
+ const others = (await this.composioRecords()).filter(([other]) => other !== name);
357
+ const before = was ? recordedMade(await this.store.settings.get(composioMadeKey(name)), was.createdAt) : undefined;
358
+ const record = madeToWrite(stands, before, others.map(([, other]) => other));
359
+ await this.store.settings.put(composioMadeKey(name), storedMade(record, saved));
360
+ // What the save before made that this one no longer stands on: another saved server's now (its record rewritten to
361
+ // own it), or the caller's to remove at Composio, with the key it was made with.
362
+ if (was && before) {
363
+ const done = droppedOf(before, record, others.map(([other, mine]) => [other, mine]));
364
+ await this.handOver(others, done.handover);
365
+ left = done.cleanup;
366
+ }
367
+ }
368
+ else if (moved) {
369
+ // Moved off Composio: what its save made there goes as a delete's does (cleanupOf), the MCP server first, unless the
370
+ // new address names the same Composio MCP server, which still stands on it.
371
+ const before = recordedMade(await this.store.settings.get(composioMadeKey(name)), was.createdAt);
372
+ await this.store.settings.remove(composioMadeKey(name));
373
+ // Only for a caller in the Composio turn (`dropped`, with its `guard`), so no preset save still at Composio is counted out.
374
+ if (before && leftMcp && dropped) {
375
+ const others = (await this.composioRecords()).filter(([other]) => other !== name);
376
+ const done = cleanupOf(before, others.map(([other, record]) => [other, record]));
377
+ await this.handOver(others, done.handover);
378
+ left = done.cleanup;
379
+ }
380
+ }
381
+ if (was && (leftMcp || left?.remove.length || left?.kept.length)) {
382
+ let key;
383
+ try {
384
+ key = composioKeyOf(openMcpRow(this.sealKey, was));
385
+ }
386
+ catch {
387
+ key = undefined;
388
+ }
389
+ dropped?.({ ...(key ? { key } : { unusable: true }), cleanup: left ?? { remove: [], kept: [] }, ...(leftMcp ? { mcp: leftMcp } : {}) });
390
+ }
391
+ return saved;
392
+ };
393
+ const saved = guard ? await guard.turn(write) : await write();
312
394
  await this.store.flush();
313
395
  return this.view(saved);
314
396
  }
@@ -350,6 +432,9 @@ export class McpServersOverStore {
350
432
  const fresh = await this.store.mcp.server(name);
351
433
  if (!fresh)
352
434
  throw notFound(name);
435
+ // A save over a row changed meanwhile is the owner's to redo, read again: never retried as it stands.
436
+ if (!still(fresh) && doing === "save")
437
+ changedMeanwhile(name, undefined);
353
438
  if (!still(fresh))
354
439
  throw new ApiError("unavailable", `The MCP server ${name} was changed while this ${doing} was made; nothing was saved. Read it again and try again.`);
355
440
  if (tries >= REWRITE_TRIES)
@@ -366,6 +451,8 @@ export class McpServersOverStore {
366
451
  const row = await this.need(name);
367
452
  // Whether it is a Composio preset server: from its record (source composio), read before the row goes.
368
453
  const preset = row.auth === "headers" && (await this.sourceOf(row)).source === "composio";
454
+ // What it stands on at Composio, as its save recorded it (none: saved before that was recorded, or not a preset).
455
+ const stands = preset ? recordedMade(await this.store.settings.get(composioMadeKey(name)), row.createdAt) : undefined;
369
456
  // The credential revoked is the one the deleting statement saw (RETURNING): a run's refresh landing before it is in it,
370
457
  // one landing after finds no row to keep. A sign-in kept as expired has no refresh token left to revoke.
371
458
  const removed = checkedAgainst === undefined ? await removeMcpServer(this.store, this.sealKey, name)
@@ -376,12 +463,44 @@ export class McpServersOverStore {
376
463
  // never read for another row (mcp-sources.ts), so a server saved again says what it is afresh.
377
464
  if (!recordedForAnother(await this.store.settings.get(mcpSourceKey(name)), row.createdAt))
378
465
  await this.store.settings.remove(mcpSourceKey(name));
466
+ // What it made at Composio that another saved server uses stays, that one's now (its record rewritten to own it); the
467
+ // rest the delete route removes there.
468
+ let cleanup;
469
+ if (stands) {
470
+ if (!recordedForAnother(await this.store.settings.get(composioMadeKey(name)), row.createdAt))
471
+ await this.store.settings.remove(composioMadeKey(name));
472
+ const others = (await this.composioRecords()).filter(([other]) => other !== name);
473
+ const done = cleanupOf(stands, others.map(([other, record]) => [other, record]));
474
+ await this.handOver(others, done.handover);
475
+ cleanup = done.cleanup;
476
+ }
379
477
  await this.store.flush();
380
478
  const open = removed?.opened;
381
479
  const credential = open && "credential" in open && open.credential.type === "oauth" && !open.credential.expired ? open.credential : undefined;
382
480
  if (credential && removed)
383
481
  void this.track(this.signIns.revoke(credential.set, removed.url, this.stopped.signal));
384
- return preset ? { composio: composioHandleOf(removed) } : {};
482
+ return preset ? { composio: composioHandleOf(removed, cleanup) } : {};
483
+ }
484
+ /** Whether `name` is a Composio preset server now (auth headers, source composio): a save of it takes the Composio turn,
485
+ * since one that moves it off Composio removes there what the preset made for it. */
486
+ async composioPreset(name) {
487
+ const row = await this.store.mcp.server(name);
488
+ return row !== undefined && row.auth === "headers" && (await this.sourceOf(row)).source === "composio";
489
+ }
490
+ /** Writes each record a cleanup passes a thing to (composio-made.ts `handover`), for its own row of `others`. */
491
+ async handOver(others, handover) {
492
+ for (const [other, record] of handover) {
493
+ const of = others.find(([n]) => n === other)?.[2];
494
+ if (of !== undefined)
495
+ await this.store.settings.put(composioMadeKey(other), storedMade(record, { createdAt: of }));
496
+ }
497
+ }
498
+ /** The saved servers' records of what they stand on at Composio (composio-made.ts), each read for its own row: name,
499
+ * record and the row's created_at. */
500
+ async composioRecords() {
501
+ const rows = await listMcpServers(this.store);
502
+ const read = await Promise.all(rows.map(async (row) => [row.name, recordedMade(await this.store.settings.get(composioMadeKey(row.name)), row.createdAt), row.createdAt]));
503
+ return read.filter((entry) => entry[1] !== undefined).map(([name, record, at]) => [name, record, at]);
385
504
  }
386
505
  /** POST .../{name}/oauth/start: `{url, scopes?, client_id?, client_secret?, toolkit?}`; answers the URL the owner opens.
387
506
  * Its toolkit, as a save's, is written for the server the sign-in saves. */
package/dist/mcp.d.ts CHANGED
@@ -41,10 +41,10 @@ export declare const TOOLS: Tool[];
41
41
  /** GET /llms.txt: what this server is, for a coding agent, without a credential. The text is the repository's
42
42
  * `src/llms.txt`, copied beside the server by the build; it holds no data of this server's. */
43
43
  export declare function answerLlms(req: IncomingMessage, res: ServerResponse): Promise<void>;
44
- /** The endpoint: `route` serves each tool, `authorized` checks an Authorization header against the token. */
44
+ /** The endpoint: `route` serves each tool, `authorized` checks an Authorization header against the server's tokens (and keeps which one opened `req`). */
45
45
  export declare function mcpEndpoint({ route, authorized, authFailed, version }: {
46
46
  route: Route;
47
- authorized: (header: string) => boolean;
47
+ authorized: (header: string, req: IncomingMessage) => boolean;
48
48
  authFailed: (route: string, reason: string) => void;
49
49
  version: string;
50
50
  }): (req: IncomingMessage, res: ServerResponse) => Promise<void>;
package/dist/mcp.js CHANGED
@@ -265,7 +265,7 @@ export async function answerLlms(req, res) {
265
265
  res.writeHead(200, { "content-type": "text/plain; charset=utf-8", "content-length": String(body.length), "cache-control": "no-cache", "x-content-type-options": "nosniff" });
266
266
  res.end(req.method === "HEAD" ? undefined : body);
267
267
  }
268
- /** The endpoint: `route` serves each tool, `authorized` checks an Authorization header against the token. */
268
+ /** The endpoint: `route` serves each tool, `authorized` checks an Authorization header against the server's tokens (and keeps which one opened `req`). */
269
269
  export function mcpEndpoint({ route, authorized, authFailed, version }) {
270
270
  function reply(res, status, body, headers = {}) {
271
271
  res.writeHead(status, { ...(body === undefined ? {} : { "content-type": "application/json" }), "cache-control": "no-store", "x-content-type-options": "nosniff", ...headers });
@@ -349,7 +349,7 @@ export function mcpEndpoint({ route, authorized, authFailed, version }) {
349
349
  return reply(res, 403, rpcError(null, -32600, "this Origin may not call this server's MCP endpoint"));
350
350
  // The token only: the page's session cookie is not taken here (server.ts answers this path before the page).
351
351
  const authorization = req.headers.authorization;
352
- if (authorization === undefined || !authorized(authorization)) {
352
+ if (authorization === undefined || !authorized(authorization, req)) {
353
353
  authFailed(MCP_PATH, authorization === undefined ? "no_credential" : "wrong_token");
354
354
  return reply(res, 401, rpcError(null, -32001, "the MCP endpoint needs Authorization: Bearer <the token in the data directory>"), { "www-authenticate": "Bearer" });
355
355
  }
@@ -1,4 +1,7 @@
1
1
  import type { IncomingMessage, ServerResponse } from "node:http";
2
2
  import { Observations } from "./observer.js";
3
3
  export declare function isObservationRoute(path: string): boolean;
4
- export declare function observationHttp(req: IncomingMessage, res: ServerResponse, url: URL, observer: Observations, ownerToken: string): Promise<void>;
4
+ export declare function observationHttp(req: IncomingMessage, res: ServerResponse, url: URL, observer: Observations,
5
+ /** Whether the Authorization header holds one of the server's API tokens (api-token.ts bearerCheck: every entry
6
+ * compared in constant time). */
7
+ authorized: (header: string | undefined) => boolean): Promise<void>;
@@ -1,9 +1,7 @@
1
1
  /** Compatibility routes for the existing source-side CLI. Only bearer auth; browser cookies confer no authority. */
2
- import { createHash, timingSafeEqual } from "node:crypto";
3
2
  import { gunzipSync } from "node:zlib";
4
3
  import { MAX_OTLP_PAYLOAD_BYTES, observationCapabilities, ObservationError, } from "./observer.js";
5
4
  const PREFIX = "/api/v2/control";
6
- const digest = (v) => createHash("sha256").update(v).digest();
7
5
  const send = (res, status, body, headers = {}) => {
8
6
  res.writeHead(status, {
9
7
  "content-type": "application/json",
@@ -52,7 +50,10 @@ async function read(req, maxBytes = 65536) {
52
50
  export function isObservationRoute(path) {
53
51
  return path === PREFIX || path.startsWith(PREFIX + "/");
54
52
  }
55
- export async function observationHttp(req, res, url, observer, ownerToken) {
53
+ export async function observationHttp(req, res, url, observer,
54
+ /** Whether the Authorization header holds one of the server's API tokens (api-token.ts bearerCheck: every entry
55
+ * compared in constant time). */
56
+ authorized) {
56
57
  try {
57
58
  const path = url.pathname.slice(PREFIX.length), method = req.method ?? "GET";
58
59
  const credential = String(req.headers.authorization ?? "").replace(/^Bearer /, "");
@@ -72,7 +73,7 @@ export async function observationHttp(req, res, url, observer, ownerToken) {
72
73
  : await observer.otlp(id, credential, body, Number(req.headers["x-agentrun-selections-revision"]));
73
74
  return send(res, 200, result);
74
75
  }
75
- if (!timingSafeEqual(digest(String(req.headers.authorization ?? "")), digest("Bearer " + ownerToken)))
76
+ if (!authorized(req.headers.authorization))
76
77
  throw new ObservationError(401, "connector_unauthorized");
77
78
  const workspace = url.searchParams.get("workspace_id");
78
79
  if (workspace !== null && workspace !== "local")