@parcha/agentrun-serve 0.1.0-beta.56 → 0.1.0-beta.58

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 (312) hide show
  1. package/CHANGELOG.md +281 -0
  2. package/README.md +246 -66
  3. package/dist/acp-package.d.ts +2 -0
  4. package/dist/adapters.d.ts +15 -3
  5. package/dist/adapters.js +17 -6
  6. package/dist/agent-package.d.ts +3 -3
  7. package/dist/agent-package.js +17 -8
  8. package/dist/api-keys.d.ts +76 -0
  9. package/dist/api-keys.js +217 -0
  10. package/dist/api-only.d.ts +15 -5
  11. package/dist/api-only.js +32 -8
  12. package/dist/box-paths.d.ts +4 -3
  13. package/dist/box-paths.js +7 -4
  14. package/dist/browser-hold.d.ts +23 -0
  15. package/dist/browser-hold.js +48 -0
  16. package/dist/browser-person.d.ts +3 -0
  17. package/dist/browser-person.js +4 -1
  18. package/dist/chatgpt-plan.d.ts +18 -8
  19. package/dist/chatgpt-plan.js +91 -34
  20. package/dist/claude-login-token.d.ts +117 -0
  21. package/dist/claude-login-token.js +737 -0
  22. package/dist/claude-login.d.ts +120 -22
  23. package/dist/claude-login.js +347 -63
  24. package/dist/claude-sign-in.d.ts +17 -6
  25. package/dist/claude-sign-in.js +42 -39
  26. package/dist/cli.js +33 -10
  27. package/dist/composio-made.d.ts +4 -0
  28. package/dist/composio-made.js +4 -0
  29. package/dist/composio-preset.d.ts +43 -2
  30. package/dist/composio-preset.js +92 -4
  31. package/dist/computer-attach.d.ts +35 -17
  32. package/dist/computer-attach.js +301 -49
  33. package/dist/computer-held-routes.d.ts +5 -4
  34. package/dist/computer-held-routes.js +29 -8
  35. package/dist/computer-held.d.ts +6 -1
  36. package/dist/computer-held.js +14 -0
  37. package/dist/computer-record.js +4 -2
  38. package/dist/computer-viewer.js +4 -1
  39. package/dist/computers.d.ts +10 -10
  40. package/dist/computers.js +5 -5
  41. package/dist/console/assets/{backend-Boh7tC4i.js → backend-CSAWUqtZ.js} +19 -19
  42. package/dist/console/assets/index-Bwn1oTem.css +1 -0
  43. package/dist/console/assets/index-DPh29cyz.js +747 -0
  44. package/dist/console/index.html +2 -2
  45. package/dist/decisions.d.ts +1 -1
  46. package/dist/decisions.js +1 -1
  47. package/dist/dial-relay.d.ts +25 -4
  48. package/dist/dial-relay.js +129 -1
  49. package/dist/docker-host-addresses.d.ts +22 -11
  50. package/dist/docker-host-addresses.js +38 -26
  51. package/dist/env-switch.d.ts +8 -0
  52. package/dist/env-switch.js +31 -2
  53. package/dist/errors.d.ts +1 -0
  54. package/dist/errors.js +2 -0
  55. package/dist/fal-price.d.ts +56 -20
  56. package/dist/fal-price.js +400 -90
  57. package/dist/handed-values.d.ts +43 -1
  58. package/dist/handed-values.js +119 -2
  59. package/dist/harness-archive.d.ts +13 -10
  60. package/dist/harness-archive.js +60 -34
  61. package/dist/harness-check.d.ts +3 -1
  62. package/dist/harness-check.js +25 -46
  63. package/dist/harness-keys.d.ts +73 -27
  64. package/dist/harness-keys.js +194 -61
  65. package/dist/harness-recipe-entry.d.ts +8 -7
  66. package/dist/harness-recipe-entry.js +21 -32
  67. package/dist/harness-recipe.d.ts +38 -25
  68. package/dist/harness-recipe.js +49 -36
  69. package/dist/harness-sign-in.js +12 -23
  70. package/dist/harness-table.d.ts +10 -3
  71. package/dist/harness-table.js +26 -21
  72. package/dist/harness.d.ts +1 -0
  73. package/dist/harness.js +17 -5
  74. package/dist/hosted-search.d.ts +1 -1
  75. package/dist/hosted-search.js +1 -2
  76. package/dist/import-worker.d.ts +4 -2
  77. package/dist/import-worker.js +9 -2
  78. package/dist/in-flight.d.ts +26 -0
  79. package/dist/in-flight.js +52 -0
  80. package/dist/key-refusal.d.ts +9 -4
  81. package/dist/key-refusal.js +107 -25
  82. package/dist/learn/ledger.d.ts +170 -0
  83. package/dist/learn/ledger.js +218 -0
  84. package/dist/learn/promote.d.ts +3 -3
  85. package/dist/learn/promote.js +1 -1
  86. package/dist/learn/secrets.d.ts +13 -3
  87. package/dist/learn/secrets.js +118 -17
  88. package/dist/learning-cost.d.ts +28 -23
  89. package/dist/learning-cost.js +19 -23
  90. package/dist/link-check.js +1 -1
  91. package/dist/live-reach.d.ts +2 -0
  92. package/dist/live-reach.js +2 -0
  93. package/dist/llms.txt +1 -1
  94. package/dist/marketplace.d.ts +77 -0
  95. package/dist/marketplace.js +224 -0
  96. package/dist/mcp-api-only-origins.d.ts +35 -0
  97. package/dist/mcp-api-only-origins.js +57 -0
  98. package/dist/mcp-gateway.d.ts +7 -5
  99. package/dist/mcp-gateway.js +9 -12
  100. package/dist/mcp-secret-writes.js +5 -3
  101. package/dist/mcp-servers-store.d.ts +28 -6
  102. package/dist/mcp-servers-store.js +53 -4
  103. package/dist/media-duration.d.ts +3 -0
  104. package/dist/media-duration.js +90 -9
  105. package/dist/micro.d.ts +2 -0
  106. package/dist/micro.js +2 -0
  107. package/dist/model-form.d.ts +5 -4
  108. package/dist/model-form.js +11 -7
  109. package/dist/model.d.ts +10 -6
  110. package/dist/model.js +16 -11
  111. package/dist/monid.d.ts +14 -1
  112. package/dist/monid.js +103 -26
  113. package/dist/ollama-provider.d.ts +7 -1
  114. package/dist/ollama-provider.js +14 -2
  115. package/dist/openapi.js +210 -37
  116. package/dist/otel/genai.d.ts +65 -0
  117. package/dist/otel/genai.js +116 -0
  118. package/dist/otel/tracer.d.ts +55 -0
  119. package/dist/otel/tracer.js +308 -0
  120. package/dist/page.d.ts +2 -0
  121. package/dist/page.js +3 -1
  122. package/dist/paid-calls.d.ts +1 -32
  123. package/dist/paid-calls.js +4 -39
  124. package/dist/place-offers.d.ts +4 -0
  125. package/dist/place-offers.js +7 -4
  126. package/dist/provider.d.ts +11 -2
  127. package/dist/provider.js +59 -8
  128. package/dist/redact/match.d.ts +30 -3
  129. package/dist/redact/match.js +422 -41
  130. package/dist/refusal-words.d.ts +11 -0
  131. package/dist/refusal-words.js +11 -0
  132. package/dist/run-census.d.ts +67 -0
  133. package/dist/run-census.js +240 -0
  134. package/dist/run-computer.d.ts +6 -3
  135. package/dist/run-computer.js +4 -1
  136. package/dist/run-cut.d.ts +15 -6
  137. package/dist/run-cut.js +30 -9
  138. package/dist/run-files.d.ts +3 -0
  139. package/dist/run-files.js +3 -0
  140. package/dist/run-launch.d.ts +12 -1
  141. package/dist/run-launch.js +9 -10
  142. package/dist/run-learning-served.d.ts +4 -2
  143. package/dist/run-model-key.d.ts +8 -0
  144. package/dist/run-model-key.js +31 -1
  145. package/dist/run-reads-over-store.d.ts +24 -6
  146. package/dist/run-reads-over-store.js +67 -23
  147. package/dist/run-recordings.d.ts +5 -1
  148. package/dist/run-recordings.js +39 -14
  149. package/dist/run-timeline-served.d.ts +2 -0
  150. package/dist/run-timeline-served.js +2 -2
  151. package/dist/run-usage.d.ts +1 -0
  152. package/dist/run-view.d.ts +1 -2
  153. package/dist/run-view.js +2 -1
  154. package/dist/runnable.d.ts +10 -1
  155. package/dist/runnable.js +20 -8
  156. package/dist/runner/adapter-loop.d.ts +11 -0
  157. package/dist/runner/adapter-loop.js +58 -26
  158. package/dist/runner/adapter-run-spec.d.ts +55 -11
  159. package/dist/runner/adapter-run-spec.js +183 -52
  160. package/dist/runner/adapters/pi.js +25 -3
  161. package/dist/runner/beside.d.ts +9 -2
  162. package/dist/runner/beside.js +27 -9
  163. package/dist/runner/big-writes.js +1 -10
  164. package/dist/runner/claim-secrets.d.ts +27 -10
  165. package/dist/runner/claim-secrets.js +49 -22
  166. package/dist/runner/cli-run-spec.d.ts +6 -0
  167. package/dist/runner/cli-run-spec.js +97 -38
  168. package/dist/runner/computer-journal.d.ts +9 -1
  169. package/dist/runner/computer-journal.js +26 -0
  170. package/dist/runner/conformance/harness.js +1 -1
  171. package/dist/runner/feedback-round.js +3 -0
  172. package/dist/runner/harness-loops.d.ts +6 -5
  173. package/dist/runner/harness-loops.js +7 -7
  174. package/dist/runner/held.d.ts +24 -6
  175. package/dist/runner/journal-kinds.d.ts +5 -0
  176. package/dist/runner/journal-kinds.js +5 -0
  177. package/dist/runner/main.d.ts +11 -6
  178. package/dist/runner/main.js +19 -9
  179. package/dist/runner/mcp-claim.js +31 -3
  180. package/dist/runner/mcp-run.d.ts +9 -0
  181. package/dist/runner/mcp-run.js +11 -5
  182. package/dist/runner/model-route.d.ts +17 -0
  183. package/dist/runner/model-route.js +120 -2
  184. package/dist/runner/presence.d.ts +11 -1
  185. package/dist/runner/presence.js +7 -0
  186. package/dist/runner/reflect-hook.js +1 -1
  187. package/dist/runner/run-child-host.d.ts +22 -8
  188. package/dist/runner/run-child-host.js +128 -41
  189. package/dist/runner/run-child.js +5 -2
  190. package/dist/runner/runner.d.ts +17 -3
  191. package/dist/runner/runner.js +130 -34
  192. package/dist/runner/save-slots.js +2 -1
  193. package/dist/runner/store-port.d.ts +1 -1
  194. package/dist/runner/store-secrets.d.ts +6 -0
  195. package/dist/runner/store-secrets.js +49 -7
  196. package/dist/runner/subagent.d.ts +11 -0
  197. package/dist/runner/subagent.js +16 -38
  198. package/dist/runner/workflow-first.d.ts +35 -15
  199. package/dist/runner/workflow-first.js +38 -25
  200. package/dist/runner/workflow-spec.js +4 -3
  201. package/dist/runs-over-store.d.ts +15 -6
  202. package/dist/runs-over-store.js +33 -21
  203. package/dist/scrub-command.d.ts +73 -0
  204. package/dist/scrub-command.js +307 -0
  205. package/dist/secret-cut.d.ts +73 -0
  206. package/dist/secret-cut.js +291 -4
  207. package/dist/secret-rules.d.ts +143 -0
  208. package/dist/secret-rules.js +2564 -0
  209. package/dist/secrets.d.ts +7 -0
  210. package/dist/secrets.js +20 -0
  211. package/dist/server-keys.d.ts +20 -0
  212. package/dist/server-keys.js +25 -6
  213. package/dist/server.d.ts +65 -13
  214. package/dist/server.js +470 -157
  215. package/dist/skills/agentrun-serve/SKILL.md +4 -0
  216. package/dist/slots.d.ts +9 -0
  217. package/dist/slots.js +45 -0
  218. package/dist/store/index.d.ts +1 -1
  219. package/dist/store/index.js +1 -1
  220. package/dist/store/journal/storage.js +1 -1
  221. package/dist/store/postgres/migrations/0027_run_launch_census.sql +31 -0
  222. package/dist/store/postgres/migrations/0028_learning_ledger.sql +44 -0
  223. package/dist/store/schema.d.ts +23 -0
  224. package/dist/store/schema.js +58 -2
  225. package/dist/store/seal.d.ts +6 -1
  226. package/dist/store/seal.js +5 -3
  227. package/dist/store/sqlite/run-launch.d.ts +9 -1
  228. package/dist/store/sqlite/run-launch.js +24 -13
  229. package/dist/store/sqlite/run-patch.d.ts +12 -2
  230. package/dist/store/sqlite/run-patch.js +42 -5
  231. package/dist/store/sqlite/store.js +105 -12
  232. package/dist/store/store.d.ts +57 -2
  233. package/dist/store/store.js +20 -0
  234. package/dist/store-reads/learning.d.ts +84 -124
  235. package/dist/store-reads/learning.js +210 -274
  236. package/dist/store-view.d.ts +3 -0
  237. package/dist/store-view.js +3 -3
  238. package/dist/suggestions.js +3 -2
  239. package/dist/template-eval.d.ts +39 -9
  240. package/dist/template-eval.js +191 -60
  241. package/dist/template-import.js +6 -2
  242. package/dist/templates.d.ts +10 -2
  243. package/dist/templates.js +28 -8
  244. package/dist/timeline/labels.d.ts +6 -4
  245. package/dist/timeline/labels.js +18 -6
  246. package/dist/timeline/timeline.d.ts +5 -0
  247. package/dist/timeline/timeline.js +14 -8
  248. package/dist/timeline/util.js +1 -1
  249. package/dist/timeline/web-calls.d.ts +22 -7
  250. package/dist/timeline/web-calls.js +106 -35
  251. package/dist/tool-gate.d.ts +42 -3
  252. package/dist/tool-gate.js +66 -5
  253. package/dist/tool-keys-store.d.ts +2 -4
  254. package/dist/tool-keys-store.js +5 -21
  255. package/dist/tool-keys.d.ts +2 -2
  256. package/dist/tool-keys.js +2 -2
  257. package/dist/tool-list.js +1 -1
  258. package/dist/tool-plane.d.ts +2 -2
  259. package/dist/tool-plane.js +35 -33
  260. package/dist/tools.js +13 -7
  261. package/dist/trigger-targets.d.ts +4 -0
  262. package/dist/trigger-targets.js +9 -2
  263. package/dist/triggers.d.ts +67 -4
  264. package/dist/triggers.js +171 -22
  265. package/dist/until.d.ts +3 -0
  266. package/dist/until.js +11 -0
  267. package/dist/web-fake.d.ts +1 -3
  268. package/dist/web-fake.js +7 -18
  269. package/dist/web-fetch.d.ts +6 -72
  270. package/dist/web-fetch.js +11 -265
  271. package/dist/web-run.d.ts +31 -0
  272. package/dist/web-run.js +90 -0
  273. package/dist/web-save.d.ts +10 -13
  274. package/dist/web-save.js +13 -55
  275. package/dist/web-search.d.ts +9 -127
  276. package/dist/web-search.js +23 -259
  277. package/dist/wires.d.ts +13 -0
  278. package/dist/wires.js +11 -0
  279. package/dist/workflow-run.d.ts +5 -4
  280. package/dist/workflow-run.js +5 -4
  281. package/dist/workspace/attached-computers.d.ts +32 -9
  282. package/dist/workspace/attached-computers.js +77 -13
  283. package/dist/workspace/computer-deps.d.ts +8 -2
  284. package/dist/workspace/computer-deps.js +10 -3
  285. package/dist/workspace/computer-for-claim.d.ts +12 -1
  286. package/dist/workspace/computer-for-claim.js +83 -11
  287. package/dist/workspace/computer-kept.d.ts +3 -0
  288. package/dist/workspace/computer-kept.js +11 -2
  289. package/dist/workspace/index.d.ts +1 -1
  290. package/dist/workspace/index.js +1 -1
  291. package/dist/workspace/kind-skills.d.ts +4 -0
  292. package/dist/workspace/kind-skills.js +9 -0
  293. package/dist/workspace/paired-route.d.ts +91 -0
  294. package/dist/workspace/paired-route.js +153 -0
  295. package/dist/workspace/synced-folder.js +3 -4
  296. package/dist/wrapped.d.ts +20 -6
  297. package/dist/wrapped.js +66 -25
  298. package/package.json +17 -11
  299. package/skills/agentrun-serve/SKILL.md +4 -0
  300. package/templates/README.md +32 -10
  301. package/dist/console/assets/index-CQ3cJRzI.js +0 -746
  302. package/dist/console/assets/index-DKkaS3a0.css +0 -1
  303. package/dist/exa-keyless.d.ts +0 -34
  304. package/dist/exa-keyless.js +0 -118
  305. package/dist/firecrawl-keyless.d.ts +0 -41
  306. package/dist/firecrawl-keyless.js +0 -152
  307. package/dist/keyless-mcp.d.ts +0 -36
  308. package/dist/keyless-mcp.js +0 -127
  309. package/dist/text-urls.d.ts +0 -38
  310. package/dist/text-urls.js +0 -170
  311. package/dist/web-fetch-direct.d.ts +0 -119
  312. package/dist/web-fetch-direct.js +0 -190
