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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (287) hide show
  1. package/CHANGELOG.md +149 -1
  2. package/README.md +295 -37
  3. package/dist/agent-delete.d.ts +5 -6
  4. package/dist/agent-delete.js +30 -67
  5. package/dist/agent-package.d.ts +71 -0
  6. package/dist/agent-package.js +345 -0
  7. package/dist/agent-rows.d.ts +1 -1
  8. package/dist/agents-store.d.ts +26 -20
  9. package/dist/agents-store.js +42 -34
  10. package/dist/api-only.d.ts +25 -6
  11. package/dist/api-only.js +34 -13
  12. package/dist/claude-login.d.ts +1 -0
  13. package/dist/claude-login.js +1 -1
  14. package/dist/cli-learning/cli.d.ts +3 -0
  15. package/dist/cli-learning/cli.js +17 -3
  16. package/dist/cli-learning/connections.js +3 -2
  17. package/dist/cli-learning/schema.js +2 -1
  18. package/dist/cli.js +76 -8
  19. package/dist/composio-preset.d.ts +3 -1
  20. package/dist/composio-preset.js +5 -3
  21. package/dist/composio-triggers.d.ts +4 -0
  22. package/dist/composio-triggers.js +4 -1
  23. package/dist/computer-needs.d.ts +32 -0
  24. package/dist/computer-needs.js +80 -0
  25. package/dist/computer-setting.d.ts +5 -2
  26. package/dist/computer-setting.js +8 -1
  27. package/dist/computers.d.ts +0 -2
  28. package/dist/computers.js +1 -1
  29. package/dist/console/assets/index-B_85An2t.js +745 -0
  30. package/dist/console/assets/index-n1YsbnYh.css +1 -0
  31. package/dist/console/index.html +2 -2
  32. package/dist/console-links.d.ts +1 -0
  33. package/dist/console-links.js +2 -0
  34. package/dist/env-switch.d.ts +14 -0
  35. package/dist/env-switch.js +23 -0
  36. package/dist/errors.d.ts +5 -0
  37. package/dist/errors.js +10 -0
  38. package/dist/eval-previous.js +4 -3
  39. package/dist/fal-price.js +10 -13
  40. package/dist/github-connection.d.ts +50 -1
  41. package/dist/github-connection.js +96 -3
  42. package/dist/github-faux.d.ts +11 -2
  43. package/dist/github-faux.js +138 -7
  44. package/dist/github-pull-request.d.ts +37 -0
  45. package/dist/github-pull-request.js +110 -0
  46. package/dist/handed-secret.d.ts +4 -0
  47. package/dist/handed-secret.js +10 -0
  48. package/dist/harness-archive.d.ts +15 -5
  49. package/dist/harness-archive.js +71 -34
  50. package/dist/harness-check.d.ts +2 -1
  51. package/dist/harness-check.js +36 -95
  52. package/dist/harness-egress.d.ts +23 -0
  53. package/dist/harness-egress.js +69 -0
  54. package/dist/harness-recipe-entry.d.ts +71 -0
  55. package/dist/harness-recipe-entry.js +184 -0
  56. package/dist/harness-recipe.d.ts +73 -6
  57. package/dist/harness-recipe.js +185 -31
  58. package/dist/harness-sign-in.d.ts +29 -0
  59. package/dist/harness-sign-in.js +122 -0
  60. package/dist/harness-table.d.ts +21 -0
  61. package/dist/harness-table.js +58 -3
  62. package/dist/harness-zip.d.ts +6 -0
  63. package/dist/harness-zip.js +203 -0
  64. package/dist/ids.d.ts +11 -0
  65. package/dist/ids.js +36 -0
  66. package/dist/learn/commit.d.ts +14 -1
  67. package/dist/learn/commit.js +156 -1
  68. package/dist/learn/compile.js +22 -8
  69. package/dist/learn/folder.d.ts +5 -0
  70. package/dist/learn/folder.js +10 -1
  71. package/dist/learn/learning.sh +15 -3
  72. package/dist/learn/promote.d.ts +2 -2
  73. package/dist/learn/secrets.js +30 -7
  74. package/dist/learning-routes.d.ts +23 -11
  75. package/dist/learning-routes.js +110 -20
  76. package/dist/learning.d.ts +9 -6
  77. package/dist/learning.js +9 -4
  78. package/dist/live-reach.d.ts +34 -7
  79. package/dist/live-reach.js +76 -11
  80. package/dist/mcp-gateway.js +15 -2
  81. package/dist/mcp-probe.d.ts +3 -0
  82. package/dist/mcp-probe.js +8 -3
  83. package/dist/mcp-resources.d.ts +44 -0
  84. package/dist/mcp-resources.js +100 -0
  85. package/dist/mcp-servers-store.d.ts +16 -12
  86. package/dist/model.d.ts +4 -4
  87. package/dist/model.js +6 -6
  88. package/dist/native/cli.js +9 -2
  89. package/dist/native/connection.d.ts +2 -2
  90. package/dist/native/connection.js +5 -2
  91. package/dist/native/discovery.d.ts +2 -0
  92. package/dist/native/discovery.js +10 -6
  93. package/dist/native/remote-worker-bridge.js +36 -4
  94. package/dist/native/remote.d.ts +18 -1
  95. package/dist/native/remote.js +126 -37
  96. package/dist/native/schema.d.ts +6 -0
  97. package/dist/native/schema.js +31 -6
  98. package/dist/native/source-account.d.ts +13 -0
  99. package/dist/native/source-account.js +114 -0
  100. package/dist/native/source-capture-hooks.d.ts +5 -0
  101. package/dist/native/source-capture-hooks.js +102 -0
  102. package/dist/native/source-mcp-selection.d.ts +13 -0
  103. package/dist/native/source-mcp-selection.js +72 -0
  104. package/dist/native/source-runtime-tools.d.ts +19 -0
  105. package/dist/native/source-runtime-tools.js +103 -0
  106. package/dist/native/source-snapshot-types.d.ts +138 -0
  107. package/dist/native/source-snapshot-types.js +12 -0
  108. package/dist/native/source-snapshot.d.ts +8 -0
  109. package/dist/native/source-snapshot.js +1201 -0
  110. package/dist/observation/learning.js +3 -2
  111. package/dist/openapi.js +275 -40
  112. package/dist/print.js +1 -1
  113. package/dist/purged-workflow.d.ts +12 -0
  114. package/dist/purged-workflow.js +43 -0
  115. package/dist/run-keys.d.ts +46 -0
  116. package/dist/run-keys.js +109 -0
  117. package/dist/run-launch.d.ts +16 -1
  118. package/dist/run-launch.js +30 -1
  119. package/dist/run-learning-served.d.ts +2 -2
  120. package/dist/run-model-key.d.ts +2 -2
  121. package/dist/run-model-key.js +5 -5
  122. package/dist/run-secrets.d.ts +2 -0
  123. package/dist/run-secrets.js +7 -4
  124. package/dist/run-view.d.ts +17 -0
  125. package/dist/run-view.js +25 -1
  126. package/dist/runner/adapter-loop.d.ts +11 -3
  127. package/dist/runner/adapter-loop.js +138 -22
  128. package/dist/runner/adapter-run-spec.js +26 -13
  129. package/dist/runner/audit.d.ts +2 -0
  130. package/dist/runner/audit.js +9 -1
  131. package/dist/runner/beside.js +2 -1
  132. package/dist/runner/claim-secrets.d.ts +29 -3
  133. package/dist/runner/claim-secrets.js +38 -4
  134. package/dist/runner/cli-run-spec.js +24 -13
  135. package/dist/runner/harness-loops.d.ts +6 -0
  136. package/dist/runner/harness-loops.js +11 -1
  137. package/dist/runner/held.d.ts +4 -0
  138. package/dist/runner/journal-kinds.d.ts +2 -0
  139. package/dist/runner/learned-first.d.ts +2 -0
  140. package/dist/runner/learned-first.js +1 -1
  141. package/dist/runner/learning-end.d.ts +7 -2
  142. package/dist/runner/learning-end.js +22 -10
  143. package/dist/runner/learning-seed.d.ts +9 -3
  144. package/dist/runner/learning-seed.js +2 -2
  145. package/dist/runner/main.d.ts +1 -0
  146. package/dist/runner/main.js +20 -13
  147. package/dist/runner/mcp-claim.js +6 -1
  148. package/dist/runner/mcp-run.d.ts +10 -7
  149. package/dist/runner/mcp-run.js +3 -5
  150. package/dist/runner/metrics.d.ts +4 -2
  151. package/dist/runner/metrics.js +15 -3
  152. package/dist/runner/monid-run.js +9 -11
  153. package/dist/runner/pr-checkout.d.ts +21 -4
  154. package/dist/runner/pr-checkout.js +103 -4
  155. package/dist/runner/project-checkpoint.d.ts +35 -0
  156. package/dist/runner/project-checkpoint.js +116 -0
  157. package/dist/runner/project-drain.d.ts +8 -0
  158. package/dist/runner/project-drain.js +25 -0
  159. package/dist/runner/project-host.d.ts +10 -0
  160. package/dist/runner/project-host.js +52 -0
  161. package/dist/runner/promotion.d.ts +14 -6
  162. package/dist/runner/promotion.js +98 -41
  163. package/dist/runner/redact.d.ts +13 -0
  164. package/dist/runner/redact.js +67 -1
  165. package/dist/runner/run-channel.d.ts +9 -0
  166. package/dist/runner/run-channel.js +15 -2
  167. package/dist/runner/run-child-host.d.ts +8 -4
  168. package/dist/runner/run-child-host.js +178 -45
  169. package/dist/runner/run-errors.js +2 -2
  170. package/dist/runner/runner-check.d.ts +3 -0
  171. package/dist/runner/runner-check.js +28 -2
  172. package/dist/runner/runner.js +26 -9
  173. package/dist/runner/store-secrets.js +7 -3
  174. package/dist/runner/workflow-first.d.ts +4 -0
  175. package/dist/runner/workflow-first.js +13 -0
  176. package/dist/runner/workflow-loop.d.ts +2 -1
  177. package/dist/runner/workflow-loop.js +2 -1
  178. package/dist/runner/workflow-spec.js +1 -1
  179. package/dist/runs-over-store.d.ts +34 -6
  180. package/dist/runs-over-store.js +133 -25
  181. package/dist/sdk/runs.d.ts +11 -1
  182. package/dist/sdk/runs.js +117 -26
  183. package/dist/sdk/schema.js +12 -2
  184. package/dist/sdk/workflows.d.ts +1 -1
  185. package/dist/server.d.ts +79 -32
  186. package/dist/server.js +673 -113
  187. package/dist/skills/agentrun-serve/SKILL.md +2 -1
  188. package/dist/source-sync/adoption.d.ts +15 -0
  189. package/dist/source-sync/adoption.js +36 -0
  190. package/dist/source-sync/auxiliary.d.ts +23 -0
  191. package/dist/source-sync/auxiliary.js +64 -0
  192. package/dist/source-sync/capture-git.d.ts +5 -0
  193. package/dist/source-sync/capture-git.js +272 -0
  194. package/dist/source-sync/capture-project.d.ts +53 -0
  195. package/dist/source-sync/capture-project.js +206 -0
  196. package/dist/source-sync/capture-refusal.d.ts +7 -0
  197. package/dist/source-sync/capture-refusal.js +16 -0
  198. package/dist/source-sync/capture.d.ts +11 -0
  199. package/dist/source-sync/capture.js +22 -0
  200. package/dist/source-sync/checkpoint-gate.d.ts +21 -0
  201. package/dist/source-sync/checkpoint-gate.js +52 -0
  202. package/dist/source-sync/checkpoints.d.ts +66 -0
  203. package/dist/source-sync/checkpoints.js +168 -0
  204. package/dist/source-sync/claim.d.ts +11 -0
  205. package/dist/source-sync/claim.js +48 -0
  206. package/dist/source-sync/destination.d.ts +47 -0
  207. package/dist/source-sync/destination.js +239 -0
  208. package/dist/source-sync/io.d.ts +15 -0
  209. package/dist/source-sync/io.js +52 -0
  210. package/dist/source-sync/local.d.ts +43 -0
  211. package/dist/source-sync/local.js +229 -0
  212. package/dist/source-sync/prepare.d.ts +59 -0
  213. package/dist/source-sync/prepare.js +93 -0
  214. package/dist/source-sync/projects.d.ts +61 -0
  215. package/dist/source-sync/projects.js +130 -0
  216. package/dist/source-sync/registry.d.ts +95 -0
  217. package/dist/source-sync/registry.js +226 -0
  218. package/dist/source-sync/service.d.ts +33 -0
  219. package/dist/source-sync/service.js +118 -0
  220. package/dist/source-sync/skill-edits.d.ts +12 -0
  221. package/dist/source-sync/skill-edits.js +122 -0
  222. package/dist/source-sync/snapshots.d.ts +48 -0
  223. package/dist/source-sync/snapshots.js +448 -0
  224. package/dist/source-sync/types.d.ts +9 -0
  225. package/dist/source-sync/types.js +14 -0
  226. package/dist/source-sync/workspace.d.ts +66 -0
  227. package/dist/source-sync/workspace.js +273 -0
  228. package/dist/store/agent-body.d.ts +6 -2
  229. package/dist/store/agent-body.js +18 -7
  230. package/dist/store/index.d.ts +2 -2
  231. package/dist/store/index.js +1 -1
  232. package/dist/store/schema.d.ts +2 -1
  233. package/dist/store/schema.js +2 -1
  234. package/dist/store/seal.d.ts +5 -1
  235. package/dist/store/seal.js +12 -3
  236. package/dist/store/sqlite/project-checkpoints.d.ts +11 -0
  237. package/dist/store/sqlite/project-checkpoints.js +70 -0
  238. package/dist/store/sqlite/run-launch.d.ts +4 -12
  239. package/dist/store/sqlite/run-launch.js +5 -19
  240. package/dist/store/sqlite/store.js +224 -170
  241. package/dist/store/store.d.ts +116 -39
  242. package/dist/store/store.js +14 -1
  243. package/dist/store-reads/learning.d.ts +2 -2
  244. package/dist/store-view.d.ts +3 -1
  245. package/dist/store-view.js +17 -5
  246. package/dist/suggestions.d.ts +282 -0
  247. package/dist/suggestions.js +919 -0
  248. package/dist/telemetry.d.ts +8 -1
  249. package/dist/telemetry.js +12 -4
  250. package/dist/template-import.d.ts +27 -2
  251. package/dist/template-import.js +148 -13
  252. package/dist/templates.d.ts +103 -77
  253. package/dist/templates.js +71 -17
  254. package/dist/timeline/index.d.ts +1 -1
  255. package/dist/timeline/index.js +1 -1
  256. package/dist/timeline/timeline.d.ts +5 -0
  257. package/dist/timeline/timeline.js +8 -0
  258. package/dist/tool-plane.d.ts +12 -12
  259. package/dist/tools.d.ts +8 -8
  260. package/dist/trigger-launch-hook.d.ts +49 -0
  261. package/dist/trigger-launch-hook.js +91 -0
  262. package/dist/trigger-targets.d.ts +14 -1
  263. package/dist/trigger-targets.js +20 -0
  264. package/dist/triggers.d.ts +54 -5
  265. package/dist/triggers.js +143 -8
  266. package/dist/uploads-archil.js +1 -1
  267. package/dist/uploads.js +1 -1
  268. package/dist/validate.d.ts +1 -1
  269. package/dist/validate.js +3 -4
  270. package/dist/workspace/computer-for-claim.d.ts +2 -0
  271. package/dist/workspace/computer-for-claim.js +43 -0
  272. package/dist/workspace/paths.d.ts +6 -0
  273. package/dist/workspace/paths.js +6 -0
  274. package/dist/workspace/resolve-computer.d.ts +1 -0
  275. package/dist/workspace/run-tools.d.ts +2 -0
  276. package/dist/workspace/run-tools.js +8 -0
  277. package/dist/workspace/synced-folder.d.ts +1 -1
  278. package/dist/workspace/synced-folder.js +11 -14
  279. package/launcher/agentrun-serve +1 -1
  280. package/package.json +10 -10
  281. package/skills/agentrun-serve/SKILL.md +2 -1
  282. package/templates/README.md +8 -4
  283. package/templates/agent-scout/agent.md +46 -0
  284. package/templates/agent-scout/skills/scout/SKILL.md +88 -0
  285. package/templates/agent-scout/skills/scout/suggestions.schema.json +112 -0
  286. package/dist/console/assets/index-B-D0EM3j.js +0 -733
  287. package/dist/console/assets/index-DlQepP2J.css +0 -1
