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

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 (224) hide show
  1. package/CHANGELOG.md +138 -3
  2. package/README.md +346 -99
  3. package/dist/adapters.d.ts +10 -0
  4. package/dist/adapters.js +46 -0
  5. package/dist/agent-package.d.ts +3 -3
  6. package/dist/agent-package.js +7 -14
  7. package/dist/agent-rows.d.ts +1 -1
  8. package/dist/agents-store.js +7 -6
  9. package/dist/api-only.d.ts +17 -6
  10. package/dist/api-only.js +22 -9
  11. package/dist/cli.js +11 -4
  12. package/dist/composio-made.d.ts +26 -1
  13. package/dist/composio-made.js +39 -2
  14. package/dist/composio-preset.d.ts +6 -4
  15. package/dist/composio-preset.js +50 -17
  16. package/dist/computer-held-routes.js +2 -3
  17. package/dist/computer-needs.d.ts +1 -1
  18. package/dist/computer-needs.js +1 -1
  19. package/dist/computer-setting.d.ts +8 -4
  20. package/dist/computer-setting.js +0 -2
  21. package/dist/computers-running.d.ts +8 -0
  22. package/dist/computers-running.js +27 -0
  23. package/dist/computers.d.ts +0 -2
  24. package/dist/computers.js +1 -1
  25. package/dist/console/assets/backend-D5EmB4N3.js +166 -0
  26. package/dist/console/assets/index-DUYLaqiR.js +746 -0
  27. package/dist/console/assets/index-DYhU4adm.css +1 -0
  28. package/dist/console/index.html +2 -2
  29. package/dist/docker-host-addresses.d.ts +23 -3
  30. package/dist/docker-host-addresses.js +90 -18
  31. package/dist/errors.d.ts +4 -0
  32. package/dist/errors.js +7 -0
  33. package/dist/exa-keyless.d.ts +2 -3
  34. package/dist/exa-keyless.js +43 -127
  35. package/dist/firecrawl-keyless.d.ts +41 -0
  36. package/dist/firecrawl-keyless.js +152 -0
  37. package/dist/github-connection.d.ts +50 -1
  38. package/dist/github-connection.js +96 -3
  39. package/dist/github-faux.d.ts +11 -2
  40. package/dist/github-faux.js +138 -7
  41. package/dist/github-pull-request.d.ts +37 -0
  42. package/dist/github-pull-request.js +110 -0
  43. package/dist/handed-secret.d.ts +3 -1
  44. package/dist/handed-secret.js +4 -2
  45. package/dist/harness-keys.d.ts +98 -0
  46. package/dist/harness-keys.js +247 -0
  47. package/dist/harness-recipe-entry.d.ts +14 -9
  48. package/dist/harness-recipe-entry.js +25 -14
  49. package/dist/harness-table.d.ts +16 -1
  50. package/dist/harness-table.js +19 -7
  51. package/dist/harness.d.ts +4 -0
  52. package/dist/harness.js +12 -1
  53. package/dist/host-check.d.ts +2 -0
  54. package/dist/host-check.js +6 -0
  55. package/dist/import-summary.d.ts +1 -1
  56. package/dist/import-summary.js +1 -1
  57. package/dist/import.d.ts +5 -5
  58. package/dist/import.js +54 -67
  59. package/dist/keyless-mcp.d.ts +36 -0
  60. package/dist/keyless-mcp.js +127 -0
  61. package/dist/learn/audit.d.ts +3 -3
  62. package/dist/learn/audit.js +3 -3
  63. package/dist/learn/commit.d.ts +8 -7
  64. package/dist/learn/commit.js +60 -20
  65. package/dist/learn/compile.d.ts +4 -3
  66. package/dist/learn/compile.js +7 -5
  67. package/dist/learn/folder.d.ts +16 -3
  68. package/dist/learn/folder.js +46 -13
  69. package/dist/learn/promote.d.ts +37 -13
  70. package/dist/learn/promote.js +112 -40
  71. package/dist/learn/secrets.js +10 -2
  72. package/dist/learning-routes.d.ts +22 -17
  73. package/dist/learning-routes.js +40 -39
  74. package/dist/learning.js +2 -2
  75. package/dist/live-reach.d.ts +34 -7
  76. package/dist/live-reach.js +76 -11
  77. package/dist/manifest.d.ts +10 -0
  78. package/dist/manifest.js +30 -0
  79. package/dist/mcp-pin-first.d.ts +4 -2
  80. package/dist/mcp-pin-first.js +5 -2
  81. package/dist/mcp-probe.js +2 -2
  82. package/dist/mcp-secret-writes.d.ts +16 -7
  83. package/dist/mcp-secret-writes.js +35 -27
  84. package/dist/mcp-servers-store.d.ts +30 -6
  85. package/dist/mcp-servers-store.js +112 -28
  86. package/dist/mcp-sources.d.ts +10 -2
  87. package/dist/mcp-sources.js +9 -2
  88. package/dist/mcp-store.d.ts +13 -7
  89. package/dist/mcp-store.js +12 -9
  90. package/dist/model-form.d.ts +3 -2
  91. package/dist/model-form.js +11 -7
  92. package/dist/model.d.ts +20 -4
  93. package/dist/model.js +68 -9
  94. package/dist/native/history.d.ts +1 -1
  95. package/dist/native/history.js +2 -2
  96. package/dist/ollama-provider.d.ts +92 -0
  97. package/dist/ollama-provider.js +495 -0
  98. package/dist/openapi/agentrun-v2.openapi.json +2 -2
  99. package/dist/openapi.js +235 -41
  100. package/dist/page.d.ts +11 -3
  101. package/dist/page.js +22 -7
  102. package/dist/place-offers.d.ts +17 -1
  103. package/dist/place-offers.js +46 -5
  104. package/dist/print.js +1 -1
  105. package/dist/purged-workflow.d.ts +35 -7
  106. package/dist/purged-workflow.js +73 -26
  107. package/dist/run-computer.d.ts +2 -0
  108. package/dist/run-computer.js +2 -0
  109. package/dist/run-files.d.ts +4 -0
  110. package/dist/run-files.js +4 -0
  111. package/dist/run-keys.d.ts +2 -4
  112. package/dist/run-keys.js +6 -7
  113. package/dist/run-launch.d.ts +4 -0
  114. package/dist/run-launch.js +4 -0
  115. package/dist/run-reads-over-store.d.ts +3 -2
  116. package/dist/run-reads-over-store.js +66 -2
  117. package/dist/run-secrets.js +5 -2
  118. package/dist/runner/adapter-loop.d.ts +6 -3
  119. package/dist/runner/adapter-loop.js +34 -15
  120. package/dist/runner/adapter-run-spec.d.ts +3 -0
  121. package/dist/runner/adapter-run-spec.js +6 -4
  122. package/dist/runner/audit.js +8 -4
  123. package/dist/runner/beside.d.ts +2 -1
  124. package/dist/runner/beside.js +6 -2
  125. package/dist/runner/claim-secrets.d.ts +5 -8
  126. package/dist/runner/claim-secrets.js +6 -0
  127. package/dist/runner/cli-run-spec.d.ts +1 -1
  128. package/dist/runner/cli-run-spec.js +39 -7
  129. package/dist/runner/harness-loops.d.ts +22 -9
  130. package/dist/runner/harness-loops.js +21 -11
  131. package/dist/runner/held.d.ts +3 -0
  132. package/dist/runner/learning-end.d.ts +1 -1
  133. package/dist/runner/learning-end.js +8 -3
  134. package/dist/runner/loop-contract.d.ts +5 -4
  135. package/dist/runner/main.js +4 -2
  136. package/dist/runner/mcp-claim.d.ts +3 -0
  137. package/dist/runner/mcp-claim.js +26 -2
  138. package/dist/runner/mcp-run.d.ts +3 -0
  139. package/dist/runner/mcp-run.js +2 -1
  140. package/dist/runner/metrics.d.ts +10 -8
  141. package/dist/runner/metrics.js +20 -27
  142. package/dist/runner/model-route.d.ts +3 -0
  143. package/dist/runner/model-route.js +6 -2
  144. package/dist/runner/pr-checkout.d.ts +21 -4
  145. package/dist/runner/pr-checkout.js +103 -4
  146. package/dist/runner/promotion.d.ts +15 -9
  147. package/dist/runner/promotion.js +25 -15
  148. package/dist/runner/run-child-host.js +24 -11
  149. package/dist/runner/run-child.js +3 -1
  150. package/dist/runner/runner-check.d.ts +3 -0
  151. package/dist/runner/runner-check.js +23 -0
  152. package/dist/runner/sdk-loop.js +2 -0
  153. package/dist/runner/workflow-loop.d.ts +2 -2
  154. package/dist/runner/workflow-loop.js +1 -2
  155. package/dist/runner/workflow-spec.d.ts +1 -1
  156. package/dist/runner/workflow-spec.js +6 -6
  157. package/dist/sdk/check.d.ts +4 -1
  158. package/dist/sdk/check.js +2 -1
  159. package/dist/sdk/runs.d.ts +2 -2
  160. package/dist/sdk/runs.js +8 -6
  161. package/dist/secret-cut.js +2 -1
  162. package/dist/secret-writes.d.ts +3 -2
  163. package/dist/secret-writes.js +1 -1
  164. package/dist/server.d.ts +55 -8
  165. package/dist/server.js +363 -118
  166. package/dist/standard-webhooks.d.ts +11 -0
  167. package/dist/standard-webhooks.js +20 -2
  168. package/dist/store/agent-body.d.ts +2 -2
  169. package/dist/store/agent-body.js +2 -2
  170. package/dist/store/index.d.ts +1 -1
  171. package/dist/store/schema.js +5 -2
  172. package/dist/store/sqlite/store.js +90 -34
  173. package/dist/store/store.d.ts +54 -14
  174. package/dist/store-reads/journal.d.ts +7 -2
  175. package/dist/store-reads/journal.js +9 -6
  176. package/dist/store-reads/learning.d.ts +12 -9
  177. package/dist/store-reads/learning.js +18 -24
  178. package/dist/store-view.d.ts +0 -5
  179. package/dist/store-view.js +9 -8
  180. package/dist/suggestions.d.ts +282 -0
  181. package/dist/suggestions.js +919 -0
  182. package/dist/telemetry.d.ts +8 -1
  183. package/dist/telemetry.js +12 -4
  184. package/dist/template-eval.d.ts +49 -4
  185. package/dist/template-eval.js +168 -45
  186. package/dist/template-import.d.ts +17 -0
  187. package/dist/template-import.js +36 -2
  188. package/dist/templates.d.ts +83 -76
  189. package/dist/templates.js +29 -48
  190. package/dist/timeline/labels.d.ts +2 -2
  191. package/dist/timeline/labels.js +2 -2
  192. package/dist/timeline/timeline.d.ts +2 -2
  193. package/dist/timeline/timeline.js +1 -1
  194. package/dist/tool-plane.d.ts +17 -9
  195. package/dist/tool-plane.js +38 -17
  196. package/dist/tools.js +2 -2
  197. package/dist/trigger-launch-hook.d.ts +19 -9
  198. package/dist/trigger-launch-hook.js +35 -25
  199. package/dist/trigger-targets.d.ts +18 -8
  200. package/dist/trigger-targets.js +42 -19
  201. package/dist/triggers.d.ts +85 -23
  202. package/dist/triggers.js +303 -96
  203. package/dist/validate.d.ts +1 -1
  204. package/dist/validate.js +2 -2
  205. package/dist/web-fake.js +3 -3
  206. package/dist/web-fetch-direct.d.ts +4 -0
  207. package/dist/web-fetch-direct.js +8 -1
  208. package/dist/web-fetch.d.ts +12 -3
  209. package/dist/web-fetch.js +47 -14
  210. package/dist/web-search.d.ts +33 -4
  211. package/dist/web-search.js +100 -41
  212. package/dist/webhooks.js +4 -5
  213. package/dist/workspace/synced-folder.d.ts +1 -1
  214. package/dist/workspace/synced-folder.js +11 -14
  215. package/launcher/agentrun-serve +5 -1
  216. package/package.json +17 -13
  217. package/templates/README.md +5 -4
  218. package/templates/agent-scout/agent.md +46 -0
  219. package/templates/agent-scout/skills/scout/SKILL.md +88 -0
  220. package/templates/agent-scout/skills/scout/suggestions.schema.json +112 -0
  221. package/dist/console/assets/index-BFgyZzF_.js +0 -734
  222. package/dist/console/assets/index-DbilxljH.css +0 -1
  223. package/dist/import-sources.d.ts +0 -116
  224. package/dist/import-sources.js +0 -693