@@ -23,10 +23,12 @@ import { isFenced } from "./store-port.js";
23
23
  import { FINAL_STATES } from "../store/store.js";
24
24
  import { Unanswered } from "../store/postgres/connection.js";
25
25
  import { clearWaitEnded } from "../browser-wait-ended.js";
26
+ import { clearBrowserHeld } from "../browser-hold.js";
26
27
  import { keptBy, readKept } from "../workspace/computer-kept.js";
27
28
  import { cutDeep, heldRedactor, processSecretRedactor } from "./redact.js";
28
29
  import { withLiveTicker } from "./live-ticker.js";
29
30
  import { keepPresence } from "./presence.js";
31
+ import { flushTraces } from "../otel/tracer.js";
30
32
  /** Tries of the re-read after a claim or release commit was answered Unanswered (the commit may have landed). */
31
33
  const UNKNOWN_READS = 5;
32
34
  /** Passes of the sweep after a claim answered Unanswered: the commit may still be on its way when the first read comes back
@@ -76,11 +78,14 @@ const PASSES_A_BLOCKED_ROW = new Set([...HELD_COMMANDS, COMPUTER_CALL, HAND_BACK
76
78
  export const END_RETRY_CAP_MS = 300_000;
77
79
  /** The tries at that cap before the run ends stopped on its row alone (about an hour of retries in all; endRefused). */
