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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (296) hide show
  1. package/CHANGELOG.md +261 -0
  2. package/README.md +228 -45
  3. package/dist/acp-package.d.ts +2 -0
  4. package/dist/adapters.d.ts +18 -5
  5. package/dist/adapters.js +23 -9
  6. package/dist/agent-package.d.ts +3 -3
  7. package/dist/agent-package.js +17 -8
  8. package/dist/answer-json.d.ts +6 -2
  9. package/dist/answer-json.js +22 -4
  10. package/dist/api-keys.d.ts +76 -0
  11. package/dist/api-keys.js +217 -0
  12. package/dist/api-only.d.ts +17 -5
  13. package/dist/api-only.js +36 -8
  14. package/dist/browser-hold.d.ts +23 -0
  15. package/dist/browser-hold.js +48 -0
  16. package/dist/browser-person.d.ts +3 -0
  17. package/dist/browser-person.js +4 -1
  18. package/dist/calendar/tools.js +3 -2
  19. package/dist/chatgpt-plan.d.ts +28 -3
  20. package/dist/chatgpt-plan.js +182 -21
  21. package/dist/claude-login.d.ts +101 -14
  22. package/dist/claude-login.js +232 -49
  23. package/dist/claude-sign-in.d.ts +46 -0
  24. package/dist/claude-sign-in.js +93 -0
  25. package/dist/cli.js +63 -6
  26. package/dist/composio-made.d.ts +4 -0
  27. package/dist/composio-made.js +4 -0
  28. package/dist/composio-preset.d.ts +43 -2
  29. package/dist/composio-preset.js +92 -4
  30. package/dist/computer-held-routes.d.ts +5 -4
  31. package/dist/computer-held-routes.js +29 -8
  32. package/dist/computer-held.d.ts +6 -1
  33. package/dist/computer-held.js +14 -0
  34. package/dist/computer-record.js +4 -2
  35. package/dist/computer-viewer.js +4 -1
  36. package/dist/console/assets/{backend-D5EmB4N3.js → backend-DVhHzJX2.js} +19 -19
  37. package/dist/console/assets/index-Bwn1oTem.css +1 -0
  38. package/dist/console/assets/index-okP-y8PK.js +747 -0
  39. package/dist/console/index.html +2 -2
  40. package/dist/decisions.d.ts +1 -1
  41. package/dist/decisions.js +1 -1
  42. package/dist/docker-host-addresses.d.ts +22 -11
  43. package/dist/docker-host-addresses.js +38 -26
  44. package/dist/env-switch.d.ts +10 -0
  45. package/dist/env-switch.js +33 -2
  46. package/dist/errors.d.ts +1 -0
  47. package/dist/errors.js +2 -0
  48. package/dist/fal-price.d.ts +58 -20
  49. package/dist/fal-price.js +341 -82
  50. package/dist/handed-values.d.ts +43 -1
  51. package/dist/handed-values.js +119 -2
  52. package/dist/harness-archive.d.ts +13 -10
  53. package/dist/harness-archive.js +60 -34
  54. package/dist/harness-check.d.ts +3 -1
  55. package/dist/harness-check.js +25 -46
  56. package/dist/harness-keys.d.ts +73 -27
  57. package/dist/harness-keys.js +194 -61
  58. package/dist/harness-recipe-entry.d.ts +8 -7
  59. package/dist/harness-recipe-entry.js +21 -32
  60. package/dist/harness-recipe.d.ts +38 -25
  61. package/dist/harness-recipe.js +49 -36
  62. package/dist/harness-sign-in.js +12 -23
  63. package/dist/harness-table.d.ts +10 -3
  64. package/dist/harness-table.js +26 -21
  65. package/dist/harness.d.ts +1 -0
  66. package/dist/harness.js +17 -5
  67. package/dist/host-check.d.ts +4 -0
  68. package/dist/host-check.js +4 -0
  69. package/dist/hosted-search.d.ts +1 -1
  70. package/dist/hosted-search.js +1 -2
  71. package/dist/import-worker.d.ts +4 -2
  72. package/dist/import-worker.js +9 -2
  73. package/dist/in-flight.d.ts +26 -0
  74. package/dist/in-flight.js +52 -0
  75. package/dist/key-refusal.d.ts +26 -5
  76. package/dist/key-refusal.js +313 -37
  77. package/dist/learn/secrets.d.ts +31 -11
  78. package/dist/learn/secrets.js +152 -191
  79. package/dist/learning-cost.d.ts +6 -3
  80. package/dist/learning-cost.js +4 -2
  81. package/dist/link-check.js +1 -1
  82. package/dist/llms.txt +2 -2
  83. package/dist/marketplace.d.ts +77 -0
  84. package/dist/marketplace.js +224 -0
  85. package/dist/mcp-api-only-origins.d.ts +30 -0
  86. package/dist/mcp-api-only-origins.js +57 -0
  87. package/dist/mcp-gateway.d.ts +7 -5
  88. package/dist/mcp-gateway.js +9 -12
  89. package/dist/mcp-secret-writes.js +5 -3
  90. package/dist/mcp-servers-store.d.ts +28 -6
  91. package/dist/mcp-servers-store.js +53 -4
  92. package/dist/media-duration.d.ts +3 -0
  93. package/dist/media-duration.js +90 -9
  94. package/dist/model-form.d.ts +5 -4
  95. package/dist/model-form.js +11 -7
  96. package/dist/model.d.ts +5 -2
  97. package/dist/model.js +9 -5
  98. package/dist/ollama-provider.d.ts +7 -1
  99. package/dist/ollama-provider.js +14 -2
  100. package/dist/openapi.d.ts +3 -3
  101. package/dist/openapi.js +245 -42
  102. package/dist/otel/genai.d.ts +65 -0
  103. package/dist/otel/genai.js +116 -0
  104. package/dist/otel/tracer.d.ts +55 -0
  105. package/dist/otel/tracer.js +308 -0
  106. package/dist/page.d.ts +2 -0
  107. package/dist/page.js +3 -1
  108. package/dist/paid-calls.d.ts +1 -32
  109. package/dist/paid-calls.js +4 -39
  110. package/dist/place-offers.d.ts +14 -6
  111. package/dist/place-offers.js +26 -13
  112. package/dist/provider.d.ts +9 -0
  113. package/dist/provider.js +50 -3
  114. package/dist/redact/match.d.ts +101 -0
  115. package/dist/redact/match.js +1152 -0
  116. package/dist/refusal-words.d.ts +11 -0
  117. package/dist/refusal-words.js +11 -0
  118. package/dist/run-census.d.ts +67 -0
  119. package/dist/run-census.js +240 -0
  120. package/dist/run-computer.d.ts +6 -3
  121. package/dist/run-computer.js +4 -1
  122. package/dist/run-cut.d.ts +15 -6
  123. package/dist/run-cut.js +30 -9
  124. package/dist/run-files.d.ts +3 -0
  125. package/dist/run-files.js +3 -0
  126. package/dist/run-launch.d.ts +12 -1
  127. package/dist/run-launch.js +9 -10
  128. package/dist/run-learning-served.d.ts +2 -0
  129. package/dist/run-model-key.d.ts +8 -0
  130. package/dist/run-model-key.js +31 -1
  131. package/dist/run-reads-over-store.d.ts +24 -6
  132. package/dist/run-reads-over-store.js +67 -23
  133. package/dist/run-recordings.d.ts +5 -1
  134. package/dist/run-recordings.js +39 -14
  135. package/dist/run-timeline-served.d.ts +3 -1
  136. package/dist/run-timeline-served.js +4 -4
  137. package/dist/run-usage.d.ts +1 -0
  138. package/dist/runnable.d.ts +10 -1
  139. package/dist/runnable.js +20 -8
  140. package/dist/runner/adapter-loop.d.ts +14 -0
  141. package/dist/runner/adapter-loop.js +56 -11
  142. package/dist/runner/adapter-run-spec.d.ts +45 -8
  143. package/dist/runner/adapter-run-spec.js +154 -29
  144. package/dist/runner/adapters/pi.js +25 -3
  145. package/dist/runner/beside.js +11 -6
  146. package/dist/runner/big-writes.js +1 -10
  147. package/dist/runner/claim-secrets.d.ts +18 -3
  148. package/dist/runner/claim-secrets.js +35 -6
  149. package/dist/runner/cli-run-spec.d.ts +6 -0
  150. package/dist/runner/cli-run-spec.js +85 -36
  151. package/dist/runner/computer-journal.d.ts +9 -1
  152. package/dist/runner/computer-journal.js +26 -0
  153. package/dist/runner/conformance/harness.js +1 -1
  154. package/dist/runner/feedback-round.js +3 -0
  155. package/dist/runner/harness-loops.d.ts +6 -5
  156. package/dist/runner/harness-loops.js +7 -7
  157. package/dist/runner/held.d.ts +11 -5
  158. package/dist/runner/journal-kinds.d.ts +5 -0
  159. package/dist/runner/journal-kinds.js +5 -0
  160. package/dist/runner/loop-contract.d.ts +4 -0
  161. package/dist/runner/main.js +15 -6
  162. package/dist/runner/mcp-claim.js +30 -3
  163. package/dist/runner/mcp-run.d.ts +12 -0
  164. package/dist/runner/mcp-run.js +12 -5
  165. package/dist/runner/model-route.d.ts +17 -0
  166. package/dist/runner/model-route.js +120 -2
  167. package/dist/runner/presence.d.ts +4 -3
  168. package/dist/runner/presence.js +4 -2
  169. package/dist/runner/run-child-host.d.ts +5 -0
  170. package/dist/runner/run-child-host.js +71 -30
  171. package/dist/runner/run-child.js +5 -2
  172. package/dist/runner/runner.d.ts +18 -3
  173. package/dist/runner/runner.js +162 -36
  174. package/dist/runner/store-port.d.ts +1 -1
  175. package/dist/runner/store-secrets.d.ts +6 -0
  176. package/dist/runner/store-secrets.js +49 -7
  177. package/dist/runner/subagent.js +4 -40
  178. package/dist/runner/workflow-first.d.ts +11 -4
  179. package/dist/runner/workflow-first.js +14 -8
  180. package/dist/runner/workflow-spec.js +3 -2
  181. package/dist/runs-over-store.d.ts +15 -6
  182. package/dist/runs-over-store.js +33 -21
  183. package/dist/scrub-command.d.ts +73 -0
  184. package/dist/scrub-command.js +307 -0
  185. package/dist/secret-cut.d.ts +73 -0
  186. package/dist/secret-cut.js +291 -4
  187. package/dist/secret-rules.d.ts +143 -0
  188. package/dist/secret-rules.js +2564 -0
  189. package/dist/secrets.d.ts +7 -0
  190. package/dist/secrets.js +20 -0
  191. package/dist/server-keys.d.ts +20 -0
  192. package/dist/server-keys.js +25 -6
  193. package/dist/server.d.ts +57 -13
  194. package/dist/server.js +371 -113
  195. package/dist/skills/agentrun-serve/SKILL.md +4 -0
  196. package/dist/store/dialect.d.ts +3 -0
  197. package/dist/store/dialect.js +1 -0
  198. package/dist/store/index.d.ts +1 -1
  199. package/dist/store/index.js +1 -1
  200. package/dist/store/journal/storage.js +1 -1
  201. package/dist/store/postgres/dialect.js +3 -0
  202. package/dist/store/postgres/migrations/0027_run_launch_census.sql +31 -0
  203. package/dist/store/schema.d.ts +6 -0
  204. package/dist/store/schema.js +11 -1
  205. package/dist/store/seal.d.ts +6 -1
  206. package/dist/store/seal.js +5 -3
  207. package/dist/store/sqlite/run-launch.d.ts +9 -1
  208. package/dist/store/sqlite/run-launch.js +24 -13
  209. package/dist/store/sqlite/run-patch.d.ts +1 -1
  210. package/dist/store/sqlite/run-patch.js +13 -4
  211. package/dist/store/sqlite/store.js +76 -16
  212. package/dist/store/store.d.ts +53 -3
  213. package/dist/store/store.js +27 -0
  214. package/dist/store-reads/learning.d.ts +6 -3
  215. package/dist/store-reads/learning.js +22 -7
  216. package/dist/store-view.d.ts +3 -0
  217. package/dist/store-view.js +4 -4
  218. package/dist/suggestions.js +3 -2
  219. package/dist/template-eval.d.ts +22 -11
  220. package/dist/template-eval.js +124 -41
  221. package/dist/template-import.d.ts +10 -0
  222. package/dist/template-import.js +16 -7
  223. package/dist/templates.d.ts +10 -2
  224. package/dist/templates.js +28 -8
  225. package/dist/timeline/index.d.ts +1 -1
  226. package/dist/timeline/index.js +1 -1
  227. package/dist/timeline/labels.d.ts +6 -4
  228. package/dist/timeline/labels.js +18 -6
  229. package/dist/timeline/timeline.d.ts +17 -7
  230. package/dist/timeline/timeline.js +28 -14
  231. package/dist/timeline/util.js +1 -1
  232. package/dist/timeline/web-calls.d.ts +26 -9
  233. package/dist/timeline/web-calls.js +124 -37
  234. package/dist/tool-gate.d.ts +42 -3
  235. package/dist/tool-gate.js +69 -6
  236. package/dist/tool-keys-store.d.ts +2 -4
  237. package/dist/tool-keys-store.js +5 -21
  238. package/dist/tool-keys.d.ts +2 -2
  239. package/dist/tool-keys.js +2 -2
  240. package/dist/tool-list.js +1 -1
  241. package/dist/tool-plane.d.ts +2 -2
  242. package/dist/tool-plane.js +35 -33
  243. package/dist/tools.js +13 -7
  244. package/dist/trigger-targets.d.ts +4 -0
  245. package/dist/trigger-targets.js +9 -2
  246. package/dist/triggers.d.ts +67 -4
  247. package/dist/triggers.js +171 -22
  248. package/dist/until.d.ts +3 -0
  249. package/dist/until.js +11 -0
  250. package/dist/validate.js +1 -1
  251. package/dist/web-fake.d.ts +1 -3
  252. package/dist/web-fake.js +7 -18
  253. package/dist/web-fetch.d.ts +6 -72
  254. package/dist/web-fetch.js +11 -265
  255. package/dist/web-run.d.ts +31 -0
  256. package/dist/web-run.js +90 -0
  257. package/dist/web-save.d.ts +6 -4
  258. package/dist/web-save.js +9 -12
  259. package/dist/web-search.d.ts +9 -127
  260. package/dist/web-search.js +23 -259
  261. package/dist/wires.d.ts +13 -0
  262. package/dist/wires.js +11 -0
  263. package/dist/workflow-run.d.ts +5 -4
  264. package/dist/workflow-run.js +5 -4
  265. package/dist/workspace/computer-deps.d.ts +3 -1
  266. package/dist/workspace/computer-deps.js +12 -4
  267. package/dist/workspace/computer-for-claim.d.ts +19 -2
  268. package/dist/workspace/computer-for-claim.js +101 -13
  269. package/dist/workspace/computer-janitor.d.ts +15 -7
  270. package/dist/workspace/computer-janitor.js +33 -8
  271. package/dist/workspace/computer-kept.d.ts +55 -4
  272. package/dist/workspace/computer-kept.js +129 -8
  273. package/dist/workspace/index.d.ts +1 -1
  274. package/dist/workspace/index.js +1 -1
  275. package/dist/workspace/kind-skills.d.ts +4 -0
  276. package/dist/workspace/kind-skills.js +9 -0
  277. package/dist/workspace/run-end-computers.d.ts +5 -1
  278. package/dist/workspace/run-end-computers.js +27 -1
  279. package/dist/workspace/synced-folder.js +3 -4
  280. package/dist/wrapped.d.ts +65 -0
  281. package/dist/wrapped.js +77 -0
  282. package/package.json +17 -11
  283. package/skills/agentrun-serve/SKILL.md +4 -0
  284. package/templates/README.md +38 -15
  285. package/dist/console/assets/index-DUYLaqiR.js +0 -746
  286. package/dist/console/assets/index-DYhU4adm.css +0 -1
  287. package/dist/exa-keyless.d.ts +0 -34
  288. package/dist/exa-keyless.js +0 -118
  289. package/dist/firecrawl-keyless.d.ts +0 -41
  290. package/dist/firecrawl-keyless.js +0 -152
  291. package/dist/keyless-mcp.d.ts +0 -36
  292. package/dist/keyless-mcp.js +0 -127
  293. package/dist/text-urls.d.ts +0 -38
  294. package/dist/text-urls.js +0 -170
  295. package/dist/web-fetch-direct.d.ts +0 -119
  296. package/dist/web-fetch-direct.js +0 -190