@@ -1,8 +1,9 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { CORRECTIONS_CAP, draftProblems, frontKeys, isHeld, LEARNED_KEYS, learnedPlace, learnedStatus, printable, released, restorable, restoredLearned, retiredLearned, UNCLEAR_FRONT, unclearFront, unstorable, WORKFLOW_NAME, WORKFLOWS_DIR } from "./learn/index.js";
3
3
  import { readmeProblems } from "./learn/workflow-draft.js";
4
- import { putCorrections, readCorrections } from "./learn/commit.js";
5
- import { blobOid, FolderBusy, FolderRefused, FolderTooLarge, FolderUnreadable, readLearning, PATCH_CAP, readRunDiff, readSnapshot, runDiffKey, textsAt, writeLearning } from "./learn/folder.js";
4
+ import { forgetRunText, putCorrections, readCorrections } from "./learn/commit.js";
5
+ import { blobOid, FolderBusy, FolderRefused, FolderTooLarge, FolderUnreadable, readLearning, PATCH_CAP, readRunDiff, readSnapshot, runDiffKey, snapshotAt, textsAt, writeLearning } from "./learn/folder.js";
6
+ import { purgedRun, purgedWorkflows } from "./purged-workflow.js";
6
7
  import { ApiError, invalid } from "./errors.js";
