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

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 (66) hide show
  1. package/CHANGELOG.md +29 -2
  2. package/README.md +82 -13
  3. package/dist/agent-package.js +1 -1
  4. package/dist/agent-rows.d.ts +1 -1
  5. package/dist/agents-store.js +1 -1
  6. package/dist/api-only.d.ts +1 -2
  7. package/dist/api-only.js +1 -2
  8. package/dist/cli.js +6 -1
  9. package/dist/composio-preset.d.ts +3 -2
  10. package/dist/composio-preset.js +4 -3
  11. package/dist/computer-needs.d.ts +1 -1
  12. package/dist/computer-needs.js +1 -1
  13. package/dist/computer-setting.d.ts +4 -2
  14. package/dist/computers.d.ts +0 -2
  15. package/dist/computers.js +1 -1
  16. package/dist/console/assets/index-B_85An2t.js +745 -0
  17. package/dist/console/assets/index-n1YsbnYh.css +1 -0
  18. package/dist/console/index.html +2 -2
  19. package/dist/errors.d.ts +4 -0
  20. package/dist/errors.js +7 -0
  21. package/dist/github-connection.d.ts +50 -1
  22. package/dist/github-connection.js +96 -3
  23. package/dist/github-faux.d.ts +11 -2
  24. package/dist/github-faux.js +138 -7
  25. package/dist/github-pull-request.d.ts +37 -0
  26. package/dist/github-pull-request.js +110 -0
  27. package/dist/live-reach.d.ts +34 -7
  28. package/dist/live-reach.js +76 -11
  29. package/dist/mcp-probe.js +2 -2
  30. package/dist/openapi.js +108 -4
  31. package/dist/runner/adapter-run-spec.js +1 -1
  32. package/dist/runner/cli-run-spec.js +1 -1
  33. package/dist/runner/metrics.d.ts +4 -2
  34. package/dist/runner/metrics.js +15 -3
  35. package/dist/runner/pr-checkout.d.ts +21 -4
  36. package/dist/runner/pr-checkout.js +103 -4
  37. package/dist/runner/run-child-host.js +7 -4
  38. package/dist/runner/runner-check.d.ts +3 -0
  39. package/dist/runner/runner-check.js +23 -0
  40. package/dist/server.d.ts +11 -0
  41. package/dist/server.js +80 -10
  42. package/dist/store/agent-body.d.ts +2 -2
  43. package/dist/store/agent-body.js +2 -2
  44. package/dist/suggestions.d.ts +282 -0
  45. package/dist/suggestions.js +919 -0
  46. package/dist/telemetry.d.ts +8 -1
  47. package/dist/telemetry.js +12 -4
  48. package/dist/template-import.d.ts +17 -0
  49. package/dist/template-import.js +32 -0
  50. package/dist/templates.d.ts +78 -73
  51. package/dist/templates.js +10 -8
  52. package/dist/trigger-launch-hook.d.ts +5 -3
  53. package/dist/trigger-launch-hook.js +5 -4
  54. package/dist/triggers.js +1 -1
  55. package/dist/validate.d.ts +1 -1
  56. package/dist/validate.js +2 -2
  57. package/dist/workspace/synced-folder.d.ts +1 -1
  58. package/dist/workspace/synced-folder.js +11 -14
  59. package/launcher/agentrun-serve +1 -1
  60. package/package.json +10 -10
  61. package/templates/README.md +3 -2
  62. package/templates/agent-scout/agent.md +46 -0
  63. package/templates/agent-scout/skills/scout/SKILL.md +88 -0
  64. package/templates/agent-scout/skills/scout/suggestions.schema.json +112 -0
  65. package/dist/console/assets/index-BFgyZzF_.js +0 -734
  66. package/dist/console/assets/index-DbilxljH.css +0 -1
@@ -3,20 +3,70 @@
3
3
  // signed delivery fired) run in a real browser with nothing sent to GitHub. It answers the API calls the server makes of
4
4
  // the App (github.ts, github-connection.ts): the App's installations, one installation's read, an installation token's
5
5
  // mint narrowed to the repositories asked, that token's read of the repositories it covers and its revoke, and which
6
- // installation covers a repository. The App, its private key and its webhook secret are made fresh at each start; a test
7
- // signs a delivery with the webhook secret, kept beside the data (FAUX_GITHUB_FILE). Never on a server without --faux.
8
- import { generateKeyPairSync, randomBytes } from "node:crypto";
6
+ // installation covers a repository. And what a suggested agent's create writes (suggestions.ts, github-pull-request.ts):
7
+ // a repository's read, its default branch's head, which files it has, a tree, a commit, a branch and a pull request,
8
+ // each kept in memory and read back whole at GET /_faux/state, where a test or a person sees what a create pushed. The
9
+ // installation holds contents write, as an App connected with `contents: write` does; POST /_faux/permissions sets what
10
+ // it holds, so a test (or a demo) shows a create refused for a permission. The App, its private key and its webhook
11
+ // secret are made fresh at each start; a test signs a delivery with the webhook secret, kept beside the data
12
+ // (FAUX_GITHUB_FILE). Never on a server without --faux.
13
+ import { execFileSync } from "node:child_process";
14
+ import { createHash, generateKeyPairSync, randomBytes } from "node:crypto";
15
+ import { mkdirSync, rmSync, writeFileSync } from "node:fs";
16
+ import { dirname, join } from "node:path";
9
17
  import { createServer } from "node:http";
10
18
  /** The file beside the data that tells a test the fake App's webhook secret, installation and repositories. */
11
19
  export const FAUX_GITHUB_FILE = "faux-github.json";
12
20
  /** The fake App's one installation and the repositories it covers. */
