@parcha/agentrun-serve 0.1.0-beta.34 → 0.1.0-beta.35

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 (227) hide show
  1. package/CHANGELOG.md +135 -0
  2. package/README.md +84 -16
  3. package/dist/adapters.d.ts +3 -0
  4. package/dist/adapters.js +7 -0
  5. package/dist/agent-rows.d.ts +1 -0
  6. package/dist/agents-store.js +17 -2
  7. package/dist/archil-settings.d.ts +11 -1
  8. package/dist/archil-settings.js +10 -0
  9. package/dist/bash-read-only.d.ts +13 -0
  10. package/dist/bash-read-only.js +77 -0
  11. package/dist/browser-cost.d.ts +2 -2
  12. package/dist/browser-cost.js +6 -4
  13. package/dist/budget.d.ts +0 -5
  14. package/dist/budget.js +0 -5
  15. package/dist/cap.d.ts +6 -3
  16. package/dist/cap.js +7 -4
  17. package/dist/cli.js +32 -5
  18. package/dist/computer-keys.d.ts +20 -10
  19. package/dist/computer-keys.js +36 -57
  20. package/dist/computer-setting.d.ts +6 -5
  21. package/dist/computer-setting.js +54 -26
  22. package/dist/computers.d.ts +9 -4
  23. package/dist/computers.js +4 -2
  24. package/dist/console/assets/index-B7NKTU8E.css +1 -0
  25. package/dist/console/assets/index-CXZMgJE7.js +550 -0
  26. package/dist/console/index.html +2 -2
  27. package/dist/content-filter.d.ts +7 -0
  28. package/dist/content-filter.js +23 -0
  29. package/dist/decision-cap.d.ts +7 -29
  30. package/dist/decision-cap.js +3 -94
  31. package/dist/errors.d.ts +1 -0
  32. package/dist/errors.js +3 -0
  33. package/dist/explain.js +3 -1
  34. package/dist/github-connection.js +25 -7
  35. package/dist/github-faux.d.ts +26 -0
  36. package/dist/github-faux.js +76 -0
  37. package/dist/github.d.ts +6 -2
  38. package/dist/github.js +5 -3
  39. package/dist/graph-served.d.ts +5 -3
  40. package/dist/graph-served.js +14 -6
  41. package/dist/graph-view.js +5 -2
  42. package/dist/harness-opencode/harness.js +0 -1
  43. package/dist/harness-opencode/host/policy.js +2 -2
  44. package/dist/index.d.ts +1 -0
  45. package/dist/index.js +1 -0
  46. package/dist/learn/check.d.ts +3 -1
  47. package/dist/learn/check.js +3 -3
  48. package/dist/learn/folder.d.ts +6 -3
  49. package/dist/learn/folder.js +7 -16
  50. package/dist/learn/grade.d.ts +4 -1
  51. package/dist/learn/grade.js +43 -5
  52. package/dist/learn/index.d.ts +2 -2
  53. package/dist/learn/index.js +2 -2
  54. package/dist/learn/learning.sh +1 -14
  55. package/dist/learn/notes.d.ts +14 -3
  56. package/dist/learn/notes.js +16 -6
  57. package/dist/learn/reflect.js +5 -3
  58. package/dist/learn/skills.d.ts +48 -5
  59. package/dist/learn/skills.js +97 -21
  60. package/dist/learned-nodes.d.ts +14 -0
  61. package/dist/learned-nodes.js +8 -0
  62. package/dist/learned-workflow.d.ts +9 -5
  63. package/dist/learned-workflow.js +53 -9
  64. package/dist/learning-routes.d.ts +41 -0
  65. package/dist/learning-routes.js +94 -26
  66. package/dist/learning-run.d.ts +7 -5
  67. package/dist/learning-run.js +9 -6
  68. package/dist/learning.d.ts +0 -22
  69. package/dist/learning.js +0 -16
  70. package/dist/llm.d.ts +4 -1
  71. package/dist/llm.js +4 -2
  72. package/dist/mcp-gateway.d.ts +6 -0
  73. package/dist/mcp-gateway.js +11 -1
  74. package/dist/mcp-servers-store.d.ts +12 -12
  75. package/dist/model.d.ts +3 -0
  76. package/dist/model.js +8 -0
  77. package/dist/openapi.js +37 -13
  78. package/dist/paid-calls.js +1 -1
  79. package/dist/pause.d.ts +2 -19
  80. package/dist/pause.js +5 -74
  81. package/dist/port-models.d.ts +10 -3
  82. package/dist/port-models.js +26 -6
  83. package/dist/propose.d.ts +2 -0
  84. package/dist/propose.js +1 -10
  85. package/dist/run-launch.d.ts +5 -3
  86. package/dist/run-launch.js +6 -5
  87. package/dist/run-learning-served.d.ts +11 -0
  88. package/dist/run-reads-over-store.d.ts +4 -2
  89. package/dist/run-reads-over-store.js +10 -8
  90. package/dist/run-timeline-served.js +12 -2
  91. package/dist/run-view.d.ts +30 -14
  92. package/dist/run-view.js +60 -32
  93. package/dist/runnable.d.ts +4 -1
  94. package/dist/runnable.js +14 -2
  95. package/dist/runner/adapter-loop.d.ts +30 -4
  96. package/dist/runner/adapter-loop.js +253 -29
  97. package/dist/runner/adapter-run-spec.d.ts +21 -0
  98. package/dist/runner/adapter-run-spec.js +104 -28
  99. package/dist/runner/adapters/pi.d.ts +29 -1
  100. package/dist/runner/adapters/pi.js +95 -23
  101. package/dist/runner/beside.d.ts +8 -0
  102. package/dist/runner/beside.js +18 -0
  103. package/dist/runner/claim-secrets.d.ts +6 -0
  104. package/dist/runner/claim-secrets.js +15 -1
  105. package/dist/runner/cli-run-spec.d.ts +3 -0
  106. package/dist/runner/cli-run-spec.js +123 -34
  107. package/dist/runner/conformance/harness.d.ts +1 -0
  108. package/dist/runner/conformance/harness.js +5 -5
  109. package/dist/runner/github-app.d.ts +7 -2
  110. package/dist/runner/github-app.js +46 -15
  111. package/dist/runner/harness-loops.d.ts +6 -1
  112. package/dist/runner/harness-loops.js +23 -0
  113. package/dist/runner/journal-kinds.d.ts +38 -2
  114. package/dist/runner/journal-kinds.js +23 -0
  115. package/dist/runner/learning-end.js +88 -16
  116. package/dist/runner/learning-loop.d.ts +2 -0
  117. package/dist/runner/learning-loop.js +13 -5
  118. package/dist/runner/learning-seed.d.ts +6 -0
  119. package/dist/runner/learning-seed.js +6 -0
  120. package/dist/runner/loop-contract.d.ts +4 -0
  121. package/dist/runner/main.d.ts +9 -4
  122. package/dist/runner/main.js +26 -11
  123. package/dist/runner/mcp-claim.d.ts +3 -0
  124. package/dist/runner/mcp-claim.js +6 -1
  125. package/dist/runner/mcp-github.d.ts +11 -2
  126. package/dist/runner/mcp-github.js +55 -4
  127. package/dist/runner/mcp-run.js +1 -0
  128. package/dist/runner/metrics.d.ts +14 -1
  129. package/dist/runner/metrics.js +72 -1
  130. package/dist/runner/model-route.d.ts +3 -0
  131. package/dist/runner/model-route.js +1 -1
  132. package/dist/runner/runner.js +90 -8
  133. package/dist/runner/spec-holds.d.ts +7 -2
  134. package/dist/runner/spec-holds.js +4 -3
  135. package/dist/runner/workflow-host.d.ts +7 -2
  136. package/dist/runner/workflow-host.js +3 -1
  137. package/dist/runner/workflow-loop.d.ts +4 -1
  138. package/dist/runner/workflow-loop.js +8 -2
  139. package/dist/runner/workflow-spec.d.ts +3 -0
  140. package/dist/runner/workflow-spec.js +156 -78
  141. package/dist/runs-over-store.d.ts +7 -1
  142. package/dist/runs-over-store.js +42 -11
  143. package/dist/seal-key.d.ts +0 -2
  144. package/dist/seal-key.js +0 -2
  145. package/dist/server-lock.js +4 -5
  146. package/dist/server.d.ts +21 -18
  147. package/dist/server.js +183 -34
  148. package/dist/stop-signals.d.ts +4 -2
  149. package/dist/stop-signals.js +5 -3
  150. package/dist/store/agent-body.d.ts +5 -1
  151. package/dist/store/agent-body.js +11 -5
  152. package/dist/store/deadline.d.ts +18 -0
  153. package/dist/store/deadline.js +45 -0
  154. package/dist/store/postgres/connection.d.ts +4 -0
  155. package/dist/store/postgres/connection.js +55 -9
  156. package/dist/store/sqlite/connection.js +3 -38
  157. package/dist/store-reads/journal.js +39 -4
  158. package/dist/store-reads/learning.d.ts +58 -2
  159. package/dist/store-reads/learning.js +172 -7
  160. package/dist/store-view.d.ts +15 -1
  161. package/dist/store-view.js +45 -12
  162. package/dist/templates.d.ts +9 -4
  163. package/dist/templates.js +14 -9
  164. package/dist/timeline/timeline.d.ts +8 -0
  165. package/dist/tool-budget.d.ts +18 -0
  166. package/dist/tool-budget.js +50 -0
  167. package/dist/tool-gate.d.ts +6 -2
  168. package/dist/tool-gate.js +8 -5
  169. package/dist/tool-plane.d.ts +9 -10
  170. package/dist/tools.d.ts +37 -7
  171. package/dist/tools.js +73 -12
  172. package/dist/uploads.d.ts +28 -5
  173. package/dist/uploads.js +82 -9
  174. package/dist/usage.d.ts +1 -47
  175. package/dist/usage.js +3 -82
  176. package/dist/validate.d.ts +2 -0
  177. package/dist/validate.js +11 -1
  178. package/dist/workspace/archil-claim.d.ts +2 -2
  179. package/dist/workspace/archil-claim.js +4 -3
  180. package/dist/workspace/archil-disk.d.ts +10 -1
  181. package/dist/workspace/archil-disk.js +4 -0
  182. package/dist/workspace/archil-exec.d.ts +12 -2
  183. package/dist/workspace/archil-exec.js +16 -0
  184. package/dist/workspace/archil.d.ts +2 -2
  185. package/dist/workspace/archil.js +25 -5
  186. package/dist/workspace/attach.js +2 -0
  187. package/dist/workspace/computer-deps.d.ts +9 -10
  188. package/dist/workspace/computer-deps.js +53 -40
  189. package/dist/workspace/computer-for-claim.d.ts +5 -3
  190. package/dist/workspace/computer-for-claim.js +28 -16
  191. package/dist/workspace/computer-ledger.d.ts +1 -8
  192. package/dist/workspace/computer-ledger.js +0 -3
  193. package/dist/workspace/computer-providers.d.ts +5 -3
  194. package/dist/workspace/computer-providers.js +11 -9
  195. package/dist/workspace/hands.d.ts +5 -2
  196. package/dist/workspace/hands.js +4 -3
  197. package/dist/workspace/index.d.ts +3 -3
  198. package/dist/workspace/index.js +1 -1
  199. package/dist/workspace/local.d.ts +3 -0
  200. package/dist/workspace/local.js +9 -0
  201. package/dist/workspace/paths.js +3 -2
  202. package/dist/workspace/pi-env.d.ts +4 -0
  203. package/dist/workspace/pi-env.js +3 -2
  204. package/dist/workspace/resolve-computer.d.ts +8 -3
  205. package/dist/workspace/resolve-computer.js +28 -11
  206. package/dist/workspace/run-tools.d.ts +2 -0
  207. package/dist/workspace/run-tools.js +9 -3
  208. package/dist/workspace/workspace.d.ts +5 -0
  209. package/dist/workspace.d.ts +0 -3
  210. package/dist/workspace.js +1 -14
  211. package/package.json +14 -14
  212. package/skills/agentrun-serve/SKILL.md +1 -1
  213. package/templates/README.md +2 -2
  214. package/templates/code-review/evals/mentions-defused/case.yaml +15 -0
  215. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +254 -0
  216. package/templates/code-review/evals/mentions-defused/graders/no-pings.md +16 -0
  217. package/templates/code-review/evals/mentions-defused/graders/posted-a-review.md +5 -0
  218. package/templates/code-review/evals/mentions-defused/graders/schema.md +5 -0
  219. package/templates/code-review/evals/mentions-defused/prompt.md +10 -0
  220. package/templates/kyb/evals/clean-public-company/graders/no-opensanctions.md +5 -0
  221. package/templates/kyb/evals/opensanctions-on/case.yaml +5 -0
  222. package/templates/kyb/evals/opensanctions-on/graders/licence-and-evidence.md +18 -0
  223. package/templates/kyb/evals/opensanctions-on/graders/schema.md +5 -0
  224. package/templates/kyb/evals/opensanctions-on/prompt.md +11 -0
  225. package/templates/release-notes/agent.md +11 -0
  226. package/dist/console/assets/index-RPHGlXmM.js +0 -540
  227. package/dist/console/assets/index-opTN5Naq.css +0 -1