7
8
  import { detailShown, filesView, learningFolderOf, reasonShown, withAgentRepo } from "./learning.js";
8
9
  import { isObject } from "./validate.js";
@@ -49,6 +50,30 @@ function routeFailure(error) {
49
50
  return error.link ? new Error(error.message) : new ApiError("unavailable", error.message);
50
51
  return error;
51
52
  }
53
+ /** Whether a change of `snapshot`'s log is served: none by a purged run (a run's purge, agent-delete.ts purgeRun), so
54
+ * the folder's history reads serve none of its merges. Asked at each read, so a log the folder rebuilds names them and
55
+ * still serves none. */
56
+ async function servedIn(snapshot, purgedOf) {
57
+ const runs = [...new Set(snapshot.log.flatMap(({ by }) => ("run" in by ? [by.run] : [])))];
58
+ const purged = runs.length ? await purgedOf(runs) : new Set();
59
+ return ({ by }) => !("run" in by && purged.has(by.run));
60
+ }
61
+ /** Run `runId`'s text taken off agent `agentId`'s learning folder's current files at its purge (learn/commit.ts
62
+ * forgetRunText), in the agent's queue, as every write of the folder is. */
63
+ export async function forgetRunLearning(data, agentId, runId) {
64
+ await withAgentRepo(data, agentId, async () => {
65
+ const { workspace: ws, end } = learningFolderOf(data, agentId);
66
+ try {
67
+ await forgetRunText(ws, runId);
68
+ }
69
+ catch (error) {
70
+ throw routeFailure(error);
71
+ }
72
+ finally {
73
+ await end();
74
+ }
75
+ });
76
+ }
52
77
  /** A read of agent `agentId`'s folder: `read` over its snapshot and the bodies it names (learn/folder.ts readLearning),
53
78
  * `none` for a folder with no main yet; the folder ended after. */