@@ -23,9 +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";
27
+ import { keptBy, readKept } from "../workspace/computer-kept.js";
26
28
  import { cutDeep, heldRedactor, processSecretRedactor } from "./redact.js";
27
29
  import { withLiveTicker } from "./live-ticker.js";
28
30
  import { keepPresence } from "./presence.js";
31
+ import { flushTraces } from "../otel/tracer.js";
29
32
  /** Tries of the re-read after a claim or release commit was answered Unanswered (the commit may have landed). */
30
33
  const UNKNOWN_READS = 5;
31
34
  /** Passes of the sweep after a claim answered Unanswered: the commit may still be on its way when the first read comes back
@@ -75,11 +78,14 @@ const PASSES_A_BLOCKED_ROW = new Set([...HELD_COMMANDS, COMPUTER_CALL, HAND_BACK
75
78
  export const END_RETRY_CAP_MS = 300_000;
76
79
  /** The tries at that cap before the run ends stopped on its row alone (about an hour of retries in all; endRefused). */
77
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;
78
84
  const message = (error) => (error instanceof Error ? error.message : String(error));
79
85
  /** The run states a run patch makes final: a commit that lands one is the run's end, and its release. */
80
86
  const FINAL = new Set(["ended", "stopped", "failed"]);
81
87
  export function startRunner(options) {
82
- 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;
83
89
  // The one instance every run's loop gets (LoopDeps.redact), able to hold what each claim opens from the store
84
90
  // (redact.ts holdClaimed): a stored key is cut wherever a key of the runner's environment is.
85
91
  const redact = heldRedactor(given);
@@ -154,6 +160,8 @@ export function startRunner(options) {
154
160
  const replaced = new Set();
155
161
  /** The refused stopped ends this runner is trying again (endRetried): close() waits for them. */
156
162
  const endings = new Set();
163
+ /** The claims those ends hold, renewed (renewAll) until each end lands. */
164
+ const endOnly = new Set();
157
165
  /** Each run's ends in a row, on this runner, as interrupted on its own: its next release's backoff doubles with them. */
158
166
  const interruptedInARow = new Map();
159
167
  let closed = false;
@@ -165,6 +173,31 @@ export function startRunner(options) {
165
173
  /** Stops listening for written commands (store.watchCommands); set once the runner has started. */
166
174
  let unwatchCommands;
167
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
+ };
168
201
  /** The run's journal with this runner's fence on its one write: after the claim is lost, commit throws ClaimLost. A
169
202
  * commit that lands a final run patch (the loop's own end, which is the run's release) calls `ended` at once: from
170
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
@@ -176,6 +209,12 @@ export function startRunner(options) {
176
209
  const fenced = (journal, fence, runId, ended) => {
177
210
  /** The effect of the final patch staged and not yet landed, as the store keeps it until a commit stores it. */
178
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;
179
218
  const carriedOut = (given) => {
180
219
  const carried = redact.carried(runId);
181
220
  return carried ? cutDeep(given, carried, true) : given;
@@ -187,10 +226,13 @@ export function startRunner(options) {
187
226
  return value;
188
227
  if (property === "stage") {
189
228
  return (staged, ...rest) => {
190
- const result = value.call(target, carriedOut(staged), ...rest);
229
+ const given = carriedOut(staged);
230
+ const result = value.call(target, given, ...rest);
191
231
  // As the store keeps it: a run patch or rows staged again replace the one staged before.
192
- if (staged?.run !== undefined || staged?.also !== undefined)
232
+ if (staged?.run !== undefined || staged?.also !== undefined) {
193
233
  finalEffect = FINAL.has(staged.run?.state ?? "") ? Number(staged.effect) : undefined;
234
+ finalStaged = finalEffect !== undefined && given ? { staged: given, census: censusFor(runId) } : undefined;
235
+ }
194
236
  return result;
195
237
  };
196
238
  }
@@ -204,7 +246,23 @@ export function startRunner(options) {
204
246
  const effect = finalEffect;
205
247
  const batches = (Array.isArray(args[0]) ? args[0] : [args[0]]);
206
248
  const at = effect === undefined ? -1 : batches.findIndex((batch) => (Array.isArray(batch) ? batch : [batch]).some((write) => Number(write?.value?.id) === effect));
207
- 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) => {
208
266
  if (at >= 0 && at < (result?.stored ?? 0) && finalEffect === effect) {
209
267
  finalEffect = undefined;
210
268
  ended();
@@ -215,6 +273,17 @@ export function startRunner(options) {
215
273
  },
216
274
  });
217
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
+ };
218
287
  const armDeadline = (held, at) => {
219
288
  clock.clearTimeout(held.deadline);
220
289
  held.deadline = clock.setTimeout(() => loseClaim(held, "not-renewed"), Math.max(0, at - clock.now()));
@@ -244,20 +313,25 @@ export function startRunner(options) {
244
313
  };
245
314
  /** Every held claim renewed in one transaction (store.renewMany), never one per run: a claim answered Fenced is lost,
246
315
  * the others move on. Any other failure (a busy store) is tried at the next renew; each run's deadline stops its loop
247
- * 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. */
248
321
  const renewAll = async () => {
249
322
  if (killed)
250
323
  return;
251
324
  beat();
252
- const due = [...runs.values()].filter((held) => !held.renewing && !held.fence.lost && !held.ending);
253
- 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)
254
328
  return;
255
- for (const held of due)
256
- held.renewing = true;
329
+ for (const one of [...due, ...ends])
330
+ one.renewing = true;
257
331
  const sentAt = clock.now();
258
332
  try {
259
- const results = await store.renewMany(due.map((held) => held.claim), { leaseMs });
260
- 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) => {
261
335
  const held = due[i];
262
336
  if (held.fence.lost || held.ending || killed)
263
337
  return;
@@ -265,17 +339,17 @@ export function startRunner(options) {
265
339
  loseClaim(held, "fenced");
266
340
  else {
267
341
  held.claim = result;
268
- armDeadline(held, sentAt + leaseMs - stopMarginMs);
342
+ armDeadline(held, deadlineOf(held.claim, sentAt));
269
343
  }
270
344
  });
271
345
  }
272
346
  catch (error) {
273
- for (const held of due)
274
- 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) });
275
349
  }