@@ -37,7 +37,9 @@ import { said, STOPPED } from "../learning-words.js";
37
37
  import { proposeRun } from "../propose.js";
38
38
  import { learningStartOf, readLaunchBody, seedFailed } from "../run-launch.js";
39
39
  import { costOf } from "../run-view.js";
40
+ import { readApprovers } from "../server-approvers.js";
40
41
  import { runEntries, runReflect, runTimeline } from "../store-reads/journal.js";
42
+ import { capNowOf } from "./journal-kinds.js";
41
43
  import { createReflectHook } from "./reflect-hook.js";
42
44
  import { runnerSecrets } from "./redact.js";
43
45
  /** The end-of-run step for a run launched with `launch`: undefined when its launch records no learning start (a run that
@@ -49,12 +51,13 @@ export function learningEndOfRun(launch, deps) {
49
51
  const env = deps.env ?? process.env;
50
52
  // The grade model the server named at the run's start (its learning start's), none: the agent's own grades it.
51
53
  const gradeModel = start.gradeModel;
52
- const capUsd = launch.maxCostUsd;
53
54
  const hookFor = (runId) => createReflectHook({
54
55
  // reflectSkip's facts: a run its cap stopped has no room left, and one whose spend is unknown under a cap cannot be
55
- // kept within it. A person's stop comes to the hook as its `cut`.
56
+ // kept within it. The cap is the run's now (capNowOf: its newest raise's, else its launch's), the one its requests
57
+ // were admitted under, never the launch's alone. A person's stop comes to the hook as its `cut`.
56
58
  facts: async (runId) => {
57
59
  const costUsd = costOf(await runTimeline(deps.store, runId, BACKGROUND_CONTEXT, { settled: false }));
60
+ const capUsd = launch.maxCostUsd === undefined ? undefined : capNowOf(launch.maxCostUsd, await runEntries(deps.store, runId, BACKGROUND_CONTEXT));
58
61
  return { learns: true, costUsd, ...(capUsd !== undefined ? { capUsd, capReached: costUsd !== null && costUsd >= capUsd } : {}) };
59
62
  },
60
63
  nothingNew: async (runId) => onlyLearnedWorkflows(await runTimeline(deps.store, runId, BACKGROUND_CONTEXT, { settled: false })),
@@ -63,7 +66,7 @@ export function learningEndOfRun(launch, deps) {
63
66
  const { tools } = await draftTools(deps, runId);
64
67
  const draftFor = await draftForOf(deps, agentId, runId, start.skills ?? []).catch(() => []);
65
68
  // With a draft asked for, what each tool its call nodes may run takes and gives, in the server's own words.
66
- const described = draftFor.length ? await describedOf(tools) : [];
69
+ const described = draftFor.length ? await describedOf(tools, deps.store) : [];
67
70
  return { active: start.seedNotes ?? start.given.length, tools, draftFor, described };
68
71
  },
69
72
  asked: async (runId) => {
@@ -134,14 +137,74 @@ export function onlyLearnedWorkflows(rows) {
134
137
  const answered = new Set(results.filter((row) => !row.parent_tool_use_id).map((row) => row.tool_use_id));
135
138
  return calls.every((row) => answered.has(row.tool_use_id));
136
139
  }
140
+ /** Why each draft of `proposal` waits for its owner's OK whatever the grade: its steps calling an MCP tool with no
141
+ * declared price (skills.ts unpricedCalls), by its workflow.json's path, from the prices each server's row keeps
142
+ * (mcp-probe.ts McpPrices). A server the store can't read gives no price: held. */
143
+ async function heldOf(store, proposal) {
144
+ const files = (proposal?.files ?? []).filter((one) => typeof one?.file === "string" && one.file.endsWith("/workflow.json") && typeof one.text === "string");
145
+ const { draftMcpTools, unpricedCalls, unpricedLine } = await import("../learn/skills.js");
146
+ const rows = new Map();
147
+ const priced = new Map();
148
+ const held = {};
149
+ for (const { file, text } of files) {
150
+ let doc;
151
+ try {
152
+ doc = JSON.parse(text);
153
+ }
154
+ catch {
155
+ continue;
156
+ }
157
+ // Every MCP tool its call nodes run, as the workflow's own read reads them (draftMcpTools over the parsed JSON: an
158
+ // escaped "\/" is a slash there), its price read first (unpricedCalls asks synchronously).
159
+ for (const name of draftMcpTools(doc)) {
160
+ const [server, tool] = name.slice("mcp:".length).split("/");
161
+ if (!rows.has(server))
162
+ rows.set(server, store.mcp.server(server).catch(() => undefined));
163
+ const price = (await rows.get(server))?.prices?.[tool];
164
+ priced.set(name, typeof price === "number" && Number.isFinite(price) ? price : undefined);
165
+ }
166
+ const lines = unpricedCalls(doc, (tool) => priced.get(tool)).map(unpricedLine);
167
+ if (lines.length)
168
+ held[file] = lines;
169
+ }
170
+ return held;
171
+ }
172
+ /** The tools each saved MCP server lists now, by the server's name (none for one not saved, or a store that can't be
173
+ * read): what a wildcard grant names (tools.ts mcpGrantsListed). */
174
+ async function mcpListedOf(store) {
175
+ const rows = await store.mcp.servers().catch(() => []);
176
+ const byName = new Map(rows.map((row) => [row.name, (row.tools ?? []).flatMap((tool) => (typeof tool?.name === "string" ? [tool.name] : []))]));
177
+ return (server) => byName.get(server) ?? [];
178
+ }
137
179
  /** What each of `tools` takes and gives a workflow's call node, in the server's own words for it (tools.ts ToolEntry's
138
- * summary): the draft ask's `describe`. */
139
- async function describedOf(tools) {
180
+ * summary): the draft ask's `describe`. An MCP tool (`mcp:<server>/<tool>`, LS-07) is described by its server's listing
181
+ * as the store keeps it: what it does, the schema it takes and, when it lists one, the one it gives (reflect.ts cuts
182
+ * each line to its cap). A server or a tool the store does not list is described by none. */
183
+ async function describedOf(tools, store) {
140
184
  const { toolOf } = await import("../tools.js");
141
- return tools.flatMap((name) => {
142
- const does = toolOf(name)?.summary;
143
- return does ? [{ name, does }] : [];
144
- });
185
+ const listed = new Map();
186
+ const out = [];
187
+ for (const name of tools) {
188
+ const mcp = /^mcp:([^/]+)\/(.+)$/.exec(name);
189
+ if (!mcp) {
190
+ const does = toolOf(name)?.summary;
191
+ if (does)
192
+ out.push({ name, does });
193
+ continue;
194
+ }
195
+ const server = mcp[1];
196
+ const tool = mcp[2];
197
+ if (!listed.has(server))
198
+ listed.set(server, store.mcp.server(server).catch(() => undefined));
199
+ const row = await listed.get(server);
200
+ const entry = (row?.tools ?? []).find((one) => one?.name === tool);
201
+ if (!entry)
202
+ continue;
203
+ const said = typeof entry.description === "string" && entry.description.trim() ? entry.description.trim() : typeof entry.title === "string" ? entry.title.trim() : "";
204
+ const does = [said ? `${said.replace(/[.\s]+$/, "")}.` : "", `Takes ${JSON.stringify(entry.input_schema ?? {})}.`, entry.output_schema !== undefined ? `Gives ${JSON.stringify(entry.output_schema)}.` : ""].filter(Boolean).join(" ");
205
+ out.push({ name, does });
206
+ }
207
+ return out;
145
208
  }
