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

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 (296) hide show
  1. package/CHANGELOG.md +261 -0
  2. package/README.md +228 -45
  3. package/dist/acp-package.d.ts +2 -0
  4. package/dist/adapters.d.ts +18 -5
  5. package/dist/adapters.js +23 -9
  6. package/dist/agent-package.d.ts +3 -3
  7. package/dist/agent-package.js +17 -8
  8. package/dist/answer-json.d.ts +6 -2
  9. package/dist/answer-json.js +22 -4
  10. package/dist/api-keys.d.ts +76 -0
  11. package/dist/api-keys.js +217 -0
  12. package/dist/api-only.d.ts +17 -5
  13. package/dist/api-only.js +36 -8
  14. package/dist/browser-hold.d.ts +23 -0
  15. package/dist/browser-hold.js +48 -0
  16. package/dist/browser-person.d.ts +3 -0
  17. package/dist/browser-person.js +4 -1
  18. package/dist/calendar/tools.js +3 -2
  19. package/dist/chatgpt-plan.d.ts +28 -3
  20. package/dist/chatgpt-plan.js +182 -21
  21. package/dist/claude-login.d.ts +101 -14
  22. package/dist/claude-login.js +232 -49
  23. package/dist/claude-sign-in.d.ts +46 -0
  24. package/dist/claude-sign-in.js +93 -0
  25. package/dist/cli.js +63 -6
  26. package/dist/composio-made.d.ts +4 -0
  27. package/dist/composio-made.js +4 -0
  28. package/dist/composio-preset.d.ts +43 -2
  29. package/dist/composio-preset.js +92 -4
  30. package/dist/computer-held-routes.d.ts +5 -4
  31. package/dist/computer-held-routes.js +29 -8
  32. package/dist/computer-held.d.ts +6 -1
  33. package/dist/computer-held.js +14 -0
  34. package/dist/computer-record.js +4 -2
  35. package/dist/computer-viewer.js +4 -1
  36. package/dist/console/assets/{backend-D5EmB4N3.js → backend-DVhHzJX2.js} +19 -19
  37. package/dist/console/assets/index-Bwn1oTem.css +1 -0
  38. package/dist/console/assets/index-okP-y8PK.js +747 -0
  39. package/dist/console/index.html +2 -2
  40. package/dist/decisions.d.ts +1 -1
  41. package/dist/decisions.js +1 -1
  42. package/dist/docker-host-addresses.d.ts +22 -11
  43. package/dist/docker-host-addresses.js +38 -26
  44. package/dist/env-switch.d.ts +10 -0
  45. package/dist/env-switch.js +33 -2
  46. package/dist/errors.d.ts +1 -0
  47. package/dist/errors.js +2 -0
  48. package/dist/fal-price.d.ts +58 -20
  49. package/dist/fal-price.js +341 -82
  50. package/dist/handed-values.d.ts +43 -1
  51. package/dist/handed-values.js +119 -2
  52. package/dist/harness-archive.d.ts +13 -10
  53. package/dist/harness-archive.js +60 -34
  54. package/dist/harness-check.d.ts +3 -1
  55. package/dist/harness-check.js +25 -46
  56. package/dist/harness-keys.d.ts +73 -27
  57. package/dist/harness-keys.js +194 -61
  58. package/dist/harness-recipe-entry.d.ts +8 -7
  59. package/dist/harness-recipe-entry.js +21 -32
  60. package/dist/harness-recipe.d.ts +38 -25
  61. package/dist/harness-recipe.js +49 -36
  62. package/dist/harness-sign-in.js +12 -23
  63. package/dist/harness-table.d.ts +10 -3
  64. package/dist/harness-table.js +26 -21
  65. package/dist/harness.d.ts +1 -0
  66. package/dist/harness.js +17 -5
  67. package/dist/host-check.d.ts +4 -0
  68. package/dist/host-check.js +4 -0
  69. package/dist/hosted-search.d.ts +1 -1
  70. package/dist/hosted-search.js +1 -2
  71. package/dist/import-worker.d.ts +4 -2
  72. package/dist/import-worker.js +9 -2
  73. package/dist/in-flight.d.ts +26 -0
  74. package/dist/in-flight.js +52 -0
  75. package/dist/key-refusal.d.ts +26 -5
  76. package/dist/key-refusal.js +313 -37
  77. package/dist/learn/secrets.d.ts +31 -11
  78. package/dist/learn/secrets.js +152 -191
  79. package/dist/learning-cost.d.ts +6 -3
  80. package/dist/learning-cost.js +4 -2
  81. package/dist/link-check.js +1 -1
  82. package/dist/llms.txt +2 -2
  83. package/dist/marketplace.d.ts +77 -0
  84. package/dist/marketplace.js +224 -0
  85. package/dist/mcp-api-only-origins.d.ts +30 -0
  86. package/dist/mcp-api-only-origins.js +57 -0
  87. package/dist/mcp-gateway.d.ts +7 -5
  88. package/dist/mcp-gateway.js +9 -12
  89. package/dist/mcp-secret-writes.js +5 -3
  90. package/dist/mcp-servers-store.d.ts +28 -6
  91. package/dist/mcp-servers-store.js +53 -4
  92. package/dist/media-duration.d.ts +3 -0
  93. package/dist/media-duration.js +90 -9
  94. package/dist/model-form.d.ts +5 -4
  95. package/dist/model-form.js +11 -7
  96. package/dist/model.d.ts +5 -2
  97. package/dist/model.js +9 -5
  98. package/dist/ollama-provider.d.ts +7 -1
  99. package/dist/ollama-provider.js +14 -2
  100. package/dist/openapi.d.ts +3 -3
  101. package/dist/openapi.js +245 -42
  102. package/dist/otel/genai.d.ts +65 -0
  103. package/dist/otel/genai.js +116 -0
  104. package/dist/otel/tracer.d.ts +55 -0
  105. package/dist/otel/tracer.js +308 -0
  106. package/dist/page.d.ts +2 -0
  107. package/dist/page.js +3 -1
  108. package/dist/paid-calls.d.ts +1 -32
  109. package/dist/paid-calls.js +4 -39
  110. package/dist/place-offers.d.ts +14 -6
  111. package/dist/place-offers.js +26 -13
  112. package/dist/provider.d.ts +9 -0
  113. package/dist/provider.js +50 -3
  114. package/dist/redact/match.d.ts +101 -0
  115. package/dist/redact/match.js +1152 -0
  116. package/dist/refusal-words.d.ts +11 -0
  117. package/dist/refusal-words.js +11 -0
  118. package/dist/run-census.d.ts +67 -0
  119. package/dist/run-census.js +240 -0
  120. package/dist/run-computer.d.ts +6 -3
  121. package/dist/run-computer.js +4 -1
  122. package/dist/run-cut.d.ts +15 -6
  123. package/dist/run-cut.js +30 -9
  124. package/dist/run-files.d.ts +3 -0
  125. package/dist/run-files.js +3 -0
  126. package/dist/run-launch.d.ts +12 -1
  127. package/dist/run-launch.js +9 -10
  128. package/dist/run-learning-served.d.ts +2 -0
  129. package/dist/run-model-key.d.ts +8 -0
  130. package/dist/run-model-key.js +31 -1
  131. package/dist/run-reads-over-store.d.ts +24 -6
  132. package/dist/run-reads-over-store.js +67 -23
  133. package/dist/run-recordings.d.ts +5 -1
  134. package/dist/run-recordings.js +39 -14
  135. package/dist/run-timeline-served.d.ts +3 -1
  136. package/dist/run-timeline-served.js +4 -4
  137. package/dist/run-usage.d.ts +1 -0
  138. package/dist/runnable.d.ts +10 -1
  139. package/dist/runnable.js +20 -8
  140. package/dist/runner/adapter-loop.d.ts +14 -0
  141. package/dist/runner/adapter-loop.js +56 -11
  142. package/dist/runner/adapter-run-spec.d.ts +45 -8
  143. package/dist/runner/adapter-run-spec.js +154 -29
  144. package/dist/runner/adapters/pi.js +25 -3
  145. package/dist/runner/beside.js +11 -6
  146. package/dist/runner/big-writes.js +1 -10
  147. package/dist/runner/claim-secrets.d.ts +18 -3
  148. package/dist/runner/claim-secrets.js +35 -6
  149. package/dist/runner/cli-run-spec.d.ts +6 -0
  150. package/dist/runner/cli-run-spec.js +85 -36
  151. package/dist/runner/computer-journal.d.ts +9 -1
  152. package/dist/runner/computer-journal.js +26 -0
  153. package/dist/runner/conformance/harness.js +1 -1
  154. package/dist/runner/feedback-round.js +3 -0
  155. package/dist/runner/harness-loops.d.ts +6 -5
  156. package/dist/runner/harness-loops.js +7 -7
  157. package/dist/runner/held.d.ts +11 -5
  158. package/dist/runner/journal-kinds.d.ts +5 -0
  159. package/dist/runner/journal-kinds.js +5 -0
  160. package/dist/runner/loop-contract.d.ts +4 -0
  161. package/dist/runner/main.js +15 -6
  162. package/dist/runner/mcp-claim.js +30 -3
  163. package/dist/runner/mcp-run.d.ts +12 -0
  164. package/dist/runner/mcp-run.js +12 -5
  165. package/dist/runner/model-route.d.ts +17 -0
  166. package/dist/runner/model-route.js +120 -2
  167. package/dist/runner/presence.d.ts +4 -3
  168. package/dist/runner/presence.js +4 -2
  169. package/dist/runner/run-child-host.d.ts +5 -0
  170. package/dist/runner/run-child-host.js +71 -30
  171. package/dist/runner/run-child.js +5 -2
  172. package/dist/runner/runner.d.ts +18 -3
  173. package/dist/runner/runner.js +162 -36
  174. package/dist/runner/store-port.d.ts +1 -1
  175. package/dist/runner/store-secrets.d.ts +6 -0
  176. package/dist/runner/store-secrets.js +49 -7
  177. package/dist/runner/subagent.js +4 -40
  178. package/dist/runner/workflow-first.d.ts +11 -4
  179. package/dist/runner/workflow-first.js +14 -8
  180. package/dist/runner/workflow-spec.js +3 -2
  181. package/dist/runs-over-store.d.ts +15 -6
  182. package/dist/runs-over-store.js +33 -21
  183. package/dist/scrub-command.d.ts +73 -0
  184. package/dist/scrub-command.js +307 -0
  185. package/dist/secret-cut.d.ts +73 -0
  186. package/dist/secret-cut.js +291 -4
  187. package/dist/secret-rules.d.ts +143 -0
  188. package/dist/secret-rules.js +2564 -0
  189. package/dist/secrets.d.ts +7 -0
  190. package/dist/secrets.js +20 -0
  191. package/dist/server-keys.d.ts +20 -0
  192. package/dist/server-keys.js +25 -6
  193. package/dist/server.d.ts +57 -13
  194. package/dist/server.js +371 -113
  195. package/dist/skills/agentrun-serve/SKILL.md +4 -0
  196. package/dist/store/dialect.d.ts +3 -0
  197. package/dist/store/dialect.js +1 -0
  198. package/dist/store/index.d.ts +1 -1
  199. package/dist/store/index.js +1 -1
  200. package/dist/store/journal/storage.js +1 -1
  201. package/dist/store/postgres/dialect.js +3 -0
  202. package/dist/store/postgres/migrations/0027_run_launch_census.sql +31 -0
  203. package/dist/store/schema.d.ts +6 -0
  204. package/dist/store/schema.js +11 -1
  205. package/dist/store/seal.d.ts +6 -1
  206. package/dist/store/seal.js +5 -3
  207. package/dist/store/sqlite/run-launch.d.ts +9 -1
  208. package/dist/store/sqlite/run-launch.js +24 -13
  209. package/dist/store/sqlite/run-patch.d.ts +1 -1
  210. package/dist/store/sqlite/run-patch.js +13 -4
  211. package/dist/store/sqlite/store.js +76 -16
  212. package/dist/store/store.d.ts +53 -3
  213. package/dist/store/store.js +27 -0
  214. package/dist/store-reads/learning.d.ts +6 -3
  215. package/dist/store-reads/learning.js +22 -7
  216. package/dist/store-view.d.ts +3 -0
  217. package/dist/store-view.js +4 -4
  218. package/dist/suggestions.js +3 -2
  219. package/dist/template-eval.d.ts +22 -11
  220. package/dist/template-eval.js +124 -41
  221. package/dist/template-import.d.ts +10 -0
  222. package/dist/template-import.js +16 -7
  223. package/dist/templates.d.ts +10 -2
  224. package/dist/templates.js +28 -8
  225. package/dist/timeline/index.d.ts +1 -1
  226. package/dist/timeline/index.js +1 -1
  227. package/dist/timeline/labels.d.ts +6 -4
  228. package/dist/timeline/labels.js +18 -6
  229. package/dist/timeline/timeline.d.ts +17 -7
  230. package/dist/timeline/timeline.js +28 -14
  231. package/dist/timeline/util.js +1 -1
  232. package/dist/timeline/web-calls.d.ts +26 -9
  233. package/dist/timeline/web-calls.js +124 -37
  234. package/dist/tool-gate.d.ts +42 -3
  235. package/dist/tool-gate.js +69 -6
  236. package/dist/tool-keys-store.d.ts +2 -4
  237. package/dist/tool-keys-store.js +5 -21
  238. package/dist/tool-keys.d.ts +2 -2
  239. package/dist/tool-keys.js +2 -2
  240. package/dist/tool-list.js +1 -1
  241. package/dist/tool-plane.d.ts +2 -2
  242. package/dist/tool-plane.js +35 -33
  243. package/dist/tools.js +13 -7
  244. package/dist/trigger-targets.d.ts +4 -0
  245. package/dist/trigger-targets.js +9 -2
  246. package/dist/triggers.d.ts +67 -4
  247. package/dist/triggers.js +171 -22
  248. package/dist/until.d.ts +3 -0
  249. package/dist/until.js +11 -0
  250. package/dist/validate.js +1 -1
  251. package/dist/web-fake.d.ts +1 -3
  252. package/dist/web-fake.js +7 -18
  253. package/dist/web-fetch.d.ts +6 -72
  254. package/dist/web-fetch.js +11 -265
  255. package/dist/web-run.d.ts +31 -0
  256. package/dist/web-run.js +90 -0
  257. package/dist/web-save.d.ts +6 -4
  258. package/dist/web-save.js +9 -12
  259. package/dist/web-search.d.ts +9 -127
  260. package/dist/web-search.js +23 -259
  261. package/dist/wires.d.ts +13 -0
  262. package/dist/wires.js +11 -0
  263. package/dist/workflow-run.d.ts +5 -4
  264. package/dist/workflow-run.js +5 -4
  265. package/dist/workspace/computer-deps.d.ts +3 -1
  266. package/dist/workspace/computer-deps.js +12 -4
  267. package/dist/workspace/computer-for-claim.d.ts +19 -2
  268. package/dist/workspace/computer-for-claim.js +101 -13
  269. package/dist/workspace/computer-janitor.d.ts +15 -7
  270. package/dist/workspace/computer-janitor.js +33 -8
  271. package/dist/workspace/computer-kept.d.ts +55 -4
  272. package/dist/workspace/computer-kept.js +129 -8
  273. package/dist/workspace/index.d.ts +1 -1
  274. package/dist/workspace/index.js +1 -1
  275. package/dist/workspace/kind-skills.d.ts +4 -0
  276. package/dist/workspace/kind-skills.js +9 -0
  277. package/dist/workspace/run-end-computers.d.ts +5 -1
  278. package/dist/workspace/run-end-computers.js +27 -1
  279. package/dist/workspace/synced-folder.js +3 -4
  280. package/dist/wrapped.d.ts +65 -0
  281. package/dist/wrapped.js +77 -0
  282. package/package.json +17 -11
  283. package/skills/agentrun-serve/SKILL.md +4 -0
  284. package/templates/README.md +38 -15
  285. package/dist/console/assets/index-DUYLaqiR.js +0 -746
  286. package/dist/console/assets/index-DYhU4adm.css +0 -1
  287. package/dist/exa-keyless.d.ts +0 -34
  288. package/dist/exa-keyless.js +0 -118
  289. package/dist/firecrawl-keyless.d.ts +0 -41
  290. package/dist/firecrawl-keyless.js +0 -152
  291. package/dist/keyless-mcp.d.ts +0 -36
  292. package/dist/keyless-mcp.js +0 -127
  293. package/dist/text-urls.d.ts +0 -38
  294. package/dist/text-urls.js +0 -170
  295. package/dist/web-fetch-direct.d.ts +0 -119
  296. package/dist/web-fetch-direct.js +0 -190