@@ -11,6 +11,10 @@ export declare const FAUX_GITHUB: {
11
11
  export type FauxGitHub = {
12
12
  /** Its API's base, which the server's Connect GitHub asks in place of GitHub's own; never a URL anyone gives. */
13
13
  url: string;
14
+ /** GitHub's site as a checkout fetches from it (runner/pr-checkout.ts `web`): a folder of bare repositories on this
15
+ * machine holding the fake's one repository, so a run's checkout of it never leaves the machine. Undefined when the
16
+ * start was given no folder for it. */
17
+ web?: string;
14
18
  /** The App as Connect GitHub keeps it (github-connection.ts GitHubConnection.save). */
15
19
  app: {
16
20
  id: string;
@@ -22,5 +26,10 @@ export type FauxGitHub = {
22
26
  };
23
27
  close(): Promise<void>;
24
28
  };
25
- /** Starts the fake GitHub API on loopback, with its App. */
26
- export declare function startFauxGitHub(): Promise<FauxGitHub>;
29
+ /** The fake repository's files on its default branch: what its contents API answers, and what its bare repository holds
30
+ * (a small help desk whose support queue and refunds a person works by hand, for a scan to find). */
31
+ export declare const FAUX_REPO_FILES: Readonly<Record<string, string>>;
32
+ /** Starts the fake GitHub API on loopback, with its App; with `webDir`, its repository as a bare git repository there. */
33
+ export declare function startFauxGitHub({ webDir }?: {
34
+ webDir?: string;
35
+ }): Promise<FauxGitHub>;
@@ -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,6 @@
1
1
  import type { InputIssue } from "./errors.js";
2
+ /** A handed key's characters: visible ASCII alone, no space. The API's schema states the same (openapi.ts). */
3
+ export declare const HANDED_SECRET: RegExp;
2
4
  /** Why `value` (text) is not a key a run can be handed at `field`, as a 422 issue that never shows it, or undefined for
3
- * one it can: MIN_SECRET to `max` characters with no space or control character. */
5
+ * one it can: MIN_SECRET to `max` characters of visible ASCII. */
4
6
  export declare function handedSecretOf(value: string, field: string, max: number): InputIssue | undefined;
@@ -1,10 +1,12 @@
1
1
  import { MIN_SECRET } from "./learn/secrets.js";
2
+ /** A handed key's characters: visible ASCII alone, no space. The API's schema states the same (openapi.ts). */
3
+ export const HANDED_SECRET = /^[\x21-\x7e]+$/;
2
4
  /** Why `value` (text) is not a key a run can be handed at `field`, as a 422 issue that never shows it, or undefined for
3
- * one it can: MIN_SECRET to `max` characters with no space or control character. */
5
+ * one it can: MIN_SECRET to `max` characters of visible ASCII. */
4
6
  export function handedSecretOf(value, field, max) {
5
7
  const wrong = value.length < MIN_SECRET ? `at least ${MIN_SECRET} characters: a shorter key can't be cut from what the run writes`
6
8
  : value.length > max ? `at most ${max} characters`
7
- : /[\s\x00-\x1f\x7f]/.test(value) ? "text with no space or control character"
9
+ : !HANDED_SECRET.test(value) ? "visible ASCII alone, with no space or control character: a key goes in a header"
8
10
  : undefined;
9
11
  return wrong === undefined ? undefined : { field, reason: "invalid", message: `${field} is ${wrong}.` };
10
12
  }
@@ -0,0 +1,98 @@
1
+ import type { PlanRecipe } from "./harness-table.js";
2
+ import { type SecretMeta } from "./secret-writes.js";
3
+ import { type SealedKeys } from "./store/index.js";
4
+ /** The console's page for these keys (Settings → Harness keys). */
5
+ export declare const HARNESS_KEYS_PAGE = "/#/settings/harness-keys";
6
+ /** The plane of a harness key's name (its row's, and its view's: harness:<harness>:<KEY>). */
7
+ export declare const HARNESS_KEY_PLANE = "harness";
8
+ /** How many replaced or removed values of one key stay sealed for the cut: the oldest beyond it leaves. */
9
+ export declare const RETIRED_KEPT = 8;
10
+ /** The row (and view) name of `key` saved for `harness`. */
11
+ export declare const harnessKeyRow: (harness: string, key: string) => string;
12
+ type HarnessKeysStore = {
13
+ readonly sealedKeys: Pick<SealedKeys, "all" | "get" | "put" | "remove">;
14
+ flush(): Promise<void>;
15
+ };
16
+ /** The keys of `names` saved for `harness` that open under `sealKey`, by name. One that does not open (another seal key, or
17
+ * damaged) reads as not saved, never a clear fallback. For a runner's claim, whose run is on that harness. */
18
+ export declare function openHarnessKeys(store: {
19
+ sealedKeys: Pick<SealedKeys, "get">;
20
+ }, sealKey: Buffer, harness: string, names: readonly string[]): Promise<Record<string, string>>;
21
+ /** Whether every key of `names` has a row saved for `harness` (its bytes never opened): a trigger's check, and a runner's
22
+ * claim before it opens them. */
23
+ export declare function harnessKeysSaved(store: {
24
+ sealedKeys: Pick<SealedKeys, "all">;
25
+ }, harness: string, names: readonly string[]): Promise<boolean>;
26
+ /** Whether a claim laid every key of `names` on `env` (layHarnessKeys: own, never enumerable, not empty), which is when
27
+ * a start takes the keys route (harness-recipe-entry.ts serverRoute). A variable of the same name the environment
28
+ * carries enumerable (one the operator's shell set) is never one: a run takes the keys saved for its harness alone. */
29
+ export declare function keysLaid(env: NodeJS.ProcessEnv, names: readonly string[]): boolean;
30
+ export declare const harnessKeysSavedHere: (data: string, harness: string) => boolean;
31
+ /** The words a run no person started (a schedule's, a trigger's, a learned workflow's audit shadow or replay:
32
+ * run-launch.ts personStarted) on a plan-billed recipe is refused in at its claim (runner/harness-loops.ts,
33
+ * runner/cli-run-spec.ts): such a run takes keys saved for that harness, never its owner's own sign-in, and not every
34
+ * one is saved, or not every one opened. */
35
+ export declare const RECIPE_SIGN_IN_PERSON_ONLY = "A run its owner did not start (a scheduled or triggered run, a learned workflow's audit or replay) on a harness recipe billed to its vendor's plan runs on keys saved for that harness, never on its owner's own sign-in, and not every one of its keys is saved: save them in Settings \u2192 Harness keys (/#/settings/harness-keys), start this run yourself, or run the agent on a harness billed through this server's model proxy.";
36
+ /** The words a trigger's message is refused in by a session its claim started with not every key of its plan-billed
37
+ * recipe laid (runner/adapter-loop.ts, the spec's personOnly): that session runs on its owner's own sign-in, or on
38
+ * nothing, whatever was saved since, so a turn no person sent never goes into it. */
39
+ export declare const RECIPE_TURN_PERSON_ONLY = "This run started on its owner's own sign-in (its harness recipe is billed to its vendor's plan, and its claim opened not every key saved for that harness), so a trigger's message never runs in it, keys saved since or not: message the run yourself, or target a run started once every key was saved in Settings \u2192 Harness keys (/#/settings/harness-keys).";
40
+ /** Lays `keys` on `env` where only a direct read finds them: never enumerable, so no spread, copy or child environment
41
+ * built from `env` carries them (claim-secrets.ts withModelKeys). */
42
+ export declare function layHarnessKeys(env: NodeJS.ProcessEnv, keys: Readonly<Record<string, string>>): void;
43
+ /** What one plan-billed recipe's keys look like in Settings → Harness keys: each key's SecretMeta (never a value), and
44
+ * whether every one is saved, which is when its runs take the keys route. */
45
+ export type HarnessKeysView = {
46
+ readonly id: string;
47
+ readonly label: string;
48
+ readonly keys: SecretMeta[];
49
+ readonly ready: boolean;
50
+ };
51
+ /** The saved harness keys over the one store, for the server (the one writer of these rows): a snapshot loaded once at
52
+ * start (load()) and kept in step with every write, so a read answers without a round trip. */
53
+ export declare class HarnessKeysOverStore {
54
+ private readonly store;
55
+ private readonly sealKey;
56
+ readonly recipes: readonly PlanRecipe[];
57
+ private readonly data;
58
+ private current;
59
+ private retired;
60
+ /** The last write in flight (save, remove): each waits for the one before it, so two that overlap never read the same
61
+ * value as the one they replace, and every value a claim may have opened is retired. */
62
+ private writing;
63
+ /** `work` once every write before it has settled, its failure its own. */
64
+ private serial;
65
+ /** `recipes`: the plan-billed recipes this server is started with (harness-table.ts planRecipesOf), the only harnesses
66
+ * whose keys it saves or shows. `data`: its data directory, which its registry (harnessKeysSavedHere) is kept under. */
67
+ constructor(store: HarnessKeysStore, sealKey: Buffer, recipes: readonly PlanRecipe[], data: string);
68
+ /** This server's registry (harnessKeysSavedHere) set from the snapshot: each recipe whose every key is saved. */
69
+ private mark;
70
+ /** Reads every harness key row once: each current one opened, each retired one opened for the cut. A row that does not
71
+ * open reads as not saved. */
72
+ load(): Promise<void>;
73
+ /** Whether every key `recipe` runs on is saved for it. */
74
+ saved(recipe: Pick<PlanRecipe, "id" | "keys">): boolean;
75
+ /** Every value to cut: each saved key's, and each retired one's still kept. */
76
+ values(): string[];
77
+ /** GET: `recipe`'s keys, each by name, whether saved and when it changed: never a value. */
78
+ view(recipe: PlanRecipe): HarnessKeysView;
79
+ /** GET /settings/harness-keys: every plan-billed recipe this server is started with, its keys by name. */
80
+ list(): {
81
+ harnesses: HarnessKeysView[];
82
+ };
83
+ /** The plan-billed recipe `id` names on this server, else 404. */
84
+ recipe(id: string): PlanRecipe;
85
+ /** PUT: `value` sealed as `key` for `recipe`'s harness alone; a value it replaces kept as a retired row. Durable before it
86
+ * resolves, so a 204 never outruns the store. */
87
+ save(recipe: PlanRecipe, key: string, body: unknown): Promise<void>;
88
+ /** DELETE: `key`'s value for `recipe`'s harness gone from its runs, kept as a retired row for the cut. A row the snapshot
89
+ * does not hold (one that does not open under this server's seal key) is removed too, so no claim counts it saved. */
90
+ remove(recipe: PlanRecipe, key: string): Promise<void>;
91
+ /** `value`, which `key` held, sealed as a retired row of its own; the oldest beyond RETIRED_KEPT leaves. */
92
+ private retire;
93
+ }
94
+ /** 404 for a harness that is not a plan-billed recipe on this server's table: its keys are saved nowhere. */
95
+ export declare function planRecipeOr404(recipes: readonly PlanRecipe[], id: string): PlanRecipe;
96
+ /** The bytes a value would be sealed as, for a test that checks a key is sealed at rest. */
97
+ export declare const sealedHarnessKeyBytes: (key: Buffer, harness: string, name: string, value: string) => Uint8Array;
98
+ export {};