78
80
  export const END_RETRY_AT_CAP = 11;
81
+ /** The most a run's end waits for its census (RunnerOptions.census): 60 s, for up to CENSUS_BYTES_MAX (64 MiB) read
82
+ * over the run's Workspace (an Archil disk's included). Past it the end goes on without one. */
83
+ export const CENSUS_MS = 60_000;
79
84
  const message = (error) => (error instanceof Error ? error.message : String(error));
80
85
  /** The run states a run patch makes final: a commit that lands one is the run's end, and its release. */
81
86
  const FINAL = new Set(["ended", "stopped", "failed"]);
82
87
  export function startRunner(options) {
83
- const { store, createLoop, name = runnerName(), loops = RUNNER_LOOPS, leaseMs = RUNNER_LEASE_MS, renewEveryMs = RUNNER_RENEW_EVERY_MS, stopMarginMs = RUNNER_STOP_MARGIN_MS, pollMs = 1_000, commandPollMs = 500, resumeTries = 3, resumeBackoffMs = 5_000, interruptBackoffMs = 1_000, unknownBackoffMs = 200, endWaitMs = 5_000, drainMs = 0, memory, endRetryBackoffMs = END_RETRY_BACKOFF_MS, endRetryCapMs = END_RETRY_CAP_MS, endRetryAtCap = END_RETRY_AT_CAP, onEvent = () => { }, runEnded, redact: given = processSecretRedactor(), now = Date.now, onBeat = () => { }, clock = { now: () => Date.now(), setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: (handle) => clearTimeout(handle) }, } = options;
88
+ const { store, createLoop, name = runnerName(), loops = RUNNER_LOOPS, leaseMs = RUNNER_LEASE_MS, renewEveryMs = RUNNER_RENEW_EVERY_MS, stopMarginMs = RUNNER_STOP_MARGIN_MS, pollMs = 1_000, commandPollMs = 500, resumeTries = 3, resumeBackoffMs = 5_000, interruptBackoffMs = 1_000, unknownBackoffMs = 200, endWaitMs = 5_000, drainMs = 0, memory, census, censusMs = CENSUS_MS, endRetryBackoffMs = END_RETRY_BACKOFF_MS, endRetryCapMs = END_RETRY_CAP_MS, endRetryAtCap = END_RETRY_AT_CAP, onEvent = () => { }, runEnded, redact: given = processSecretRedactor(), now = Date.now, onBeat = () => { }, clock = { now: () => Date.now(), setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: (handle) => clearTimeout(handle) }, } = options;
84
89
  // The one instance every run's loop gets (LoopDeps.redact), able to hold what each claim opens from the store
85
90
  // (redact.ts holdClaimed): a stored key is cut wherever a key of the runner's environment is.
86
91
  const redact = heldRedactor(given);
@@ -155,6 +160,8 @@ export function startRunner(options) {
155
160
  const replaced = new Set();
156
161
  /** The refused stopped ends this runner is trying again (endRetried): close() waits for them. */
157
162
  const endings = new Set();
163
+ /** The claims those ends hold, renewed (renewAll) until each end lands. */
164
+ const endOnly = new Set();
158
165
  /** Each run's ends in a row, on this runner, as interrupted on its own: its next release's backoff doubles with them. */
159
166
  const interruptedInARow = new Map();
160
167
  let closed = false;
@@ -166,6 +173,31 @@ export function startRunner(options) {
166
173
  /** Stops listening for written commands (store.watchCommands); set once the runner has started. */
167
174
  let unwatchCommands;
168
175
  let polling = false;
176
+ /** Run `runId`'s census for its end (RunnerOptions.census), as a patch's part: none past censusMs, or when it fails.
177
+ * Either is said as an error event (step "census") with the run's id and why, so a 403 on the run's files after its
178
+ * end can be traced: an error's code or name only, never its message, which may name a file of the run's. */
179
+ const censusFor = async (runId) => {
180
+ if (!census)
181
+ return {};
182
+ let stop = () => { };
183
+ let why;
184
+ const late = new Promise((resolve) => {
185
+ const timer = setTimeout(() => {
186
+ why = `none within ${censusMs} ms`;
187
+ resolve(undefined);
188
+ }, censusMs);
189
+ stop = () => clearTimeout(timer);
190
+ });
191
+ const failed = (error) => {
192
+ const code = error?.code;
193
+ why = `it failed (${typeof code === "string" ? code : error instanceof Error ? error.name : "unknown"})`;
194
+ return undefined;
195
+ };
196
+ const made = await Promise.race([census(runId).catch(failed), late]).finally(() => stop());
197
+ if (!made && why !== undefined)
198
+ emit({ type: "error", runId, step: "census", message: `${why}: the end writes "unscanned", and the run's files are withheld from a cut read after it` });
199
+ return made ? { census: made } : {};
200
+ };
169
201
  /** The run's journal with this runner's fence on its one write: after the claim is lost, commit throws ClaimLost. A
170
202
  * commit that lands a final run patch (the loop's own end, which is the run's release) calls `ended` at once: from
171
203
  * then the run is ending, before the loop's teardown, so a renew answered Fenced by that end's epoch is never a lost
@@ -177,6 +209,12 @@ export function startRunner(options) {
177
209
  const fenced = (journal, fence, runId, ended) => {
178
210
  /** The effect of the final patch staged and not yet landed, as the store keeps it until a commit stores it. */
179
211
  let finalEffect;
212
+ /** That final patch's stage as given to the store, and its census, begun when it was staged: the commit that writes
213
+ * its effect stages it again with the census, so the end's commit writes it (refuseLeftovers). */
214
+ let finalStaged;
215
+ /** The commit that carries the final patch, while it waits for its census: a commit asked after it waits for it, so
216
+ * the run's commits land in the order they were asked. */
217
+ let ending;
180
218
  const carriedOut = (given) => {
181
219
  const carried = redact.carried(runId);
182
220
  return carried ? cutDeep(given, carried, true) : given;
@@ -188,10 +226,13 @@ export function startRunner(options) {
188
226
  return value;
189
227
  if (property === "stage") {
190
228
  return (staged, ...rest) => {
191
- const result = value.call(target, carriedOut(staged), ...rest);
229
+ const given = carriedOut(staged);
230
+ const result = value.call(target, given, ...rest);
192
231
  // As the store keeps it: a run patch or rows staged again replace the one staged before.
193
- if (staged?.run !== undefined || staged?.also !== undefined)
232
+ if (staged?.run !== undefined || staged?.also !== undefined) {
194
233
  finalEffect = FINAL.has(staged.run?.state ?? "") ? Number(staged.effect) : undefined;
234
+ finalStaged = finalEffect !== undefined && given ? { staged: given, census: censusFor(runId) } : undefined;
235
+ }
195
236
  return result;
196
237
  };
197
238
  }
@@ -205,7 +246,23 @@ export function startRunner(options) {
205
246
  const effect = finalEffect;
206
247
  const batches = (Array.isArray(args[0]) ? args[0] : [args[0]]);
207
248
  const at = effect === undefined ? -1 : batches.findIndex((batch) => (Array.isArray(batch) ? batch : [batch]).some((write) => Number(write?.value?.id) === effect));
208
- return value.apply(target, [carriedOut(args[0]), ...args.slice(1)]).then((result) => {
249
+ const before = ending;
250
+ const carrying = at >= 0 ? finalStaged : undefined;
251
+ const applied = (async () => {
252
+ await before?.catch(() => undefined);
253
+ if (carrying) {
254
+ const { census: made } = await carrying.census;
255
+ // Staged again only while it is still the final patch staged, with its census beside it.
256
+ if (made && finalStaged === carrying)
257
+ Reflect.get(target, "stage", target).call(target, { ...carrying.staged, run: { ...carrying.staged.run, census: made } });
258
+ }
259
+ if (fence.lost)
260
+ throw new ClaimLost(`run ${runId}: this runner lost its claim; the commit is not written`);
261
+ return (await value.apply(target, [carriedOut(args[0]), ...args.slice(1)]));
262
+ })();
263
+ if (carrying || before)
264
+ ending = applied;
265
+ return applied.then((result) => {
209
266
  if (at >= 0 && at < (result?.stored ?? 0) && finalEffect === effect) {
210
267
  finalEffect = undefined;
211
268
  ended();
@@ -216,6 +273,17 @@ export function startRunner(options) {
216
273
  },
217
274
  });
218
275
  };
276
+ /** When a claim answered now (a claim's, or a renew's, asked at `sentAt`) is lost unless renewed, on `clock`: its
277
+ * lease less the stop margin. On a store whose lease clock is this process's own (Store.leaseClock: SQLite) that is
278
+ * the claim's `until`, read on that clock now, less the margin: the store granted the lease from when the call held
279
+ * the writer lock, so a call that waited in line for it (another write holding the lock, this runner's own calls
280
+ * before it on a loaded disk) keeps what it was granted. Otherwise (Postgres: the database's clock) it is reckoned
281
+ * from when the call was asked, which is never later than its lock. Either way it falls the margin before the
282
+ * store's lease runs out, and another runner may claim the run. */
283
+ const deadlineOf = (claim, sentAt) => {
284
+ const leaseNow = store.leaseClock?.();
285
+ return leaseNow === undefined ? sentAt + leaseMs - stopMarginMs : clock.now() + (claim.until - leaseNow) - stopMarginMs;
286
+ };
219
287
  const armDeadline = (held, at) => {
220
288
  clock.clearTimeout(held.deadline);
221
289
  held.deadline = clock.setTimeout(() => loseClaim(held, "not-renewed"), Math.max(0, at - clock.now()));
@@ -245,20 +313,25 @@ export function startRunner(options) {
245
313
  };
246
314
  /** Every held claim renewed in one transaction (store.renewMany), never one per run: a claim answered Fenced is lost,
247
315
  * the others move on. Any other failure (a busy store) is tried at the next renew; each run's deadline stops its loop
248
- * if none lands. */
316
+ * if none lands. An ending claim is renewed too, until the write that ends its run lands (Held.landed): its end waits
317
+ * for the run's census (up to censusMs, longer than a lease), and a claim that ran out meanwhile would have that write
318
+ * refused (Fenced), the run left unfinished and claimed again. Its renew's answer is not read: an ending claim is never
319
+ * lost (loseClaim) and has no deadline. So are the claims that only end a run (endRetried), until theirs lands. Once an
320
+ * end lands its claim is spent: no renew races the release that follows. */
249
321
  const renewAll = async () => {
250
322
  if (killed)
251
323
  return;
252
324
  beat();
253
- const due = [...runs.values()].filter((held) => !held.renewing && !held.fence.lost && !held.ending);
254
- if (due.length === 0)
325
+ const due = [...runs.values()].filter((held) => !held.renewing && !held.fence.lost && !held.landed);
326
+ const ends = [...endOnly].filter((only) => !only.renewing && !only.landed);
327
+ if (due.length === 0 && ends.length === 0)
255
328
  return;
256
- for (const held of due)
257
- held.renewing = true;
329
+ for (const one of [...due, ...ends])
330
+ one.renewing = true;
258
331
  const sentAt = clock.now();
259
332
  try {
260
- const results = await store.renewMany(due.map((held) => held.claim), { leaseMs });
261
- results.forEach((result, i) => {
333
+ const results = await store.renewMany([...due, ...ends].map((one) => one.claim), { leaseMs });
334
+ results.slice(0, due.length).forEach((result, i) => {
262
335
  const held = due[i];
263
336
  if (held.fence.lost || held.ending || killed)
264
337
  return;
@@ -266,17 +339,17 @@ export function startRunner(options) {
266
339
  loseClaim(held, "fenced");
267
340
  else {
268
341
  held.claim = result;
269
- armDeadline(held, sentAt + leaseMs - stopMarginMs);
342
+ armDeadline(held, deadlineOf(held.claim, sentAt));
270
343
  }
271
344
  });
272
345
  }
273
346
  catch (error) {
274
- for (const held of due)
275
- emit({ type: "error", runId: held.claim.runId, step: "renew", message: message(error) });
347
+ for (const one of [...due, ...ends])
348
+ emit({ type: "error", runId: one.claim.runId, step: "renew", message: message(error) });
276
349
  }
277
350
  finally {
278
- for (const held of due)
279
- held.renewing = false;
351
+ for (const one of [...due, ...ends])
352
+ one.renewing = false;
280
353
  }
281
354
  };
282
355
  const renewTimer = setInterval(() => void renewAll(), renewEveryMs);
@@ -428,13 +501,15 @@ export function startRunner(options) {
428
501
  * in its journal, a reopen would find no turn to follow (its next claim would read the run as never started), so it
429
502
  * reads as a stop that is over (cancelled), as it read before a stop and a cancel were told apart.
430
503
  */
431
- const endRun = async (claim, given, take, withdrawnAs = "withdrawn") => {
504
+ const endRun = async (claim, given, take, withdrawnAs = "withdrawn", landed = () => { }) => {
432
505
  // Why the run ended, as its end and its row say it: cut of every secret the runner holds (an error's text may echo one).
433
506
  const data = { ...given, summary: redact(given.summary) };
434
507
  // Unknown means it may withdraw: false only once the journal was read and no call of it waits.
435
508
  let mayWithdraw = data.state === "stopped";
436
509
  // A run whose journal holds no conversation never sent a request: its end carries a cost of $0, as a loop's end does.
437
510
  let neverSent = false;
511
+ // Where in the run's files what its caller handed it sits, written in its place as this end erases it.
512
+ const counted = await censusFor(claim.runId);
438
513
  try {
439
514
  const journal = store.journal(claim);
440
515
  const [root] = (await journal.scanConversations({}, 1, undefined, BACKGROUND_CONTEXT)).items;
@@ -459,34 +534,39 @@ export function startRunner(options) {
459
534
  }
460
535
  const id = (await journal.mintId());
461
536
  writes.push({ type: "entry", value: { id, conversationId, kind: KINDS.end, data: data } });
462
- journal.stage({ run: { state: data.state, summary: data.summary, ...(data.outcome ? { outcome: data.outcome } : {}), ...(neverSent ? { costUsd: 0 } : {}) }, effect: id, ...(take.length ? { take: take.map((command) => ({ command, effect: id })) } : {}) });
537
+ journal.stage({ run: { state: data.state, summary: data.summary, ...(data.outcome ? { outcome: data.outcome } : {}), ...(neverSent ? { costUsd: 0 } : {}), ...counted }, effect: id, ...(take.length ? { take: take.map((command) => ({ command, effect: id })) } : {}) });
463
538
  const result = await journal.commit([writes], () => { }, BACKGROUND_CONTEXT);
464
539
  if (result.stored !== 1)
465
540
  throw result.refused ?? new Error("the run's end was not stored");
541
+ landed();
466
542
  }
467
543
  catch (error) {
468
544
  if (isFenced(error))
469
545
  throw error;
470
546
  if (mayWithdraw)
471
547
  throw new EndNotWithdrawn(claim.runId, error);
472
- await store.runs.update(claim, { state: data.state, summary: data.summary, ...(data.outcome === "cancelled" ? { outcome: data.outcome } : {}) }, take.length ? { take } : undefined);
548
+ await store.runs.update(claim, { state: data.state, summary: data.summary, ...(data.outcome === "cancelled" ? { outcome: data.outcome } : {}), ...counted }, take.length ? { take } : undefined);
549
+ landed();
473
550
  }
474
551
  // An ended run's Screen has no ended-while-waiting state to keep (browser-wait-ended.ts): its row goes with the end.
475
552
  if (store.settings)
476
553
  await clearWaitEnded(store.settings, claim.runId, claim.epoch).catch(() => undefined);
554
+ // Nor a take of its browser (browser-hold.ts).
555
+ if (store.settings)
556
+ await clearBrowserHeld(store.settings, claim.runId, claim.epoch).catch(() => undefined);
477
557
  };
478
558
  /** Ends the run under `claim` stopped on its untaken `stop` (or cancel) row (endRun). False when that end may withdraw a
479
559
  * call and the journal would not take it or could not be read: the refusal is then the run's (endRefused). */
480
- const endStopped = async (claim, stop) => {
560
+ const endStopped = async (claim, stop, landed) => {
481
561
  try {
482
562
  const end = stopEnd(stop.kind === "cancel");
483
- await endRun(claim, end, [stop.id], stop.kind === "cancel" ? "canceled" : "withdrawn");
563
+ await endRun(claim, end, [stop.id], stop.kind === "cancel" ? "canceled" : "withdrawn", landed);
484
564
  return true;
485
565
  }
486
566
  catch (error) {
487
567
  if (!(error instanceof EndNotWithdrawn))
488
568
  throw error;
489
- await endRefused(claim, stop, error);
569
+ await endRefused(claim, stop, error, landed);
490
570
  return false;
491
571
  }
492
572
  };
@@ -513,14 +593,15 @@ export function startRunner(options) {
513
593
  * 11 tries at the cap): 6 growing waits (5 s to 160 s, 315 s in all), then 11 of 5 min, so about an hour (3,615 s) of
514
594
  * retries, and the 18th refusal gives up.
515
595
  */
516
- const endRefused = async (claim, stop, refused) => {
596
+ const endRefused = async (claim, stop, refused, landed) => {
517
597
  const tries = await store.retry(claim, stop.id);
518
598
  const why = message(refused.cause);
519
599
  if (tries >= endRetryCapFrom + endRetryAtCap) {
520
600
  emit({ type: "error", runId: claim.runId, step: "end", message: `run ${claim.runId} ended without withdrawing: journal unreadable or refusing (after ${tries} tries; the last: ${why})` });
521
601
  // On its row alone, so no outcome 'stopped' (endRun): a run whose journal never took its end is never reopened.
522
602
  const end = stopEnd(stop.kind === "cancel");
523
- await store.runs.update(claim, { state: end.state, summary: redact(end.summary), ...(end.outcome === "cancelled" ? { outcome: end.outcome } : {}) }, { take: [stop.id] });
603
+ await store.runs.update(claim, { state: end.state, summary: redact(end.summary), ...(end.outcome === "cancelled" ? { outcome: end.outcome } : {}), ...(await censusFor(claim.runId)) }, { take: [stop.id] });
604
+ landed();
524
605
  await releaseStopped(claim, stop);
525
606
  return;
526
607
  }
@@ -566,15 +647,21 @@ export function startRunner(options) {
566
647
  /** A claim of a run whose stopped end was refused (its untaken stop row has tries): it only ends the run, with no loop,
567
648
  * so no turn, model request or tool runs on a run that is stopping. */
568
649
  const endRetried = async (claim, stop) => {
650
+ // Renewed with the held claims (renewAll) until its end lands: its end waits for the run's census too.
651
+ const only = { claim, landed: false, renewing: false };
652
+ endOnly.add(only);
569
653
  try {
570
654
  // A run stopped before any loop started still has its one start line, ahead of its end.
571
655
  await announceStart(claim);
572
- if (await endStopped(claim, stop))
656
+ if (await endStopped(claim, stop, () => (only.landed = true)))
573
657
  await releaseStopped(claim, stop);
574
658
  }
575
659
  catch (error) {
576
660
  emit({ type: "error", runId: claim.runId, step: isFenced(error) ? "end (fenced)" : "end", message: message(error) });
577
661
  }
662
+ finally {
663
+ endOnly.delete(only);
664
+ }
578
665
  };
579
666
  const finish = async (held, end, threw) => {
580
667
  // Whether the runner asked the loop to stop before it ended (only stopLoop sets this).
@@ -582,6 +669,10 @@ export function startRunner(options) {
582
669
  held.ending = true;
583
670
  clock.clearTimeout(held.deadline);
584
671
  const { claim } = held;
672
+ // The runner's own end of the run, once its write lands: the claim is renewed until then (renewAll), no further.
673
+ const landed = () => {
674
+ held.landed = true;
675
+ };
585
676
  // A command still with the loop: its refusal is written before anything of the end, never after the release. A loop
586
677
  // that does not answer within endWaitMs has its answer dropped (the claim is sealed first).
587
678
  if (held.inFlight) {
@@ -614,12 +705,12 @@ export function startRunner(options) {
614
705
  // never refused as a failed run's; else the run ends failed with why. Either way its end is in the journal.
615
706
  const stop = endingRow((await store.commands(claim.runId, 0)).filter((row) => row.takenAt === null));
616
707
  if (stop) {
617
- if (!(await endStopped(claim, stop)))
708
+ if (!(await endStopped(claim, stop, landed)))
618
709
  return;
619
710
  end = { state: "stopped" };
620
711
  }
621
712
  else {
622
- await endRun(claim, { state: "failed", summary: end.error.message }, []);
713
+ await endRun(claim, { state: "failed", summary: end.error.message }, [], "withdrawn", landed);
623
714
  }
624
715
  }
625
716
  if (end.state === "ended" || end.state === "stopped" || end.state === "failed") {
@@ -633,6 +724,8 @@ export function startRunner(options) {
633
724
  // The run's end (a normal completion among them) leaves no browser-released message behind for a follow-up (browser-wait-ended.ts).
634
725
  if (store.settings)
635
726
  await clearWaitEnded(store.settings, claim.runId, claim.epoch).catch(() => undefined);
727
+ if (store.settings)
728
+ await clearBrowserHeld(store.settings, claim.runId, claim.epoch).catch(() => undefined);
636
729
  }
637
730
  await store.flush();
638
731
  // A loop that ended interrupted with no stop asked of it (its Session closed itself) is released with a backoff that
@@ -649,7 +742,7 @@ export function startRunner(options) {
649
742
  const cut = end.state !== "interrupted" ? undefined : closedItself ? "retry" : held.stoppedFor === "shutdown" ? "drain" : undefined;
650
743
  await release(claim, {
651
744
  ...(end.state === "parked" && end.wakeAt !== undefined ? { wakeAt: end.wakeAt }
652
- : inARow > 0 ? { backoffUntil: Date.now() + interruptBackoffMs * 2 ** Math.min(inARow - 1, 6) }
745
+ : inARow > 0 ? { backoffUntil: now() + interruptBackoffMs * 2 ** Math.min(inARow - 1, 6) }
653
746
  : {}),
654
747
  ...(cut ? { cut } : {}),
655
748
  });
@@ -683,7 +776,7 @@ export function startRunner(options) {
683
776
  // A stop never waits on a loop that cannot start: the run ends stopped here, its stop row taken, and every other
684
777
  // untaken row refused as a stopped run's.
685
778
  // One write: the run ends stopped with its stop row taken, or neither (a final run never keeps its stop untaken).
686
- if (await endStopped(claim, stop))
779
+ if (await endStopped(claim, stop, () => (held.landed = true)))
687
780
  await releaseStopped(claim, stop);
688
781
  return;
689
782
  }
@@ -698,7 +791,7 @@ export function startRunner(options) {
698
791
  }
699
792
  else {
700
793
  await store.flush();
701
- await release(claim, { state: "parked", backoffUntil: Date.now() + resumeBackoffMs * 2 ** (tries - 1) });
794
+ await release(claim, { state: "parked", backoffUntil: now() + resumeBackoffMs * 2 ** (tries - 1) });
702
795
  }
703
796
  }
704
797
  else {
@@ -734,15 +827,16 @@ export function startRunner(options) {
734
827
  },
735
828
  redact,
736
829
  });
737
- const held = { passed: new Set(), claim, loop, fence, abort, cursor: 0, stopping: false, ending: false, sealed: false, renewing: false, delivering: false, deliverAgain: false, mib };
830
+ const held = { passed: new Set(), claim, loop, fence, abort, cursor: 0, stopping: false, ending: false, landed: false, sealed: false, renewing: false, delivering: false, deliverAgain: false, mib };
738
831
  heldNow = held;
739
832
  // The loop's own end landed: the run is ending from here, its teardown included (no renew, no lost claim).
740
833
  ending = () => {
741
834
  held.ending = true;
835
+ held.landed = true;
742
836
  clock.clearTimeout(held.deadline);
743
837
  };
744
838
  runs.set(claim.runId, held);
745
- armDeadline(held, sentAt + leaseMs - stopMarginMs);
839
+ armDeadline(held, deadlineOf(claim, sentAt));
746
840
  emit({ type: "claimed", claim });
747
841
  void announceStart(claim);
748
842
  held.done = (async () => {
@@ -913,7 +1007,7 @@ export function startRunner(options) {
913
1007
  catch (error) {
914
1008
  // The loop could not be made: the run fails here, so it is not claimed again and again.
915
1009
  emit({ type: "error", runId: claim.runId, step: "create loop", message: message(error) });
916
- await store.runs.update(claim, { state: "failed", summary: redact(message(error)) }).catch(() => { });
1010
+ await store.runs.update(claim, { state: "failed", summary: redact(message(error)), ...(await censusFor(claim.runId)) }).catch(() => { });
917
1011
  await store.flush().catch(() => { });
918
1012
  await release(claim, {}).catch(() => { });
919
1013
  }
@@ -1023,7 +1117,7 @@ export function startRunner(options) {
1023
1117
  };
1024
1118
  // Its word in the store that a runner that claims is here (presence.ts), for as long as it runs: a server reads a
1025
1119
  // refusal left by an earlier runner as over once this is there. One its caller keeps is its caller's to close.
1026
- const presence = options.presence ? undefined : store.runners ? keepPresence(store.runners, name, null, { warn: (line) => emit({ type: "error", step: "presence", message: line }), slots: loops }) : undefined;
1120
+ const presence = options.presence ? undefined : store.runners ? keepPresence(store.runners, name, null, { warn: (line) => emit({ type: "error", step: "presence", message: line }), slots: loops, ...(options.incarnation ? { incarnation: options.incarnation } : {}) }) : undefined;
1027
1121
  poll();
1028
1122
  commandTimer = setTimeout(deliverAll, commandPollMs);
1029
1123
  // A run queued in this process is claimed now (claimNow). A command written for a run this runner holds is handed on
@@ -1172,6 +1266,8 @@ export function startRunner(options) {
1172
1266
  await ticker?.close();
1173
1267
  // It claims no more: its word that it is here goes.
1174
1268
  await presence?.close();
1269
+ // Its runs' trace spans still waiting in the batch are sent, at most FLUSH_MS (nothing when tracing is off).
1270
+ await flushTraces();
1175
1271
  },
1176
1272
  kill() {
1177
1273
  killed = true;
@@ -69,7 +69,8 @@ export function remoteSaveSlots(channel) {
69
69
  waiting++;
70
70
  let release;
71
71
  try {
72
- release = await channel.call(TARGET, "take", [signal]);
72
+ // The channel takes a slot under a signal: with none given, one that never aborts (Slots.take waits until free).
73
+ release = await channel.call(TARGET, "take", [signal ?? new AbortController().signal]);
73
74
  }
74
75
  finally {
75
76
  waiting--;
@@ -1,5 +1,5 @@
1
1
  import { type Store } from "../store/store.js";
2
- export type RunnerStore = Pick<Store, "claim" | "renew" | "renewMany" | "release" | "journal" | "flush" | "commands" | "commandsOf" | "take" | "retry" | "watchCommands"> & {
2
+ export type RunnerStore = Pick<Store, "leaseClock" | "claim" | "renew" | "renewMany" | "release" | "journal" | "flush" | "commands" | "commandsOf" | "take" | "retry" | "watchCommands"> & {
3
3
  readonly runs: Pick<Store["runs"], "claimMany" | "claimable" | "claimsOf" | "update"> & Partial<Pick<Store["runs"], "launch" | "get">>;
4
4
  /** The revision's kind, read for a run's start line (runner.ts). A store without it (a test's) says no start or end line. */
5
5
  readonly agents?: Pick<Store["agents"], "revision">;
@@ -3,6 +3,12 @@ import type { TriggerAdapter } from "../trigger-adapter.js";
3
3
  import type { HeldRedact } from "./redact.js";
4
4
  /** The store slice the read needs. */
5
5
  export type StoreSecretsStore = Pick<Store, "sealedSecrets">;
6
+ /** A launch's sealed JSON: its own listed values (jsonSecrets), each handed MCP credential's headers (store/seal.ts
7
+ * sealRunLaunch: `{"mcp": {"<server>": {"headers": {...}}}}`), as a saved server's are listed, each per-run Composio
8
+ * binding's user and account (`{"mcp": {"<server>": {"composio": {"user_id", "connected_account_id"}}}}`), the run's
9
+ * own model key (`{"model": {"key": "..."}}`), each of its own tool keys (`{"keys": {"<NAME>": "..."}}`) and each value a
10
+ * message replaced since its turn began (`{"retired": ["..."]}`). */
11
+ export declare function launchSecrets(text: string): string[];
6
12
  /** Every secret the server keeps sealed that `sealKey` opens: the store's (one read across its planes) and, where the runner
7
13
  * shares the server's data directory `data`, what it keeps beside the store. With no key (a run's own process, which
8
14
  * never holds the server's secrets, so has none of them to write), none: its runner cuts what crosses to it from what
@@ -15,6 +15,7 @@ import { CHATGPT_PLAN_ROW } from "../chatgpt-plan.js";
15
15
  import { calendarRowSecrets } from "../calendar/address.js";
16
16
  import { CALENDAR_ROW } from "../calendar/names.js";
17
17
  import { accountRowSecrets, EMAIL_ACCOUNT_ROW } from "../email/account.js";
18
+ import { MIN_SECRET } from "../learn/secrets.js";
18
19
  import { GATEWAY_KEY_ROW, gatewayKeyRowSecrets } from "../model-gateway.js";
19
20
  import { unseal } from "../sealing.js";
20
21
  import { besideTheStore, ServerSecrets } from "../server-secrets.js";
@@ -22,8 +23,31 @@ import { SLACK_CHANNEL, slackUrlForms } from "../slack-url.js";
22
23
  import { TRIGGER_ADAPTERS } from "../trigger-adapters.js";
23
24
  /** The keys of a sealed JSON value that hold secrets: OAuth tokens, a client's secret, a PKCE verifier. */
24
25
  const JSON_SECRETS = ["access_token", "refresh_token", "id_token", "client_secret", "verifier"];
25
- /** The secret strings of an opened JSON value: each header's value (a bearer's token alone too), and every string under
26
- * one of JSON_SECRETS, wherever it is nested. */
26
+ /** The authorization schemes whose header value is the scheme's word then its credential (`Bearer <token>`), in any case.
27
+ * Their second word is listed alone whatever its shape. */
28
+ const CREDENTIAL_SCHEMES = new Set(["bearer", "basic", "token", "digest", "apikey", "key"]);
29
+ /** Whether the second word of a two-word header value in a scheme CREDENTIAL_SCHEMES doesn't name (Okta's `SSWS`,
30
+ * Discord's `Bot`, `OAuth`, `Splunk`, `Klaviyo-API-Key`) is shaped like a credential: it has a digit, or is 20
31
+ * characters or more, or is base64 at MIN_SECRET or more with its punctuation (`+`, `/`, `=`) or with both cases past
32
+ * its first letter, or is hex at MIN_SECRET or more. A client's name (`Acme Integration`, `Acme integration-service`)
33
+ * is none of these and is not split: a word of it is no credential, and listed alone it would be cut from every run
34
+ * and refused in every learned draft. */
35
+ function credentialShaped(word) {
36
+ if (/\d/.test(word) || word.length >= 20)
37
+ return true;
38
+ if (word.length < MIN_SECRET)
39
+ return false;
40
+ if (/^[0-9a-f]+$/i.test(word))
41
+ return true;
42
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(word))
43
+ return false;
44
+ return /[+/=]/.test(word) || (/[a-z]/.test(word.slice(1)) && /[A-Z]/.test(word.slice(1)));
45
+ }
46
+ /** The secret strings of an opened JSON value: each header's value, and its credential alone where it is one of
47
+ * CREDENTIAL_SCHEMES' or credentialShaped (`Bearer <token>`, `Basic <credential>`, `SSWS <token>`: a value with a
48
+ * space is never listed whole, server-secrets.ts); a Basic credential's `user:password`, its password, and its user
49
+ * when the password is too short to be the secret (a key sent as the user, `-u KEY:`); and every string under one of
50
+ * JSON_SECRETS, wherever nested. */
27
51
  function jsonSecrets(text) {
28
52
  let value;
29
53
  try {
@@ -49,9 +73,21 @@ function jsonSecrets(text) {
49
73
  if (typeof header !== "string")
50
74
  continue;
51
75
  out.push(header);
52
- const bearer = /^Bearer\s+(.+)$/i.exec(header);
53
- if (bearer)
54
- out.push(bearer[1]);
76
+ const scheme = /^([A-Za-z][\w.-]*)\s+(\S+)\s*$/.exec(header);
77
+ if (!scheme || !(CREDENTIAL_SCHEMES.has(scheme[1].toLowerCase()) || credentialShaped(scheme[2])))
78
+ continue;
79
+ out.push(scheme[2]);
80
+ if (scheme[1].toLowerCase() !== "basic")
81
+ continue;
82
+ const pair = Buffer.from(scheme[2], "base64").toString("utf8");
83
+ const colon = pair.indexOf(":");
84
+ if (colon < 0 || /[\u0000-\u001f\ufffd]/.test(pair))
85
+ continue;
86
+ const user = pair.slice(0, colon);
87
+ const password = pair.slice(colon + 1);
88
+ out.push(pair, password);
89
+ if (password.length < MIN_SECRET)
90
+ out.push(user);
55
91
  }
56
92
  }
57
93
  walk(value);
@@ -60,8 +96,9 @@ function jsonSecrets(text) {
60
96
  /** A launch's sealed JSON: its own listed values (jsonSecrets), each handed MCP credential's headers (store/seal.ts
61
97
  * sealRunLaunch: `{"mcp": {"<server>": {"headers": {...}}}}`), as a saved server's are listed, each per-run Composio
62
98
  * binding's user and account (`{"mcp": {"<server>": {"composio": {"user_id", "connected_account_id"}}}}`), the run's
63
- * own model key (`{"model": {"key": "..."}}`) and each of its own tool keys (`{"keys": {"<NAME>": "..."}}`). */
64
- function launchSecrets(text) {
99
+ * own model key (`{"model": {"key": "..."}}`), each of its own tool keys (`{"keys": {"<NAME>": "..."}}`) and each value a
100
+ * message replaced since its turn began (`{"retired": ["..."]}`). */
101
+ export function launchSecrets(text) {
65
102
  const out = jsonSecrets(text);
66
103
  let opened;
67
104
  try {
@@ -86,6 +123,11 @@ function launchSecrets(text) {
86
123
  for (const value of Object.values(opened.keys))
87
124
  if (typeof value === "string")
88
125
  out.push(value);
126
+ // Each value a message replaced since the turn began (store/seal.ts RunLaunchSecrets.retired): cut, never used.
127
+ if (Array.isArray(opened?.retired))
128
+ for (const value of opened.retired)
129
+ if (typeof value === "string")
130
+ out.push(value);
89
131
  return out;
90
132
  }
91
133
  /** The ChatGPT sign-in's sealed row (chatgpt-plan.ts): its access and refresh tokens, each alone, as a renewal in any
@@ -4,6 +4,17 @@ export declare const SUBAGENT_TOOL = "subagent";
4
4
  * none runs its child on the agent's own model. */
5
5
  export declare const SUBAGENT_TIERS: readonly ["fast", "strong"];
6
6
  export type SubagentTier = (typeof SUBAGENT_TIERS)[number];
7
+ /** The subagent tiers a run routes a model on, with the model its revision names for each: a tier its revision's
8
+ * modelTiers names (a string), else one `env`'s tier variable names (AGENT_MODEL_FAST, AGENT_MODEL_STRONG: tierModelOf),
9
+ * and no other. The one answer for the runner that hands a run's process its tiers' saved model keys (run-child-host.ts
10
+ * heldFor), for the run that routes the tiers (adapter-run-spec.ts) and for a replay's grader on the fast tier, so a
11
+ * tier is never routed with no key handed for it, nor a key handed for a tier no route reads. */
12
+ export declare function routedSubagentTiers(body: {
13
+ readonly modelTiers?: unknown;
14
+ }, env: NodeJS.ProcessEnv): {
15
+ readonly tiers: SubagentTier[];
16
+ readonly refs: Partial<Record<SubagentTier, string>>;
17
+ };
7
18
  /** How many of a run's children work at once; a call past it waits for a slot. */
8
19
  export declare const SUBAGENT_PARALLEL = 4;
9
20
  /** A child's instructions: the call's prompt is its whole task. Nothing of the parent's prompt is carried over. */
@@ -1,6 +1,8 @@
1
1
  import { configure, defineTool, ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
2
2
  import { HOST_RESULT_MAX_CHARS } from "@parcha/agentrun-kernel";
3
+ import { tierModelOf } from "../model.js";
3
4
  import { ASK_TOOL } from "../tools.js";
5
+ import { slots } from "../slots.js";
4
6
  import { durableWait } from "../workflow/pi-versions.js";
5
7
  import { HOST_TOOL_OUTPUT } from "./adapters/pi.js";
6
8
  import { cutAtLimit } from "./loop-contract.js";
@@ -9,6 +11,19 @@ export const SUBAGENT_TOOL = "subagent";
9
11
  /** The tiers a call may name for its child (its definition's model_tiers, else this server's tier); a call that names
10
12
  * none runs its child on the agent's own model. */
11
13
  export const SUBAGENT_TIERS = ["fast", "strong"];
14
+ /** The subagent tiers a run routes a model on, with the model its revision names for each: a tier its revision's
15
+ * modelTiers names (a string), else one `env`'s tier variable names (AGENT_MODEL_FAST, AGENT_MODEL_STRONG: tierModelOf),
16
+ * and no other. The one answer for the runner that hands a run's process its tiers' saved model keys (run-child-host.ts
17
+ * heldFor), for the run that routes the tiers (adapter-run-spec.ts) and for a replay's grader on the fast tier, so a
18
+ * tier is never routed with no key handed for it, nor a key handed for a tier no route reads. */
19
+ export function routedSubagentTiers(body, env) {
20
+ const named = (body.modelTiers ?? {});
21
+ const refs = {};
22
+ for (const tier of SUBAGENT_TIERS)
23
+ if (typeof named[tier] === "string")
24
+ refs[tier] = named[tier];
25
+ return { tiers: SUBAGENT_TIERS.filter((tier) => refs[tier] !== undefined || tierModelOf(env, tier) !== undefined), refs };
26
+ }
12
27
  /** How many of a run's children work at once; a call past it waits for a slot. */
13
28
  export const SUBAGENT_PARALLEL = 4;
14
29
  /** Tools no child is given: a subagent of its own (depth 1), and the person, whom only the run's own conversation asks. */
@@ -17,44 +32,6 @@ const NEVER_GIVEN = [SUBAGENT_TOOL, ASK_TOOL];
17
32
  export const SUBAGENT_INSTRUCTIONS = "You are a subagent. The message you are given is your whole task: do it with the tools you have, then answer. Your last message is returned, as it is, to the agent that called you.";
18
33
  /** The thinking levels a call may give its child (`effort`); absent, the child thinks at the agent's own level. */
19
34
  export const SUBAGENT_EFFORTS = ["low", "medium", "high"];
20
- /** One counter of free slots for the run's children (SUBAGENT_PARALLEL), handed out in call order. */
21
- function slots(count) {
22
- let free = count;
23
- const waiting = [];
24
- return {
25
- async take(signal) {
26
- if (free > 0)
27
- free -= 1;
28
- else {
29
- await new Promise((resolve, reject) => {
30
- const go = () => {
31
- signal?.removeEventListener("abort", stop);
32
- resolve();
33
- };
34
- const stop = () => {
35
- const at = waiting.indexOf(go);
36
- if (at >= 0)
37
- waiting.splice(at, 1);
38
- reject(signal?.reason ?? new Error("aborted"));
39
- };
40
- waiting.push(go);
41
- signal?.addEventListener("abort", stop, { once: true });
42
- });
43
- }
44
- let given = false;
45
- return () => {
46
- if (given)
47
- return;
48
- given = true;
49
- const next = waiting.shift();
50
- if (next)
51
- next();
52
- else
53
- free += 1;
54
- };
55
- },
56
- };
57
- }
58
35
  /** The text of an assistant message: its text parts, joined. */
59
36
  const textOf = (message) => Array.isArray(message?.content) ? message.content.map((part) => (part?.type === "text" ? (part.text ?? "") : "")).join("") : typeof message?.content === "string" ? message.content : "";
60
37
  /** `text` within the host's bound on a tool result (HOST_RESULT_MAX_CHARS), saying where it was cut. */
@@ -87,6 +64,7 @@ export function chosenTools(asked, options) {
87
64
  }
88
65
  /** The subagent tool: one of the session's own tools (adapters/pi.ts `tools`), so it needs no extension of its own. */
89
66
  export function subagentTool(options) {
67
+ // The run's children's slots (SUBAGENT_PARALLEL), handed out in call order.
90
68
  const free = slots(SUBAGENT_PARALLEL);
91
69
  return defineTool({
92
70
  name: SUBAGENT_TOOL,