146
209
  /** How many of an agent's latest runs draftForOf reads at most: a skill offered to fewer than DRAFT_AFTER_RUNS of them is
147
210
  * no repeated job. */
@@ -201,28 +264,34 @@ async function draftTools(deps, runId) {
201
264
  const run = await deps.store.runs.get(runId);
202
265
  const revision = run ? await deps.store.agents.revision(run.revisionId) : undefined;
203
266
  if (revision?.kind !== "agentic")
204
- return { tools: [], gated: {} };
267
+ return { tools: [], gated: {}, deniedBy: {}, asked: [] };
205
268
  const body = revision.body;
206
- const [{ learnedDraftTools }, { permissionFrom }, { loadToolSettings }] = await Promise.all([import("../tools.js"), import("../tool-gate.js"), import("../tool-plane.js")]);
269
+ const [{ learnedDraftTools, mcpGrantsListed }, { permissionFrom }, { loadToolSettings }] = await Promise.all([import("../tools.js"), import("../tool-gate.js"), import("../tool-plane.js")]);
207
270
  // The server's settings from the one store, as the run's gate reads them: a stored row that does not read carries
208
271
  // SETTINGS_UNREAD, which permissionFrom honours (no ask is lifted over a deny the row may hold).
209
272
  const server = (await loadToolSettings(deps.store)).settings;
210
273
  const agent = (body.toolSettings ?? {});
211
274
  const approvals = body.approvals === "never" ? "never" : "ask";
212
- const { tools, gated } = learnedDraftTools(body.tools ?? [], (name) => permissionFrom(name, server, agent, approvals).permission, undefined, (name) => permissionFrom(name, server, agent, approvals).from);
213
- return { tools, gated };
275
+ // A server's wildcard grant read as the tools its server lists now (tools.ts mcpGrantsListed, LS-07).
276
+ const granted = (body.tools ?? []).some((name) => /^mcp:[^/]+\/\*$/.test(name)) ? mcpGrantsListed(body.tools ?? [], await mcpListedOf(deps.store)) : (body.tools ?? []);
277
+ // `deniedBy`: where each deny was set (the agent's tool settings, the server's, a default), which a left-out draft's
278
+ // words name.
279
+ const { tools, gated, deniedBy, asked } = learnedDraftTools(granted, (name) => permissionFrom(name, server, agent, approvals).permission, undefined, (name) => permissionFrom(name, server, agent, approvals).from, { mcp: true, approvers: await readApprovers(deps.store.settings) });
280
+ return { tools, gated, deniedBy, asked };
214
281
  }