276
350
  finally {
277
- for (const held of due)
278
- held.renewing = false;
351
+ for (const one of [...due, ...ends])
352
+ one.renewing = false;
279
353
  }
280
354
  };
281
355
  const renewTimer = setInterval(() => void renewAll(), renewEveryMs);
@@ -427,13 +501,15 @@ export function startRunner(options) {
427
501
  * in its journal, a reopen would find no turn to follow (its next claim would read the run as never started), so it
428
502
  * reads as a stop that is over (cancelled), as it read before a stop and a cancel were told apart.
429
503
  */
430
- const endRun = async (claim, given, take, withdrawnAs = "withdrawn") => {
504
+ const endRun = async (claim, given, take, withdrawnAs = "withdrawn", landed = () => { }) => {
431
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).
432
506
  const data = { ...given, summary: redact(given.summary) };
433
507
  // Unknown means it may withdraw: false only once the journal was read and no call of it waits.
434
508
  let mayWithdraw = data.state === "stopped";
435
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.
436
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);
437
513
  try {
438
514
  const journal = store.journal(claim);
439
515
  const [root] = (await journal.scanConversations({}, 1, undefined, BACKGROUND_CONTEXT)).items;
@@ -458,34 +534,39 @@ export function startRunner(options) {
458
534
  }
459
535
  const id = (await journal.mintId());
460
536
  writes.push({ type: "entry", value: { id, conversationId, kind: KINDS.end, data: data } });
461
- 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 })) } : {}) });
462
538
  const result = await journal.commit([writes], () => { }, BACKGROUND_CONTEXT);