54
79
  async function reading(data, agentId, read, none) {
@@ -110,7 +135,18 @@ function pageAt(agentId, snapshot, at) {
110
135
  return kept ? { snapshot: kept, offset: at.offset } : { snapshot, offset: 0 };
111
136
  }
112
137
  /** A page of the changes on main, newest first, cut of the host's secrets. */
113
- const logPage = (snapshot, offset, limit, shown) => ({ items: snapshot.log.slice(offset, offset + limit).map((change) => changeView(change, shown)), total: snapshot.log.length, next_cursor: offset + limit < snapshot.log.length ? cursorOf(snapshot.main, offset + limit) : null });
138
+ /** `served` changes only: the offset and the cursor count the log as the snapshot keeps it, so a run purged between two
139
+ * pages moves no change the next page starts at. */
140
+ function logPage(snapshot, offset, limit, shown, served) {
141
+ const { log } = snapshot;
142
+ const items = [];
143
+ let at = offset;
144
+ for (; at < log.length && items.length < limit; at++)
145
+ if (served(log[at]))
146
+ items.push(changeView(log[at], shown));
147
+ const more = log.slice(at).some(served);
148
+ return { items, total: log.filter(served).length, next_cursor: more ? cursorOf(snapshot.main, at) : null };
149
+ }
114
150
  /** For tests: how many times a folder's statuses were read (once per commit of its main). */
115
151
  export const pendingTestHooks = { reads: 0 };
116
152
  /** By agent: its folder's main commit and each draft's status there. */
@@ -146,21 +182,23 @@ export async function pendingCount(data, agentId) {
146
182
  const status = await statusesOf(data, agentId);
147
183
  return status === undefined ? undefined : [...status.values()].filter((value) => value.status === "pending").length;
148
184
  }
149
- export async function agentLearning(data, agentId, shown, counts, impact, stateOf) {
185
+ export async function agentLearning(data, agentId, shown, counts, impact, stateOf, purgedOf) {
150
186
  return reading(data, agentId, async ({ snapshot, body }) => {
187
+ const served = await servedIn(snapshot, purgedOf);
151
188
  const corrections = (await readCorrections(snapshot, body)).text;
152
189
  // A retired draft whose README.md can't be read is said so (unclearFront), read from its file now, as the snapshot's
153
190
  // status was: a few retired items, one read each.
154
191
  const unread = async (item) => item.status === "retired" && unclearFront(await body(item.file, item.oid));
155
- return { agent: agentId, main: snapshot.main, corrections: shown.text(corrections), workflows: await Promise.all(snapshot.workflows.map(async (item) => workflowView(item, shown, stateOf, await unread(item)))), log: logPage(snapshot, 0, LOG_PAGE, shown), counts, impact };
192
+ return { agent: agentId, main: snapshot.main, corrections: shown.text(corrections), workflows: await Promise.all(snapshot.workflows.map(async (item) => workflowView(item, shown, stateOf, await unread(item)))), log: logPage(snapshot, 0, LOG_PAGE, shown, served), counts, impact };
156
193
  }, () => ({ agent: agentId, main: null, corrections: "", workflows: [], log: EMPTY, counts, impact }));
157
194
  }
158
- /** GET /agents/{id}/learning/log?cursor=&limit=: a page of the changes on main, newest first. */
159
- export async function learningLog(data, agentId, query, shown) {
195
+ /** GET /agents/{id}/learning/log?cursor=&limit=: a page of the changes on main, newest first, a purged run's left out
196
+ * (`purgedOf`). */
197
+ export async function learningLog(data, agentId, query, shown, purgedOf) {
160
198
  const { limit, at } = pageRequest(query, LOG_PAGE);
161
199
  return reading(data, agentId, async ({ snapshot }) => {
162
200
  const page = pageAt(agentId, snapshot, at);
163
- return logPage(page.snapshot, page.offset, limit, shown);
201
+ return logPage(page.snapshot, page.offset, limit, shown, await servedIn(page.snapshot, purgedOf));
164
202
  }, () => EMPTY);
165
203
  }
166
204
  /** GET /agents/{id}/learning/corrections: corrections.md on main as text (empty when main holds none), its ETag (its blob
@@ -206,8 +244,9 @@ const REVISIONS_DEFAULT = 20;
206
244
  * commits on main's log that changed `workflows/<name>/workflow.json`), oldest first, each with the workflow's text at
207
245
  * that commit, so a person can step through how it changed. One read-only exec per revision (textsAt), at most `limit`
208
246
  * of them. `total` counts every such commit the log holds, `truncated` says the log itself is cut (it keeps the latest
209
- * LOG_KEEP changes). A workflow no commit of the log changed is not_found. */
210
- export async function workflowRevisions(data, agentId, name, query, shown) {
247
+ * LOG_KEEP changes). A purged run's merge is no revision (`purgedOf`). A workflow no commit of the log changed is
248
+ * not_found. */
249
+ export async function workflowRevisions(data, agentId, name, query, shown, purgedOf) {
211
250
  if (!WORKFLOW_NAME.test(name))
212
251
  throw new ApiError("bad_request", "A workflow's folder is named with lowercase letters, digits, dashes and underscores.");
213
252
  const given = query.get("limit");
@@ -218,7 +257,8 @@ export async function workflowRevisions(data, agentId, name, query, shown) {
218
257
  if (shown.name(path) !== path)
219
258
  throw new ApiError("not_found", "the agent's learning folder has no such workflow");
220
259
  const found = await reading(data, agentId, async ({ ws, snapshot }) => {
221
- const touched = snapshot.log.filter((change) => change.files.includes(path));
260
+ const served = await servedIn(snapshot, purgedOf);
261
+ const touched = snapshot.log.filter((change) => served(change) && change.files.includes(path));
222
262
  const latest = touched.slice(0, limit).reverse();
223
263
  const revisions = [];
224
264
  for (const change of latest) {
@@ -237,16 +277,22 @@ export async function workflowRevisions(data, agentId, name, query, shown) {
237
277
  /** Learned workflow `name`'s text at `digest` (a champion's, as its promotion records name it), read by that digest and
238
278
  * never by paging the workflow's history: at `commits` (the records' learning commits, newest first), then at main, the
239
279
  * first commit whose workflow.json is that digest's text, with the commit it was read at. Undefined when none is (no
240
- * main yet, or no commit read holds it). One read-only exec per commit tried (textsAt). */
241
- export async function workflowAtDigest(data, agentId, name, digest, commits) {
280
+ * main yet, or no commit read holds it). A commit whose text a purged run wrote is never read (purged-workflow.ts),
281
+ * however old. One read-only exec per commit tried (textsAt), and one more for the commit that holds the digest, unless
282
+ * it is main (snapshotAt). */
283
+ export async function workflowAtDigest(data, agentId, name, digest, commits, store) {
242
284
  if (!WORKFLOW_NAME.test(name))
243
285
  return undefined;
244
286
  const path = `${WORKFLOWS_DIR}/${name}/workflow.json`;
245
287
  return reading(data, agentId, async ({ ws, snapshot }) => {
246
288
  for (const commit of new Set([...commits, snapshot.main])) {
247
289
  const raw = (await textsAt(ws, commit, [path]).catch(() => undefined))?.[path];
248
- if (raw !== undefined && createHash("sha256").update(raw).digest("hex").slice(0, 16) === digest)
249
- return { text: raw, commit };
290
+ if (raw === undefined || createHash("sha256").update(raw).digest("hex").slice(0, 16) !== digest)
291
+ continue;
292
+ const at = commit === snapshot.main ? snapshot : await snapshotAt(ws, commit).catch(() => undefined);
293
+ if (!at || (await purgedWorkflows(at, store)).has(name))
294
+ continue;
295
+ return { text: raw, commit };
250
296
  }
251
297
  return undefined;
252
298
  }, () => undefined);
@@ -279,12 +325,20 @@ function fileOf(raw, use) {
279
325
  return file;
280
326
  }
281
327
  /** GET /agents/{id}/learning/files/{file}: a draft's file on main as text, its ETag, and its type (workflow.json is
282
- * JSON). */
283
- export async function readLearnedFile(data, agentId, raw, shown) {
328
+ * JSON). A purged run's workflow left main with its purge (learn/commit.ts forgetRunText), so its files are the 404
329
+ * any missing file is. A workflow.json still on main whose writer is purged (a run purged before purges took its
330
+ * workflows off, until its DELETE is sent again) is 410 purged, as every route of that run is (purged-workflow.ts). */
331
+ export async function readLearnedFile(data, agentId, raw, shown, store) {
284
332
  const file = fileOf(raw, "read");
333
+ const place = learnedPlace(file);
285
334
  const found = await reading(data, agentId, async ({ snapshot, body }) => {
286
335
  const oid = blobIn(snapshot, file);
287
- return oid === undefined ? undefined : { oid, text: await body(file, oid) };
336
+ if (oid === undefined)
337
+ return undefined;
338
+ const purged = place.kind === "workflow" ? (await purgedWorkflows(snapshot, store)).get(place.name) : undefined;
339
+ if (purged)
340
+ throw purgedRun(purged);
341
+ return { oid, text: await body(file, oid) };
288
342
  }, () => undefined);
289
343
  if (!found)
290
344
  throw new ApiError("not_found", "the agent's learning folder has no such file on main");
@@ -476,10 +530,46 @@ export async function runDiffOverStore(data, store, runId, shown) {
476
530
  };
477
531
  if (end?.merged) {
478
532
  const folder = learningFolderOf(data, row.agentId);
479
- const diff = await readRunDiff(folder.workspace, runDiffKey(runId, kept?.round)).catch((error) => Promise.reject(routeFailure(error))).finally(() => folder.end());
480
- if (!diff || diff.merge !== end.merged)
533
+ const diff = await readRunDiff(folder.workspace, runDiffKey(runId, kept?.round)).then((read) => (read && read.merge === end.merged ? againstPurged(folder.workspace, read, store) : undefined)).catch((error) => Promise.reject(routeFailure(error))).finally(() => folder.end());
534
+ if (!diff)
481
535
  throw new ApiError("not_found", "the run's merge is not in its agent's learning folder");
482
536
  return { base: diff.parent, head: diff.merge, files: diff.files.map((entry) => ("patch" in entry ? file(entry.path, entry.status, entry.patch) : { path: shown.name(entry.path), status: entry.status, withheld: entry.withheld })) };
483
537
  }
484
538
  return { base: start?.seed ?? null, head: null, files: [] };
485
539
  }
540
+ /** `diff` with each file of a learned workflow whose text at its parent a purged run wrote (purged-workflow.ts), its
541
+ * whole `workflows/<name>/` folder (README.md too), diffed against nothing, so its patch never shows that text: its
542
+ * text at the merge as an added file, or, deleted there, no file. One more read-only exec when the merge changed such
543
+ * a file (snapshotAt), and one per file served so. */
544
+ async function againstPurged(ws, diff, store) {
545
+ const replaced = (path, status) => {
546
+ const [dir, name, ...rest] = path.split("/");
547
+ return status !== "added" && dir === WORKFLOWS_DIR && rest.length ? name : undefined;
548
+ };
549
+ if (!diff.files.some(({ path, status }) => replaced(path, status)))
550
+ return diff;
551
+ const purged = await purgedWorkflows(await snapshotAt(ws, diff.parent), store);
552
+ const files = [];
553
+ for (const entry of diff.files) {
554
+ const name = replaced(entry.path, entry.status);
555
+ if (name === undefined || !purged.has(name))
556
+ files.push(entry);
557
+ else if (entry.status === "modified") {
558
+ const text = (await textsAt(ws, diff.merge, [entry.path]))?.[entry.path];
559
+ if (text !== undefined)
560
+ files.push({ path: entry.path, status: "added", patch: addedPatch(text) });
561
+ }
562
+ }
563
+ return { ...diff, files };
564
+ }
565
+ /** `text` as git's unified diff writes an added file, its hunk alone (as the learning script keeps a patch): no hunk for
566
+ * an empty file, a one-line hunk's count left out, and a last line with no newline marked so. */
567
+ function addedPatch(text) {
568
+ if (text === "")
569
+ return "";
570
+ const lines = text.split("\n");
571
+ const ended = text.endsWith("\n");
572
+ if (ended)
573
+ lines.pop();
574
+ return `@@ -0,0 +1${lines.length === 1 ? "" : `,${lines.length}`} @@\n${lines.map((line) => `+${line}\n`).join("")}${ended ? "" : "\\n"}`;
575
+ }
@@ -1,5 +1,6 @@
1
1
  import { type Problem } from "./learn/index.js";
2
2
  import { type LearningFolder } from "./learn/folder.js";
3
+ import type { Store } from "./store/index.js";
3
4
  import type { Workspace } from "./workspace/index.js";
4
5
  export { learnsOf } from "./learning-setting.js";
5
6
  /** The server's learning switch (`--learning`, AGENTRUN_SERVE_LEARNING; capabilities.features.learning). `on`, the
@@ -111,7 +112,7 @@ export declare const detailShown: (learning: Learning, shown: Shown, max?: numbe
111
112
  export declare const learningView: (learning: Learning, shown: Shown) => {
112
113
  workflows?: LearnedFile[];
113
114
  state: "dropped" | "merged" | "seeded" | "reflecting";
114
- reason: "cancelled" | "reset" | "use" | "empty" | "crashed" | "reflect_failed" | "no_budget" | "checker" | "unknown_cost" | "seed_failed" | null;
115
+ reason: "cancelled" | "reset" | "use" | "empty" | "seed_failed" | "no_budget" | "unknown_cost" | "crashed" | "reflect_failed" | "checker" | null;
115
116
  detail: string | null;
116
117
  at: string;
117
118
  };
@@ -126,9 +127,9 @@ export declare function shortOf<T extends {
126
127
  at: string;
127
128
  }>({ state, reason, detail, at: _, ...rest }: T): {
128
129
  state: "dropped" | "merged" | "seeded" | "reflecting";
129
- reason: "cancelled" | "reset" | "use" | "empty" | "crashed" | "reflect_failed" | "no_budget" | "checker" | "unknown_cost" | "seed_failed" | null;
130
+ reason: "cancelled" | "reset" | "use" | "empty" | "seed_failed" | "no_budget" | "unknown_cost" | "crashed" | "reflect_failed" | "checker" | null;
130
131
  detail: string | null;
131
- } & Omit<T, "at" | "reason" | "state" | "detail">;
132
+ } & Omit<T, "at" | "reason" | "detail" | "state">;
132
133
  /** The label of the end-of-run turn's timeline rows, and the kind and label of a run's learning row. */
133
134
  export declare const LEARNING_LABEL = "learning";
134
135
  /** A message a trigger sent the run that its owner did not write (a webhook body, a Slack or GitHub event), by its
@@ -175,9 +176,11 @@ export declare const learningFolderOf: (data: string, agentId: string) => Learni
175
176
  * learning script's init), what main holds for a run (seedIn), and when it was read (`at`). In the agent's queue, as a
176
177
  * reset is (learning-reset.ts). No git in this process: the folder's own script and file API. */
177
178
  export declare function seedOf(data: string, agentId: string): Promise<Seed>;
178
- /** What commit `commit` of the folder holds for a run, as seedOf reads main (one read-only exec of the script). No commit
179
- * (null) is the empty seed; a commit the folder no longer holds throws. */
180
- export declare function seedAt(ws: Workspace, commit: string | null): Promise<Seed>;
179
+ /** What commit `commit` of the folder holds for a run, as seedOf reads main (one read-only exec of the script), but a
180
+ * learned workflow a purged run wrote, by `store`'s runs (purged-workflow.ts): no claim lays, checks, replays or serves
181
+ * it. `store` null: a run's own process, which reads no other run; its runner reads the seed again with its store
182
+ * (runner/learning-seed.ts). No commit (null) is the empty seed; a commit the folder no longer holds throws. */
183
+ export declare function seedAt(ws: Workspace, commit: string | null, store: Pick<Store, "runs"> | null): Promise<Seed>;
181
184
  /** Whether `text` holds a host secret (`shown`): as written, or, read as JSON, in any string it decodes to (its escapes
182
185
  * decoded), or nested past the bound. The one check a learned workflow's text passes at a run's start (chooseWorkflows)
183
186
  * and every text its compile turn is told (runner/learning-end.ts compileAskOf); a text that is not JSON is read as
package/dist/learning.js CHANGED
@@ -18,6 +18,7 @@ import { folderAt, learningInit, learningWorkspace, readLearning } from "./learn
18
18
  import { agentFolderOf, serialBy } from "./files.js";
19
19
  import { withoutLoopbackAddresses } from "./key-refusal.js";
20
20
  import { DETAIL_MAX, LIST_DETAIL, said, short, wordsOf } from "./learning-words.js";
21
+ import { purgedWorkflows } from "./purged-workflow.js";
21
22
  export { learnsOf } from "./learning-setting.js";
22
23
  /** The server's learning switch (`--learning`, AGENTRUN_SERVE_LEARNING; capabilities.features.learning). `on`, the
23
24
  * default: a run learns when its agent's definition says `learning: true`. `off`: no run this server starts does. */
@@ -204,20 +205,24 @@ export function seedOf(data, agentId) {
204
205
  }
205
206
  });
206
207
  }
207
- /** What commit `commit` of the folder holds for a run, as seedOf reads main (one read-only exec of the script). No commit
208
- * (null) is the empty seed; a commit the folder no longer holds throws. */
209
- export async function seedAt(ws, commit) {
208
+ /** What commit `commit` of the folder holds for a run, as seedOf reads main (one read-only exec of the script), but a
209
+ * learned workflow a purged run wrote, by `store`'s runs (purged-workflow.ts): no claim lays, checks, replays or serves
210
+ * it. `store` null: a run's own process, which reads no other run; its runner reads the seed again with its store
211
+ * (runner/learning-seed.ts). No commit (null) is the empty seed; a commit the folder no longer holds throws. */
212
+ export async function seedAt(ws, commit, store) {
210
213
  if (commit === null)
211
214
  return { sha: null, corrections: "", workflows: [] };
212
215
  const at = await folderAt(ws, commit);
213
216
  if (!at)
214
217
  throw new Error(`the learning folder's read at ${commit} is gone`);
215
- return seedIn(commit, at.snapshot, async (_path, oid) => {
218
+ const purged = store ? await purgedWorkflows(at.snapshot, store) : new Map();
219
+ const seed = await seedIn(commit, at.snapshot, async (_path, oid) => {
216
220
  const bytes = at.blobs.get(oid);
217
221
  if (!bytes)
218
222
  throw new Error(`the learning folder's read at ${commit} holds no blob ${oid}`);
219
223
  return bytes.toString("utf8");
220
224
  });
225
+ return { ...seed, workflows: seed.workflows.filter(({ name }) => !purged.has(name)) };
221
226
  }
222
227
  /** Whether `text` holds a host secret (`shown`): as written, or, read as JSON, in any string it decodes to (its escapes
223
228
  * decoded), or nested past the bound. The one check a learned workflow's text passes at a run's start (chooseWorkflows)
@@ -1,4 +1,5 @@
1
1
  import type { IncomingMessage } from "node:http";
2
+ import { networkInterfaces } from "node:os";
2
3
  /** The header the proxy's proof travels in. */
3
4
  export declare const LIVE_PROOF_HEADER = "x-agentrun-live";
4
5
  /** How far a proof's time may be from the endpoint's clock. */
@@ -6,17 +7,34 @@ export declare const LIVE_PROOF_MS = 60000;
6
7
  /** Where every viewer answers when its runner is on the server's own machine. */
7
8
  export declare const LOOPBACK = "127.0.0.1";
8
9
  export declare const isLiveHost: (host: unknown) => host is string;
9
- /** What the server needs to reach a runner's viewer: the hosts it dials (its runners'), and the proof's key. */
10
+ /** An IPv4 block, `a.b.c.d/n`: its network address as a 32-bit number and its prefix length. */
11
+ export type Ipv4Block = {
12
+ readonly base: number;
13
+ readonly bits: number;
14
+ };
15
+ /** The shortest prefix a block may have: a /8 is a whole private range, and anything wider is no runners' network. */
16
+ export declare const MIN_BLOCK_BITS = 8;
17
+ /** `address` (dotted IPv4, no leading zeros) as a 32-bit number, or undefined. */
18
+ export declare function ipv4Of(address: string): number | undefined;
19
+ /** `value` as an IPv4 block: its address the block's network address (no host bits set) and its prefix from
20
+ * MIN_BLOCK_BITS to 32; else undefined. */
21
+ export declare function ipv4BlockOf(value: string): Ipv4Block | undefined;
22
+ /** Whether IPv4 `address` is in `block`. */
23
+ export declare const inBlock: (address: number, block: Ipv4Block) => boolean;
24
+ /** What the server needs to reach a runner's viewer: the hosts it dials (its runners'), the IPv4 blocks whose every
25
+ * address it dials (its runners' network), and the proof's key. */
10
26
  export type LiveReach = {
11
27
  readonly hosts: ReadonlySet<string>;
28
+ readonly blocks: readonly Ipv4Block[];
12
29
  readonly key: Buffer;
13
30
  };
14
- /** The server's reach, from its environment (AGENTRUN_RUNNER_HOSTS) and the seal key. A name that is not a host is left
15
- * out. */
31
+ /** The server's reach, from its environment (AGENTRUN_RUNNER_HOSTS: host names, IPv4 addresses and IPv4 blocks) and
32
+ * the seal key. An entry that is none of them is left out. */
16
33
  export declare function liveReachOf(env: {
17
34
  readonly AGENTRUN_RUNNER_HOSTS?: string | undefined;
18
35
  }, sealKey: Buffer): LiveReach;
19
- /** Where the server dials `host` (a row's): loopback with none; the host when it is one of its runners'; else nowhere. */
36
+ /** Where the server dials `host` (a row's): loopback with none; the host when it is one of its runners' or an IPv4
37
+ * address in one of their blocks; else nowhere. */
20
38
  export declare function dialHost(host: string | undefined, reach: LiveReach | undefined): string | undefined;
21
39
  /** The proxy's proof for viewer `viewerId`, at `at` (ms). */
22
40
  export declare const liveProof: (reach: Pick<LiveReach, "key">, viewerId: string, at?: number) => string;
@@ -27,13 +45,22 @@ export type RunnerLive = {
27
45
  readonly bind: string;
28
46
  readonly key: Buffer;
29
47
  };
48
+ /** This machine's network interfaces, as node:os reads them: an injection point for tests. */
49
+ export type Interfaces = () => ReturnType<typeof networkInterfaces>;
50
+ /** A runner's live host it cannot take: its AGENTRUN_RUNNER_LIVE_HOST names a block that holds none, or more than one,
51
+ * of this machine's addresses. Thrown at the runner's start, so it never says it answers where the server cannot
52
+ * reach it. */
53
+ export declare class RunnerLiveRefused extends Error {
54
+ readonly name = "RunnerLiveRefused";
55
+ }
30
56
  /** The runner's live host, from its environment (AGENTRUN_RUNNER_LIVE_HOST, AGENTRUN_RUNNER_LIVE_BIND) and the seal key;
31
- * undefined with none (or one that is not a host): its viewers answer on loopback, as on a server's own machine. */
57
+ * undefined with none (or one that is not a host): its viewers answer on loopback, as on a server's own machine. An
58
+ * IPv4 block for a host is this machine's own address in it (refused, RunnerLiveRefused, with none or several). */
32
59
  export declare function runnerLiveOf(env: {
33
60
  readonly AGENTRUN_RUNNER_LIVE_HOST?: string | undefined;
34
61
  readonly AGENTRUN_RUNNER_LIVE_BIND?: string | undefined;
35
- }, sealKey: Buffer): RunnerLive | undefined;
36
- /** The server's reach for run `runId`'s viewers: its hosts, under that run's key. */
62
+ }, sealKey: Buffer, interfaces?: Interfaces): RunnerLive | undefined;
63
+ /** The server's reach for run `runId`'s viewers: its hosts and blocks, under that run's key. */
37
64
  export declare const reachForRun: (reach: LiveReach, runId: string) => LiveReach;
38
65
  /** A runner's live address for run `runId`'s viewers: its host and bind, under that run's key. */
39
66
  export declare const liveForRun: (live: RunnerLive, runId: string) => RunnerLive;
@@ -9,7 +9,15 @@
9
9
  // endpoint off loopback takes no request without a good, fresh proof for its own viewer. The proof is not the viewer's:
10
10
  // the hello's token still decides who watches. The hop is plain HTTP, for a private network (the server and its
11
11
  // runners' own); TLS on it is a later step.
12
+ //
13
+ // Runners that are replicas of one deployment (Kubernetes pods, a platform's instances) have no host name of their own
14
+ // the server resolves, and their addresses change at each start. For them both settings take an IPv4 block in CIDR form:
15
+ // a runner whose AGENTRUN_RUNNER_LIVE_HOST is a block answers at its own address in that block (its one network
16
+ // interface address there), and a server whose AGENTRUN_RUNNER_HOSTS lists a block dials any IPv4 address in it. The
17
+ // block is the private network the runners' addresses come from (a cluster's pod range), and the proof above still
18
+ // guards every request on it.
12
19
  import { createHmac, hkdfSync, timingSafeEqual } from "node:crypto";
20
+ import { networkInterfaces } from "node:os";
13
21
  /** The header the proxy's proof travels in. */
14
22
  export const LIVE_PROOF_HEADER = "x-agentrun-live";
15
23
  /** How far a proof's time may be from the endpoint's clock. */
@@ -23,26 +31,83 @@ const LABEL = "agentrun live proxy v1";
23
31
  export const isLiveHost = (host) => typeof host === "string" && HOST.test(host);
24
32
  const proofKey = (sealKey) => Buffer.from(hkdfSync("sha256", sealKey, Buffer.alloc(0), LABEL, 32));
25
33
  const mac = (key, viewerId, at) => createHmac("sha256", key).update(`${viewerId}\n${at}`).digest("hex");
26
- /** The server's reach, from its environment (AGENTRUN_RUNNER_HOSTS) and the seal key. A name that is not a host is left
27
- * out. */
34
+ /** The shortest prefix a block may have: a /8 is a whole private range, and anything wider is no runners' network. */
35
+ export const MIN_BLOCK_BITS = 8;
36
+ const IPV4 = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;
37
+ /** `address` (dotted IPv4, no leading zeros) as a 32-bit number, or undefined. */
38
+ export function ipv4Of(address) {
39
+ const match = IPV4.exec(address);
40
+ return match ? match.slice(1).reduce((sum, octet) => sum * 256 + Number(octet), 0) : undefined;
41
+ }
42
+ const maskOf = (bits) => (bits === 0 ? 0 : (0xffffffff << (32 - bits)) >>> 0);
43
+ /** `value` as an IPv4 block: its address the block's network address (no host bits set) and its prefix from
44
+ * MIN_BLOCK_BITS to 32; else undefined. */
45
+ export function ipv4BlockOf(value) {
46
+ const match = /^([0-9.]+)\/(\d{1,2})$/.exec(value);
47
+ if (!match)
48
+ return undefined;
49
+ const base = ipv4Of(match[1]);
50
+ const bits = Number(match[2]);
51
+ if (base === undefined || bits < MIN_BLOCK_BITS || bits > 32 || ((base & ~maskOf(bits)) >>> 0) !== 0)
52
+ return undefined;
53
+ return { base, bits };
54
+ }
55
+ /** Whether IPv4 `address` is in `block`. */
56
+ export const inBlock = (address, block) => ((address & maskOf(block.bits)) >>> 0) === block.base;
57
+ /** The server's reach, from its environment (AGENTRUN_RUNNER_HOSTS: host names, IPv4 addresses and IPv4 blocks) and
58
+ * the seal key. An entry that is none of them is left out. */
28
59
  export function liveReachOf(env, sealKey) {
29
- const hosts = new Set((env.AGENTRUN_RUNNER_HOSTS ?? "").split(",").map((host) => host.trim().toLowerCase()).filter(isLiveHost));
30
- return { hosts, key: proofKey(sealKey) };
60
+ const entries = (env.AGENTRUN_RUNNER_HOSTS ?? "").split(",").map((host) => host.trim().toLowerCase());
61
+ const hosts = new Set(entries.filter(isLiveHost));
62
+ const blocks = entries.map(ipv4BlockOf).filter((block) => block !== undefined);
63
+ return { hosts, blocks, key: proofKey(sealKey) };
31
64
  }
32
- /** Where the server dials `host` (a row's): loopback with none; the host when it is one of its runners'; else nowhere. */
65
+ /** Where the server dials `host` (a row's): loopback with none; the host when it is one of its runners' or an IPv4
66
+ * address in one of their blocks; else nowhere. */
33
67
  export function dialHost(host, reach) {
34
68
  if (host === undefined || host === LOOPBACK)
35
69
  return LOOPBACK;
36
- return reach?.hosts.has(host.toLowerCase()) ? host : undefined;
70
+ if (reach === undefined)
71
+ return undefined;
72
+ if (reach.hosts.has(host.toLowerCase()))
73
+ return host;
74
+ const address = ipv4Of(host);
75
+ return address !== undefined && reach.blocks.some((block) => inBlock(address, block)) ? host : undefined;
37
76
  }
38
77
  /** The proxy's proof for viewer `viewerId`, at `at` (ms). */
39
78
  export const liveProof = (reach, viewerId, at = Date.now()) => `${at}.${mac(reach.key, viewerId, at)}`;
79
+ /** A runner's live host it cannot take: its AGENTRUN_RUNNER_LIVE_HOST names a block that holds none, or more than one,
80
+ * of this machine's addresses. Thrown at the runner's start, so it never says it answers where the server cannot
81
+ * reach it. */
82
+ export class RunnerLiveRefused extends Error {
83
+ name = "RunnerLiveRefused";
84
+ }
85
+ /** This machine's one IPv4 address in `block` (AGENTRUN_RUNNER_LIVE_HOST as a block, named `given`); refused in words
86
+ * with none or several. */
87
+ function ownAddressIn(block, given, interfaces) {
88
+ const found = new Set();
89
+ for (const addresses of Object.values(interfaces())) {
90
+ for (const one of addresses ?? []) {
91
+ const address = one.family === "IPv4" && !one.internal ? ipv4Of(one.address) : undefined;
92
+ if (address !== undefined && inBlock(address, block))
93
+ found.add(one.address);
94
+ }
95
+ }
96
+ if (found.size === 1)
97
+ return [...found][0];
98
+ throw new RunnerLiveRefused(found.size === 0
99
+ ? `AGENTRUN_RUNNER_LIVE_HOST is ${given}, and no network interface of this machine has an IPv4 address in it: name the block this runner's address is in, or the host the server reaches it at`
100
+ : `AGENTRUN_RUNNER_LIVE_HOST is ${given}, and this machine has ${found.size} IPv4 addresses in it (${[...found].sort().join(", ")}): name a narrower block, or the host the server reaches it at`);
101
+ }
40
102
  /** The runner's live host, from its environment (AGENTRUN_RUNNER_LIVE_HOST, AGENTRUN_RUNNER_LIVE_BIND) and the seal key;
41
- * undefined with none (or one that is not a host): its viewers answer on loopback, as on a server's own machine. */
42
- export function runnerLiveOf(env, sealKey) {
103
+ * undefined with none (or one that is not a host): its viewers answer on loopback, as on a server's own machine. An
104
+ * IPv4 block for a host is this machine's own address in it (refused, RunnerLiveRefused, with none or several). */
105
+ export function runnerLiveOf(env, sealKey, interfaces = networkInterfaces) {
43
106
  // Lower case, as a URL's hostname reads a DNS name and the server's runners' hosts are read (liveReachOf): one form for
44
107
  // the links, the origins and the rows.
45
- const host = env.AGENTRUN_RUNNER_LIVE_HOST?.trim().toLowerCase();
108
+ const given = env.AGENTRUN_RUNNER_LIVE_HOST?.trim().toLowerCase();
109
+ const block = given === undefined ? undefined : ipv4BlockOf(given);
110
+ const host = block !== undefined ? ownAddressIn(block, given, interfaces) : given;
46
111
  if (!isLiveHost(host) || host === LOOPBACK)
47
112
  return undefined;
48
113
  const bind = env.AGENTRUN_RUNNER_LIVE_BIND?.trim().toLowerCase();
@@ -53,8 +118,8 @@ export function runnerLiveOf(env, sealKey) {
53
118
  const runKey = (key, runId) => createHmac("sha256", key).update(`${RUN_LABEL}\n${runId}`).digest();
54
119
  /** The run label of runKey: another MAC than the proof's own. */
55
120
  const RUN_LABEL = "agentrun live run v1";
56
- /** The server's reach for run `runId`'s viewers: its hosts, under that run's key. */
57
- export const reachForRun = (reach, runId) => ({ hosts: reach.hosts, key: runKey(reach.key, runId) });
121
+ /** The server's reach for run `runId`'s viewers: its hosts and blocks, under that run's key. */
122
+ export const reachForRun = (reach, runId) => ({ hosts: reach.hosts, blocks: reach.blocks, key: runKey(reach.key, runId) });
58
123
  /** A runner's live address for run `runId`'s viewers: its host and bind, under that run's key. */
59
124
  export const liveForRun = (live, runId) => ({ host: live.host, bind: live.bind, key: runKey(live.key, runId) });
60
125
  /** Whether `req` carries a good, fresh proof for viewer `viewerId` under `live`'s key: its time within `windowMs` of
@@ -28,6 +28,7 @@ import { paidLedger, paidStep } from "./paid-calls.js";
28
28
  import { metaToolOf } from "./mcp-meta.js";
29
29
  import { SIGN_IN_AGAIN } from "./mcp-oauth.js";
30
30
  import { capped, mcpClient, scrub } from "./mcp-wire.js";
31
+ import { resourceResult, resourceToolOperation, resourceToolProblem } from "./mcp-resources.js";
31
32
  import { mcpNameOf, mcpToolName } from "./tool-names.js";
32
33
  import { workspaceAt, workspaceErrorWords } from "./workspace/index.js";
33
34
  /** The longest answer the model reads whole; past it, the rest is filed in the run's work/ as lines read pages through
@@ -121,6 +122,9 @@ export function mcpPinOf(names, source) {
121
122
  throw new Error(`The MCP tool ${name} cannot be pinned: no MCP server ${parsed.server} is saved.`);
122
123
  if (!tool)
123
124
  throw new Error(`The MCP tool ${name} cannot be pinned: the MCP server ${parsed.server} does not list ${parsed.tool}.`);
125
+ const resourceProblem = resourceToolProblem(tool);
126
+ if (resourceProblem)
127
+ throw new Error(`The MCP tool ${name} cannot be pinned: ${resourceProblem}.`);
124
128
  // A meta tool granted before the rule (mcp-meta.ts): refused here, never run.
125
129
  const meta = metaToolOf(saved.url, tool.name);
126
130
  if (meta)
@@ -325,6 +329,8 @@ export function mcpGateway(options) {
325
329
  * takes the server's raw result, when one came back. */
326
330
  const forward = async (server, url, headers, tool, args, signal, sending, outcome = {}, back) => {
327
331
  let connected = false;
332
+ const operation = resourceToolOperation(tool);
333
+ const boundedSignal = operation ? AbortSignal.any([signal, AbortSignal.timeout(options.bounds?.callMs ?? CALL_MS)]) : signal;
328
334
  // Read at each use: a token refreshed while the call is out, and sent, is scrubbed with the one it took.
329
335
  const held = callSet(server);
330
336
  const scrubbed = scrubberOf(server, hold(server, headers), held.values);
@@ -332,7 +338,7 @@ export function mcpGateway(options) {
332
338
  const clean = back ? (text) => back(scrubbed(text)) : scrubbed;
333
339
  hold(server, queryOf(server));
334
340
  try {
335
- const upstream = await until(connect(server, url, headers), signal);
341
+ const upstream = await until(connect(server, url, headers), boundedSignal);
336
342
  connected = true;
337
343
  if (sending && !signal.aborted) {
338
344
  const refused = await sending();
@@ -341,7 +347,9 @@ export function mcpGateway(options) {
341
347
  }
342
348
  // The pinned definition, so the SDK mirrors its x-mcp-header parameters into Mcp-Param-* headers on a 2026-07-28
343
349
  // server, as its own listing would have it do.
344
- const result = (await upstream.callTool({ name: tool.name, arguments: args }, { signal, timeout: options.bounds?.callMs ?? CALL_MS, toolDefinition: { name: tool.name, inputSchema: tool.inputSchema } }));
350
+ const result = operation
351
+ ? await resourceResult(upstream, operation, args, boundedSignal, options.bounds?.callMs ?? CALL_MS, scrubbed)
352
+ : (await upstream.callTool({ name: tool.name, arguments: args }, { signal, timeout: options.bounds?.callMs ?? CALL_MS, toolDefinition: { name: tool.name, inputSchema: tool.inputSchema } }));
345
353
  outcome.raw = result;
346
354
  // A meter's own read (`quiet`): its raw result is all that is wanted, nothing filed for a model to read.
347
355
  return said(outcome.quiet ? "" : await textOf(server, tool.name, result, clean), result.isError === true);
@@ -349,6 +357,8 @@ export function mcpGateway(options) {
349
357
  catch (error) {
350
358
  if (signal.aborted)
351
359
  return said(`The call to the MCP server ${server} was stopped.`, true);
360
+ if (boundedSignal.aborted)
361
+ return said(`The resource operation on the MCP server ${server} exceeded its deadline.`, true);
352
362
  // The next call connects again (a server that dropped its session, say); this one is never sent again.
353
363
  clients.delete(server);
354
364
  // Its address refused before the request left (reach): nothing reached it. Read from this call's own error, never
@@ -381,6 +391,9 @@ export function mcpGateway(options) {
381
391
  const pinned = pins.get(server);
382
392
  if (!pinned?.tools.some((t) => t.name === tool))
383
393
  return `${tool} is not a tool of the MCP server ${server} in this run.`;
394
+ const resourceProblem = resourceToolProblem(pinned.tools.find(t => t.name === tool));
395
+ if (resourceProblem)
396
+ return `The MCP operation ${tool} is invalid: ${resourceProblem}. Nothing was sent.`;
384
397
  const meta = metaToolOf(pinned.url, tool);
385
398
  if (meta)
386
399
  return `mcp:${server}/${tool} can't be granted: ${meta.reason} Nothing was sent.`;
@@ -1,5 +1,6 @@
1
1
  import { ApiError, type InputIssue } from "./errors.js";
2
2
  import type { ComposioBinding } from "./store/seal.js";
3
+ import { type ResourceOperation } from "./mcp-resources.js";
3
4
  /** `per_run`: the server keeps no credential; each run's caller hands one with the run (mcp_auth), held for that run alone. */
4
5
  export declare const MCP_AUTH_TYPES: readonly ["none", "bearer", "headers", "oauth", "github_app", "per_run"];
5
6
  /** Why a saved credential can't be used for a run's calls, each with its own remedy and no other, as the model reads it
@@ -35,6 +36,7 @@ export type McpTool = {
35
36
  input_schema: unknown;
36
37
  output_schema?: unknown;
37
38
  annotations?: unknown;
39
+ resource?: ResourceOperation;
38
40
  };
39
41
  /** A registry tool (input_schema, as the server listed it) in the harnesses' shape (the kernel's McpTool: inputSchema),
40
42
  * as a run is pinned to it and a session binds it. */
@@ -44,6 +46,7 @@ export declare function boundTool(tool: McpTool): {
44
46
  description?: string;
45
47
  inputSchema: Record<string, unknown>;
46
48
  annotations?: Record<string, unknown>;
49
+ resource?: ResourceOperation;
47
50
  };
48
51
  export type Listed = {
49
52
  protocol: string;