13
21
  export const FAUX_GITHUB = { appId: "1", slug: "agentrun-faux", installation: 1, account: "faux-org", repositories: ["faux-org/demo"] };
14
22
  const TOKEN_MS = 60 * 60_000;
15
- /** Starts the fake GitHub API on loopback, with its App. */
16
- export async function startFauxGitHub() {
23
+ /** The fake repository's files on its default branch: what its contents API answers, and what its bare repository holds
24
+ * (a small help desk whose support queue and refunds a person works by hand, for a scan to find). */
25
+ export const FAUX_REPO_FILES = {
26
+ "README.md": "# Demo shop\n\nA help desk and billing app for small shops.\n",
27
+ "package.json": `${JSON.stringify({ name: "demo-shop", private: true, type: "module" }, null, 2)}\n`,
28
+ "src/support/inbox.ts": `${Array.from({ length: 41 }, (_, i) => `// inbox line ${i + 1}`).join("\n")}\nexport const saved = (ticket: { subject: string; body: string }) => ({ ...ticket, status: "needs_triage" }); // a person sets category and priority\n`,
29
+ "src/support/classify.ts": "// Keyword rules for a ticket's category.\nexport function classify(text: string): string {\n if (/refund|invoice/i.test(text)) return \"billing\";\n return \"other\";\n}\n",
30
+ "app/refunds.py": "def request_refund(refund):\n refund.status = 'pending_review' # someone in ops reads it\n return refund\n",
31
+ };
32
+ /** The fake repository as a bare git repository under `dir` (<dir>/<owner>/<name>.git), one commit on main: what a run's
33
+ * checkout fetches with `web` set to file://<dir>. Undefined, with the folder left empty, where git does not run. */
34
+ function bareRepository(dir) {
35
+ const env = { PATH: process.env.PATH ?? "", HOME: dir, GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null", GIT_AUTHOR_NAME: "faux", GIT_AUTHOR_EMAIL: "faux@example.invalid", GIT_COMMITTER_NAME: "faux", GIT_COMMITTER_EMAIL: "faux@example.invalid" };
36
+ const work = join(dir, ".work");
37
+ try {
38
+ rmSync(dir, { recursive: true, force: true });
39
+ for (const [path, text] of Object.entries(FAUX_REPO_FILES)) {
40
+ mkdirSync(dirname(join(work, path)), { recursive: true });
41
+ writeFileSync(join(work, path), text);
42
+ }
43
+ const git = (cwd, ...args) => execFileSync("git", args, { cwd, env, stdio: "ignore" });
44
+ git(work, "init", "-q", "-b", "main");
45
+ git(work, "add", "-A");
46
+ git(work, "commit", "-q", "-m", "The demo shop");
47
+ const bare = join(dir, `${FAUX_GITHUB.repositories[0]}.git`);
48
+ mkdirSync(dirname(bare), { recursive: true });
49
+ git(dir, "clone", "-q", "--bare", work, bare);
50
+ return `file://${dir}`;
51
+ }
52
+ catch {
53
+ return undefined;
54
+ }
55
+ finally {
56
+ rmSync(work, { recursive: true, force: true });
57
+ }
58
+ }
59
+ /** Starts the fake GitHub API on loopback, with its App; with `webDir`, its repository as a bare git repository there. */
60
+ export async function startFauxGitHub({ webDir } = {}) {
61
+ const web = webDir ? bareRepository(webDir) : undefined;
17
62
  const { privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048, privateKeyEncoding: { type: "pkcs1", format: "pem" }, publicKeyEncoding: { type: "spki", format: "pem" } });
18
63
  const app = { id: FAUX_GITHUB.appId, slug: FAUX_GITHUB.slug, clientId: `Iv1.faux${randomBytes(6).toString("hex")}`, pem: privateKey, webhookSecret: randomBytes(24).toString("hex"), settingsUrl: `https://github.com/organizations/${FAUX_GITHUB.account}/settings/apps/${FAUX_GITHUB.slug}` };
19
- const installation = { id: FAUX_GITHUB.installation, account: { login: FAUX_GITHUB.account, type: "Organization" }, app_id: Number(FAUX_GITHUB.appId), suspended_at: null, permissions: { metadata: "read", contents: "read", pull_requests: "write", issues: "read" } };
64
+ const installation = { id: FAUX_GITHUB.installation, account: { login: FAUX_GITHUB.account, type: "Organization" }, app_id: Number(FAUX_GITHUB.appId), suspended_at: null, permissions: { metadata: "read", contents: "write", pull_requests: "write", issues: "read" } };
65
+ // Each repository the installation covers, on its default branch main: its files at one commit, and what writes add.
66
+ const sha = (text) => createHash("sha1").update(text).digest("hex");
67
+ const BASE = sha("faux-base");
68
+ const files = new Set(Object.keys(FAUX_REPO_FILES));
69
+ const state = { branches: new Map([["main", BASE]]), trees: new Map(), commits: new Map(), pulls: [] };
20
70
  /** Each token minted, by its value: the repositories it was narrowed to (by name), or every one the installation covers. */
21
71
  const tokens = new Map();
22
72
  const covered = (names) => FAUX_GITHUB.repositories.filter((full) => !names || names.includes(full.split("/")[1]));
@@ -43,7 +93,7 @@ export async function startFauxGitHub() {
43
93
  return answer(res, 422, { message: "There is at least one repository that does not exist or is not accessible to the parent installation." });
44
94
  const token = `faux-installation-token-${randomBytes(16).toString("hex")}`;
45
95
  tokens.set(token, names);
46
- return answer(res, 201, { token, expires_at: new Date(Date.now() + TOKEN_MS).toISOString(), permissions: { metadata: "read", contents: "read", pull_requests: "write", issues: "read" }, repository_selection: "selected" });
96
+ return answer(res, 201, { token, expires_at: new Date(Date.now() + TOKEN_MS).toISOString(), permissions: { ...installation.permissions }, repository_selection: "selected" });
47
97
  }
48
98
  const bearer = String(req.headers.authorization ?? "").replace(/^Bearer /, "");
49
99
  if (req.method === "GET" && path === "/installation/repositories") {
@@ -60,6 +110,86 @@ export async function startFauxGitHub() {
60
110
  const repo = /^\/repos\/([^/]+)\/([^/]+)\/installation$/.exec(path);
61
111
  if (req.method === "GET" && repo)
62
112
  return FAUX_GITHUB.repositories.includes(`${repo[1]}/${repo[2]}`) ? answer(res, 200, installation) : answer(res, 404, { message: "Not Found" });
113
+ // What a test or a demo reads and sets of the fake: everything written, and the installation's permissions.
114
+ if (req.method === "GET" && path === "/_faux/state")
115
+ return answer(res, 200, { permissions: installation.permissions, branches: Object.fromEntries(state.branches), commits: Object.fromEntries(state.commits), trees: Object.fromEntries(state.trees), pulls: state.pulls });
116
+ if (req.method === "POST" && path === "/_faux/permissions") {
117
+ try {
118
+ installation.permissions = { ...installation.permissions, ...JSON.parse(body || "{}") };
119
+ }
120
+ catch {
121
+ return answer(res, 400, { message: "Problems parsing JSON" });
122
+ }
123
+ return answer(res, 200, installation.permissions);
124
+ }
125
+ // A repository's reads and writes, each with a token of the installation narrowed to it (or covering every one).
126
+ const on = /^\/repos\/([^/]+)\/([^/]+)(\/.*)?$/.exec(path);
127
+ if (on && FAUX_GITHUB.repositories.includes(`${on[1]}/${on[2]}`)) {
128
+ const full = `${on[1]}/${on[2]}`;
129
+ const rest = on[3] ?? "";
130
+ if (!tokens.has(bearer) || !covered(tokens.get(bearer)).includes(full))
131
+ return answer(res, 404, { message: "Not Found" });
132
+ const writes = installation.permissions.contents === "write";
133
+ const json = () => { try {
134
+ return JSON.parse(body || "{}");
135
+ }
136
+ catch {
137
+ return {};
138
+ } };
139
+ if (req.method === "GET" && rest === "")
140
+ return answer(res, 200, { full_name: full, private: true, default_branch: "main" });
141
+ const ref = /^\/git\/ref\/heads\/(.+)$/.exec(rest);
142
+ if (req.method === "GET" && ref)
143
+ return state.branches.has(decodeURIComponent(ref[1])) ? answer(res, 200, { ref: `refs/heads/${decodeURIComponent(ref[1])}`, object: { sha: state.branches.get(decodeURIComponent(ref[1])), type: "commit" } }) : answer(res, 404, { message: "Not Found" });
144
+ const commit = /^\/git\/commits\/([0-9a-f]{40})$/.exec(rest);
145
+ if (req.method === "GET" && commit)
146
+ return commit[1] === BASE ? answer(res, 200, { sha: BASE, tree: { sha: sha("faux-base-tree") } }) : state.commits.has(commit[1]) ? answer(res, 200, state.commits.get(commit[1])) : answer(res, 404, { message: "Not Found" });
147
+ const content = /^\/contents\/(.+)$/.exec(rest);
148
+ if (req.method === "GET" && content)
149
+ return files.has(decodeURIComponent(content[1])) ? answer(res, 200, { type: "file", path: decodeURIComponent(content[1]) }) : answer(res, 404, { message: "Not Found" });
150
+ // Writes: GitHub answers an installation that can't write contents 403 ("Resource not accessible by integration").
151
+ if (req.method === "POST" && (rest === "/git/trees" || rest === "/git/commits" || rest === "/git/refs") && !writes)
152
+ return answer(res, 403, { message: "Resource not accessible by integration" });
153
+ if (req.method === "POST" && rest === "/git/trees") {
154
+ const made = sha(`tree ${body}`);
155
+ state.trees.set(made, json());
156
+ return answer(res, 201, { sha: made });
157
+ }
158
+ if (req.method === "POST" && rest === "/git/commits") {
159
+ const asked = json();
160
+ const made = sha(`commit ${body}`);
161
+ state.commits.set(made, { sha: made, tree: { sha: asked.tree }, message: asked.message, parents: asked.parents });
162
+ return answer(res, 201, { sha: made });
163
+ }
164
+ if (req.method === "POST" && rest === "/git/refs") {
165
+ const asked = json();
166
+ const name = String(asked.ref ?? "").replace(/^refs\/heads\//, "");
167
+ if (state.branches.has(name))
168
+ return answer(res, 422, { message: "Reference already exists" });
169
+ state.branches.set(name, String(asked.sha));
170
+ return answer(res, 201, { ref: asked.ref, object: { sha: asked.sha } });
171
+ }
172
+ const gone = /^\/git\/refs\/heads\/(.+)$/.exec(rest);
173
+ if (req.method === "DELETE" && gone)
174
+ return state.branches.delete(decodeURIComponent(gone[1])) ? answer(res, 204) : answer(res, 422, { message: "Reference does not exist" });
175
+ if (req.method === "POST" && rest === "/pulls") {
176
+ if (installation.permissions.pull_requests !== "write")
177
+ return answer(res, 403, { message: "Resource not accessible by integration" });
178
+ const asked = json();
179
+ if (!state.branches.has(String(asked.head)))
180
+ return answer(res, 422, { message: "Validation Failed" });
181
+ if (state.pulls.some((p) => p.repo === full && p.head === asked.head))
182
+ return answer(res, 422, { message: "A pull request already exists" });
183
+ const number = state.pulls.length + 1;
184
+ const pull = { number, title: String(asked.title), head: String(asked.head), base: String(asked.base), body: String(asked.body), html_url: `https://github.com/${full}/pull/${number}`, repo: full };
185
+ state.pulls.push(pull);
186
+ return answer(res, 201, pull);
187
+ }
188
+ if (req.method === "GET" && rest === "/pulls") {
189
+ const head = new URL(req.url ?? "/", "http://faux").searchParams.get("head")?.split(":")[1];
190
+ return answer(res, 200, state.pulls.filter((p) => p.repo === full && (!head || p.head === head)));
191
+ }
192
+ }
63
193
  return answer(res, 404, { message: "Not Found" });
64
194
  };
65
195
  const server = createServer((req, res) => {
@@ -70,6 +200,7 @@ export async function startFauxGitHub() {
70
200
  await new Promise((resolve, reject) => server.once("error", reject).listen(0, host, () => resolve()));
71
201
  return {
72
202
  url: `http://${host}:${server.address().port}`,
203
+ ...(web ? { web } : {}),
73
204
  app,
74
205
  close: () => new Promise((resolve) => (server.close(() => resolve()), server.closeAllConnections())),
75
206
  };
@@ -0,0 +1,37 @@
1
+ /** A file the pull request adds: its path from the repository's root, and its text. */
2
+ export type NewFile = {
3
+ readonly path: string;
4
+ readonly content: string;
5
+ };
6
+ /** Why a write was refused: a file already there, the token's permissions, a branch name taken five times, or GitHub. */
7
+ export declare class GithubWriteRefused extends Error {
8
+ readonly kind: "file_exists" | "not_permitted" | "branch_taken" | "github_failed";
9
+ readonly path?: string | undefined;
10
+ constructor(kind: "file_exists" | "not_permitted" | "branch_taken" | "github_failed", message: string, path?: string | undefined);
11
+ }
12
+ /** The commit pushed: on `branch`, made over the default branch `base` at `baseSha`. */
13
+ export type Pushed = {
14
+ readonly branch: string;
15
+ readonly commit: string;
16
+ readonly base: string;
17
+ readonly baseSha: string;
18
+ };
19
+ /** The files of `files` that `repo` already has at `sha` (each asked by path: 200 there, 404 not). */
20
+ export declare function filesThere(api: string, token: string, repo: string, sha: string, files: readonly NewFile[], signal?: AbortSignal): Promise<string[]>;
21
+ /** `files` committed over the head of `repo`'s default branch, on a new branch named `branch` (or `branch-2` ... when
22
+ * that name is taken). Refused, with nothing written, when a file is already there. */
23
+ export declare function pushFiles(api: string, token: string, repo: string, change: {
24
+ branch: string;
25
+ message: string;
26
+ files: readonly NewFile[];
27
+ }, signal?: AbortSignal): Promise<Pushed>;
28
+ /** The pull request of `pushed.branch` into its base, or the open one GitHub already has for that branch. */
29
+ export declare function openPull(api: string, token: string, repo: string, pushed: Pick<Pushed, "branch" | "base">, text: {
30
+ title: string;
31
+ body: string;
32
+ }, signal?: AbortSignal): Promise<{
33
+ number: number;
34
+ url: string;
35
+ }>;
36
+ /** The branch removed: what a create that failed after its push leaves behind. Best effort; false when GitHub did not. */
37
+ export declare function deleteBranch(api: string, token: string, repo: string, branch: string): Promise<boolean>;
@@ -0,0 +1,110 @@
1
+ // A pull request that adds files to one repository, made through GitHub's REST API with one installation token of the
2
+ // server's GitHub App, narrowed to that repository with contents and pull requests write (suggestions.ts mints it): the
3
+ // default branch's head, a tree of the new files over it, a commit, a branch at that commit, then the pull request. No git
4
+ // binary and no clone: GitHub's Git Data API. A file the base already has is refused before anything is written, so a pull
5
+ // request made here only ever adds files, and never touches a workflow (`.github/`), which the caller refuses first.
6
+ // What GitHub answers is worded here; its own words are never passed on whole.
7
+ import { githubCall } from "./github.js";
8
+ import { isObject } from "./validate.js";
9
+ /** Why a write was refused: a file already there, the token's permissions, a branch name taken five times, or GitHub. */
10
+ export class GithubWriteRefused extends Error {
11
+ kind;
12
+ path;
13
+ constructor(kind, message, path) {
14
+ super(message);
15
+ this.kind = kind;
16
+ this.path = path;
17
+ }
18
+ }
19
+ /** How many names a branch is tried under (`b`, `b-2`, ... `b-5`) before it is refused. */
20
+ const BRANCH_TRIES = 5;
21
+ const segments = (path) => path.split("/").map(encodeURIComponent).join("/");
22
+ const field = (json, name) => (isObject(json) ? json[name] : undefined);
23
+ /** A refusal for an answer GitHub gave a write: 403 and 404 are the token's permissions (GitHub answers 404 for a write
24
+ * an installation may not make on a repository it can read), anything else GitHub's failure. */
25
+ function refused(step, repo, status) {
26
+ if (status === 403 || status === 404)
27
+ return new GithubWriteRefused("not_permitted", `GitHub refused to ${step} on ${repo} (HTTP ${status}): the GitHub App's installation needs Contents: write and Pull requests: write there.`);
28
+ return new GithubWriteRefused("github_failed", `GitHub did not ${step} on ${repo} (HTTP ${status}).`);
29
+ }
30
+ /** The default branch of `repo` and its head, read with `token`. */
31
+ async function defaultHead(api, token, repo, signal) {
32
+ const opts = { jwt: token, ...(signal ? { signal } : {}) };
33
+ const about = await githubCall(api, `/repos/${repo}`, opts);
34
+ const base = field(about.json, "default_branch");
35
+ if (about.status !== 200 || typeof base !== "string" || !base)
36
+ throw refused("read the repository", repo, about.status);
37
+ const ref = await githubCall(api, `/repos/${repo}/git/ref/heads/${segments(base)}`, opts);
38
+ const baseSha = field(field(ref.json, "object"), "sha");
39
+ if (ref.status !== 200 || typeof baseSha !== "string")
40
+ throw refused(`read the head of ${base}`, repo, ref.status);
41
+ const commit = await githubCall(api, `/repos/${repo}/git/commits/${baseSha}`, opts);
42
+ const tree = field(field(commit.json, "tree"), "sha");
43
+ if (commit.status !== 200 || typeof tree !== "string")
44
+ throw refused(`read the commit ${baseSha}`, repo, commit.status);
45
+ return { base, baseSha, tree };
46
+ }
47
+ /** The files of `files` that `repo` already has at `sha` (each asked by path: 200 there, 404 not). */
48
+ export async function filesThere(api, token, repo, sha, files, signal) {
49
+ const there = [];
50
+ for (const file of files) {
51
+ const read = await githubCall(api, `/repos/${repo}/contents/${segments(file.path)}?ref=${sha}`, { jwt: token, ...(signal ? { signal } : {}) });
52
+ if (read.status === 200)
53
+ there.push(file.path);
54
+ else if (read.status !== 404)
55
+ throw refused(`read ${file.path}`, repo, read.status);
56
+ }
57
+ return there;
58
+ }
59
+ /** `files` committed over the head of `repo`'s default branch, on a new branch named `branch` (or `branch-2` ... when
60
+ * that name is taken). Refused, with nothing written, when a file is already there. */
61
+ export async function pushFiles(api, token, repo, change, signal) {
62
+ const opts = { jwt: token, ...(signal ? { signal } : {}) };
63
+ const { base, baseSha, tree } = await defaultHead(api, token, repo, signal);
64
+ const there = await filesThere(api, token, repo, baseSha, change.files, signal);
65
+ if (there.length)
66
+ throw new GithubWriteRefused("file_exists", `${repo} already has ${there.join(", ")} on ${base}: a suggested agent's pull request only adds files, so nothing was written.`, there[0]);
67
+ const made = await githubCall(api, `/repos/${repo}/git/trees`, { ...opts, method: "POST", body: { base_tree: tree, tree: change.files.map((file) => ({ path: file.path, mode: "100644", type: "blob", content: file.content })) } });
68
+ const newTree = field(made.json, "sha");
69
+ if (made.status !== 201 || typeof newTree !== "string")
70
+ throw refused("write the files", repo, made.status);
71
+ const committed = await githubCall(api, `/repos/${repo}/git/commits`, { ...opts, method: "POST", body: { message: change.message, tree: newTree, parents: [baseSha] } });
72
+ const commit = field(committed.json, "sha");
73
+ if (committed.status !== 201 || typeof commit !== "string")
74
+ throw refused("commit the files", repo, committed.status);
75
+ for (let i = 1; i <= BRANCH_TRIES; i++) {
76
+ const branch = i === 1 ? change.branch : `${change.branch}-${i}`;
77
+ const ref = await githubCall(api, `/repos/${repo}/git/refs`, { ...opts, method: "POST", body: { ref: `refs/heads/${branch}`, sha: commit } });
78
+ if (ref.status === 201)
79
+ return { branch, commit, base, baseSha };
80
+ // 422: the name is taken (GitHub's "Reference already exists"): the next name.
81
+ if (ref.status !== 422)
82
+ throw refused(`make the branch ${branch}`, repo, ref.status);
83
+ }
84
+ throw new GithubWriteRefused("branch_taken", `${repo} already has branches ${change.branch} to ${change.branch}-${BRANCH_TRIES}: delete the old ones, then create again.`);
85
+ }
86
+ /** The pull request of `pushed.branch` into its base, or the open one GitHub already has for that branch. */
87
+ export async function openPull(api, token, repo, pushed, text, signal) {
88
+ const opts = { jwt: token, ...(signal ? { signal } : {}) };
89
+ const opened = await githubCall(api, `/repos/${repo}/pulls`, { ...opts, method: "POST", body: { title: text.title, head: pushed.branch, base: pushed.base, body: text.body } });
90
+ const number = field(opened.json, "number");
91
+ const url = field(opened.json, "html_url");
92
+ if (opened.status === 201 && Number.isSafeInteger(number) && typeof url === "string")
93
+ return { number: number, url };
94
+ if (opened.status === 422) {
95
+ // One already open for this branch (a create sent again): that one.
96
+ const owner = repo.split("/")[0];
97
+ const open = await githubCall(api, `/repos/${repo}/pulls?state=open&head=${encodeURIComponent(`${owner}:${pushed.branch}`)}`, opts);
98
+ const first = Array.isArray(open.json) ? open.json[0] : undefined;
99
+ const n = field(first, "number");
100
+ const u = field(first, "html_url");
101
+ if (open.status === 200 && Number.isSafeInteger(n) && typeof u === "string")
102
+ return { number: n, url: u };
103
+ }
104
+ throw refused(`open the pull request from ${pushed.branch}`, repo, opened.status);
105
+ }
106
+ /** The branch removed: what a create that failed after its push leaves behind. Best effort; false when GitHub did not. */
107
+ export async function deleteBranch(api, token, repo, branch) {
108
+ const gone = await githubCall(api, `/repos/${repo}/git/refs/heads/${segments(branch)}`, { method: "DELETE", jwt: token }).catch(() => undefined);
109
+ return gone?.status === 204;
110
+ }
@@ -1,4 +1,5 @@
1
1
  import type { IncomingMessage } from "node:http";
2
+ import { networkInterfaces } from "node:os";
2
3
  /** The header the proxy's proof travels in. */
3
4
  export declare const LIVE_PROOF_HEADER = "x-agentrun-live";
4
5
  /** How far a proof's time may be from the endpoint's clock. */
@@ -6,17 +7,34 @@ export declare const LIVE_PROOF_MS = 60000;
6
7
  /** Where every viewer answers when its runner is on the server's own machine. */
7
8
  export declare const LOOPBACK = "127.0.0.1";
8
9
  export declare const isLiveHost: (host: unknown) => host is string;
9
- /** What the server needs to reach a runner's viewer: the hosts it dials (its runners'), and the proof's key. */
10
+ /** An IPv4 block, `a.b.c.d/n`: its network address as a 32-bit number and its prefix length. */
11
+ export type Ipv4Block = {
12
+ readonly base: number;
13
+ readonly bits: number;
14
+ };
15
+ /** The shortest prefix a block may have: a /8 is a whole private range, and anything wider is no runners' network. */
16
+ export declare const MIN_BLOCK_BITS = 8;
17
+ /** `address` (dotted IPv4, no leading zeros) as a 32-bit number, or undefined. */
18
+ export declare function ipv4Of(address: string): number | undefined;
19
+ /** `value` as an IPv4 block: its address the block's network address (no host bits set) and its prefix from
20
+ * MIN_BLOCK_BITS to 32; else undefined. */
21
+ export declare function ipv4BlockOf(value: string): Ipv4Block | undefined;
22
+ /** Whether IPv4 `address` is in `block`. */
23
+ export declare const inBlock: (address: number, block: Ipv4Block) => boolean;
24
+ /** What the server needs to reach a runner's viewer: the hosts it dials (its runners'), the IPv4 blocks whose every
25
+ * address it dials (its runners' network), and the proof's key. */
10
26
  export type LiveReach = {
11
27
  readonly hosts: ReadonlySet<string>;
28
+ readonly blocks: readonly Ipv4Block[];
12
29
  readonly key: Buffer;
13
30
  };
14
- /** The server's reach, from its environment (AGENTRUN_RUNNER_HOSTS) and the seal key. A name that is not a host is left
15
- * out. */
31
+ /** The server's reach, from its environment (AGENTRUN_RUNNER_HOSTS: host names, IPv4 addresses and IPv4 blocks) and
32
+ * the seal key. An entry that is none of them is left out. */
16
33
  export declare function liveReachOf(env: {
17
34
  readonly AGENTRUN_RUNNER_HOSTS?: string | undefined;
18
35
  }, sealKey: Buffer): LiveReach;
19
- /** Where the server dials `host` (a row's): loopback with none; the host when it is one of its runners'; else nowhere. */
36
+ /** Where the server dials `host` (a row's): loopback with none; the host when it is one of its runners' or an IPv4
37
+ * address in one of their blocks; else nowhere. */
20
38
  export declare function dialHost(host: string | undefined, reach: LiveReach | undefined): string | undefined;
21
39
  /** The proxy's proof for viewer `viewerId`, at `at` (ms). */
22
40
  export declare const liveProof: (reach: Pick<LiveReach, "key">, viewerId: string, at?: number) => string;
@@ -27,13 +45,22 @@ export type RunnerLive = {
27
45
  readonly bind: string;
28
46
  readonly key: Buffer;
29
47
  };
48
+ /** This machine's network interfaces, as node:os reads them: an injection point for tests. */
49
+ export type Interfaces = () => ReturnType<typeof networkInterfaces>;
50
+ /** A runner's live host it cannot take: its AGENTRUN_RUNNER_LIVE_HOST names a block that holds none, or more than one,
51
+ * of this machine's addresses. Thrown at the runner's start, so it never says it answers where the server cannot
52
+ * reach it. */
53
+ export declare class RunnerLiveRefused extends Error {
54
+ readonly name = "RunnerLiveRefused";
55
+ }
30
56
  /** The runner's live host, from its environment (AGENTRUN_RUNNER_LIVE_HOST, AGENTRUN_RUNNER_LIVE_BIND) and the seal key;
31
- * undefined with none (or one that is not a host): its viewers answer on loopback, as on a server's own machine. */
57
+ * undefined with none (or one that is not a host): its viewers answer on loopback, as on a server's own machine. An
58
+ * IPv4 block for a host is this machine's own address in it (refused, RunnerLiveRefused, with none or several). */
32
59
  export declare function runnerLiveOf(env: {
33
60
  readonly AGENTRUN_RUNNER_LIVE_HOST?: string | undefined;
34
61
  readonly AGENTRUN_RUNNER_LIVE_BIND?: string | undefined;
35
- }, sealKey: Buffer): RunnerLive | undefined;
36
- /** The server's reach for run `runId`'s viewers: its hosts, under that run's key. */
62
+ }, sealKey: Buffer, interfaces?: Interfaces): RunnerLive | undefined;
63
+ /** The server's reach for run `runId`'s viewers: its hosts and blocks, under that run's key. */
37
64
  export declare const reachForRun: (reach: LiveReach, runId: string) => LiveReach;
38
65
  /** A runner's live address for run `runId`'s viewers: its host and bind, under that run's key. */
39
66
  export declare const liveForRun: (live: RunnerLive, runId: string) => RunnerLive;
@@ -9,7 +9,15 @@
9
9
  // endpoint off loopback takes no request without a good, fresh proof for its own viewer. The proof is not the viewer's:
10
10
  // the hello's token still decides who watches. The hop is plain HTTP, for a private network (the server and its
11
11
  // runners' own); TLS on it is a later step.
12
+ //
13
+ // Runners that are replicas of one deployment (Kubernetes pods, a platform's instances) have no host name of their own
14
+ // the server resolves, and their addresses change at each start. For them both settings take an IPv4 block in CIDR form:
15
+ // a runner whose AGENTRUN_RUNNER_LIVE_HOST is a block answers at its own address in that block (its one network
16
+ // interface address there), and a server whose AGENTRUN_RUNNER_HOSTS lists a block dials any IPv4 address in it. The
17
+ // block is the private network the runners' addresses come from (a cluster's pod range), and the proof above still
18
+ // guards every request on it.
12
19
  import { createHmac, hkdfSync, timingSafeEqual } from "node:crypto";
20
+ import { networkInterfaces } from "node:os";
13
21
  /** The header the proxy's proof travels in. */
14
22
  export const LIVE_PROOF_HEADER = "x-agentrun-live";
15
23
  /** How far a proof's time may be from the endpoint's clock. */
@@ -23,26 +31,83 @@ const LABEL = "agentrun live proxy v1";
23
31
  export const isLiveHost = (host) => typeof host === "string" && HOST.test(host);
24
32
  const proofKey = (sealKey) => Buffer.from(hkdfSync("sha256", sealKey, Buffer.alloc(0), LABEL, 32));
25
33
  const mac = (key, viewerId, at) => createHmac("sha256", key).update(`${viewerId}\n${at}`).digest("hex");
26
- /** The server's reach, from its environment (AGENTRUN_RUNNER_HOSTS) and the seal key. A name that is not a host is left
27
- * out. */
34
+ /** The shortest prefix a block may have: a /8 is a whole private range, and anything wider is no runners' network. */
35
+ export const MIN_BLOCK_BITS = 8;
36
+ const IPV4 = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;
37
+ /** `address` (dotted IPv4, no leading zeros) as a 32-bit number, or undefined. */
38
+ export function ipv4Of(address) {
39
+ const match = IPV4.exec(address);
40
+ return match ? match.slice(1).reduce((sum, octet) => sum * 256 + Number(octet), 0) : undefined;
41
+ }
42
+ const maskOf = (bits) => (bits === 0 ? 0 : (0xffffffff << (32 - bits)) >>> 0);
43
+ /** `value` as an IPv4 block: its address the block's network address (no host bits set) and its prefix from
44
+ * MIN_BLOCK_BITS to 32; else undefined. */
45
+ export function ipv4BlockOf(value) {
46
+ const match = /^([0-9.]+)\/(\d{1,2})$/.exec(value);
47
+ if (!match)
48
+ return undefined;
49
+ const base = ipv4Of(match[1]);
50
+ const bits = Number(match[2]);
51
+ if (base === undefined || bits < MIN_BLOCK_BITS || bits > 32 || ((base & ~maskOf(bits)) >>> 0) !== 0)
52
+ return undefined;
53
+ return { base, bits };
54
+ }
55
+ /** Whether IPv4 `address` is in `block`. */
56
+ export const inBlock = (address, block) => ((address & maskOf(block.bits)) >>> 0) === block.base;
57
+ /** The server's reach, from its environment (AGENTRUN_RUNNER_HOSTS: host names, IPv4 addresses and IPv4 blocks) and
58
+ * the seal key. An entry that is none of them is left out. */
28
59
  export function liveReachOf(env, sealKey) {
29
- const hosts = new Set((env.AGENTRUN_RUNNER_HOSTS ?? "").split(",").map((host) => host.trim().toLowerCase()).filter(isLiveHost));
30
- return { hosts, key: proofKey(sealKey) };
60
+ const entries = (env.AGENTRUN_RUNNER_HOSTS ?? "").split(",").map((host) => host.trim().toLowerCase());
61
+ const hosts = new Set(entries.filter(isLiveHost));
62
+ const blocks = entries.map(ipv4BlockOf).filter((block) => block !== undefined);
63
+ return { hosts, blocks, key: proofKey(sealKey) };
31
64
  }
32
- /** Where the server dials `host` (a row's): loopback with none; the host when it is one of its runners'; else nowhere. */
65
+ /** Where the server dials `host` (a row's): loopback with none; the host when it is one of its runners' or an IPv4
66
+ * address in one of their blocks; else nowhere. */
33
67
  export function dialHost(host, reach) {
34
68
  if (host === undefined || host === LOOPBACK)
35
69
  return LOOPBACK;
36
- return reach?.hosts.has(host.toLowerCase()) ? host : undefined;
70
+ if (reach === undefined)
71
+ return undefined;
72
+ if (reach.hosts.has(host.toLowerCase()))
73
+ return host;
74
+ const address = ipv4Of(host);
75
+ return address !== undefined && reach.blocks.some((block) => inBlock(address, block)) ? host : undefined;
37
76
  }
38
77
  /** The proxy's proof for viewer `viewerId`, at `at` (ms). */
39
78
  export const liveProof = (reach, viewerId, at = Date.now()) => `${at}.${mac(reach.key, viewerId, at)}`;
79
+ /** A runner's live host it cannot take: its AGENTRUN_RUNNER_LIVE_HOST names a block that holds none, or more than one,
80
+ * of this machine's addresses. Thrown at the runner's start, so it never says it answers where the server cannot
81
+ * reach it. */
82
+ export class RunnerLiveRefused extends Error {
83
+ name = "RunnerLiveRefused";
84
+ }
85
+ /** This machine's one IPv4 address in `block` (AGENTRUN_RUNNER_LIVE_HOST as a block, named `given`); refused in words
86
+ * with none or several. */
87
+ function ownAddressIn(block, given, interfaces) {
88
+ const found = new Set();
89
+ for (const addresses of Object.values(interfaces())) {
90
+ for (const one of addresses ?? []) {
91
+ const address = one.family === "IPv4" && !one.internal ? ipv4Of(one.address) : undefined;
92
+ if (address !== undefined && inBlock(address, block))
93
+ found.add(one.address);
94
+ }
95
+ }
96
+ if (found.size === 1)
97
+ return [...found][0];
98
+ throw new RunnerLiveRefused(found.size === 0
99
+ ? `AGENTRUN_RUNNER_LIVE_HOST is ${given}, and no network interface of this machine has an IPv4 address in it: name the block this runner's address is in, or the host the server reaches it at`
100
+ : `AGENTRUN_RUNNER_LIVE_HOST is ${given}, and this machine has ${found.size} IPv4 addresses in it (${[...found].sort().join(", ")}): name a narrower block, or the host the server reaches it at`);
101
+ }
40
102
  /** The runner's live host, from its environment (AGENTRUN_RUNNER_LIVE_HOST, AGENTRUN_RUNNER_LIVE_BIND) and the seal key;
41
- * undefined with none (or one that is not a host): its viewers answer on loopback, as on a server's own machine. */
42
- export function runnerLiveOf(env, sealKey) {
103
+ * undefined with none (or one that is not a host): its viewers answer on loopback, as on a server's own machine. An
104
+ * IPv4 block for a host is this machine's own address in it (refused, RunnerLiveRefused, with none or several). */
105
+ export function runnerLiveOf(env, sealKey, interfaces = networkInterfaces) {
43
106
  // Lower case, as a URL's hostname reads a DNS name and the server's runners' hosts are read (liveReachOf): one form for
44
107
  // the links, the origins and the rows.
45
- const host = env.AGENTRUN_RUNNER_LIVE_HOST?.trim().toLowerCase();
108
+ const given = env.AGENTRUN_RUNNER_LIVE_HOST?.trim().toLowerCase();
109
+ const block = given === undefined ? undefined : ipv4BlockOf(given);
110
+ const host = block !== undefined ? ownAddressIn(block, given, interfaces) : given;
46
111
  if (!isLiveHost(host) || host === LOOPBACK)
47
112
  return undefined;
48
113
  const bind = env.AGENTRUN_RUNNER_LIVE_BIND?.trim().toLowerCase();
@@ -53,8 +118,8 @@ export function runnerLiveOf(env, sealKey) {
53
118
  const runKey = (key, runId) => createHmac("sha256", key).update(`${RUN_LABEL}\n${runId}`).digest();
54
119
  /** The run label of runKey: another MAC than the proof's own. */
55
120
  const RUN_LABEL = "agentrun live run v1";
56
- /** The server's reach for run `runId`'s viewers: its hosts, under that run's key. */
57
- export const reachForRun = (reach, runId) => ({ hosts: reach.hosts, key: runKey(reach.key, runId) });
121
+ /** The server's reach for run `runId`'s viewers: its hosts and blocks, under that run's key. */
122
+ export const reachForRun = (reach, runId) => ({ hosts: reach.hosts, blocks: reach.blocks, key: runKey(reach.key, runId) });
58
123
  /** A runner's live address for run `runId`'s viewers: its host and bind, under that run's key. */
59
124
  export const liveForRun = (live, runId) => ({ host: live.host, bind: live.bind, key: runKey(live.key, runId) });
60
125
  /** Whether `req` carries a good, fresh proof for viewer `viewerId` under `live`'s key: its time within `windowMs` of
package/dist/mcp-probe.js CHANGED
@@ -5,7 +5,7 @@
5
5
  // Nothing here opens a credential or touches a store: listServer connects to a URL with the official SDK client, agrees a
6
6
  // protocol revision and lists every tool (all pages, under caps); the validation turns a request body into a URL, auth and
7
7
  // prices, or a 422; no redirect is followed, so a credential goes only where the owner sends it.
8
- import { COMPOSIO_ACCOUNT_ID, COMPOSIO_USER, COMPOSIO_USER_ID } from "./composio-preset.js";
8
+ import { COMPOSIO_ACCOUNT_ID, COMPOSIO_USER, COMPOSIO_USER_ID, COMPOSIO_USER_ID_WORDS } from "./composio-preset.js";
9
9
  import { ApiError, invalid } from "./errors.js";
10
10
  import { metaToolOf } from "./mcp-meta.js";
11
11
  import { SIGN_IN_AGAIN } from "./mcp-oauth.js";
@@ -278,7 +278,7 @@ function composioBindingOf(field, entry, issues) {
278
278
  const user = entry.composio_user_id;
279
279
  const account = entry.connected_account_id;
280
280
  if (typeof user !== "string" || !COMPOSIO_USER_ID.test(user))
281
- issues.push({ field: `${field}.composio_user_id`, reason: "invalid", message: "composio_user_id is the Composio user this run's calls run as: letters, digits and . _ @ : - (1 to 128)." });
281
+ issues.push({ field: `${field}.composio_user_id`, reason: "invalid", message: `composio_user_id is the Composio user this run's calls run as: ${COMPOSIO_USER_ID_WORDS}.` });
282
282
  // The preset's default user is the one single-user preset servers call as: a run that forgot to name its own never lands there.
283
283
  else if (user === COMPOSIO_USER)
284
284
  issues.push({ field: `${field}.composio_user_id`, reason: "not_allowed", message: "That composio_user_id is the Composio preset's shared default user, the one single-user preset servers call as: bind the run to its own person's Composio user." });