463
539
  if (result.stored !== 1)
464
540
  throw result.refused ?? new Error("the run's end was not stored");
541
+ landed();
465
542
  }
466
543
  catch (error) {
467
544
  if (isFenced(error))
468
545
  throw error;
469
546
  if (mayWithdraw)
470
547
  throw new EndNotWithdrawn(claim.runId, error);
471
- 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();
472
550
  }
473
551
  // An ended run's Screen has no ended-while-waiting state to keep (browser-wait-ended.ts): its row goes with the end.
474
552
  if (store.settings)
475
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);
476
557
  };
477
558
  /** Ends the run under `claim` stopped on its untaken `stop` (or cancel) row (endRun). False when that end may withdraw a
478
559
  * call and the journal would not take it or could not be read: the refusal is then the run's (endRefused). */
479
- const endStopped = async (claim, stop) => {
560
+ const endStopped = async (claim, stop, landed) => {
480
561
  try {
481
562
  const end = stopEnd(stop.kind === "cancel");
482
- await endRun(claim, end, [stop.id], stop.kind === "cancel" ? "canceled" : "withdrawn");
563
+ await endRun(claim, end, [stop.id], stop.kind === "cancel" ? "canceled" : "withdrawn", landed);
483
564
  return true;
484
565
  }
485
566
  catch (error) {
486
567
  if (!(error instanceof EndNotWithdrawn))
487
568
  throw error;
488
- await endRefused(claim, stop, error);
569
+ await endRefused(claim, stop, error, landed);
489
570
  return false;
490
571
  }
491
572
  };
@@ -512,14 +593,15 @@ export function startRunner(options) {
512
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
513
594
  * retries, and the 18th refusal gives up.
514
595
  */
515
- const endRefused = async (claim, stop, refused) => {
596
+ const endRefused = async (claim, stop, refused, landed) => {
516
597
  const tries = await store.retry(claim, stop.id);
517
598
  const why = message(refused.cause);
518
599
  if (tries >= endRetryCapFrom + endRetryAtCap) {
519
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})` });
520
601
  // On its row alone, so no outcome 'stopped' (endRun): a run whose journal never took its end is never reopened.
521
602
  const end = stopEnd(stop.kind === "cancel");
522
- 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();
523
605
  await releaseStopped(claim, stop);
524
606
  return;
525
607
  }
@@ -545,18 +627,41 @@ export function startRunner(options) {
545
627
  return false;
546
628
  }
547
629
  };
630
+ /** Whether the run under `claim` has a computer its park kept pinned to a runner other than this one, this process
631
+ * (computer-kept.ts: the row names a runner and incarnation, keptBy). A row that cannot be read says yes: a loop
632
+ * started on a guess would read the row again in its claim's computer, take it and try the machine from here,
633
+ * dropping the row that runner's timer ends it by. Ending the stop with no loop touches no computer, and the row's
634
+ * runner (or any janitor, once that runner is gone) still ends it. */
635
+ const keptElsewhere = async (claim) => {
636
+ if (!store.settings)
637
+ return false;
638
+ try {
639
+ const kept = await readKept(store.settings, claim.runId);
640
+ const ours = (options.presence ?? presence)?.incarnation;
641
+ return kept?.runner !== undefined && !keptBy(kept, ours ? { runner: name, incarnation: ours } : undefined);
642
+ }
643
+ catch {
644
+ return true;
645
+ }
646
+ };
548
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,
549
648
  * so no turn, model request or tool runs on a run that is stopping. */
550
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);
551
653
  try {
552
654
  // A run stopped before any loop started still has its one start line, ahead of its end.
553
655
  await announceStart(claim);
554
- if (await endStopped(claim, stop))
656
+ if (await endStopped(claim, stop, () => (only.landed = true)))
555
657
  await releaseStopped(claim, stop);
556
658
  }
557
659
  catch (error) {
558
660
  emit({ type: "error", runId: claim.runId, step: isFenced(error) ? "end (fenced)" : "end", message: message(error) });
559
661
  }
662
+ finally {
663
+ endOnly.delete(only);
664
+ }
560
665
  };
561
666
  const finish = async (held, end, threw) => {
562
667
  // Whether the runner asked the loop to stop before it ended (only stopLoop sets this).
@@ -564,6 +669,10 @@ export function startRunner(options) {
564
669
  held.ending = true;
565
670
  clock.clearTimeout(held.deadline);
566
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
+ };
567
676
  // A command still with the loop: its refusal is written before anything of the end, never after the release. A loop
568
677
  // that does not answer within endWaitMs has its answer dropped (the claim is sealed first).
569
678
  if (held.inFlight) {
@@ -596,12 +705,12 @@ export function startRunner(options) {
596
705
  // never refused as a failed run's; else the run ends failed with why. Either way its end is in the journal.
597
706
  const stop = endingRow((await store.commands(claim.runId, 0)).filter((row) => row.takenAt === null));
598
707
  if (stop) {
599
- if (!(await endStopped(claim, stop)))
708
+ if (!(await endStopped(claim, stop, landed)))
600
709
  return;
601
710
  end = { state: "stopped" };
602
711
  }
603
712
  else {
604
- await endRun(claim, { state: "failed", summary: end.error.message }, []);
713
+ await endRun(claim, { state: "failed", summary: end.error.message }, [], "withdrawn", landed);
605
714
  }
606
715
  }
607
716
  if (end.state === "ended" || end.state === "stopped" || end.state === "failed") {
@@ -615,6 +724,8 @@ export function startRunner(options) {
615
724
  // The run's end (a normal completion among them) leaves no browser-released message behind for a follow-up (browser-wait-ended.ts).
616
725
  if (store.settings)
617
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);
618
729
  }
619
730
  await store.flush();
620
731
  // A loop that ended interrupted with no stop asked of it (its Session closed itself) is released with a backoff that
@@ -631,7 +742,7 @@ export function startRunner(options) {
631
742
  const cut = end.state !== "interrupted" ? undefined : closedItself ? "retry" : held.stoppedFor === "shutdown" ? "drain" : undefined;
632
743
  await release(claim, {
633
744
  ...(end.state === "parked" && end.wakeAt !== undefined ? { wakeAt: end.wakeAt }
634
- : inARow > 0 ? { backoffUntil: Date.now() + interruptBackoffMs * 2 ** Math.min(inARow - 1, 6) }
745
+ : inARow > 0 ? { backoffUntil: now() + interruptBackoffMs * 2 ** Math.min(inARow - 1, 6) }
635
746
  : {}),
636
747
  ...(cut ? { cut } : {}),
637
748
  });
@@ -665,7 +776,7 @@ export function startRunner(options) {
665
776
  // A stop never waits on a loop that cannot start: the run ends stopped here, its stop row taken, and every other
666
777
  // untaken row refused as a stopped run's.
667
778
  // One write: the run ends stopped with its stop row taken, or neither (a final run never keeps its stop untaken).
668
- if (await endStopped(claim, stop))
779
+ if (await endStopped(claim, stop, () => (held.landed = true)))
669
780
  await releaseStopped(claim, stop);
670
781
  return;
671
782
  }
@@ -680,7 +791,7 @@ export function startRunner(options) {
680
791
  }
681
792
  else {
682
793
  await store.flush();
683
- await release(claim, { state: "parked", backoffUntil: Date.now() + resumeBackoffMs * 2 ** (tries - 1) });
794
+ await release(claim, { state: "parked", backoffUntil: now() + resumeBackoffMs * 2 ** (tries - 1) });
684
795
  }
685
796
  }
686
797
  else {
@@ -698,7 +809,11 @@ export function startRunner(options) {
698
809
  let ending = () => { };
699
810
  // Set below, once held is made: the loop asks deliverNow only once its first turn has ended, well after.
700
811
  let heldNow;
812
+ // This runner's process as its word in the store names it (presence.ts), for the claim's computer: a park that keeps one
813
+ // only this runner can reach again pins it to this runner and this incarnation (computer-kept.ts pinnedOf).
814
+ const ours = (options.presence ?? presence)?.incarnation;
701
815
  const loop = loopsOf({
816
+ ...(ours ? { incarnation: ours } : {}),
702
817
  journal: (forClaim) => fenced(store.journal(forClaim), fence, forClaim.runId, () => ending()),
703
818
  flush: () => store.flush(),
704
819
  signal: abort.signal,
@@ -712,15 +827,16 @@ export function startRunner(options) {
712
827
  },
713
828
  redact,
714
829
  });
715
- 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 };
716
831
  heldNow = held;
717
832
  // The loop's own end landed: the run is ending from here, its teardown included (no renew, no lost claim).
718
833
  ending = () => {
719
834
  held.ending = true;
835
+ held.landed = true;
720
836
  clock.clearTimeout(held.deadline);
721
837
  };
722
838
  runs.set(claim.runId, held);
723
- armDeadline(held, sentAt + leaseMs - stopMarginMs);
839
+ armDeadline(held, deadlineOf(claim, sentAt));
724
840
  emit({ type: "claimed", claim });
725
841
  void announceStart(claim);
726
842
  held.done = (async () => {
@@ -849,13 +965,18 @@ export function startRunner(options) {
849
965
  // starts now, not even its first input: a loop started first would send that input before the stop reached it;
850
966
  // - a run whose untaken stop row has tries, which failed to apply that stop before. Either source of tries counts: a
851
967
  // refused stopped end (endRefused, released running) or a failed resume (resumeFailed's store.retry, released
852
- // parked).
968
+ // parked);
969
+ // - a parked run stopped or cancelled whose computer its park kept pinned to another runner, or whose kept row can't
970
+ // be read (keptElsewhere): the store gives a stop to any runner at once, never waiting on the pin, and this
971
+ // runner can't reach that machine.
972
+ // A loop would take the kept row (takeKept) and try to attach it, orphaning it on that runner's host; ending here
973
+ // leaves the row that runner's, whose own timer at its time, or its janitor once the run is final, ends it.
853
974
  // One read of those claims' rows, made only when the batch has a queued or a released run.
854
975
  const reread = claims.filter((claim) => claim.from === "queued" || claim.from === "running" || claim.from === "parked");
855
976
  const rows = reread.length ? await store.commandsOf(reread.map((claim) => ({ runId: claim.runId, after: 0 }))) : new Map();
856
977
  for (const claim of claims) {
857
978
  const stop = endingRow((rows.get(claim.runId) ?? []).filter((row) => row.takenAt === null));
858
- const endsOnly = stop !== undefined && (claim.from === "queued" || stop.tries > 0 || (claim.from === "running" && (await neverStarted(claim))));
979
+ const endsOnly = stop !== undefined && (claim.from === "queued" || stop.tries > 0 || (claim.from === "running" && (await neverStarted(claim))) || (claim.from === "parked" && (await keptElsewhere(claim))));
859
980
  if (stop && endsOnly && !closed && !killed && !runs.has(claim.runId)) {
860
981
  const key = `${claim.runId}:${claim.epoch}`;
861
982
  endingClaims.add(key);
@@ -886,7 +1007,7 @@ export function startRunner(options) {
886
1007
  catch (error) {
887
1008
  // The loop could not be made: the run fails here, so it is not claimed again and again.
888
1009
  emit({ type: "error", runId: claim.runId, step: "create loop", message: message(error) });
889
- 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(() => { });
890
1011
  await store.flush().catch(() => { });
891
1012
  await release(claim, {}).catch(() => { });
892
1013
  }
@@ -903,7 +1024,8 @@ export function startRunner(options) {
903
1024
  * claim's loop still running holds its weight too): each claimed on its own, its weight put in `weights`. The first that
904
1025
  * does not fit ends the claim, unless the runner holds nothing: then it is claimed alone. */
905
1026
  const claimByMemory = async (budget, free, weights) => {
906
- const waiting = await store.runs.claimable({ limit: free });
1027
+ // As this runner's claimer: a run whose computer is kept for another runner still there is not among them.
1028
+ const waiting = await store.runs.claimable({ limit: free, runner: name });
907
1029
  if (waiting.length === 0)
908
1030
  return [];
909
1031
  const weighed = await budget.weigh(waiting);
@@ -1068,8 +1190,10 @@ export function startRunner(options) {
1068
1190
  for (const held of runs.values())
1069
1191
  clock.clearTimeout(held.deadline);
1070
1192
  };
1193
+ const incarnation = (options.presence ?? presence)?.incarnation;
1071
1194
  return {
1072
1195
  name,
1196
+ ...(incarnation ? { incarnation } : {}),
1073
1197
  held: () => [...runs.values()].filter((held) => !held.fence.lost && !held.ending).map((held) => held.claim),
1074
1198
  async close() {
1075
1199
  if (closed || killed)
@@ -1142,6 +1266,8 @@ export function startRunner(options) {
1142
1266
  await ticker?.close();
1143
1267
  // It claims no more: its word that it is here goes.
1144
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();
1145
1271
  },
1146
1272
  kill() {
1147
1273
  killed = true;
@@ -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