package/dist/adapters.js CHANGED
@@ -14,7 +14,7 @@ import { facts as openCodeFacts } from "./harness-opencode/facts.js";
14
14
  import { CLAUDE_SDK, codexBinaryIn, HarnessNotInstalled, installDirOf, installLine, loadSdk } from "./harness-install.js";
15
15
  import { DATA_ENV, defaultData } from "./files.js";
16
16
  import { harnessOf, onAdapter } from "./harness-table.js";
17
- import { HarnessUnavailable, providerFor } from "./provider.js";
17
+ import { HarnessUnavailable, heldRefusedProvider, providerFor } from "./provider.js";
18
18
  import { keyShaped } from "./secret-cut.js";
19
19
  import { servedSkills } from "./learn/workflow-draft.js";
20
20
  import { runKeyOf } from "./key-refusal.js";
@@ -83,8 +83,9 @@ const freeName = (base, exists) => {
83
83
  return name;
84
84
  };
85
85
  /**
86
- * A start `npx @parcha/agentrun` made (NPX_PACKAGE_ENV) that a data directory refused because an earlier version wrote it
87
- * (store.ts StoreFromEarlierVersion, or SchemaVersionUnknown on an earlier release's store): the refusal's own first line,
86
+ * A start the agentrun launcher made (NPX_PACKAGE_ENV: by npx, or by the installer's bin/agentrun and its service, the
87
+ * same launcher) that a data directory refused because an earlier version wrote it (store.ts StoreFromEarlierVersion,
88
+ * or SchemaVersionUnknown on an earlier release's store): the refusal's own first line,
88
89
  * then the two ways on as commands to paste. That command keeps its data in ~/.agentrun wherever it is run, so a new
89
90
  * folder alone is not a new AgentRun. First, the old folder moved aside whole, so the same command starts this version
90
91
  * where it was, and the earlier version still opens what it holds; then this version on a new, empty folder: the same
@@ -108,7 +109,9 @@ export function earlierDataRefusal(error, data, env = {}, exists = existsSync) {
108
109
  const again = `${command}${dir === launcherData ? "" : ` --data ${shellWord(dir)}`}${flags}`;
109
110
  const fresh = freeName(`${dir}-new`, exists);
110
111
  const aside = freeName(`${dir}-earlier`, exists);
111
- const installed = exists(join(dir, "bin", "agentrun")) ? " Its bin/agentrun (the earlier installer's command) moves with it: run the installer again for this version's." : "";
112
+ // install.sh keeps its Node, its packages and the command in the folder beside the data (node/, lib/, bin/agentrun):
113
+ // that command, or the service that runs it, may be what started this. Moved, they go too, whichever version they are.
114
+ const installed = exists(join(dir, "bin", "agentrun")) ? " That takes the agentrun the installer put there with it (its Node in node/, lib/ and bin/agentrun): run the installer again to put this version's back." : "";
112
115
  return [
113
116
  refused.message.split("\n")[0],
114
117
  // Moved aside first: every later command (doctor, the harness commands, the service) then finds this version where it
@@ -208,6 +211,10 @@ function unavailable(facts, error, npx, env) {
208
211
  const hinted = installHint(said, facts.install.npmLine, facts.install.spec, npx, env);
209
212
  return new HarnessUnavailable(hinted, hinted === said ? fixOf(facts, error) : undefined);
210
213
  }
214
+ /** Where a run's adapter sends its model's requests (providerFor), or, for a held run its model kept from running at its
215
+ * create, the stand-in (heldRefusedProvider): no key is read, and its proxy refuses every request in the create's words,
216
+ * sending none. */
217
+ export const providerOf = (wire, env, needs, who) => needs.heldRefusal !== undefined ? heldRefusedProvider(needs.model, needs.heldRefusal) : providerFor(wire, env, needs.model, who);
211
218
  /** The ConfineChild that starts a child under `prefix` (the argv pi's commands start under, ending in "--"); none when
212
219
  * the run confines nothing (macOS), since an adapter refuses a confinement that adds nothing. */