215
282
  /** proposeRun's checks over the turn, against seed `seed`, in a directory of the step's own: the proposal it keeps there
216
283
  * is read back for the hook to store with the run's end, and the directory is removed. */
217
284
  async function checkedOf(deps, input) {
218
285
  const runDir = await mkdtemp(join(tmpdir(), "agentrun-learning-end-"));
219
286
  try {
220
- const { tools, gated } = await draftTools(deps, input.runId);
287
+ const { tools, gated, deniedBy, asked } = await draftTools(deps, input.runId);
288
+ // #2424's card rule (learnedAskFits): a draft whose ask-set MCP tools would not all show on its approval card is refused.
289
+ const { learnedAskFits } = await import("../learned-workflow.js");
221
290
  const turn = { answer: input.turn.answer, asked: [...input.turn.asked], ...(input.turn.triggered?.length ? { triggered: input.turn.triggered.map((one) => ({ ...one })) } : {}) };
222
291
  const folder = deps.learningFolder(input.agentId);
223
292
  let proposed;
224
293
  try {
225
- proposed = await proposeRun({ folder: folder.workspace, runDir, seed: input.seed, turn, refuse: input.refuse, outcome: input.outcome, tools, ...(Object.keys(gated).length ? { gated } : {}) });
294
+ proposed = await proposeRun({ folder: folder.workspace, runDir, seed: input.seed, turn, refuse: input.refuse, outcome: input.outcome, tools, ...(Object.keys(gated).length ? { gated } : {}), ...(Object.keys(deniedBy).length ? { deniedBy } : {}), ask: { asked, fits: learnedAskFits } });
226
295
  }
227
296
  finally {
228
297
  await folder.end();
@@ -230,7 +299,10 @@ async function checkedOf(deps, input) {
230
299
  if (proposed.state !== "proposed")
231
300
  return proposed;
232
301
  const proposal = JSON.parse(await readFile(join(runDir, PROPOSAL), "utf8"));
233
- return { ...proposed, proposal };
302
+ // A draft calling an MCP tool with no declared price waits for its owner's OK whatever the grade (LS-07): held here,
303
+ // from the prices the store keeps now, and said to the grader.
304
+ const held = await heldOf(deps.store, proposal);
305
+ return { ...proposed, proposal: Object.keys(held).length ? { ...proposal, held } : proposal };
234
306
  }
235
307
  finally {
236
308
  await rm(runDir, { recursive: true, force: true });
@@ -18,6 +18,8 @@ export interface KeptProposal {
18
18
  readonly detail?: string;
19
19
  }>>;
20
20
  readonly asked?: readonly string[];
21
+ /** Why each draft waits for its owner's OK whatever the grade (the learning end's: skills.ts unpricedCalls). */
22
+ readonly held?: Readonly<Record<string, readonly string[]>>;
21
23
  readonly triggered?: readonly {
22
24
  readonly source: string;
23
25
  readonly text: string;
@@ -90,12 +90,17 @@ export function createLearningLoop(learning) {
90
90
  return (deps) => {
91
91
  let stopped = null;
92
92
  const now = learning.now ?? Date.now;
93
+ /** Aborted by a person's stop (a stop row): the grade's request is cut at once, never left running past it, while the
94
+ * claim's signal stays whole so the stopped end is still written. */
95
+ const stopAsk = new AbortController();
93
96
  return {
94
97
  async command(_command) {
95
98
  return { refused: "a learning run takes no messages or answers" };
96
99
  },
97
100
  async stop(reason) {
98
101
  stopped = reason;
102
+ if (reason.kind === "command")
103
+ stopAsk.abort(new Error("the run was stopped"));
99
104
  },
100
105
  async start(claim) {
101
106
  const context = withAbortSignal(deps.signal, BACKGROUND_CONTEXT);
@@ -170,7 +175,7 @@ export function createLearningLoop(learning) {
170
175
  const items = gradedItems(proposal.notes, (proposal.files ?? []));
171
176
  const prompt = gradePrompt({
172
177
  run: source.runId, ...(source.instructions ? { instructions: source.instructions } : {}), active: main.active, superseded: main.superseded, proposed: proposal.notes,
173
- ...(proposal.files?.length ? { files: proposal.files } : {}), ...(proposal.dryRuns ? { dryRuns: proposal.dryRuns } : {}), ...(proposal.asked ? { asked: proposal.asked } : {}), ...(proposal.triggered ? { triggered: proposal.triggered } : {}),
178
+ ...(proposal.files?.length ? { files: proposal.files } : {}), ...(proposal.dryRuns ? { dryRuns: proposal.dryRuns } : {}), ...(proposal.asked ? { asked: proposal.asked } : {}), ...(proposal.triggered ? { triggered: proposal.triggered } : {}), ...(proposal.held ? { held: proposal.held } : {}),
174
179
  });
175
180
  // What the grade spends, as the server's grade counted it (grade.ts counter): each ask's dollars and tokens
176
181
  // added, either unknown (null) once any ask's is, and an ask that fails spent what nobody knows.
@@ -178,10 +183,13 @@ export function createLearningLoop(learning) {
178
183
  let tokens = { input: 0, cache_read: 0, cache_write: 0, output: 0 };
179
184
  // `again`: what the grade is told after its last answer, below the same prompt.
180
185
  const ask = async (again) => {
186
+ // Stopped before this ask: nothing is sent, so nothing of it is spent (what it spent stays as it was).
187
+ if (stopAsk.signal.aborted)
188
+ throw stopAsk.signal.reason;
181
189
  const timer = AbortSignal.timeout(GRADE_TIMEOUT_MS);
182
190
  let answer;
183
191
  try {
184
- answer = await learning.ask({ prompt: again ? `${prompt}\n\n${again}` : prompt, maxTokens: GRADE_MAX_TOKENS }, AbortSignal.any([deps.signal, timer]), { journal: () => deps.journal(claim), flush: () => deps.flush() });
192
+ answer = await learning.ask({ prompt: again ? `${prompt}\n\n${again}` : prompt, maxTokens: GRADE_MAX_TOKENS }, AbortSignal.any([deps.signal, timer, stopAsk.signal]), { journal: () => deps.journal(claim), flush: () => deps.flush() });
185
193
  }
186
194
  catch (error) {
187
195
  usd = null;
@@ -195,15 +203,15 @@ export function createLearningLoop(learning) {
195
203
  };
196
204
  let verdict;
197
205
  try {
198
- verdict = parseVerdict(await ask(), items);
206
+ verdict = parseVerdict(await ask(), items, proposal.held);
199
207
  // An answer the host cannot read is asked once more, as the server's grade did.
200
208
  if (verdict.reason === UNREADABLE_REASON && !verdict.items.length)
201
- verdict = parseVerdict(await ask(), items);
209
+ verdict = parseVerdict(await ask(), items, proposal.held);
202
210
  // One that kept every item and said no merge contradicts itself: asked once more, the contradiction named. A
203
211
  // second contradiction stands as no merge, said in the host's words as twice (learning-words.ts notKept); a
204
212
  // contradiction after an unreadable answer is one, and is said so.
205
213
  else if (verdict.reason === CONTRADICTED_REASON) {
206
- const again = parseVerdict(await ask(CONTRADICTION_ASK), items);
214
+ const again = parseVerdict(await ask(CONTRADICTION_ASK), items, proposal.held);
207
215
  verdict = again.reason === CONTRADICTED_REASON ? { ...again, reason: CONTRADICTED_TWICE_REASON } : again;
208
216
  }
209
217
  }
@@ -25,6 +25,12 @@ export type LaidSeed = {
25
25
  readonly skills: readonly string[];
26
26
  readonly workflows: readonly LearnedWorkflow[];
27
27
  };
28
+ /** What a claim laid of a run's learning seed, by name, as the adapter loop records it (KINDS.learningLaid): each learned
29
+ * skill whose files it laid, and each learned workflow it handed the tool; none when nothing was laid. */
30
+ export declare const laidOf: (laid: LaidSeed | undefined) => {
31
+ skills: string[];
32
+ workflows: string[];
33
+ };
28
34
  /** Lays the run's learning seed (see the file's head). Undefined when the seed could not be read: nothing was laid.
29
35
  * Never throws. */
30
36
  export declare function layLearningSeed(lay: LearningSeedLay): Promise<LaidSeed | undefined>;
@@ -1,5 +1,11 @@
1
1
  import { chooseSkills, chooseWorkflows, layLearned, LEARNED_DIR, laySkills, readerOf, seedFrom, takeSkills } from "../learning.js";
2
2
  const message = (error) => (error instanceof Error ? error.message : String(error));
3
+ /** What a claim laid of a run's learning seed, by name, as the adapter loop records it (KINDS.learningLaid): each learned
4
+ * skill whose files it laid, and each learned workflow it handed the tool; none when nothing was laid. */
5
+ export const laidOf = (laid) => ({
6
+ skills: [...new Set((laid?.skills ?? []).map((path) => path.split("/")[0]))],
7
+ workflows: (laid?.workflows ?? []).map(({ name }) => name),
8
+ });
3
9
  /** Lays the run's learning seed (see the file's head). Undefined when the seed could not be read: nothing was laid.
4
10
  * Never throws. */
5
11
  export async function layLearningSeed(lay) {
@@ -128,6 +128,10 @@ export interface LoopDeps {
128
128
  * or at once when there were none: a resumed ask with no answer row waits for it before it parks again, so an
129
129
  * approve already on its way is never raced. Never rejects. */
130
130
  delivered?: Promise<void>;
131
+ /** Hands the run's command rows the runner has not handed on yet to command() now, not at its next poll (up to its
132
+ * command poll away), and resolves once each call returned: a turn that ends asks it before the run may end, so a
133
+ * message sent while the turn worked is answered, never refused by the run's end. Absent: nothing to hand on. */
134
+ deliverNow?: () => Promise<void>;
131
135
  /** Where the loop reports what its run shows before it is stored (a running tool, a partial answer), as it changes: a
132
136
  * reader of the newest held state (`undefined` once there is nothing held), called once per tick by the runner's live
133
137
  * ticker (runner/live-ticker.ts), never on every change, so a change costs the same however long the answer has grown.
@@ -38,6 +38,9 @@ export interface RunnerProcess {
38
38
  readonly kind: string;
39
39
  readonly schema: number;
40
40
  };
41
+ /** What its runs may hold, in MiB (RunnerMemory.budgetMib): its host's memory, or its container's limit, less the
42
+ * server's own. Said once at its start, after the ready line. */
43
+ readonly memoryMib: number;
41
44
  /** Closes the runner (its loops stopped, its runs released), then its store connection. */
42
45
  close(): Promise<void>;
43
46
  }
@@ -111,14 +114,16 @@ export declare function runnerHolds(args: {
111
114
  loops: number;
112
115
  drainMs: number;
113
116
  };
114
- /** The runner process's arguments: `--data D [--loops N] [--drain-timeout D] [--name N]`, or `--check --data D [--name
115
- * N]`. Each option with a value is also taken as `--option=value` (the bin hands a data directory that starts with "-"
116
- * so, never read as an option); an empty one is refused like a missing one. */
117
+ /** The runner process's arguments: `--data D [--loops N] [--drain-timeout D] [--name N] [--faux M]`, or `--check --data D
118
+ * [--name N]`. Each option with a value is also taken as `--option=value` (the bin hands a data directory that starts
119
+ * with "-" so, never read as an option); an empty one is refused like a missing one. `--faux`: the faux model module, a
120
+ * test switch, as the server's own --faux; the only way a runner loads one. */
117
121
  export declare function runnerArgs(argv: readonly string[]): {
118
122
  dataDir: string;
119
123
  loops?: number;
120
124
  drainMs?: number;
121
125
  name?: string;
126
+ faux?: string;
122
127
  check?: true;
123
128
  };
124
129
  /** Runs until SIGTERM or SIGINT, then closes. `ready` is called once the signals are handled, never before: a line that
@@ -135,7 +140,7 @@ export declare function lastResort(name: string, write?: (line: string) => void,
135
140
  /** `agentrun-serve runner ...`: the exit code. 2: bad arguments; 3: a store schema this runner does not know (or none
136
141
  * set up yet); 1: anything else; 0: closed on a signal, or --check found a fresh heartbeat. AGENTRUN_RUNNER_NAME names
137
142
  * it when --name does not. */
138
- export declare function runnerMain(argv: readonly string[], env?: NodeJS.ProcessEnv, hooks?: RunnerMainHooks): Promise<number>;
143
+ export declare function runnerMain(argv: readonly string[], given?: NodeJS.ProcessEnv, hooks?: RunnerMainHooks): Promise<number>;
139
144
  /** A test's hooks into runnerMain: `started`, awaited once the runner has started claiming and before its stop handlers
140
145
  * take over from the ones its start listened on (the window a stop must not fall through). */
141
146
  export type RunnerMainHooks = {
@@ -11,12 +11,12 @@
11
11
  // run is claimable when its lease lapses); then 0. Bad arguments exit 2, a store schema it does not know 3, anything else 1.
12
12
  // An error nothing handles exits 1 at once, said with its stack (lastResort).
13
13
  import { mkdirSync, statSync, utimesSync, writeFileSync, writeSync } from "node:fs";
14
- import { join } from "node:path";
14
+ import { join, resolve } from "node:path";
15
15
  import { dockerPathsForRuns } from "../box-paths.js";
16
16
  import { hostAddressesOnce } from "../docker-host-addresses.js";
17
17
  import { HARNESS_TABLE_ENV } from "../harness-table.js";
18
18
  import { maxRunsOf } from "../host.js";
19
- import { FAUX_PREFIX } from "../model.js";
19
+ import { FAUX_ENV, FAUX_PREFIX, withoutFaux } from "../model.js";
20
20
  import { durationMs } from "../print.js";
21
21
  import { bootSealKey } from "../seal-key.js";
22
22
  import { handedSecret, SECRET_NAMES, secret } from "../secrets.js";
@@ -154,6 +154,7 @@ export async function startRunnerProcess(options) {
154
154
  const warn = options.warn ?? ((message) => void process.stderr.write(`agentrun-serve runner: ${message}\n`));
155
155
  const env = options.env ?? process.env;
156
156
  const { store, kind, schema } = await openRunnerStore(options.dataDir, env, warn, options.storeUrl);
157
+ const memory = options.memory ?? runnerMemory(store);
157
158
  let runner;
158
159
  let seal;
159
160
  let janitor;
@@ -178,7 +179,7 @@ export async function startRunnerProcess(options) {
178
179
  name,
179
180
  ...(options.loops ? { loops: options.loops } : {}),
180
181
  ...(options.drainMs ? { drainMs: options.drainMs } : {}),
181
- memory: options.memory ?? runnerMemory(store),
182
+ memory,
182
183
  ...(options.onEvent ? { onEvent: options.onEvent } : {}),
183
184
  onBeat: heartbeat(options.dataDir, name, options.now ?? Date.now),
184
185
  });
@@ -194,6 +195,7 @@ export async function startRunnerProcess(options) {
194
195
  return {
195
196
  runner,
196
197
  store: { kind, schema },
198
+ memoryMib: memory.budgetMib,
197
199
  close: () => (closing ??= (async () => {
198
200
  // The janitor's sweep is cut and waited for on its own bound, beside the runner's close, never before it.
199
201
  await Promise.all([janitor?.close(), runner.close()]);
@@ -240,18 +242,20 @@ export function runnerHolds(args, env) {
240
242
  }
241
243
  return { loops, drainMs };
242
244
  }
243
- /** The runner process's arguments: `--data D [--loops N] [--drain-timeout D] [--name N]`, or `--check --data D [--name
244
- * N]`. Each option with a value is also taken as `--option=value` (the bin hands a data directory that starts with "-"
245
- * so, never read as an option); an empty one is refused like a missing one. */
245
+ /** The runner process's arguments: `--data D [--loops N] [--drain-timeout D] [--name N] [--faux M]`, or `--check --data D
246
+ * [--name N]`. Each option with a value is also taken as `--option=value` (the bin hands a data directory that starts
247
+ * with "-" so, never read as an option); an empty one is refused like a missing one. `--faux`: the faux model module, a
248
+ * test switch, as the server's own --faux; the only way a runner loads one. */
246
249
  export function runnerArgs(argv) {
247
250
  let dataDir;
248
251
  let loops;
249
252
  let drainMs;
250
253
  let name;
254
+ let faux;
251
255
  let check = false;
252
256
  for (let i = 0; i < argv.length; i++) {
253
257
  const given = argv[i];
254
- const equals = /^(--(?:data|loops|drain-timeout|name))=(.*)$/s.exec(given);
258
+ const equals = /^(--(?:data|loops|drain-timeout|name|faux))=(.*)$/s.exec(given);
255
259
  const arg = equals ? equals[1] : given;
256
260
  const value = () => {
257
261
  const next = equals ? equals[2] : argv[++i];
@@ -275,14 +279,16 @@ export function runnerArgs(argv) {
275
279
  }
276
280
  else if (arg === "--name")
277
281
  name = value();
282
+ else if (arg === "--faux")
283
+ faux = value();
278
284
  else if (arg === "--check")
279
285
  check = true;
280
286
  else
281
- throw new RunnerRefused(`unknown argument ${JSON.stringify(arg)}: a runner takes --data D [--loops N] [--drain-timeout D] [--name N], or --check --data D [--name N]`);
287
+ throw new RunnerRefused(`unknown argument ${JSON.stringify(arg)}: a runner takes --data D [--loops N] [--drain-timeout D] [--name N] [--faux M], or --check --data D [--name N]`);
282
288
  }
283
289
  if (!dataDir)
284
290
  throw new RunnerRefused("a runner needs its data directory: --data D");
285
- return { dataDir, ...(loops === undefined ? {} : { loops }), ...(drainMs === undefined ? {} : { drainMs }), ...(name === undefined ? {} : { name }), ...(check ? { check: true } : {}) };
291
+ return { dataDir, ...(loops === undefined ? {} : { loops }), ...(drainMs === undefined ? {} : { drainMs }), ...(name === undefined ? {} : { name }), ...(faux === undefined ? {} : { faux }), ...(check ? { check: true } : {}) };
286
292
  }
287
293
  /** Runs until SIGTERM or SIGINT, then closes. `ready` is called once the signals are handled, never before: a line that
288
294
  * says the runner is ready (on a pipe, written at once) may bring a SIGTERM back before the next statement runs, and one
@@ -326,7 +332,7 @@ function said(name, event) {
326
332
  /** `agentrun-serve runner ...`: the exit code. 2: bad arguments; 3: a store schema this runner does not know (or none
327
333
  * set up yet); 1: anything else; 0: closed on a signal, or --check found a fresh heartbeat. AGENTRUN_RUNNER_NAME names
328
334
  * it when --name does not. */
329
- export async function runnerMain(argv, env = process.env, hooks = {}) {
335
+ export async function runnerMain(argv, given = process.env, hooks = {}) {
330
336
  let args;
331
337
  try {
332
338
  args = runnerArgs(argv);
@@ -337,6 +343,10 @@ export async function runnerMain(argv, env = process.env, hooks = {}) {
337
343
  console.error(`agentrun-serve runner: ${error.message}`);
338
344
  return 2;
339
345
  }
346
+ // A test switch is this start's option alone, as on the server (server.ts withoutFaux, fauxEnvOf): one the process
347
+ // inherited (AGENTRUN_SERVE_FAUX*, the harness table, left in an operator's shell or a platform's settings) never loads
348
+ // a module or decides what a run answers. --faux sets the faux model's.
349
+ const env = { ...withoutFaux(given), ...(args.faux ? { [FAUX_ENV]: resolve(args.faux) } : {}) };
340
350
  const name = args.name ?? env.AGENTRUN_RUNNER_NAME ?? undefined;
341
351
  if (args.check) {
342
352
  if (!name) {
@@ -413,7 +423,12 @@ export async function runnerMain(argv, env = process.env, hooks = {}) {
413
423
  return 0;
414
424
  }
415
425
  // Ready is said once SIGTERM and SIGINT are handled, so a stop sent on reading it always closes the runner.
416
- await runUntilSignalled(started, RUNNER_SIGNALS, () => console.log(`Runner ${started.runner.name} ready: store ${started.store.kind} schema v${started.store.schema}, ${holds.loops} loops`));
426
+ // Then its memory budget, a line of its own (the ready line's shape is read by deploy checks): what a container's limit
427
+ // gave it is seen where it runs.
428
+ await runUntilSignalled(started, RUNNER_SIGNALS, () => {
429
+ console.log(`Runner ${started.runner.name} ready: store ${started.store.kind} schema v${started.store.schema}, ${holds.loops} loops`);
430
+ console.log(`Runner ${started.runner.name} memory: ${started.memoryMib} MiB for runs, each weighed by its harness`);
431
+ });
417
432
  return 0;
418
433
  }
419
434
  /** The signals that stop a runner process. */
@@ -53,6 +53,9 @@ export interface McpClaimStep {
53
53
  fresh(): Promise<void>;
54
54
  /** Drop every credential held: the loop ended, or the claim is lost. */
55
55
  release(): void;
56
+ /** Before each call of `server` (the gateway's beforeCall): a github_app token whose App was disconnected or replaced
57
+ * since it was minted is dropped, revoked, and the call refused in words. */
58
+ beforeCall(server: string, signal: AbortSignal): Promise<void>;
56
59
  }
57
60
  /** The MCP step of `options.claim`: its pin made or read and checked, its credentials opened (refreshed as due). */
58
61
  export declare function mcpClaim(options: McpClaimOptions): Promise<McpClaimStep>;
@@ -299,7 +299,12 @@ export async function mcpClaim(options) {
299
299
  await confirm(store, claim);
300
300
  };
301
301
  await fresh();
302
- return { pin, credentials, secrets, fresh, release };
302
+ const beforeCall = async (server, signal) => {
303
+ signal.throwIfAborted();
304
+ if (!released)
305
+ await github.check(server);
306
+ };
307
+ return { pin, credentials, secrets, fresh, release, beforeCall };
303
308
  }
304
309
  /** The run's pin: read, and checked against the meta tools known now; or made at its first claim and written once. */
305
310
  async function pinOf({ store, claim, grants, githubMcpOrigin = GITHUB_MCP_ORIGIN }) {
@@ -8,7 +8,7 @@ export type GithubAppMint = (target: {
8
8
  expires_at: number;
9
9
  } | {
10
10
  ok: false;
11
- reason: "not_installed" | "no_repo" | "github_failed";
11
+ reason: "not_installed" | "no_repo" | "github_failed" | "disconnected";
12
12
  message: string;
13
13
  }>;
14
14
  /** What the runner gives the step for a run's github_app servers: the bound mint, and the run's repository (from its
@@ -19,6 +19,11 @@ export interface GithubAppAccess {
19
19
  readonly installation?: number;
20
20
  readonly repo: string;
21
21
  } | undefined;
22
+ /** Revokes an installation token this access minted (best effort): one dropped at release or on a disconnect. */
23
+ readonly revoke?: (token: string) => Promise<void>;
24
+ /** Whether the App is still the one this access mints with (its id and key): read before each call, so a disconnect
25
+ * or a new App stops a run's token at its next call, not at its next mint. */
26
+ readonly same?: () => Promise<boolean>;
22
27
  }
23
28
  /** A timer the step arms: the refresh before expiry, the expiry itself. */
24
29
  export type GithubTimer = (fire: () => void, ms: number) => {
@@ -33,6 +38,7 @@ export declare const GITHUB_UNUSABLE: {
33
38
  notInstalled: (repo: string) => string;
34
39
  failed: (message: string) => string;
35
40
  expired: (message: string) => string;
41
+ disconnected: string;
36
42
  };
37
43
  type Entry = {
38
44
  headers?: Record<string, string>;
@@ -47,7 +53,10 @@ export declare function githubTokens(access: GithubAppAccess | undefined, { now,
47
53
  /** `name`'s token: the one held while it has more than REFRESH_BEFORE_MS left (a claim's fresh() again mints
48
54
  * nothing), else a new one. */
49
55
  open(name: string, put: (entry: Entry) => void): Promise<void>;
50
- /** Every token dropped and every timer stopped: the loop ended, or the claim is lost. */
56
+ /** Before a call of `name`: the token held for it, when the App it was minted under is gone or replaced, is dropped
57
+ * and revoked, and the server's calls refused in words. */
58
+ check(name: string): Promise<void>;
59
+ /** Every token dropped and revoked, and every timer stopped: the loop ended, or the claim is lost. */
51
60
  release(): void;
52
61
  };
53
62
  export {};
@@ -14,6 +14,7 @@ export const GITHUB_UNUSABLE = {
14
14
  notInstalled: (repo) => `the GitHub App is not installed on ${repo}: install it from Settings → GitHub`,
15
15
  failed: (message) => `GitHub did not make a token for this run (${message})`,
16
16
  expired: (message) => `its GitHub App token expired and a new one could not be made (${message})`,
17
+ disconnected: "the GitHub App this run's token came from was disconnected or replaced on this server (Settings → GitHub)",
17
18
  };
18
19
  const REAL_TIMER = (fire, ms) => {
19
20
  const timer = setTimeout(fire, Math.min(Math.max(0, ms), 2 ** 31 - 1));
@@ -24,12 +25,33 @@ const REAL_TIMER = (fire, ms) => {
24
25
  * hands its entry to `put`, then keeps it fresh until `release`. */
25
26
  export function githubTokens(access, { now = Date.now, arm = REAL_TIMER } = {}) {
26
27
  const held = new Map();
28
+ /** The tokens a refresh replaced, by server, until they expire: a call already sent may still carry one, so it is not
29
+ * revoked at the refresh, only when its server's access ends (drop) or the run's does (release). */
30
+ const replaced = new Map();
27
31
  let released = false;
32
+ /** Each server's access epoch: a drop ends it, so a mint that was out across the drop (a refresh while check() found
33
+ * the App gone) installs nothing; its token is revoked. */
34
+ const epochs = new Map();
35
+ const epochOf = (name) => epochs.get(name) ?? 0;
28
36
  const clear = (name) => {
29
37
  for (const timer of held.get(name)?.timers ?? [])
30
38
  timer.clear();
31
39
  held.delete(name);
32
40
  };
41
+ const revoke = (token) => void access?.revoke?.(token).catch(() => undefined);
42
+ /** `name`'s tokens, the one held and every one a refresh replaced that has not expired, revoked at GitHub as they are
43
+ * dropped: never left live past its run or its App. */
44
+ const drop = (name) => {
45
+ epochs.set(name, epochOf(name) + 1);
46
+ const token = held.get(name)?.token;
47
+ clear(name);
48
+ if (token)
49
+ revoke(token);
50
+ for (const old of replaced.get(name) ?? [])
51
+ if (old.expiresAt > now())
52
+ revoke(old.token);
53
+ replaced.delete(name);
54
+ };
33
55
  /** A token minted for `name` and put; its refresh and its expiry armed. On a refresh that fails, the token held keeps
34
56
  * working until it expires, then the server's calls are refused in words. */
35
57
  const mint = async (name, put, refreshing) => {
@@ -37,6 +59,7 @@ export function githubTokens(access, { now = Date.now, arm = REAL_TIMER } = {})
37
59
  return put({ unopened: GITHUB_UNUSABLE.noAccess });
38
60
  if (!access.target)
39
61
  return put({ unopened: GITHUB_UNUSABLE.noRepo });
62
+ const epoch = epochOf(name);
40
63
  let got;
41
64
  try {
42
65
  got = await access.mint(access.target);
@@ -44,8 +67,18 @@ export function githubTokens(access, { now = Date.now, arm = REAL_TIMER } = {})
44
67
  catch (error) {
45
68
  got = { ok: false, reason: "github_failed", message: String(error?.message ?? error) };
46
69
  }
47
- if (released)
70
+ // A mint that came back after the run's access ended, or the server's (its token dropped meanwhile, its calls
71
+ // refused): its token is revoked at once, never held, and the refusal stands.
72
+ if (released || epochOf(name) !== epoch) {
73
+ if (got.ok)
74
+ revoke(got.token);
48
75
  return;
76
+ }
77
+ // The App disconnected or replaced since the claim: the token held stops now, revoked, never used to its expiry.
78
+ if (!got.ok && got.reason === "disconnected") {
79
+ drop(name);
80
+ return put({ unopened: GITHUB_UNUSABLE.disconnected });
81
+ }
49
82
  if (!got.ok) {
50
83
  const why = got.reason === "not_installed" ? GITHUB_UNUSABLE.notInstalled(access.target.repo) : got.reason === "no_repo" ? GITHUB_UNUSABLE.noRepo : GITHUB_UNUSABLE.failed(got.message);
51
84
  const kept = held.get(name);
@@ -64,6 +97,9 @@ export function githubTokens(access, { now = Date.now, arm = REAL_TIMER } = {})
64
97
  clear(name);
65
98
  return put({ unopened: why });
66
99
  }
100
+ const previous = held.get(name);
101
+ if (previous && previous.token !== got.token)
102
+ replaced.set(name, [...(replaced.get(name) ?? []).filter((old) => old.expiresAt > now()), { token: previous.token, expiresAt: previous.expiresAt }]);
67
103
  clear(name);
68
104
  const entry = { token: got.token, expiresAt: got.expires_at, timers: [], put };
69
105
  held.set(name, entry);
@@ -81,11 +117,26 @@ export function githubTokens(access, { now = Date.now, arm = REAL_TIMER } = {})
81
117
  }
82
118
  await mint(name, put, false);
83
119
  },
84
- /** Every token dropped and every timer stopped: the loop ended, or the claim is lost. */
120
+ /** Before a call of `name`: the token held for it, when the App it was minted under is gone or replaced, is dropped
121
+ * and revoked, and the server's calls refused in words. */
122
+ async check(name) {
123
+ const kept = held.get(name);
124
+ // A read that fails throws on: the gateway refuses the call unsent, the token kept (fail closed, never dropped).
125
+ if (!kept || !access?.same || (await access.same()))
126
+ return;
127
+ if (released)
128
+ return;
129
+ // The App is gone or replaced: whatever is held now (a refresh may have replaced the token while the read waited)
130
+ // is dropped and revoked, and the server's calls refused, never sent on the replacement.
131
+ const now_ = held.get(name) ?? kept;
132
+ drop(name);
133
+ now_.put({ unopened: GITHUB_UNUSABLE.disconnected });
134
+ },
135
+ /** Every token dropped and revoked, and every timer stopped: the loop ended, or the claim is lost. */
85
136
  release() {
86
137
  released = true;
87
- for (const name of [...held.keys()])
88
- clear(name);
138
+ for (const name of new Set([...held.keys(), ...replaced.keys()]))
139
+ drop(name);
89
140
  },
90
141
  };
91
142
  }
@@ -43,6 +43,7 @@ export async function mcpForClaim(options) {
43
43
  const gateway = mcpGateway({
44
44
  pin,
45
45
  credentials: step.credentials,
46
+ beforeCall: step.beforeCall,
46
47
  work: options.work,
47
48
  commit: () => (change) => options.harness.commit(change, BACKGROUND_CONTEXT),
48
49
  ...(options.fetch ? { fetch: options.fetch } : {}),