213
220
  export function confineOf(prefix) {
@@ -293,12 +300,16 @@ export async function packageSkillCheck(load) {
293
300
  const pkg = (await load());
294
301
  return typeof pkg?.skillProblems === "function" ? pkg.skillProblems : undefined;
295
302
  }
303
+ /** Whether a run's web_search is its harness's own search: the run's plane resolves it native and the harness has a search
304
+ * of its own (its facts' webSearch: claude-agent's, codex's). Its adapter then searches (nativeOptions), and the run is
305
+ * not also handed the host's web_search (cli-run-spec.ts), which would sit beside it. */
306
+ export const ownSearchRuns = (facts, plane) => plane?.web_search === "native" && Boolean(facts?.webSearch);
296
307
  /** What a harness's adapter takes from the run's plane (tool-plane.ts) where web_search resolves native, by its own search
297
308
  * (its facts' webSearch): `native`, the provider's search through its proxy, with the input a search request may read in
298
309
  * beyond its body (cap.ts), which its proxy adds to that request's bound; `live`, its own live search (its adapter books
299
310
  * each search); nothing for a harness with none. */
300
311
  export function nativeOptions(facts, env) {
301
- if (planeOf(env).web_search !== "native" || !facts.webSearch)
312
+ if (!ownSearchRuns(facts, planeOf(env)))
302
313
  return {};
303
314
  return facts.webSearch === "native" ? { webSearch: true, webSearchAllowance: NATIVE_SEARCH_ALLOWANCE_TOKENS } : { webSearch: "live" };
304
315
  }
@@ -319,7 +330,7 @@ export async function claudeOf(env, needs, load = loadClaude, sdkOf = (version,
319
330
  let provider;
320
331
  let refused;
321
332
  try {
322
- provider = providerFor(claudeFacts.wire, env, needs.model, claudeFacts.id);
333
+ provider = providerOf(claudeFacts.wire, env, needs, claudeFacts.id);
323
334
  }
324
335
  catch (error) {
325
336
  refused = error;
@@ -331,6 +342,9 @@ export async function claudeOf(env, needs, load = loadClaude, sdkOf = (version,
331
342
  // (providerFor's modelId); the key goes as the endpoint takes it, and the run is priced by the catalog entry of
332
343
  // whoever bills it (its priceModel).
333
344
  const endpoint = provider ? { origin: provider.origin, credential: provider.credential, auth: provider.auth, ...(provider.headers ? { headers: provider.headers } : {}) } : { origin: "", credential: () => "" };
345
+ // A model the route translates onto the wire (an Ollama model): its proxy forwards with the route's own fetch, and the
346
+ // provider's own web search (nativeOptions), which the translation cannot run, is not offered.
347
+ const forward = provider?.fetch ? { fetch: provider.fetch } : {};
334
348
  const priced = provider ? { ...needs, model: provider.priceModel } : native;
335
349
  // Its CLI checked off the event loop first (hashed and run as a child), so the server goes on answering: a pass is
336
350
  // kept, and the adapter's own check answers from it. A CLI that fails its pins is the adapter's to report, in its
@@ -340,7 +354,7 @@ export async function claudeOf(env, needs, load = loadClaude, sdkOf = (version,
340
354
  // On Claude Code's login on this machine: the login's directories in place of a provider, billed to the plan, never
341
355
  // priced here.
342
356
  const source = provider?.login ? { login: provider.login, price: () => null } : { provider: endpoint, price: priceOf(priced) };
343
- adapter = claude.claudeAgentAdapter({ model: { default: provider?.modelId ?? native.model.modelId }, ...source, log: harnessLog(claudeFacts.id, env), sdk: sdk.sdk, sdkVersion: sdk.sdkVersion, cliPath: sdk.cliPath, mcp: sdk.mcp, ...(needs.confine ? { confine: needs.confine } : {}), ...(needs.skills?.length ? { skills: needs.skills } : {}), ...(needs.now ? { now: needs.now } : {}), ...(needs.zone ? { zone: needs.zone } : {}), ...nativeOptions(claudeFacts, env) });
357
+ adapter = claude.claudeAgentAdapter({ model: { default: provider?.modelId ?? native.model.modelId }, ...source, log: harnessLog(claudeFacts.id, env), sdk: sdk.sdk, sdkVersion: sdk.sdkVersion, cliPath: sdk.cliPath, mcp: sdk.mcp, ...(needs.confine ? { confine: needs.confine } : {}), ...(needs.skills?.length ? { skills: needs.skills } : {}), ...(needs.now ? { now: needs.now } : {}), ...(needs.zone ? { zone: needs.zone } : {}), ...(provider?.fetch ? forward : nativeOptions(claudeFacts, env)) });
344
358
  }
345
359
  catch (error) {
346
360
  // The adapter's own install line is a project's; here Claude Code is installed into the data's harnesses directory.
@@ -384,7 +398,7 @@ export async function codexOf(env, needs, load = () => import("@parcha/agentrun-
384
398
  // whole (AGENT_MODEL_GATEWAY_IDS says whether it is provider-qualified), OpenAI's model id, which chooseModel has
385
399
  // already taken out of "openai/<id>", or OpenRouter's whole slug.
386
400
  // On a ChatGPT plan: the plan's rules on its route (no output limit, no input count), billed to it, never priced here.
387
- const provider = providerFor(codexFacts.wire, env, needs.model, codexFacts.id);
401
+ const provider = providerOf(codexFacts.wire, env, needs, codexFacts.id);
388
402
  const plan = provider.billing === "plan";
389
403
  return codex.codexAdapter({ model: provider.modelId, provider: { origin: provider.origin, credential: provider.credential, ...(plan ? { plan } : {}), ...(provider.refused ? { refused: provider.refused } : {}) }, price: plan ? () => null : priceOf({ ...needs, model: provider.priceModel }), log: harnessLog(codexFacts.id, env), ...(nativeOptions(codexFacts, env).webSearch === "live" ? { webSearch: "live" } : {}), ...(needs.confine ? { confine: needs.confine } : {}), ...(needs.skills?.length ? { skills: needs.skills } : {}), ...(standIn ? { standIn } : binary ? { binary } : {}) });
390
404
  }
@@ -408,7 +422,7 @@ export async function opencodeOf(env, needs, load = () => import("./harness-open
408
422
  // The shared date line (environment.ts) reaches OpenCode in the session's system prompt (app.ts), as it reaches every
409
423
  // harness.
410
424
  // The id as the provider's endpoint names it (providerFor, as codexOf takes it): OpenRouter's is the whole slug.
411
- const provider = providerFor(openCodeFacts.wire, env, needs.model, openCodeFacts.id);
425
+ const provider = providerOf(openCodeFacts.wire, env, needs, openCodeFacts.id);
412
426
  // Its instructions list each skill by the description its SKILL.md's front matter gives on one LF line, which is all the
413
427
  // adapter reads: each SKILL.md goes as servedSkill writes it (its name and description, as a prompt reads them, on one
414
428
  // line each), so a CRLF file or a folded description is listed by its own words.
@@ -8,7 +8,7 @@ export type PackageFile = {
8
8
  };
9
9
  /** What an export's note can be about: the document's enum of them (openapi.ts), so a note of a kind not here fails the
10
10
  * build, and an answer the document does not list fails its schema check. */
11
- export declare const EXPORT_NOTE_KINDS: readonly ["mcp_server", "trigger", "pin", "tool_setting", "tool_policy", "computer", "paired_computer", "sign_in", "learning", "input_schema", "budget", "package"];
11
+ export declare const EXPORT_NOTE_KINDS: readonly ["mcp_server", "trigger", "pin", "tool_setting", "tool_policy", "computer", "paired_computer", "sign_in", "learning", "secrets", "input_schema", "budget", "package"];
12
12
  /** One thing an export could not carry as it is here: what it is, which one, and why, in words. */
13
13
  export type ExportNote = {
14
14
  kind: (typeof EXPORT_NOTE_KINDS)[number];
@@ -46,8 +46,8 @@ export type ExportInput = {
46
46
  definition: Json;
47
47
  /** The revision's skill files, by path under the agent's skills folder. */
48
48
  skills: Readonly<Record<string, string>>;
49
- /** The package the agent was applied from (agentView's `template`) with the key names its apply kept, and that package
50
- * as this server holds it now. */
49
+ /** The package the agent was applied from (agentView's `template`) with the key names its apply kept (absent on a
50
+ * revision applied before an apply kept them), and that package as this server holds it now. */
51
51
  template: {
52
52
  id: string;
53
53
  version: string;
@@ -8,7 +8,7 @@
8
8
  import { createHash } from "node:crypto";
9
9
  import { stringify } from "yaml";
10
10
  import { LOOPBACK } from "./mcp-oauth.js";
11
- import { INPUT_KEYS, ITEM_KEYS, MANIFEST, memoryFiles, onServerNames, PackageError, readPackage } from "./templates.js";
11
+ import { INPUT_KEYS, ITEM_KEYS, MANIFEST, memoryFiles, onServerNames, PackageError, readPackage, uncappedTriggers } from "./templates.js";
12
12
  import { isMcpName, isMonidName, mcpToolName, parseToolName } from "./tool-names.js";
13
13
  import { isPinKeys, permissionKeys, SHELL_FAMILY } from "./tool-gate.js";
14
14
  import { toolOf } from "./tools.js";
@@ -18,7 +18,7 @@ import { isObject, MODEL_TIER_NAMES, stable } from "./validate.js";
18
18
  import { PAIRED_ID_PREFIX } from "./workspace/attached-computers.js";
19
19
  /** What an export's note can be about: the document's enum of them (openapi.ts), so a note of a kind not here fails the
20
20
  * build, and an answer the document does not list fails its schema check. */
21
- export const EXPORT_NOTE_KINDS = ["mcp_server", "trigger", "pin", "tool_setting", "tool_policy", "computer", "paired_computer", "sign_in", "learning", "input_schema", "budget", "package"];
21
+ export const EXPORT_NOTE_KINDS = ["mcp_server", "trigger", "pin", "tool_setting", "tool_policy", "computer", "paired_computer", "sign_in", "learning", "secrets", "input_schema", "budget", "package"];
22
22
  /** The package's digest: sha256, in hex, over its files sorted by path, each written as `path NUL bytes NUL`. */
23
23
  export function packageSha256(files) {
24
24
  const hash = createHash("sha256");
@@ -285,8 +285,11 @@ export function agentPackage(input) {
285
285
  const inputs = inputSchema && inputsOf(inputSchema);
286
286
  if (inputSchema && !inputs)
287
287
  blocked.push({ kind: "input_schema", name: "inputs", reason: "Its input schema is not a closed object of fields, which is what a package's inputs are." });
288
- // The keys its package declared, as its apply kept them.
288
+ // The keys its package declared, as its apply kept them. A revision applied before an apply kept them names none here,
289
+ // so the package says none, and the note says the target sets them up.
289
290
  const secrets = [...new Set([...(template?.secrets ?? []), ...((plain ?? []).some(isMonidName) ? ["MONID_API_KEY"] : [])])].sort();
291
+ if (template && !template.secrets)
292
+ remade.push({ kind: "secrets", name: template.id, reason: `The key names version ${template.version} of ${template.id} declares were not kept when it was applied here, so the package names none: save the keys the agent uses on the target, and name them under secrets in ${MANIFEST}.` });
290
293
  const bash = settings.bash?.policy;
291
294
  // Bash's policy holds every shell tool, and a package writes it only beside bash: a shell tool kept without bash would
292
295
  // run there what the policy refuses here.
@@ -294,15 +297,21 @@ export function agentPackage(input) {
294
297
  if (typeof bash === "string" && shellKept.length && !shellKept.includes("bash"))
295
298
  blocked.push({ kind: "tool_policy", name: "bash", reason: `Its bash policy (${bash}) holds ${shellKept.join(", ")}, and a package writes that policy only beside bash: grant bash too, or take ${shellKept.length === 1 ? "it" : "them"} out of the agent.` });
296
299
  const description = (agent.description?.trim() || agent.name).slice(0, 1024);
297
- // A package's budget is a spend cap per run first, and one with triggers has one: what fires runs nobody watches.
300
+ // A package's budget is a spend cap per run first. Every run a package's trigger starts is capped, what fires runs
301
+ // nobody watches: by the budget (the agent's max_cost_usd), else by the trigger's own cap, as readPackage holds it
302
+ // (uncappedTriggers). A trigger with neither is blocked, and left out, so the read-back does not name it again.
298
303
  const cost = typeof definition.max_cost_usd === "number" ? definition.max_cost_usd : undefined;
299
304
  const requests = typeof definition.max_requests === "number" ? definition.max_requests : undefined;
300
305
  if (cost === undefined && requests !== undefined)
301
306
  blocked.push({ kind: "budget", name: "max_requests", reason: "It caps each run's requests and not its spend, and a package's budget is a spend cap per run: set the agent's max_cost_usd." });
302
- if (cost === undefined && triggers.length) {
303
- blocked.push({ kind: "budget", name: "max_cost_usd", reason: "It has triggers and no spend cap per run, and a package with triggers caps what each run they fire may spend: set the agent's max_cost_usd." });
304
- triggers.length = 0;
305
- remade.splice(0, remade.length, ...remade.filter((note) => note.kind !== "trigger"));
307
+ const uncapped = cost === undefined ? uncappedTriggers(triggers) : [];
308
+ if (uncapped.length) {
309
+ const names = new Set(uncapped.map((one) => one.name));
310
+ for (const name of names)
311
+ blocked.push({ kind: "trigger", name, reason: "It has no spend cap of its own and the agent has no max_cost_usd, and every run a package's trigger starts is capped: give the trigger's target a max_cost_usd, or set the agent's max_cost_usd." });
312
+ const left = triggers.filter((_, index) => !uncapped.some((one) => one.index === index));
313
+ triggers.splice(0, triggers.length, ...left);
314
+ remade.splice(0, remade.length, ...remade.filter((note) => !(note.kind === "trigger" && names.has(note.name))));
306
315
  }
307
316
  // The manifest, in the order templates.ts reads its fields.
308
317
  const manifest = {
@@ -1,7 +1,11 @@
1
1
  import { Compile } from "typebox/schema";
2
2
  /** The text of the last fenced `json` block in `text` (```json or a longer fence, ~~~ too), or undefined. */
3
3
  export declare function lastJsonBlock(text: string): string | undefined;
4
- /** The answer's last fenced json block, parsed, or why there is none. */
4
+ /** An answer's json block: its last fenced `json` block, else the whole answer when its trimmed text is one JSON object
5
+ * and nothing else (a reply that is the object alone). The one rule every reader of an answer's JSON keeps: a run's
6
+ * output, a template eval's target and its grader's verdict. */
7
+ export declare function jsonBlockOf(text: string): string | undefined;
8
+ /** The answer's json block (jsonBlockOf), parsed, or why there is none. */
5
9
  export declare function answerJson(answer: string): {
6
10
  value: unknown;
7
11
  } | {
@@ -33,7 +37,7 @@ export declare const outputRetryWords: (why: string) => string;
33
37
  /** Why `answer` misses `schema`, in the retry's words (structuredAnswer's why, less MISSES), or undefined when it meets
34
38
  * it. Undefined too when the schema does not compile (a save refuses one): asking the model again cannot mend a schema. */
35
39
  export declare function outputMiss(answer: string, schema: unknown): string | undefined;
36
- /** A final answer's structured part against an agent's output schema: the value of its last fenced json block when it
40
+ /** A final answer's structured part against an agent's output schema: the value of its json block (jsonBlockOf) when it
37
41
  * meets the schema, else why not (no block, not JSON, the first problems against the schema). */
38
42
  export declare function structuredAnswer(answer: string, schema: unknown): {
39
43
  value: unknown;
@@ -1,4 +1,5 @@
1
- // An answer's structured part: the last fenced `json` block of a final answer, parsed, and checked against an agent's
1
+ // An answer's structured part: the last fenced `json` block of a final answer (or the whole answer when it is one JSON
2
+ // object and nothing else), parsed, and checked against an agent's
2
3
  // output schema (definition.output_schema). The one reader of it: a completed agentic run's result.output (store-view.ts)
3
4
  // and a template eval's target graders (template-eval.ts) read an answer's JSON alike. The runner tells the
4
5
  // model the schema (outputContract, in every harness's system prompt) and asks once more on a miss (outputRetryWords,
@@ -22,9 +23,26 @@ export function lastJsonBlock(text) {
22
23
  }
23
24
  return found;
24
25
  }
25
- /** The answer's last fenced json block, parsed, or why there is none. */
26
+ /** An answer's json block: its last fenced `json` block, else the whole answer when its trimmed text is one JSON object
27
+ * and nothing else (a reply that is the object alone). The one rule every reader of an answer's JSON keeps: a run's
28
+ * output, a template eval's target and its grader's verdict. */
29
+ export function jsonBlockOf(text) {
30
+ const fenced = lastJsonBlock(text);
31
+ if (fenced !== undefined)
32
+ return fenced;
33
+ const whole = text.trim();
34
+ if (!whole.startsWith("{"))
35
+ return undefined;
36
+ try {
37
+ return isObject(JSON.parse(whole)) ? whole : undefined;
38
+ }
39
+ catch {
40
+ return undefined;
41
+ }
42
+ }
43
+ /** The answer's json block (jsonBlockOf), parsed, or why there is none. */
26
44
  export function answerJson(answer) {
27
- const block = lastJsonBlock(answer);
45
+ const block = jsonBlockOf(answer);
28
46
  if (block === undefined)
29
47
  return { why: "the answer has no fenced json block" };
30
48
  try {
@@ -80,7 +98,7 @@ export function outputMiss(answer, schema) {
80
98
  const read = structuredAnswer(answer, schema);
81
99
  return "why" in read ? read.why.replace(MISSES, "") : undefined;
82
100
  }
83
- /** A final answer's structured part against an agent's output schema: the value of its last fenced json block when it
101
+ /** A final answer's structured part against an agent's output schema: the value of its json block (jsonBlockOf) when it
84
102
  * meets the schema, else why not (no block, not JSON, the first problems against the schema). */
85
103
  export function structuredAnswer(answer, schema) {
86
104
  const compiled = schemaCheck(schema);
@@ -0,0 +1,76 @@
1
+ import { type SecretMeta } from "./secret-writes.js";
2
+ import type { Settings } from "./store/index.js";
3
+ /** Where the owner makes and revokes a key in the console. */
4
+ export declare const API_KEYS_PAGE = "/#/settings/api-keys";
5
+ /** What every key made here starts with: a person who meets one can tell what it is, and the redaction finds one by it
6
+ * (redact/match.ts holds the same prefix, and secrets-api-key.test.mjs holds the two together). */
7
+ export declare const API_KEY_PREFIX = "ar_key_";
8
+ /** The store settings a key's row is kept under: this prefix, then its id. */
9
+ export declare const API_KEY_SETTING = "api_key:";
10
+ /** The most keys a server keeps at once. */
11
+ export declare const API_KEYS_LIMIT = 50;
12
+ /** The longest name a key takes. */
13
+ export declare const API_KEY_NAME_MAX = 64;
14
+ /** A key's last use is written to the store at most this often: a busy key costs one write a minute, not one a request. */
15
+ export declare const USED_EVERY_MS = 60000;
16
+ /** A key as every read answers it: never its value, a prefix, a length or a hash. */
17
+ export type ApiKeyView = {
18
+ id: string;
19
+ name: string;
20
+ created_at: string;
21
+ last_used_at: string | null;
22
+ secret: SecretMeta;
23
+ };
24
+ /** A key's secret's metadata, named api-key:<id>: made by this server at the owner's request (source console). */
25
+ export declare const apiKeySecretMeta: (id: string, createdAt: string) => SecretMeta;
26
+ export type ApiKeysOptions = {
27
+ /** The clock (a test's). */
28
+ now?: () => number;
29
+ /** Where a row that could not be read, or a last use that could not be written, is said: fields with no secret. */
30
+ say?: (fields: Record<string, string | number>) => void;
31
+ /** The keys open nothing on this server (it is one person's, or has no owner): each is still read, listed, counted
32
+ * and revocable, so none waits unseen for a start that takes keys again. */
33
+ dormant?: boolean;
34
+ };
35
+ export declare class ApiKeys {
36
+ #private;
37
+ constructor(store: {
38
+ settings: Settings;
39
+ }, sealKey: Buffer, options?: ApiKeysOptions);
40
+ /** Reads the store's keys. A row that is no key's (another version's, or damaged) opens nothing and is said, with
41
+ * how it is removed. It is no key in the list: the list names it by id in `unreadable`, and it counts toward the
42
+ * store's limit while it stays. */
43
+ load(): Promise<void>;
44
+ /** How many keys open this server now: what the one-owner rule counts (server.ts loginRefused). Read it in a turn
45
+ * (inTurn) to decide by it: outside one, a revocation under way has taken its key out and may yet put it back. */
46
+ get count(): number;
47
+ /** One at a time: every change to which keys open the server (create, revoke) takes a turn, and so does whatever
48
+ * must decide by the keys as they stand once those changes have landed or been undone (the server turns Claude
49
+ * Code's login on in one). A turn starts when the one before it has settled, whether it kept its write or not. */
50
+ inTurn<T>(work: () => Promise<T>): Promise<T>;
51
+ /** GET /settings/api-keys: every key, oldest first, and the most a server keeps. `refused`: why this server makes
52
+ * none now (server.ts apiKeysRefused), said with the list so a page can say it before anyone tries. `unreadable`:
53
+ * the ids of the rows that are no key's, when there are any, so their owner sees what else counts toward the limit
54
+ * and removes it (revoke takes such an id). */
55
+ list(refused?: string): {
56
+ keys: ApiKeyView[];
57
+ limit: number;
58
+ refused?: string;
59
+ unreadable?: string[];
60
+ };
61
+ /** POST /settings/api-keys: a new key named `name`, its value as `api_key`, this once. `refused`: why this server
62
+ * makes no key now, asked in the create's own turn, so nothing that would refuse it starts between the answer and
63
+ * the write; its words are the 403's. */
64
+ create(body: unknown, refused?: () => Promise<string | undefined>): Promise<ApiKeyView & {
65
+ api_key: string;
66
+ }>;
67
+ /** DELETE /settings/api-keys/{id}: the key opens nothing from now on. In a turn of its own (inTurn): while its
68
+ * removal is under way the key is out of this process, and a removal that fails puts it back, so nothing decides by
69
+ * the count in between. */
70
+ revoke(id: string): Promise<void>;
71
+ /** The id of the key whose `Bearer` line `header` is, else undefined. Every key is compared on every call, with no
72
+ * early return, so the time taken says neither whether one matched nor which. A match is the key's last use. */
73
+ used(header: string | undefined): string | undefined;
74
+ /** Waits for the last-use writes under way, before the store closes. */
75
+ close(): Promise<void>;
76
+ }
@@ -0,0 +1,217 @@
1
+ // The API keys a person makes in the console (Settings → AgentRun API keys, /v2/settings/api-keys): each a Bearer token
2
+ // an app sends on /v2 and /mcp, as it would the server's own token (api-token.ts). A key is made here at random, shown
3
+ // once in the answer that made it, and kept nowhere. The store keeps an HMAC of its `Bearer` line under a key derived
4
+ // from the server's seal key, so a copy of the store names no key and a row written without the seal key opens nothing.
5
+ //
6
+ // Making and revoking a key are secret writes (secret-writes.ts): the owner's signed-in session alone, never a token,
7
+ // so a key that leaks cannot make another or outlive its revocation. A key is not the setup code: only a token the
8
+ // server was started with sets the first password (server.ts ownerRoute).
9
+ //
10
+ // Every presented header is compared with every key, in constant time, on two 32-byte digests, as bearerCheck compares
11
+ // the server's tokens. One server holds a store (its owner lock), so the keys in this process are the store's.
12
+ //
13
+ // On a server that is one person's, or has no owner, the keys are dormant: read, listed, counted and revocable, and
14
+ // opening nothing. A key never waits unseen for a later start to take it again.
15
+ //
16
+ // The server keeps no copy of a key, so it holds no value to cut a text by, as it cuts its own token. A key is found by
17
+ // its shape instead (redact/match.ts: the prefix and 43 or more of its characters), wherever a run's views, a shared
18
+ // transcript or a learned note would show one.
19
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
20
+ import { ApiError, invalid } from "./errors.js";
21
+ import { uuidv7 } from "./ids.js";
22
+ import { registerSecretPage, registerSecretWrite, secretMeta, secretName } from "./secret-writes.js";
23
+ import { isObject, unknownFields } from "./validate.js";
24
+ registerSecretWrite("createApiKey", () => true);
25
+ registerSecretWrite("revokeApiKey", () => true);
26
+ /** Where the owner makes and revokes a key in the console. */
27
+ export const API_KEYS_PAGE = "/#/settings/api-keys";
28
+ registerSecretPage(["createApiKey", "revokeApiKey"], API_KEYS_PAGE);
29
+ /** What every key made here starts with: a person who meets one can tell what it is, and the redaction finds one by it
30
+ * (redact/match.ts holds the same prefix, and secrets-api-key.test.mjs holds the two together). */
31
+ export const API_KEY_PREFIX = "ar_key_";
32
+ /** The store settings a key's row is kept under: this prefix, then its id. */
33
+ export const API_KEY_SETTING = "api_key:";
34
+ /** The most keys a server keeps at once. */
35
+ export const API_KEYS_LIMIT = 50;
36
+ /** The longest name a key takes. */
37
+ export const API_KEY_NAME_MAX = 64;
38
+ /** A key's last use is written to the store at most this often: a busy key costs one write a minute, not one a request. */
39
+ export const USED_EVERY_MS = 60_000;
40
+ const ID = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
41
+ const isDate = (value) => typeof value === "string" && !Number.isNaN(Date.parse(value));
42
+ const isKept = (value) => isObject(value) && value.v === 1 && typeof value.id === "string" && ID.test(value.id) && typeof value.name === "string" && typeof value.mac === "string" && /^[0-9a-f]{64}$/.test(value.mac)
43
+ && isDate(value.created_at) && (value.last_used_at === null || isDate(value.last_used_at));
44
+ /** A key's secret's metadata, named api-key:<id>: made by this server at the owner's request (source console). */
45
+ export const apiKeySecretMeta = (id, createdAt) => secretMeta(secretName("api-key", id), { set: true, source: "console", changedAt: createdAt });
46
+ export class ApiKeys {
47
+ #settings;
48
+ #macKey;
49
+ #now;
50
+ #say;
51
+ #dormant;
52
+ #keys = new Map();
53
+ /** The rows under the keys' prefix that are no key's, by what follows the prefix in their store key: they open
54
+ * nothing, and a revocation by that id removes one (it counts toward the store's limit until then). */
55
+ #unreadable = new Set();
56
+ #writes = new Set();
57
+ /** The turn now taken (inTurn): settled before the next one starts, whatever it did. */
58
+ #turn = Promise.resolve();
59
+ constructor(store, sealKey, options = {}) {
60
+ this.#settings = store.settings;
61
+ this.#macKey = createHmac("sha256", sealKey).update("agentrun-serve api keys").digest();
62
+ this.#now = options.now ?? Date.now;
63
+ this.#say = options.say ?? (() => undefined);
64
+ this.#dormant = options.dormant === true;
65
+ }
66
+ #mac(header) {
67
+ return createHmac("sha256", this.#macKey).update(header).digest();
68
+ }
69
+ /** Reads the store's keys. A row that is no key's (another version's, or damaged) opens nothing and is said, with
70
+ * how it is removed. It is no key in the list: the list names it by id in `unreadable`, and it counts toward the
71
+ * store's limit while it stays. */
72
+ async load() {
73
+ this.#keys.clear();
74
+ this.#unreadable.clear();
75
+ for (const row of await this.#settings.all({ prefix: API_KEY_SETTING })) {
76
+ const kept = row.value;
77
+ if (!isKept(kept) || row.key !== API_KEY_SETTING + kept.id) {
78
+ const id = row.key.slice(API_KEY_SETTING.length);
79
+ this.#unreadable.add(id);
80
+ this.#say({ condition: "api_key_unreadable", key: row.key, effect: `ignored: it opens nothing, and counts toward the limit until DELETE /v2/settings/api-keys/${encodeURIComponent(id)} removes it` });
81
+ continue;
82
+ }
83
+ const used = kept.last_used_at === null ? null : Date.parse(kept.last_used_at);
84
+ this.#keys.set(kept.id, { row: kept, mac: Buffer.from(kept.mac, "hex"), usedAt: used, triedAt: used, saving: false });
85
+ }
86
+ }
87
+ #view(held) {
88
+ const { id, name, created_at } = held.row;
89
+ return { id, name, created_at, last_used_at: held.usedAt === null ? null : new Date(held.usedAt).toISOString(), secret: apiKeySecretMeta(id, created_at) };
90
+ }
91
+ /** How many keys open this server now: what the one-owner rule counts (server.ts loginRefused). Read it in a turn
92
+ * (inTurn) to decide by it: outside one, a revocation under way has taken its key out and may yet put it back. */
93
+ get count() {
94
+ return this.#keys.size;
95
+ }
96
+ /** One at a time: every change to which keys open the server (create, revoke) takes a turn, and so does whatever
97
+ * must decide by the keys as they stand once those changes have landed or been undone (the server turns Claude
98
+ * Code's login on in one). A turn starts when the one before it has settled, whether it kept its write or not. */
99
+ inTurn(work) {
100
+ const mine = this.#turn.then(work, work);
101
+ this.#turn = mine.catch(() => undefined);
102
+ return mine;
103
+ }
104
+ /** GET /settings/api-keys: every key, oldest first, and the most a server keeps. `refused`: why this server makes
105
+ * none now (server.ts apiKeysRefused), said with the list so a page can say it before anyone tries. `unreadable`:
106
+ * the ids of the rows that are no key's, when there are any, so their owner sees what else counts toward the limit
107
+ * and removes it (revoke takes such an id). */
108
+ list(refused) {
109
+ return {
110
+ keys: [...this.#keys.values()].sort((a, b) => (a.row.id < b.row.id ? -1 : 1)).map((held) => this.#view(held)),
111
+ limit: API_KEYS_LIMIT,
112
+ ...(refused ? { refused } : {}),
113
+ ...(this.#unreadable.size ? { unreadable: [...this.#unreadable].sort() } : {}),
114
+ };
115
+ }
116
+ /** POST /settings/api-keys: a new key named `name`, its value as `api_key`, this once. `refused`: why this server
117
+ * makes no key now, asked in the create's own turn, so nothing that would refuse it starts between the answer and
118
+ * the write; its words are the 403's. */
119
+ async create(body, refused) {
120
+ if (!isObject(body))
121
+ throw invalid([{ field: "body", reason: "wrong_type", message: "The body is an object: {\"name\": \"...\"}." }]);
122
+ const unknown = unknownFields(body, ["name"]);
123
+ if (unknown.length)
124
+ throw invalid(unknown);
125
+ const name = typeof body.name === "string" ? body.name.trim() : undefined;
126
+ if (name === undefined)
127
+ throw invalid([{ field: "name", reason: body.name === undefined ? "required" : "wrong_type", message: "name is what this key is for, in a few words: the app or the person that will hold it." }]);
128
+ // No control character: a name is shown in a list, on one line.
129
+ if (name === "" || name.length > API_KEY_NAME_MAX || /[\u0000-\u001f\u007f]/.test(name)) {
130
+ throw invalid([{ field: "name", reason: "out_of_range", message: `name is 1 to ${API_KEY_NAME_MAX} characters, on one line.` }]);
131
+ }
132
+ return this.inTurn(async () => {
133
+ const why = await refused?.();
134
+ if (why)
135
+ throw new ApiError("forbidden", why);
136
+ const id = uuidv7(this.#now());
137
+ const value = `${API_KEY_PREFIX}${randomBytes(32).toString("base64url")}`;
138
+ const mac = this.#mac(`Bearer ${value}`);
139
+ const kept = { v: 1, id, name, mac: mac.toString("hex"), created_at: new Date(this.#now()).toISOString(), last_used_at: null };
140
+ const saved = await this.#settings.putIfAbsent(API_KEY_SETTING + id, kept, { prefix: API_KEY_SETTING, limit: API_KEYS_LIMIT });
141
+ if (saved === undefined)
142
+ throw new ApiError("api_keys_full", `This server keeps at most ${API_KEYS_LIMIT} API keys. Revoke one you no longer use, then create this one.`);
143
+ const held = { row: kept, mac, usedAt: null, triedAt: null, saving: false };
144
+ this.#keys.set(id, held);
145
+ return { ...this.#view(held), api_key: value };
146
+ });
147
+ }
148
+ /** DELETE /settings/api-keys/{id}: the key opens nothing from now on. In a turn of its own (inTurn): while its
149
+ * removal is under way the key is out of this process, and a removal that fails puts it back, so nothing decides by
150
+ * the count in between. */
151
+ async revoke(id) {
152
+ return this.inTurn(async () => {
153
+ const held = this.#keys.get(id);
154
+ if (!held && this.#unreadable.has(id)) {
155
+ // A row the start could not read as a key: it opens nothing already, and its removal frees its place.
156
+ await this.#settings.remove(API_KEY_SETTING + id);
157
+ this.#unreadable.delete(id);
158
+ return;
159
+ }
160
+ if (!held)
161
+ throw new ApiError("not_found", "No API key has that id: it was revoked, or never created.");
162
+ // Out of this process first, so a request that races the store's write is refused already.
163
+ this.#keys.delete(id);
164
+ try {
165
+ await this.#settings.remove(API_KEY_SETTING + id);
166
+ }
167
+ catch (error) {
168
+ // Not removed from the store: it would open again at the next start, so it stays listed, to be revoked again.
169
+ this.#keys.set(id, held);
170
+ throw error;
171
+ }
172
+ });
173
+ }
174
+ /** The id of the key whose `Bearer` line `header` is, else undefined. Every key is compared on every call, with no
175
+ * early return, so the time taken says neither whether one matched nor which. A match is the key's last use. */
176
+ used(header) {
177
+ if (this.#dormant)
178
+ return undefined;
179
+ const given = this.#mac(String(header ?? ""));
180
+ let found;
181
+ for (const held of this.#keys.values()) {
182
+ const hit = timingSafeEqual(given, held.mac);
183
+ found = hit ? held : found;
184
+ }
185
+ if (found)
186
+ this.#touch(found);
187
+ return found?.row.id;
188
+ }
189
+ /** Marks `held` used now, and writes it to the store when the last try is USED_EVERY_MS old. Paced by the try, kept
190
+ * or not: while the store refuses writes, a busy key costs one try and one line a minute, not one a request. The row
191
+ * is replaced only while it reads as this process last wrote it, so a write that loses to a revocation writes
192
+ * nothing. */
193
+ #touch(held) {
194
+ const now = this.#now();
195
+ held.usedAt = now;
196
+ if (held.saving || (held.triedAt !== null && now - held.triedAt < USED_EVERY_MS))
197
+ return;
198
+ held.saving = true;
199
+ held.triedAt = now;
200
+ const next = { ...held.row, last_used_at: new Date(now).toISOString() };
201
+ const write = this.#settings.replaceIf(API_KEY_SETTING + held.row.id, held.row, next)
202
+ .then((replaced) => {
203
+ if (replaced)
204
+ held.row = next;
205
+ })
206
+ .catch((error) => this.#say({ condition: "api_key_use_not_saved", id: held.row.id, error: error instanceof Error ? error.message : String(error) }))
207
+ .finally(() => {
208
+ held.saving = false;
209
+ this.#writes.delete(write);
210
+ });
211
+ this.#writes.add(write);
212
+ }
213
+ /** Waits for the last-use writes under way, before the store closes. */
214
+ async close() {
215
+ await Promise.all([...this.#writes]);
216
+ }
217
+ }
@@ -26,9 +26,14 @@ import type { Route } from "./server.js";
26
26
  * (mcp-secret-writes.ts tokenWriteOverRefused), and never writes a secret (secret-writes.ts). A Composio server names
27
27
  * its key by api_key_env (COMPOSIO_API_KEY, on the launcher's list of secrets, read at each use through secrets.ts
28
28
  * secret, sent to Composio's origin alone: composio-made.ts composioEnvKey), and its body names no address or headers.
29
- * There is no list or read of the servers here (listMcpServerNames above is the listing), and no generic save (saveMcpServer), so the
30
- * token saves no server at an address or with headers of its own. Previews, refreshes, sign-ins and Composio's
31
- * triggers stay refused. */
29
+ * There is no list or read of the servers here (listMcpServerNames above is the listing). The generic save
30
+ * (saveMcpServer) is served only when the operator names MCP origins (API_ONLY_MCP_ORIGINS_ENV), and then saves a
31
+ * per_run server (which keeps no credential) at one of those origins alone (apiOnlyMcpSave); unset, it is refused as
32
+ * any other route, so the token saves no server at an address or with headers of its own. Previews, refreshes,
33
+ * sign-ins and Composio's triggers stay refused;
34
+ * - the launch hook's host (the backend in front of this server) releases a firing it took and will start no run for
35
+ * (releaseTriggerFiring, triggers.ts release), so its trigger's room frees at once; with no launch hook the route is
36
+ * the route's own 422. */
32
37
  export declare const API_ONLY_ROUTES: ReadonlySet<string>;
33
38
  /** The trigger sources an apply on an API-only server makes once the server has the launch hook: the ones that fire on
34
39
  * its own clock and need nothing a refused route sets up. Each firing goes to the backend in front of it
@@ -46,8 +51,15 @@ export declare function apiOnlyTriggerSkipped(packageName: string, trigger: {
46
51
  reason: typeof NOT_SET_UP | "not_an_option";
47
52
  message: string;
48
53
  } | undefined;
54
+ /** Whether an API-only server saves `body` through the generic save (saveMcpServer) over the name its path gives: a
55
+ * per_run server (no credential kept) whose url's origin is one of `origins`, under a name that is not a Composio
56
+ * preset's (`preset`; Composio's own route saves those). Checked before anything reaches the address. A body that
57
+ * carries a credential never gets here: the secret-write gate refuses it first (403), as it refuses the token's save
58
+ * over a server it did not save or one that seals a credential (mcp-secret-writes.ts tokenWriteOverRefused). */
59
+ export declare function apiOnlyMcpSave(body: unknown, preset: boolean, origins: readonly string[]): boolean;
49
60
  /** Whether an API-only server serves `method` on `raw` (the path as sent, its query cut): a /v2 path one of
50
- * API_ONLY_ROUTES matches for that method (HEAD as GET), or a GET of a run's computer live view. */
51
- export declare function servedApiOnly(routes: readonly Route[], method: string | undefined, raw: string): boolean;
61
+ * API_ONLY_ROUTES matches for that method (HEAD as GET), the generic MCP save when the operator names MCP origins
62
+ * (`mcpSave`, its body checked at the route: apiOnlyMcpSave), or a GET of a run's computer live view. */
63
+ export declare function servedApiOnly(routes: readonly Route[], method: string | undefined, raw: string, mcpSave?: boolean): boolean;
52
64
  /** The refusal's words for `raw` on an API-only server. */
53
65
  export declare const apiOnlyRefusal: (raw: string) => string;