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

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 (474) hide show
  1. package/CHANGELOG.md +402 -1
  2. package/README.md +516 -190
  3. package/dist/acp-package.d.ts +5 -1
  4. package/dist/acp-package.js +19 -2
  5. package/dist/adapters.d.ts +23 -2
  6. package/dist/adapters.js +106 -33
  7. package/dist/agent-delete.d.ts +6 -9
  8. package/dist/agent-delete.js +5 -3
  9. package/dist/agent-package.js +11 -1
  10. package/dist/agents-store.js +1 -1
  11. package/dist/answer-text.d.ts +3 -0
  12. package/dist/answer-text.js +22 -0
  13. package/dist/api-only.d.ts +2 -2
  14. package/dist/api-only.js +3 -3
  15. package/dist/archil-routes.d.ts +4 -1
  16. package/dist/archil-routes.js +15 -12
  17. package/dist/archil-settings.d.ts +18 -8
  18. package/dist/archil-settings.js +35 -17
  19. package/dist/attach-conformance.js +5 -4
  20. package/dist/box-paths.d.ts +3 -2
  21. package/dist/box-paths.js +5 -4
  22. package/dist/browser-computer.d.ts +3 -8
  23. package/dist/browser-computer.js +12 -35
  24. package/dist/browser-cost.js +94 -20
  25. package/dist/capacity.d.ts +1 -1
  26. package/dist/capacity.js +3 -3
  27. package/dist/chatgpt-plan.d.ts +7 -0
  28. package/dist/chatgpt-plan.js +35 -11
  29. package/dist/claude-login-token.d.ts +20 -11
  30. package/dist/claude-login-token.js +175 -107
  31. package/dist/claude-login.d.ts +124 -33
  32. package/dist/claude-login.js +562 -85
  33. package/dist/claude-sign-in.d.ts +3 -0
  34. package/dist/claude-sign-in.js +10 -1
  35. package/dist/cli-learning/connections.js +1 -1
  36. package/dist/cli.js +323 -292
  37. package/dist/composio-made.d.ts +1 -6
  38. package/dist/composio-made.js +1 -6
  39. package/dist/composio-owners.d.ts +26 -0
  40. package/dist/composio-owners.js +36 -0
  41. package/dist/composio-preset.d.ts +56 -23
  42. package/dist/composio-preset.js +173 -77
  43. package/dist/composio-triggers.d.ts +4 -4
  44. package/dist/composio-triggers.js +6 -7
  45. package/dist/compute-cost.js +11 -2
  46. package/dist/computer-attach.d.ts +6 -3
  47. package/dist/computer-attach.js +41 -29
  48. package/dist/computer-held-routes.d.ts +1 -1
  49. package/dist/computer-held-routes.js +9 -4
  50. package/dist/computer-keys.d.ts +11 -1
  51. package/dist/computer-keys.js +26 -1
  52. package/dist/computer-record.js +3 -1
  53. package/dist/computer-view.d.ts +5 -3
  54. package/dist/computer-view.js +10 -6
  55. package/dist/computer-viewer.js +36 -7
  56. package/dist/computers.d.ts +2 -1
  57. package/dist/computers.js +6 -3
  58. package/dist/console/THIRD-PARTY-NOTICES.txt +50 -0
  59. package/dist/console/assets/backend-QnwGVBeU.js +166 -0
  60. package/dist/console/assets/index-DZi-muIj.js +629 -0
  61. package/dist/console/assets/share-pz61zIn9.js +6 -0
  62. package/dist/console/assets/styles-CcceGcu2.js +291 -0
  63. package/dist/console/assets/styles-fjQBFfMv.css +1 -0
  64. package/dist/console/index.html +4 -3
  65. package/dist/console/share.html +17 -0
  66. package/dist/decisions.d.ts +17 -7
  67. package/dist/decisions.js +41 -15
  68. package/dist/dial-relay.js +10 -4
  69. package/dist/docker-daemon.js +4 -5
  70. package/dist/docker-host-addresses.js +29 -11
  71. package/dist/email/account.d.ts +6 -0
  72. package/dist/email/account.js +6 -0
  73. package/dist/email/authentication.d.ts +21 -0
  74. package/dist/email/authentication.js +106 -0
  75. package/dist/email/email-faux.d.ts +11 -2
  76. package/dist/email/email-faux.js +21 -5
  77. package/dist/email/mail.d.ts +25 -0
  78. package/dist/email/mail.js +58 -2
  79. package/dist/email/names.js +2 -2
  80. package/dist/email/tools.d.ts +9 -4
  81. package/dist/email/tools.js +95 -13
  82. package/dist/env-switch.d.ts +12 -2
  83. package/dist/env-switch.js +23 -3
  84. package/dist/errors.d.ts +1 -0
  85. package/dist/errors.js +2 -0
  86. package/dist/factory-activity.d.ts +68 -0
  87. package/dist/factory-activity.js +153 -0
  88. package/dist/factory-runs.d.ts +11 -0
  89. package/dist/factory-runs.js +52 -0
  90. package/dist/fal-price.d.ts +11 -1
  91. package/dist/fal-price.js +33 -0
  92. package/dist/faux-computers.js +1 -1
  93. package/dist/filed-answer.d.ts +2 -2
  94. package/dist/filed-answer.js +2 -2
  95. package/dist/filed-tool.d.ts +32 -0
  96. package/dist/filed-tool.js +122 -0
  97. package/dist/graph-served.d.ts +10 -5
  98. package/dist/graph-served.js +40 -10
  99. package/dist/handed-values.js +1 -2
  100. package/dist/harness-check.d.ts +2 -1
  101. package/dist/harness-check.js +45 -12
  102. package/dist/harness-keys.d.ts +1 -2
  103. package/dist/harness-keys.js +10 -8
  104. package/dist/harness-opencode/facts.js +2 -0
  105. package/dist/harness-recipe-entry.d.ts +9 -3
  106. package/dist/harness-recipe-entry.js +18 -9
  107. package/dist/harness-recipe.d.ts +21 -0
  108. package/dist/harness-recipe.js +25 -3
  109. package/dist/harness-table.d.ts +12 -0
  110. package/dist/harness-table.js +21 -6
  111. package/dist/harness.js +6 -2
  112. package/dist/helper-env.d.ts +4 -1
  113. package/dist/helper-env.js +4 -1
  114. package/dist/host-check.d.ts +2 -3
  115. package/dist/host-check.js +13 -7
  116. package/dist/hosted-search.js +1 -1
  117. package/dist/import-worker.js +2 -2
  118. package/dist/import.d.ts +20 -8
  119. package/dist/import.js +448 -187
  120. package/dist/key-refusal.d.ts +14 -2
  121. package/dist/key-refusal.js +97 -33
  122. package/dist/learn/audit.d.ts +28 -27
  123. package/dist/learn/audit.js +87 -62
  124. package/dist/learn/check.js +1 -1
  125. package/dist/learn/commit.d.ts +35 -43
  126. package/dist/learn/commit.js +62 -270
  127. package/dist/learn/compile.d.ts +9 -6
  128. package/dist/learn/compile.js +51 -28
  129. package/dist/learn/corrections.js +1 -1
  130. package/dist/learn/delete.d.ts +5 -12
  131. package/dist/learn/delete.js +17 -30
  132. package/dist/learn/field-check.d.ts +111 -0
  133. package/dist/learn/field-check.js +174 -0
  134. package/dist/learn/forget-run.d.ts +16 -0
  135. package/dist/learn/forget-run.js +53 -0
  136. package/dist/learn/index.js +1 -1
  137. package/dist/learn/learning-of.d.ts +0 -4
  138. package/dist/learn/learning-of.js +0 -5
  139. package/dist/learn/ledger.d.ts +32 -29
  140. package/dist/learn/ledger.js +26 -19
  141. package/dist/learn/{folder.d.ts → legacy/folder.d.ts} +2 -1
  142. package/dist/learn/{folder.js → legacy/folder.js} +4 -7
  143. package/dist/learn/legacy/place.d.ts +16 -0
  144. package/dist/{workspace/learning-workspace.js → learn/legacy/place.js} +12 -42
  145. package/dist/learn/legacy/scrub.d.ts +28 -0
  146. package/dist/learn/legacy/scrub.js +258 -0
  147. package/dist/learn/promote.d.ts +119 -102
  148. package/dist/learn/promote.js +119 -262
  149. package/dist/learn/reset-ledger.d.ts +18 -0
  150. package/dist/learn/reset-ledger.js +14 -0
  151. package/dist/learn/rows.d.ts +186 -0
  152. package/dist/learn/rows.js +376 -0
  153. package/dist/learn/secrets.d.ts +4 -0
  154. package/dist/learn/secrets.js +12 -0
  155. package/dist/learn/workflow-draft.d.ts +4 -1
  156. package/dist/learn/workflow-draft.js +12 -2
  157. package/dist/learned-nodes.d.ts +8 -5
  158. package/dist/learned-nodes.js +8 -5
  159. package/dist/learned-workflow.d.ts +2 -1
  160. package/dist/learned-workflow.js +13 -10
  161. package/dist/learning-cost.d.ts +25 -8
  162. package/dist/learning-cost.js +23 -8
  163. package/dist/learning-reset.d.ts +1 -1
  164. package/dist/learning-reset.js +9 -11
  165. package/dist/learning-routes.d.ts +60 -81
  166. package/dist/learning-routes.js +187 -360
  167. package/dist/learning-setting.d.ts +6 -0
  168. package/dist/learning-setting.js +11 -1
  169. package/dist/learning-words.d.ts +2 -0
  170. package/dist/learning-words.js +2 -0
  171. package/dist/learning.d.ts +18 -24
  172. package/dist/learning.js +35 -66
  173. package/dist/listen-first.d.ts +5 -4
  174. package/dist/listen-first.js +4 -5
  175. package/dist/live-reach.d.ts +7 -0
  176. package/dist/live-reach.js +7 -0
  177. package/dist/mcp-api-only-origins.d.ts +15 -0
  178. package/dist/mcp-api-only-origins.js +40 -0
  179. package/dist/mcp-gateway.d.ts +22 -2
  180. package/dist/mcp-gateway.js +85 -11
  181. package/dist/mcp-oauth.d.ts +1 -1
  182. package/dist/mcp-oauth.js +3 -2
  183. package/dist/mcp-probe.d.ts +3 -0
  184. package/dist/mcp-probe.js +3 -0
  185. package/dist/mcp-resources.d.ts +1 -1
  186. package/dist/mcp-secret-writes.d.ts +24 -2
  187. package/dist/mcp-secret-writes.js +30 -2
  188. package/dist/mcp-servers-store.d.ts +52 -14
  189. package/dist/mcp-servers-store.js +165 -61
  190. package/dist/mcp-sources.d.ts +1 -2
  191. package/dist/mcp-sources.js +1 -2
  192. package/dist/mcp-store.d.ts +5 -5
  193. package/dist/mcp-store.js +3 -3
  194. package/dist/mcp.js +1 -1
  195. package/dist/model-gateway.d.ts +1 -1
  196. package/dist/model-gateway.js +20 -36
  197. package/dist/native/discovery.d.ts +6 -0
  198. package/dist/native/discovery.js +14 -1
  199. package/dist/native/remote.d.ts +5 -0
  200. package/dist/native/remote.js +16 -0
  201. package/dist/native/runtime.js +3 -2
  202. package/dist/observation/observer.d.ts +6 -6
  203. package/dist/ollama-provider.d.ts +23 -9
  204. package/dist/ollama-provider.js +49 -20
  205. package/dist/openapi.js +290 -79
  206. package/dist/otel/genai.d.ts +83 -7
  207. package/dist/otel/genai.js +69 -9
  208. package/dist/otel/tracer.d.ts +42 -13
  209. package/dist/otel/tracer.js +241 -56
  210. package/dist/page.d.ts +7 -1
  211. package/dist/page.js +76 -22
  212. package/dist/paid-calls.d.ts +6 -4
  213. package/dist/paid-calls.js +15 -7
  214. package/dist/place-offers.d.ts +58 -34
  215. package/dist/place-offers.js +96 -54
  216. package/dist/place.d.ts +41 -20
  217. package/dist/place.js +97 -47
  218. package/dist/print.js +1 -1
  219. package/dist/provider.d.ts +3 -2
  220. package/dist/provider.js +17 -8
  221. package/dist/purged-workflow.d.ts +0 -33
  222. package/dist/purged-workflow.js +3 -71
  223. package/dist/redact/match.d.ts +42 -9
  224. package/dist/redact/match.js +356 -54
  225. package/dist/run-census.d.ts +1 -1
  226. package/dist/run-census.js +4 -5
  227. package/dist/run-cut.js +4 -5
  228. package/dist/run-export-store.d.ts +15 -0
  229. package/dist/run-export-store.js +30 -0
  230. package/dist/run-export.d.ts +139 -0
  231. package/dist/run-export.js +379 -0
  232. package/dist/run-file-cut.d.ts +5 -0
  233. package/dist/run-file-cut.js +13 -0
  234. package/dist/run-launch.d.ts +3 -3
  235. package/dist/run-launch.js +16 -3
  236. package/dist/run-learning-served.d.ts +3 -3
  237. package/dist/run-learning-served.js +1 -1
  238. package/dist/run-listing.d.ts +1 -1
  239. package/dist/run-model-key.d.ts +15 -6
  240. package/dist/run-model-key.js +30 -31
  241. package/dist/run-reads-over-store.js +4 -4
  242. package/dist/run-secrets.js +3 -5
  243. package/dist/run-timeline-served.d.ts +1 -1
  244. package/dist/run-timeline-served.js +8 -5
  245. package/dist/runnable.js +26 -9
  246. package/dist/runner/adapter-loop.d.ts +35 -18
  247. package/dist/runner/adapter-loop.js +94 -47
  248. package/dist/runner/adapter-run-spec.d.ts +14 -1
  249. package/dist/runner/adapter-run-spec.js +73 -46
  250. package/dist/runner/adapters/pi.js +4 -2
  251. package/dist/runner/audit.d.ts +10 -9
  252. package/dist/runner/audit.js +64 -67
  253. package/dist/runner/beside.js +5 -6
  254. package/dist/runner/claim-secrets.d.ts +10 -3
  255. package/dist/runner/claim-secrets.js +29 -13
  256. package/dist/runner/cli-run-spec.d.ts +18 -0
  257. package/dist/runner/cli-run-spec.js +87 -58
  258. package/dist/runner/compare-end.d.ts +2 -3
  259. package/dist/runner/compare-end.js +30 -11
  260. package/dist/runner/conformance/harness.js +2 -3
  261. package/dist/runner/conformance/subject.d.ts +4 -1
  262. package/dist/runner/disk-free.d.ts +15 -4
  263. package/dist/runner/disk-free.js +25 -7
  264. package/dist/runner/feedback-round.d.ts +1 -1
  265. package/dist/runner/feedback-round.js +2 -2
  266. package/dist/runner/harness-loops.js +3 -4
  267. package/dist/runner/held.d.ts +5 -12
  268. package/dist/runner/held.js +0 -25
  269. package/dist/runner/journal-kinds.d.ts +8 -2
  270. package/dist/runner/journal-kinds.js +23 -5
  271. package/dist/runner/learned-first.d.ts +0 -2
  272. package/dist/runner/learned-first.js +23 -7
  273. package/dist/runner/learning-end.d.ts +14 -24
  274. package/dist/runner/learning-end.js +52 -94
  275. package/dist/runner/learning-seed.d.ts +13 -16
  276. package/dist/runner/learning-seed.js +13 -23
  277. package/dist/runner/live-ticker.js +7 -5
  278. package/dist/runner/loop-contract.d.ts +0 -2
  279. package/dist/runner/loop.d.ts +7 -0
  280. package/dist/runner/loop.js +1 -0
  281. package/dist/runner/main.js +13 -12
  282. package/dist/runner/mcp-claim.js +21 -5
  283. package/dist/runner/mcp-run.d.ts +4 -0
  284. package/dist/runner/mcp-run.js +2 -0
  285. package/dist/runner/meta-tools.js +3 -2
  286. package/dist/runner/metrics.d.ts +7 -0
  287. package/dist/runner/metrics.js +19 -0
  288. package/dist/runner/model-route.d.ts +10 -7
  289. package/dist/runner/model-route.js +79 -15
  290. package/dist/runner/native-loop.js +12 -11
  291. package/dist/runner/presence.d.ts +1 -4
  292. package/dist/runner/presence.js +6 -8
  293. package/dist/runner/promotion.d.ts +39 -36
  294. package/dist/runner/promotion.js +168 -112
  295. package/dist/runner/redact.d.ts +3 -1
  296. package/dist/runner/redact.js +5 -3
  297. package/dist/runner/reflect-hook.d.ts +2 -2
  298. package/dist/runner/reflect-hook.js +4 -1
  299. package/dist/runner/responses-fetch.d.ts +36 -0
  300. package/dist/runner/responses-fetch.js +511 -0
  301. package/dist/runner/run-child-host.d.ts +21 -14
  302. package/dist/runner/run-child-host.js +187 -141
  303. package/dist/runner/run-child.js +11 -4
  304. package/dist/runner/runner-check.js +5 -1
  305. package/dist/runner/runner.d.ts +3 -4
  306. package/dist/runner/runner.js +13 -9
  307. package/dist/runner/sdk-loop.js +10 -12
  308. package/dist/runner/spec-holds.d.ts +8 -1
  309. package/dist/runner/spec-holds.js +9 -4
  310. package/dist/runner/workflow-calls.d.ts +9 -0
  311. package/dist/runner/workflow-calls.js +150 -0
  312. package/dist/runner/workflow-first.d.ts +120 -32
  313. package/dist/runner/workflow-first.js +218 -94
  314. package/dist/runner/workflow-spec.js +1 -1
  315. package/dist/runs-over-store.js +8 -7
  316. package/dist/save-once.d.ts +14 -0
  317. package/dist/save-once.js +31 -0
  318. package/dist/scrub-command.d.ts +34 -31
  319. package/dist/scrub-command.js +116 -147
  320. package/dist/sdk/check.d.ts +1 -4
  321. package/dist/sdk/check.js +2 -3
  322. package/dist/sdk/runs.d.ts +26 -7
  323. package/dist/sdk/runs.js +194 -78
  324. package/dist/seal-key.js +4 -4
  325. package/dist/secret-cut.d.ts +3 -0
  326. package/dist/secret-cut.js +7 -1
  327. package/dist/secret-rules.d.ts +8 -1
  328. package/dist/secret-rules.js +482 -53
  329. package/dist/secrets.d.ts +55 -9
  330. package/dist/secrets.js +345 -21
  331. package/dist/server-fs.d.ts +1 -1
  332. package/dist/server-fs.js +1 -1
  333. package/dist/server-keys.d.ts +10 -3
  334. package/dist/server-keys.js +16 -3
  335. package/dist/server-secrets-store.js +2 -4
  336. package/dist/server.d.ts +30 -18
  337. package/dist/server.js +520 -238
  338. package/dist/share-context.d.ts +22 -0
  339. package/dist/share-context.js +76 -0
  340. package/dist/shell-lex.d.ts +105 -0
  341. package/dist/shell-lex.js +646 -0
  342. package/dist/sign-ins-store.d.ts +5 -7
  343. package/dist/sign-ins-store.js +12 -16
  344. package/dist/sign-ins.d.ts +7 -11
  345. package/dist/sign-ins.js +40 -41
  346. package/dist/skills/agentrun-serve/SKILL.md +5 -2
  347. package/dist/source-sync/auxiliary.js +2 -2
  348. package/dist/start-switches.d.ts +6 -5
  349. package/dist/start-switches.js +8 -4
  350. package/dist/stats.d.ts +5 -1
  351. package/dist/stats.js +1 -1
  352. package/dist/store/agent-body.js +2 -2
  353. package/dist/store/dialect.d.ts +4 -0
  354. package/dist/store/dialect.js +1 -0
  355. package/dist/store/index.d.ts +2 -2
  356. package/dist/store/index.js +1 -1
  357. package/dist/store/mcp-record-keys.d.ts +10 -0
  358. package/dist/store/mcp-record-keys.js +13 -0
  359. package/dist/store/postgres/dialect.js +2 -0
  360. package/dist/store/postgres/migrations/0029_run_launch_census_settle.sql +28 -0
  361. package/dist/store/postgres/migrations/0030_learning_ledger_epoch.sql +40 -0
  362. package/dist/store/postgres/migrations/0031_learning_ledger_calls.sql +12 -0
  363. package/dist/store/postgres/migrations/0032_learning_rows.sql +65 -0
  364. package/dist/store/postgres/store.js +4 -0
  365. package/dist/store/schema.d.ts +60 -11
  366. package/dist/store/schema.js +147 -17
  367. package/dist/store/seal.d.ts +4 -1
  368. package/dist/store/sqlite/learning-rows.d.ts +23 -0
  369. package/dist/store/sqlite/learning-rows.js +559 -0
  370. package/dist/store/sqlite/run-launch.d.ts +3 -10
  371. package/dist/store/sqlite/run-launch.js +12 -23
  372. package/dist/store/sqlite/run-patch.d.ts +17 -10
  373. package/dist/store/sqlite/run-patch.js +50 -13
  374. package/dist/store/sqlite/store.d.ts +9 -0
  375. package/dist/store/sqlite/store.js +194 -46
  376. package/dist/store/store-schema.js +3 -4
  377. package/dist/store/store.d.ts +286 -38
  378. package/dist/store/store.js +27 -11
  379. package/dist/store-reads/analytics.d.ts +2 -1
  380. package/dist/store-reads/analytics.js +7 -5
  381. package/dist/store-reads/journal.d.ts +33 -3
  382. package/dist/store-reads/journal.js +99 -4
  383. package/dist/store-reads/learning.d.ts +50 -45
  384. package/dist/store-reads/learning.js +153 -116
  385. package/dist/store-reads/loop.js +1 -1
  386. package/dist/store-reads/stats.d.ts +2 -2
  387. package/dist/store-reads/stats.js +13 -7
  388. package/dist/store-view.d.ts +24 -2
  389. package/dist/store-view.js +49 -17
  390. package/dist/suggestions.d.ts +1 -1
  391. package/dist/suggestions.js +29 -13
  392. package/dist/template-eval.d.ts +72 -9
  393. package/dist/template-eval.js +358 -64
  394. package/dist/templates.d.ts +10 -2
  395. package/dist/templates.js +31 -4
  396. package/dist/timeline/labels.d.ts +1 -1
  397. package/dist/timeline/labels.js +4 -3
  398. package/dist/timeline/timeline.d.ts +23 -11
  399. package/dist/timeline/timeline.js +115 -31
  400. package/dist/timeline/web-calls.d.ts +8 -6
  401. package/dist/timeline/web-calls.js +10 -6
  402. package/dist/tool-gate.d.ts +13 -1
  403. package/dist/tool-gate.js +43 -3
  404. package/dist/tool-keys-store.js +2 -4
  405. package/dist/tool-keys.d.ts +11 -0
  406. package/dist/tool-keys.js +16 -0
  407. package/dist/tool-plane.d.ts +54 -13
  408. package/dist/tool-plane.js +103 -32
  409. package/dist/tools.d.ts +5 -1
  410. package/dist/tools.js +7 -7
  411. package/dist/trigger-email.js +12 -6
  412. package/dist/triggers.d.ts +15 -34
  413. package/dist/triggers.js +119 -126
  414. package/dist/validate.d.ts +8 -1
  415. package/dist/validate.js +163 -23
  416. package/dist/web-fake.d.ts +2 -1
  417. package/dist/web-fake.js +8 -6
  418. package/dist/web-fetch.d.ts +8 -6
  419. package/dist/web-fetch.js +13 -11
  420. package/dist/web-holds.d.ts +34 -0
  421. package/dist/web-holds.js +89 -0
  422. package/dist/web-run.d.ts +32 -5
  423. package/dist/web-run.js +76 -28
  424. package/dist/web-save.js +23 -12
  425. package/dist/web-search.js +14 -25
  426. package/dist/wires.d.ts +4 -3
  427. package/dist/wires.js +5 -4
  428. package/dist/workspace/archil-claim.d.ts +12 -5
  429. package/dist/workspace/archil-claim.js +45 -5
  430. package/dist/workspace/archil-exec.js +1 -1
  431. package/dist/workspace/archil.d.ts +1 -1
  432. package/dist/workspace/archil.js +1 -1
  433. package/dist/workspace/attach.js +52 -19
  434. package/dist/workspace/attached-computers.d.ts +6 -2
  435. package/dist/workspace/attached-computers.js +5 -4
  436. package/dist/workspace/computer-deps.d.ts +23 -6
  437. package/dist/workspace/computer-deps.js +38 -18
  438. package/dist/workspace/computer-for-claim.d.ts +21 -4
  439. package/dist/workspace/computer-for-claim.js +160 -54
  440. package/dist/workspace/computer-intervals.d.ts +2 -0
  441. package/dist/workspace/computer-intervals.js +1 -1
  442. package/dist/workspace/computer-janitor.d.ts +48 -14
  443. package/dist/workspace/computer-janitor.js +153 -44
  444. package/dist/workspace/computer-kept.d.ts +158 -32
  445. package/dist/workspace/computer-kept.js +288 -63
  446. package/dist/workspace/computer-providers.d.ts +19 -4
  447. package/dist/workspace/computer-providers.js +40 -6
  448. package/dist/workspace/index.d.ts +2 -3
  449. package/dist/workspace/index.js +2 -3
  450. package/dist/workspace/local.js +41 -1
  451. package/dist/workspace/mount-revoke-left.d.ts +31 -0
  452. package/dist/workspace/mount-revoke-left.js +72 -0
  453. package/dist/workspace/paired-route.js +4 -5
  454. package/dist/workspace/paths.d.ts +0 -4
  455. package/dist/workspace/paths.js +0 -6
  456. package/dist/workspace/resolve-computer.d.ts +5 -2
  457. package/dist/workspace/resolve-computer.js +9 -3
  458. package/dist/workspace/run-end-computers.d.ts +11 -5
  459. package/dist/workspace/run-end-computers.js +153 -28
  460. package/dist/workspace/run-tools.d.ts +22 -3
  461. package/dist/workspace/run-tools.js +17 -5
  462. package/dist/workspace/run-workspace.d.ts +14 -1
  463. package/dist/workspace/run-workspace.js +34 -1
  464. package/dist/workspace/workspace.d.ts +7 -1
  465. package/dist/workspace/workspace.js +1 -1
  466. package/package.json +13 -14
  467. package/skills/agentrun-serve/SKILL.md +5 -2
  468. package/templates/README.md +22 -6
  469. package/templates/TOOLS.md +46 -0
  470. package/dist/console/assets/backend-CSAWUqtZ.js +0 -166
  471. package/dist/console/assets/index-Bwn1oTem.css +0 -1
  472. package/dist/console/assets/index-DPh29cyz.js +0 -747
  473. package/dist/workspace/learning-workspace.d.ts +0 -24
  474. /package/dist/learn/{learning.sh → legacy/learning.sh} +0 -0
package/dist/import.js CHANGED
@@ -1,4 +1,4 @@
1
- // `agentrun-serve import`: the Claude Code, Codex and pi sessions under a person's own home, into this server's agent
1
+ // `agentrun-serve import`: the Claude Code, Codex, pi and Copilot CLI sessions under a person's own home, into this server's agent
2
2
  // store, once, when asked. Each project directory is one agent; each harness seen in it one revision of that agent, its
3
3
  // instructions the project's CLAUDE.md or AGENTS.md and its skills the project's skill folders; each session one run,
4
4
  // ended as it ended, its transcript the run's timeline. An imported run is history: it takes no message, stop or cancel.
@@ -7,14 +7,14 @@
7
7
  import { createHash, randomUUID } from "node:crypto";
8
8
  import { existsSync } from "node:fs";
9
9
  import { lstat, open, realpath, stat } from "node:fs/promises";
10
- import { homedir, tmpdir } from "node:os";
10
+ import { availableParallelism, homedir, tmpdir } from "node:os";
11
11
  import { basename, join, sep } from "node:path";
12
12
  import { parseArgs } from "node:util";
13
13
  import { BACKGROUND_CONTEXT as ctx } from "@earendil-works/chord/context";
14
14
  import { AssistantEntry, ROOT_CONVERSATION_ID, ToolResultEntry, UserEntry } from "@earendil-works/pi-durable";
15
15
  import { REQUEST_COST, runMetricsOf } from "./timeline/index.js";
16
16
  import { defaultData } from "./files.js";
17
- import { childrenOf, HARNESS_OF, inOrder, locatorKey, locatorOf, mostEffortOf, priceRequests, readSession, SOURCE_NAMES, SOURCES, sessionLocators } from "@parcha/agentrun-import";
17
+ import { childrenOf, HARNESS_OF, inOrder, locatorKey, locatorOf, locatorParent, locatorSize, mirroredIn, mostEffortOf, ownRequests, priceRequests, READERS, readSession, SOURCE_NAMES, SOURCES, sessionKey, sessionLocators, withSubagentCosts } from "@parcha/agentrun-import";
18
18
  import { hoursOf, summaryLines } from "./import-summary.js";
19
19
  import { stopOnce } from "./stop-signals.js";
20
20
  import { catalogPrices, providerModels } from "./model.js";
@@ -23,7 +23,7 @@ import { launchBody } from "./run-launch.js";
23
23
  import { DEFAULT_PORT } from "./server.js";
24
24
  import { REDACTED, secretCut, secretsIn } from "./secret-cut.js";
25
25
  import { handedSecret, SECRET_NAMES, withSecrets } from "./secrets.js";
26
- import { SEAL_KEY_ENV, sealKeyOf } from "./tool-keys.js";
26
+ import { SEAL_KEY_ENV, sealKeyIn } from "./tool-keys.js";
27
27
  import { bootSealKey, SealKeyRefused, withSealKey } from "./seal-key.js";
28
28
  import { toolKeysOverStore } from "./tool-keys-store.js";
29
29
  import { openServerSecretsOverStore } from "./server-secrets-store.js";
@@ -43,7 +43,7 @@ export async function exportRemoteHistory(target, options = {}) {
43
43
  if (!Number.isSafeInteger(cursor) || cursor < 0)
44
44
  throw new Error('Invalid history cursor.');
45
45
  const project = await realpath(target.project), selected = [], skipped = new Map(), stamps = new Map();
46
- const sourceEnv = options.env ?? process.env;
46
+ const sourceEnv = options.env ?? process.env, lookups = new Map();
47
47
  const skip = (reason) => skipped.set(reason, (skipped.get(reason) ?? 0) + 1);
48
48
  for (const { locator, stats } of await inOrder(await sessionLocators(options.home ?? homedir(), target.runtime, { env: sourceEnv }), target.runtime)) {
49
49
  const file = locator.file;
@@ -98,7 +98,7 @@ export async function exportRemoteHistory(target, options = {}) {
98
98
  changed = true;
99
99
  break;
100
100
  }
101
- const part = await readSession(locatorOf(listed), target.runtime, { seen }).catch(() => undefined), after = await stat(listed.file).catch(() => undefined);
101
+ const part = await readSession(locatorOf(listed), target.runtime, { seen, lookups }).catch(() => undefined), after = await stat(listed.file).catch(() => undefined);
102
102
  if (!part || !after || remoteHistoryStamp(after) !== approvedStamp || !part.cwd || (await realpath(part.cwd).catch(() => part.cwd)) !== project || part.id !== listed.id) {
103
103
  changed = true;
104
104
  break;
@@ -160,8 +160,10 @@ const REMOTE_HISTORY_SOURCE_BYTES = 8_000_000;
160
160
  * Keep at most one bounded JSONL record and never read past the remote source limit, even if a file grows. */
161
161
  async function remoteHistoryMetadata(file, source) {
162
162
  const handle = await open(file, 'r');
163
- // Claude Code's id is its file's name (<id>.jsonl), as readSession reads it; the others' come from a record.
164
- let id = source === 'claude-code' ? basename(file, '.jsonl') : undefined, cwd, child = false;
163
+ // The id the reader gives a session no record names: Claude Code's always (its file's name), the others' when no
164
+ // record named one, which is known only at EOF.
165
+ const named = READERS[source].idOf({ file });
166
+ let id = source === 'claude-code' ? named : undefined, cwd, child = false;
165
167
  const str = (value) => typeof value === 'string' && value !== '' ? value : undefined;
166
168
  const metadataOf = (parts) => {
167
169
  try {
@@ -178,6 +180,17 @@ async function remoteHistoryMetadata(file, source) {
178
180
  cwd = str(row.cwd) ?? cwd;
179
181
  }
180
182
  }
183
+ else if (source === 'copilot') {
184
+ // The process's start (a resume holds the folder too); a run the CLI started on another session's exit is a child.
185
+ const data = row.data;
186
+ if ((row.type !== 'session.start' && row.type !== 'session.resume') || !data || typeof data !== 'object' || Array.isArray(data))
187
+ return;
188
+ if (row.type === 'session.start') {
189
+ id = str(data.sessionId) ?? id;
190
+ child ||= !!str(data.detachedFromSpawningParentSessionId);
191
+ }
192
+ cwd ??= str(data.context?.cwd);
193
+ }
181
194
  else if (row.type === 'session_meta') {
182
195
  const payload = row.payload;
183
196
  if (!payload || typeof payload !== 'object' || Array.isArray(payload))
@@ -199,8 +212,7 @@ async function remoteHistoryMetadata(file, source) {
199
212
  const { bytesRead } = await handle.read(bytes, 0, bytes.length, position);
200
213
  if (!bytesRead) {
201
214
  metadataOf(parts);
202
- // readSession uses the file name only when no source record supplied an id. That is known only at EOF.
203
- id ??= basename(file, '.jsonl');
215
+ id ??= named;
204
216
  return metadata();
205
217
  }
206
218
  position += bytesRead;
@@ -234,15 +246,29 @@ export const MAX_SESSION_BYTES = 256 * 1024 * 1024;
234
246
  export const MAX_RUN_BYTES = MAX_SESSION_BYTES;
235
247
  /** The most projects a count names for the owner to choose from: the latest active. */
236
248
  export const MAX_CANDIDATES = 500;
249
+ /** The heap of the worker that counts or imports this machine's sessions, or reads a year of them for Wrapped. A run is
250
+ * read whole, at most MAX_RUN_BYTES of files, which this holds several times over. */
251
+ export const IMPORT_HEAP_MB = 2048;
252
+ /** The most threads Wrapped's read of the home starts. */
253
+ const WRAPPED_THREADS = 8;
254
+ /** How the import worker reads a year of the home for Wrapped (wrappedHome): on the cores less one, at most
255
+ * WRAPPED_THREADS, and with a quarter of the worker's heap for the reads waiting, which it holds. */
256
+ export function wrappedReading(cores = availableParallelism()) {
257
+ return { threads: Math.max(1, Math.min(cores - 1, WRAPPED_THREADS)), readAhead: (IMPORT_HEAP_MB / 4) * 2 ** 20 };
258
+ }
237
259
  /** The most of one instructions or skill file read, and of one agent's skill files together. */
238
260
  export const MAX_FILE_BYTES = 256 * 1024;
239
261
  export const MAX_SKILL_BYTES = 1024 * 1024;
240
- /** The project's skill folders, each `<dir>/<name>/` with its SKILL.md, by where each harness keeps them. */
241
- export const SKILL_DIRS = [".agents/skills", ".claude/skills", ".codex/skills", ".pi/skills"];
262
+ /** The project's skill folders, each `<dir>/<name>/` with its SKILL.md, by where each harness keeps them. OpenCode reads
263
+ * `skill/` and `skills/` in each of its config folders, the project's `.opencode` among them. A home's own folders (its
264
+ * ~/.config/opencode, ~/.claude) are no project's, and none is read. */
265
+ export const SKILL_DIRS = [".agents/skills", ".claude/skills", ".codex/skills", ".pi/skills", ".opencode/skills", ".opencode/skill"];
242
266
  const INSTRUCTIONS = {
243
267
  "claude-agent": ["CLAUDE.md", "AGENTS.md"],
244
268
  codex: ["AGENTS.md", "CLAUDE.md"],
245
269
  pi: ["AGENTS.md", "CLAUDE.md"],
270
+ // OpenCode's rules file is AGENTS.md, CLAUDE.md where there is none.
271
+ opencode: ["AGENTS.md", "CLAUDE.md"],
246
272
  };
247
273
  const hash = (text) => createHash("sha256").update(text).digest("hex");
248
274
  /** A run's files and its subagents' are over MAX_RUN_BYTES together: the run is left out. */
@@ -269,7 +295,13 @@ export function candidatesOf(plan, env) {
269
295
  * import keep it from the same keys, or a later import would not find the run an earlier one made. */
270
296
  const redactedId = (id) => `redacted-${hash(id).slice(0, 16)}`;
271
297
  /** A file's size and time, as an import read it: the same after means the same content was read. */
272
- const stampOf = (stats) => `${stats.size}:${stats.mtimeMs}`;
298
+ const stampOf = (size) => `${size.bytes}:${size.mtimeMs}`;
299
+ /** A listed session's own size and last write (locatorSize): its file's, or its own rows' in a database of many. What
300
+ * LIVE_MS, MAX_SESSION_BYTES, MAX_RUN_BYTES and an unchanged session go by. */
301
+ const sizeOf = (listed) => sizeNow(locatorOf(listed), listed.source);
302
+ /** locatorSize after the plan: none when it cannot be had now, as when the session is gone (the read that follows, if
303
+ * any, says why). */
304
+ const sizeNow = (locator, source) => locatorSize(locator, source).catch(() => null);
273
305
  /** Bind remote consent to the enumerated source, including archive replacements that preserve size and mtime. */
274
306
  const remoteHistoryStamp = (stats) => `${stats.dev}:${stats.ino}:${stats.size}:${stats.mtimeMs}:${stats.ctimeMs}`;
275
307
  const keptId = (envs, own = []) => {
@@ -340,12 +372,12 @@ async function findKeys(plan, add, cut, held, signal, onProgress) {
340
372
  const budget = budgetOf();
341
373
  let over = false;
342
374
  for (const entry of files) {
343
- const stats = await stat(entry.file).catch(() => null);
344
- if (stats && !fits(budget, stats.size)) {
375
+ const stats = await sizeOf(entry);
376
+ if (stats && !fits(budget, stats.bytes)) {
345
377
  over = true;
346
378
  break;
347
379
  }
348
- const part = stats ? await readSession(locatorOf(entry), listed.source, { seen }).catch(() => undefined) : undefined;
380
+ const part = stats ? await readSession(locatorOf(entry), listed.source, { seen, lookups: lookupsOf(plan) }).catch(() => undefined) : undefined;
349
381
  if (!part || !stats)
350
382
  continue;
351
383
  stamps.set(locatorKey(locatorOf(entry)), stampOf(stats));
@@ -367,7 +399,7 @@ async function findKeys(plan, add, cut, held, signal, onProgress) {
367
399
  if (!subagents)
368
400
  continue;
369
401
  for (const child of subagents) {
370
- const stats = await stat(child.file).catch(() => null);
402
+ const stats = await sizeOf(child);
371
403
  if (stats)
372
404
  stamps.set(locatorKey(locatorOf(child)), stampOf(stats));
373
405
  }
@@ -382,7 +414,7 @@ export const agentIdOf = (cwd) => `imp-${hash(`dir:${cwd}`).slice(0, 32)}`;
382
414
  /** The sessions the store holds already, as `source:session`, to their run's id: a purged run's too, so a session its
383
415
  * owner purged is never imported again. */
384
416
  const importedIn = async (store) => new Map((await store.runs.list({ purged: true })).flatMap((run) => (run.importedFrom ? [[`${run.importedFrom.source}:${run.importedFrom.session}`, run.id]] : [])));
385
- const sameFile = (seen, stats) => seen !== undefined && seen.size === stats.size && seen.mtime_ms === stats.mtimeMs;
417
+ const sameFile = (seen, size) => seen !== undefined && seen.size === size.bytes && seen.mtime_ms === size.mtimeMs;
386
418
  /** The session files the store's imports read whole, by their path's sha256, with their run: the file stamp an import kept
387
419
  * on the run's `imported_from`, so an unchanged file is not parsed again. */
388
420
  async function filesIn(store) {
@@ -399,10 +431,15 @@ const clip = (text, max) => (text.length > max ? `${text.slice(0, max - 1)}…`
399
431
  /** What an import would take: the sessions under `home`, by project, with what it leaves out and why. Keeps no turns
400
432
  * (with `measure`, only until each session is measured), and reads no file `store`'s imports already read whole and
401
433
  * that has not changed since. */
434
+ /** What an import's reads look up once for all its files (readSession's `lookups`: a Codex fork's parent anywhere in
435
+ * its sessions), one map per plan: the one planImport read with, carried to the plan it returns. */
436
+ const planLookups = new WeakMap();
437
+ const lookupsOf = (plan) => planLookups.get(plan) ?? planLookups.set(plan, new Map()).get(plan);
402
438
  export async function planImport({ home, sources = SOURCES, all = false, deleted = false, now = Date.now(), temp: tempDir = tmpdir(), measure = false, env, stored, own = [], signal, keys: scan = true, onKeys, only }, store) {
403
439
  // A session's id that holds a key (one named after its file can) is kept as a hash of it: every lookup of an earlier
404
440
  // import's run then goes by the id as kept.
405
441
  const idOf = keptId([env, stored ?? {}], own);
442
+ const lookups = new Map();
406
443
  const skipped = [];
407
444
  // Each file left out here, with the project folder its read gave, if it was read that far: what `only` goes by.
408
445
  const leftFrom = new Map();
@@ -418,30 +455,51 @@ export async function planImport({ home, sources = SOURCES, all = false, deleted
418
455
  let stopped = false;
419
456
  // Each listed session's place in the import's order (inOrder).
420
457
  const rank = new Map();
458
+ // Each subagent read here, by locatorKey, as its own subagents name it (`source:id`): what holdBack walks down.
459
+ const childIds = new Map();
460
+ // Each subagent read here whose requests name another source's session (`mirrors`), with those sessions: its run
461
+ // waits for a Claude Code session it names that is on disk but not imported now.
462
+ const mirroring = new Map();
463
+ const tie = async (locator, source, size) => {
464
+ const listed = size.bytes > MAX_SESSION_BYTES ? undefined : await readSession(locator, source, { turns: false, lookups }).catch(() => undefined);
465
+ // One over the cap is not read: its parent is what its reader tells without reading it (an OpenCode row's, a Codex
466
+ // rollout's first line).
467
+ const parent = listed ? (listed.child ? listed.parent : undefined) : (size.parent ?? (await locatorParent(locator, source)));
468
+ if (parent)
469
+ child(`${source}:${await idOf(parent, scan)}`, locator);
470
+ };
421
471
  const temps = [...new Set([tempDir, await realpath(tempDir).catch(() => tempDir)])];
422
472
  for (const source of sources) {
423
- for (const { locator, stats } of await inOrder(await sessionLocators(home, source), source)) {
473
+ // Each source's own folders where `env` puts them (CLAUDE_CONFIG_DIR, CODEX_HOME, XDG_DATA_HOME, OPENCODE_DB).
474
+ for (const { locator, size, failed } of await inOrder(await sessionLocators(home, source, { env }), source)) {
424
475
  const { file } = locator;
425
476
  if (signal?.aborted) {
426
477
  stopped = true;
427
478
  break;
428
479
  }
480
+ // One whose own size cannot be had (a database locked or damaged since it was listed) is named and passed over.
481
+ if (failed !== undefined) {
482
+ leave(unread(locatorKey(locator), failed), source);
483
+ continue;
484
+ }
429
485
  const known = seen.get(hash(locatorKey(locator)));
430
- if (sameFile(known, stats)) {
486
+ if (sameFile(known, size)) {
431
487
  already += 1;
432
488
  held.push(known.run);
433
489
  continue;
434
490
  }
435
- if (now - stats.mtimeMs < LIVE_MS) {
436
- leave({ what: file, why: "written in the last 10 minutes: it may still be running", kind: "live" }, source);
437
- continue;
438
- }
439
- if (stats.size > MAX_SESSION_BYTES) {
440
- leave({ what: file, why: `over ${MAX_SESSION_BYTES} bytes`, kind: "large" }, source);
491
+ // The session's own last write and size (a database's sessions each their own): one live session, or a large
492
+ // database, leaves the rest of its file importable.
493
+ // Either one, when it is a subagent's, holds its run back (holdBack): the subagent is tied to its run as one read
494
+ // would tie it, by its listing while it is written, by the parent its source's stat names when it is over the cap.
495
+ const unreadAs = leftUnread(locator, size, now);
496
+ if (unreadAs) {
497
+ leave(unreadAs, source);
498
+ await tie(locator, source, size);
441
499
  continue;
442
500
  }
443
501
  // One file this user cannot read, or one gone since its stat, is named and passed over: the rest still import.
444
- const session = await readSession(locator, source, { turns: false }).catch((error) => leave(unread(file, error), source));
502
+ const session = await readSession(locator, source, { turns: false, lookups }).catch((error) => leave(unread(file, error), source));
445
503
  if (!session)
446
504
  continue;
447
505
  session.id = await idOf(session.id, scan);
@@ -451,29 +509,17 @@ export async function planImport({ home, sources = SOURCES, all = false, deleted
451
509
  // thread's, whichever of its files); else it counts in the totals alone, where its project would.
452
510
  if (session.child && session.parent) {
453
511
  child(`${source}:${session.parent}`, locator);
512
+ childIds.set(locatorKey(locator), `${source}:${session.id}`);
513
+ if (session.mirrors?.length)
514
+ mirroring.set(locatorKey(locator), session.mirrors);
454
515
  continue;
455
516
  }
456
- if (!session.cwd) {
457
- leave({ what: file, why: "no project directory in it", kind: "no-project" }, source);
458
- continue;
459
- }
460
- if (!all && session.users === 0 && !session.child) {
461
- leave({ what: file, why: "no message of the person's", kind: "no-words", session: `${source}:${session.id}` }, source, session.cwd);
517
+ const readAs = await leftRead(session, file, temps, all, deleted);
518
+ if (readAs) {
519
+ leave(readAs, source, session.cwd);
462
520
  continue;
463
521
  }
464
522
  const cwd = session.cwd;
465
- if (!all) {
466
- // A temp folder first, gone or not: only --all brings it in, as the left-out line says.
467
- if (temps.some((temp) => cwd === temp || cwd.startsWith(temp + sep))) {
468
- leave({ what: file, why: `its project ${cwd} is a temp directory`, kind: "temp", session: `${source}:${session.id}` }, source, cwd);
469
- continue;
470
- }
471
- const there = await lstat(cwd).catch(() => null);
472
- if (!there?.isDirectory() && !deleted) {
473
- leave({ what: file, why: `its project ${cwd} is gone`, kind: "gone", session: `${source}:${session.id}` }, source, cwd);
474
- continue;
475
- }
476
- }
477
523
  if (session.child) {
478
524
  untied.push({ locator, source });
479
525
  continue;
@@ -489,12 +535,76 @@ export async function planImport({ home, sources = SOURCES, all = false, deleted
489
535
  rank.set(session, rank.size);
490
536
  project.sessions.push(session);
491
537
  }
492
- for (const { locator, of } of await childrenOf(home, source))
538
+ for (const { locator, of } of await childrenOf(home, source, { env }))
493
539
  child(locatorKey(of), locator);
494
540
  }
541
+ // A run imports only when every subagent it has, whatever its source, can be read now: one still written or over the
542
+ // cap leaves the run out with it, said, and the run comes in whole, its subagents' usage with it, once each can be.
543
+ const holds = new Map();
544
+ for (const project of projects.values()) {
545
+ const runs = new Map();
546
+ for (const session of project.sessions)
547
+ runs.set(`${session.source}:${session.id}`, [...(runs.get(`${session.source}:${session.id}`) ?? []), session]);
548
+ for (const [key, parts] of runs) {
549
+ if (!holds.has(key))
550
+ holds.set(key, await holdBack(children, parts, childIds, now));
551
+ const why = holds.get(key);
552
+ if (why)
553
+ leave({ what: locatorKey(locatorOf(parts[0])), ...why, session: key }, parts[0].source, project.cwd);
554
+ }
555
+ project.sessions = project.sessions.filter((session) => !holds.get(`${session.source}:${session.id}`));
556
+ if (!project.sessions.length)
557
+ projects.delete(project.cwd);
558
+ }
495
559
  ownRuns(projects, rank);
496
560
  // The owner's choice, once each session has its one project: a project not chosen is no part of the plan.
497
561
  const chosen = only === undefined ? undefined : new Set(only);
562
+ // A run that leaves a request to a Claude Code session (`mirrors`, its own or a subagent's) counts it there only once
563
+ // that session is saved: saved by a later import, the request would count in both. So a run whose Claude Code session
564
+ // is on disk but not imported now (still written, held back with a live subagent, in a project not chosen, or of a
565
+ // source this import does not read) waits for it, said. One whose session no import brings in as it is (over the cap,
566
+ // unreadable, a temp or gone folder, no message of the person's), or that is no file here, imports now: the request is
567
+ // its own.
568
+ const targetsOf = (parts) => [...parts.flatMap((part) => part.mirrors ?? []), ...subagentsOf(children, parts, childIds).flatMap((locator) => mirroring.get(locatorKey(locator)) ?? [])].filter((link) => link.source === "claude-code");
569
+ const waiting = [...projects.values()].flatMap((project) => byRun(project.sessions).flatMap((parts) => (targetsOf(parts).length ? [{ project, parts }] : [])));
570
+ if (waiting.length) {
571
+ const stored = store ? await importedIn(store) : new Map();
572
+ const comingIn = new Set([...projects.values()].filter((project) => !chosen || chosen.has(project.agentId)).flatMap((project) => project.sessions.filter((session) => session.source === "claude-code").map((session) => session.id)));
573
+ const never = new Set(skipped.filter((entry) => leftFrom.get(entry)?.source === "claude-code" && NEVER_IN.has(entry.kind)).map((entry) => (entry.session?.startsWith("claude-code:") ? entry.session.slice("claude-code:".length) : basename(entry.what, ".jsonl"))));
574
+ const claude = await sessionLocators(home, "claude-code", { env }).catch(() => []);
575
+ const listed = new Set(claude.map((locator) => basename(locator.file, ".jsonl")));
576
+ // An import that reads no Claude Code left none of it out above: each Claude Code session a run's request ran
577
+ // through goes by the same rules here, so one no import brings in leaves the request the run's own, not a wait.
578
+ if (!sources.includes("claude-code")) {
579
+ // A target the store holds, or one of a run the store holds, decides nothing (the loop below): it is not read.
580
+ const targets = new Set(waiting.filter(({ parts }) => !stored.has(`${parts[0].source}:${parts[0].id}`)).flatMap(({ parts }) => targetsOf(parts).map((link) => link.sessionId)));
581
+ for (const locator of claude) {
582
+ const id = basename(locator.file, ".jsonl");
583
+ if (!targets.has(id) || stored.has(`claude-code:${await idOf(id, scan)}`))
584
+ continue;
585
+ const kind = await neverKind(locator, now, temps, all, deleted);
586
+ if (kind && NEVER_IN.has(kind))
587
+ never.add(id);
588
+ }
589
+ }
590
+ for (const { project, parts } of waiting) {
591
+ const key = `${parts[0].source}:${parts[0].id}`;
592
+ if (stored.has(key))
593
+ continue;
594
+ let target;
595
+ for (const link of targetsOf(parts)) {
596
+ const kept = await idOf(link.sessionId, scan);
597
+ if (listed.has(link.sessionId) && !comingIn.has(kept) && !stored.has(`claude-code:${kept}`) && !never.has(kept) && !never.has(link.sessionId))
598
+ target = kept;
599
+ }
600
+ if (target === undefined)
601
+ continue;
602
+ leave({ what: locatorKey(locatorOf(parts[0])), why: `a request of it ran through Claude Code session ${target}, on disk but not imported now: it comes in with that session`, kind: "mirror", session: key }, parts[0].source, project.cwd);
603
+ project.sessions = project.sessions.filter((session) => `${session.source}:${session.id}` !== key);
604
+ if (!project.sessions.length)
605
+ projects.delete(project.cwd);
606
+ }
607
+ }
498
608
  // What is left out is said of the projects chosen alone, each file by the folder it names: as its read gave it, or,
499
609
  // for a file left out unread (still written, over the cap, unreadable), as its first records say. A file that names
500
610
  // no folder is no chosen project's.
@@ -510,7 +620,17 @@ export async function planImport({ home, sources = SOURCES, all = false, deleted
510
620
  }
511
621
  skipped.splice(0, skipped.length, ...ofChosen);
512
622
  }
513
- const plan = { projects: [...projects.values()].filter((project) => !chosen || chosen.has(project.agentId)).sort((a, b) => a.cwd.localeCompare(b.cwd)), skipped, already, held, children, untied, ...(stopped ? { stopped: true } : {}) };
623
+ // Each Claude Code session a request names, by the id the import keeps it as, where that is another.
624
+ const mirrorIds = new Map();
625
+ for (const project of projects.values())
626
+ for (const parts of byRun(project.sessions))
627
+ for (const { sessionId } of targetsOf(parts)) {
628
+ const kept = await idOf(sessionId, scan);
629
+ if (kept !== sessionId)
630
+ mirrorIds.set(sessionId, kept);
631
+ }
632
+ const plan = { projects: [...projects.values()].filter((project) => !chosen || chosen.has(project.agentId)).sort((a, b) => a.cwd.localeCompare(b.cwd)), skipped, already, held, children, untied, ...(mirrorIds.size ? { mirrorIds } : {}), ...(stopped ? { stopped: true } : {}) };
633
+ planLookups.set(plan, lookups);
514
634
  if (!measure)
515
635
  return plan;
516
636
  const counting = secretCut(env, SECRET_NAMES);
@@ -520,6 +640,7 @@ export async function planImport({ home, sources = SOURCES, all = false, deleted
520
640
  // This server's own secrets first, as the import takes them.
521
641
  foundKeys(own);
522
642
  const { large } = await findKeys(plan, foundKeys, counting.text, (listed) => heldBy?.get(`${listed.source}:${listed.id}`) !== undefined, signal);
643
+ const mirrored = mirrorsOf(plan, heldBy, large);
523
644
  // Measured in the import's own order, a record or response counted once across files, each session with its
524
645
  // subagents; a session the store holds already from its run, as the import counts it, not from its file now.
525
646
  for (const project of plan.projects) {
@@ -541,13 +662,13 @@ export async function planImport({ home, sources = SOURCES, all = false, deleted
541
662
  const budget = budgetOf();
542
663
  let over = false;
543
664
  for (const listed of files) {
544
- const stats = await stat(listed.file).catch(() => null);
665
+ const stats = await sizeOf(listed);
545
666
  // Grown over the cap since the scan above: left out here as the import leaves it out, and read no further.
546
- if (stats && !fits(budget, stats.size)) {
667
+ if (stats && !fits(budget, stats.bytes)) {
547
668
  over = true;
548
669
  break;
549
670
  }
550
- const part = await readSession(locatorOf(listed), listed.source, { seen: seen(listed.source) }).catch(() => undefined);
671
+ const part = await readSession(locatorOf(listed), listed.source, { seen: seen(listed.source), lookups }).catch(() => undefined);
551
672
  if (part)
552
673
  read.push(part);
553
674
  }
@@ -558,7 +679,7 @@ export async function planImport({ home, sources = SOURCES, all = false, deleted
558
679
  const parts = read.filter((part) => !ownless(part));
559
680
  if (!parts.length)
560
681
  continue;
561
- const session = merged(parts);
682
+ const session = settled(merged(parts), mirrored);
562
683
  // What the import's cut would take out of it (its turns, its first message): the dry run's count.
563
684
  counting.json(session.turns);
564
685
  if (session.firstPrompt)
@@ -570,7 +691,7 @@ export async function planImport({ home, sources = SOURCES, all = false, deleted
570
691
  });
571
692
  if (!subagents)
572
693
  continue;
573
- found.push({ source: session.source, agent: project.agentId, ...measured(session, subagents) });
694
+ found.push({ source: session.source, agent: project.agentId, ...measured(session, subagents.map((child) => settled(child, mirrored))) });
574
695
  }
575
696
  }
576
697
  // Each project's files read as the import reads them, held agent or new: each file it leaves out (a link, one over its
@@ -587,32 +708,35 @@ export async function planImport({ home, sources = SOURCES, all = false, deleted
587
708
  for (const [path, text] of Object.entries(files.skills))
588
709
  (counting.text(path), counting.text(text));
589
710
  }
590
- return { ...plan, found, secretsFound: counting.text.removed };
711
+ const withFound = { ...plan, found, secretsFound: counting.text.removed };
712
+ planLookups.set(withFound, lookups);
713
+ return withFound;
591
714
  }
592
715
  /** The subagents tied to no session: each one's tokens and tool calls, for a summary's totals, each response once. */
593
716
  export async function untiedFound(plan) {
717
+ const mirrored = mirrorsOf(plan);
594
718
  const seen = new Map();
595
719
  const counted = (source) => seen.get(source) ?? seen.set(source, new Set()).get(source);
596
720
  // A thread resumed in a second file of the same id is one: its own subagents, which name it, count once with it.
597
721
  const threads = new Map();
598
722
  for (const { locator, source } of plan.untied) {
599
- const stats = await stat(locator.file).catch(() => null);
600
- if (!stats || stats.size > MAX_SESSION_BYTES)
723
+ const stats = await sizeNow(locator, source);
724
+ if (!stats || stats.bytes > MAX_SESSION_BYTES)
601
725
  continue;
602
- const session = await readSession(locator, source, { seen: counted(source) }).catch(() => undefined);
726
+ const session = await readSession(locator, source, { seen: counted(source), lookups: lookupsOf(plan) }).catch(() => undefined);
603
727
  if (session)
604
728
  threads.set(`${source}:${session.id}`, [...(threads.get(`${source}:${session.id}`) ?? []), session]);
605
729
  }
606
730
  const found = [];
607
731
  for (const parts of threads.values()) {
608
- const session = merged(parts);
732
+ const session = settled(merged(parts), mirrored);
609
733
  // One whose own subagents are over the cap together counts for itself alone: the totals never hold more than a run.
610
734
  const children = await readChildren(plan, session, parts, counted(session.source), budgetOf()).catch((error) => {
611
735
  if (!(error instanceof RunTooLarge))
612
736
  throw error;
613
737
  return [];
614
738
  });
615
- found.push({ source: session.source, agent: "", untied: true, metrics: metricsOf(session, children) });
739
+ found.push({ source: session.source, agent: "", untied: true, metrics: metricsOf(session, children.map((child) => settled(child, mirrored))) });
616
740
  }
617
741
  return found;
618
742
  }
@@ -696,33 +820,124 @@ function merged(parts) {
696
820
  /** A session that holds only records an earlier file of the import holds (a resumed session's copy of them). */
697
821
  const ownless = (session) => session.copies > 0 && !session.turns.some((turn) => turn.role !== "note");
698
822
  /** The records and responses an import has counted, by source, for one project: first those its runs in `store` hold
699
- * already (each answer's response id and each entry's record ids, as its transcript keeps them), then each file's as it
700
- * is read. */
823
+ * already (each answer's response id and its later parts', and each entry's record ids, as its transcript keeps them:
824
+ * Claude Code's and Copilot's; an OpenCode answer's fingerprint and its prompts', what a 1.x fork's copies of them are
825
+ * keyed by), then each file's as it is read. */
701
826
  async function seenIn(store, agentId) {
702
827
  const bySource = new Map();
703
828
  const seen = (source) => bySource.get(source) ?? bySource.set(source, new Set()).get(source);
704
829
  if (!store || !(await store.agents.get(agentId)))
705
830
  return seen;
706
831
  for (const run of await store.runs.list({ agentId })) {
707
- if (run.importedFrom?.source !== "claude-code")
832
+ const source = run.importedFrom?.source;
833
+ if (source !== "claude-code" && source !== "opencode" && source !== "copilot")
708
834
  continue;
709
835
  for (const entry of (await journalEntries(store.readJournal(run.id), ctx))) {
710
836
  const id = entry.model?.[0]?.responseId;
837
+ const { record_uuids: uuids, record_keys: keys } = (entry.data ?? {});
838
+ if (source === "opencode") {
839
+ // A request's fingerprint is its answer's response id; a prompt's, its record id.
840
+ for (const key of [id, ...(Array.isArray(uuids) ? uuids : [])])
841
+ if (typeof key === "string" && key.startsWith("o:"))
842
+ seen("opencode").add(key);
843
+ continue;
844
+ }
845
+ const into = seen(source);
711
846
  if (typeof id === "string" && id)
712
- seen("claude-code").add(`m:${id}`);
847
+ into.add(`m:${id}`);
713
848
  // A run imported before a request's key held its request id (message id:request id) keeps the bare message id:
714
849
  // the reader matches it against a request's message id alone.
715
- if (typeof id === "string" && id && !id.includes(":"))
716
- seen("claude-code").add(`l:${id}`);
717
- const uuids = entry.data?.record_uuids;
850
+ if (source === "claude-code" && typeof id === "string" && id && !id.includes(":"))
851
+ into.add(`l:${id}`);
718
852
  if (Array.isArray(uuids))
719
853
  for (const uuid of uuids)
720
854
  if (typeof uuid === "string")
721
- seen("claude-code").add(`u:${uuid}`);
855
+ into.add(`u:${uuid}`);
856
+ if (Array.isArray(keys))
857
+ for (const key of keys)
858
+ if (typeof key === "string" && key)
859
+ into.add(`m:${key}`);
722
860
  }
723
861
  }
724
862
  return seen;
725
863
  }
864
+ /** Why a session is left out before it is read, if it is: still written (live), or over the cap (large). */
865
+ const leftUnread = (locator, size, now) => now - size.mtimeMs < LIVE_MS ? { what: locatorKey(locator), why: "written in the last 10 minutes: it may still be running", kind: "live" } : size.bytes > MAX_SESSION_BYTES ? { what: locatorKey(locator), why: `over ${MAX_SESSION_BYTES} bytes`, kind: "large" } : undefined;
866
+ /** Why a session read (turns: false) is no project's run, if it is not: no project folder, no message of the person's
867
+ * (but with `all`), its project a temp folder (first, gone or not: only `all` brings it in, as the left-out line says)
868
+ * or gone (but with `all` or `deleted`). */
869
+ async function leftRead(session, file, temps, all, deleted) {
870
+ const { cwd, source, id } = session;
871
+ if (!cwd)
872
+ return { what: file, why: "no project directory in it", kind: "no-project" };
873
+ if (!all && session.users === 0 && !session.child)
874
+ return { what: file, why: "no message of the person's", kind: "no-words", session: `${source}:${id}` };
875
+ if (all)
876
+ return undefined;
877
+ if (temps.some((temp) => cwd === temp || cwd.startsWith(temp + sep)))
878
+ return { what: file, why: `its project ${cwd} is a temp directory`, kind: "temp", session: `${source}:${id}` };
879
+ const there = await lstat(cwd).catch(() => null);
880
+ if (!there?.isDirectory() && !deleted)
881
+ return { what: file, why: `its project ${cwd} is gone`, kind: "gone", session: `${source}:${id}` };
882
+ return undefined;
883
+ }
884
+ /** How planImport would leave a Claude Code session out, by the same rules (leftUnread, unread, leftRead), when it is
885
+ * not one of the sources it reads: none when it would be a run, or a subagent's part of one. */
886
+ async function neverKind(locator, now, temps, all, deleted) {
887
+ const size = await locatorSize(locator, "claude-code").catch(() => undefined);
888
+ if (size === null)
889
+ return undefined;
890
+ if (size === undefined)
891
+ return "unread";
892
+ const unreadAs = leftUnread(locator, size, now);
893
+ if (unreadAs)
894
+ return unreadAs.kind;
895
+ const session = await readSession(locator, "claude-code", { turns: false }).catch(() => undefined);
896
+ if (!session)
897
+ return "unread";
898
+ if (session.child && session.parent)
899
+ return undefined;
900
+ return (await leftRead(session, locator.file, temps, all, deleted))?.kind;
901
+ }
902
+ /** Why a Claude Code session is left out that no later import changes as it is: a request another run leaves to it
903
+ * (`mirrors`) counts in that run. */
904
+ const NEVER_IN = new Set(["large", "unread", "no-words", "temp", "gone", "no-project"]);
905
+ const LIVE_CHILD = { why: "a subagent of it was written in the last 10 minutes: it comes in with it", kind: "live" };
906
+ const LARGE_CHILD = { why: `a subagent of it is over ${MAX_SESSION_BYTES} bytes`, kind: "large" };
907
+ /** A run's subagents, theirs, and so on down, each once (the import's children relation, as readChildren walks it):
908
+ * `childIds` names each subagent the plan read, so its own subagents are found. */
909
+ function subagentsOf(children, parts, childIds) {
910
+ const out = [];
911
+ const visited = new Set();
912
+ const under = (owner) => {
913
+ for (const locator of children.get(owner) ?? []) {
914
+ const key = locatorKey(locator);
915
+ if (visited.has(key))
916
+ continue;
917
+ visited.add(key);
918
+ out.push(locator);
919
+ const id = childIds.get(key);
920
+ if (id !== undefined)
921
+ under(id);
922
+ }
923
+ };
924
+ for (const part of parts)
925
+ under(locatorKey(locatorOf(part)));
926
+ under(`${parts[0].source}:${parts[0].id}`);
927
+ return out;
928
+ }
929
+ /** Why a run waits, if it does: the first of its subagents (subagentsOf) that cannot be read now by its size now: still
930
+ * written, or over the cap. */
931
+ async function holdBack(children, parts, childIds, now) {
932
+ for (const locator of subagentsOf(children, parts, childIds)) {
933
+ const size = await sizeNow(locator, parts[0].source);
934
+ if (size && size.bytes > MAX_SESSION_BYTES)
935
+ return LARGE_CHILD;
936
+ if (size && now - size.mtimeMs < LIVE_MS)
937
+ return LIVE_CHILD;
938
+ }
939
+ return undefined;
940
+ }
726
941
  /** A run's subagents, theirs, and so on down, each file once, read with the import's `seen`: those beside each of its
727
942
  * files (Claude Code's), and those naming its thread (Codex's, whichever of its files they ran under). One gone or
728
943
  * unreadable is passed over. All of them are held at once, so their sizes are taken from `budget` (what the run's own
@@ -736,14 +951,14 @@ async function readChildren(plan, session, parts, seen, budget) {
736
951
  if (visited.has(key))
737
952
  continue;
738
953
  visited.add(key);
739
- const stats = await stat(locator.file).catch(() => null);
954
+ const stats = await sizeNow(locator, session.source);
740
955
  if (!stats)
741
956
  continue;
742
957
  // Every subagent read is held with the run: one more than the run's cap holds ends the read, and the run is left out.
743
958
  // No subagent is passed over for its size: the run would be kept without its usage.
744
- if (!fits(budget, stats.size))
959
+ if (!fits(budget, stats.bytes))
745
960
  throw new RunTooLarge();
746
- const child = await readSession(locator, session.source, { seen }).catch(() => undefined);
961
+ const child = await readSession(locator, session.source, { seen, lookups: lookupsOf(plan) }).catch(() => undefined);
747
962
  if (!child)
748
963
  continue;
749
964
  out.push(child);
@@ -760,12 +975,26 @@ async function readChildren(plan, session, parts, seen, budget) {
760
975
  * its cost (none known: null), as a request's cost is written with no answer (REQUEST_COST). The timeline shows none of
761
976
  * them, and its usage row, the run's cost and runMetricsOf all count each one. */
762
977
  const subagentMarks = (children) => children.flatMap((child) => child.turns.flatMap((turn) => {
763
- if (turn.role !== "assistant")
978
+ if (turn.role !== "assistant" || turn.mirrors)
764
979
  return [];
765
980
  const { input, output, cacheRead, cacheWrite } = turn.usage ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
766
- // A failed request's counts are its own, zeros included, as its answer's are (entryOf).
767
- return [{ kind: REQUEST_COST, data: { request: "subagent", usd: turn.costUsd ?? null, usage: { input, output, cacheRead, cacheWrite }, ...(turn.error !== undefined ? { failed: true } : {}) } }];
981
+ // A failed request's counts are its own, zeros included, as its answer's are (entryOf); so are a folded one's.
982
+ return [{ kind: REQUEST_COST, data: { request: "subagent", usd: turn.costUsd ?? null, usage: { input, output, cacheRead, cacheWrite, ...(turn.folded ? { folded: true } : {}) }, ...(turn.error !== undefined ? { failed: true } : {}) } }];
768
983
  }));
984
+ /** The sessions a request may be counted in instead of its own (mirroredIn): each the plan imports (but those over the
985
+ * run's cap, `large`), and each the store holds already. A request OpenCode ran through Claude Code is that Claude Code
986
+ * session's when either holds it. */
987
+ const mirrorsOf = (plan, held = new Map(), large = new Set()) => mirroredIn(new Set([...plan.projects.flatMap((project) => project.sessions.map((session) => sessionKey(session.source, session.id))).filter((key) => !large.has(key)), ...held.keys()]), plan.mirrorIds);
988
+ /** A session as a run counts it, read whole: a turn whose request `mirrored` gives to another session keeps its `mirrors`
989
+ * (shown, counted nothing: entryOf), any other loses it; its cost is its own requests' (ownRequests). */
990
+ function settled(session, mirrored) {
991
+ const answers = session.turns.filter((turn) => turn.role === "assistant");
992
+ for (const answer of answers)
993
+ if (answer.mirrors && !mirrored(answer))
994
+ delete answer.mirrors;
995
+ session.costUsd = ownRequests(answers, session.costUsd, mirrored).cost;
996
+ return session;
997
+ }
769
998
  /** A session's entries as its transcript holds them, its subagents' requests with them (subagentMarks). */
770
999
  const runEntries = (session, children) => [...entriesOf(session), ...subagentMarks(children)];
771
1000
  /** What a session used, its subagents' requests with it: runMetricsOf of its entries, and its subagents' models and tool
@@ -919,11 +1148,12 @@ export async function projectFiles(cwd, skipped) {
919
1148
  }
920
1149
  return { instructions, skills };
921
1150
  }
922
- /** A turn's transcript entry, with the source's ids of the records it was read from (`record_uuids`): a later import counts
923
- * a copy of them once. */
1151
+ /** A turn's transcript entry, with the source's ids of the records it was read from (`record_uuids`) and of a request's
1152
+ * later parts (`record_keys`, Turn.keys): a later import counts a copy of them once. */
924
1153
  const message = (turn, model) => {
925
1154
  const written = entryOf(turn, model);
926
- return turn.uuids?.length ? { ...written, data: { ...written.data, record_uuids: turn.uuids } } : written;
1155
+ const ids = { ...(turn.uuids?.length ? { record_uuids: turn.uuids } : {}), ...(turn.role === "assistant" && turn.keys?.length ? { record_keys: turn.keys } : {}) };
1156
+ return Object.keys(ids).length ? { ...written, data: { ...written.data, ...ids } } : written;
927
1157
  };
928
1158
  const entryOf = (turn, model) => {
929
1159
  if (turn.role === "user")
@@ -978,11 +1208,15 @@ const entryOf = (turn, model) => {
978
1208
  ...(cacheWrite1h !== undefined ? { cacheWrite1h } : {}),
979
1209
  totalTokens: input + output + cacheRead + cacheWrite,
980
1210
  cost: cost === undefined ? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } : { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: cost },
1211
+ // Its zeros are counted in a later request of the session (the source wrote a total): known, never unmetered.
1212
+ ...(turn.folded ? { folded: true } : {}),
981
1213
  },
982
1214
  // A failed request's zero counts are its counts, as a live run's failed request's are.
983
1215
  ...(turn.error !== undefined ? { stopReason: "error", errorMessage: turn.error } : { stopReason: turn.calls.length ? "toolUse" : "stop" }),
984
1216
  timestamp: turn.at,
985
1217
  },
1218
+ // A request another run of the import counts (settled kept its `mirrors`): shown here, counted there.
1219
+ ...(turn.mirrors ? { data: { mirrors: { source: turn.mirrors.source, session: turn.mirrors.sessionId } } } : {}),
986
1220
  };
987
1221
  };
988
1222
  /** The entries `message` makes of a session's turns, as a transcript holds them. */
@@ -1032,7 +1266,7 @@ async function estimateOf(entries, catalog) {
1032
1266
  return undefined;
1033
1267
  // Each answer's request at its own provider's entry, as @parcha/agentrun-import prices a session's totals.
1034
1268
  const requests = entries.flatMap((entry) => {
1035
- const answer = entry.kind === "pi.assistant" ? entry.model?.[0] : undefined;
1269
+ const answer = entry.kind === "pi.assistant" && entry.data?.mirrors === undefined ? entry.model?.[0] : undefined;
1036
1270
  if (!answer?.usage)
1037
1271
  return [];
1038
1272
  const { input = 0, output = 0, cacheRead = 0, cacheWrite = 0, cacheWrite1h } = answer.usage;
@@ -1093,8 +1327,8 @@ function runTitleOf(session, cut) {
1093
1327
  * `whsec_` from elsewhere). The per-run door token is gone (the runner cutover deleted it). A sealed value that does not
1094
1328
  * open is said to `say` (the webhook's secret once, naming the data directory): the import goes on, and does not cut it. */
1095
1329
  export async function ownSecrets(store, data, env, say = () => { }) {
1096
- if (!sealKeyOf(env[SEAL_KEY_ENV]))
1097
- throw new Error(`the server's own secrets open only under its seal key (${SEAL_KEY_ENV}), and none was handed`);
1330
+ // An import and a scrub run offline: they open the key from the server's data directory, so that is where they point.
1331
+ sealKeyIn(env[SEAL_KEY_ENV], "the server's own secrets", { none: "run it with --data at the server's data directory, which keeps the key" });
1098
1332
  return (await openServerSecretsOverStore(store, data, env, TRIGGER_ADAPTERS, say)).secrets.values();
1099
1333
  }
1100
1334
  /** The plan, into `store`: the agents it does not hold, and the runs it does not. Each run is written whole in one atomic
@@ -1118,12 +1352,134 @@ export async function runImport(store, plan, options) {
1118
1352
  };
1119
1353
  // Every key of the import is known before anything of it is written.
1120
1354
  const known = await findKeys(plan, add, text, (listed) => held.get(`${listed.source}:${listed.id}`) !== undefined, options.signal, options.onProgress);
1355
+ // A request another session counts (one the store holds, or one this import has saved) counts there, not again here:
1356
+ // one whose session is not saved (unreadable, too large, stopped before it) counts in its own run.
1357
+ const saved = new Set(held.keys());
1358
+ const mirrored = mirroredIn(saved, plan.mirrorIds);
1121
1359
  const toTake = options.onProgress ? plan.projects.reduce((n, p) => n + byRun(p.sessions).length, 0) : 0;
1122
1360
  let written = 0;
1123
1361
  if (!options.signal?.aborted)
1124
1362
  options.onProgress?.("write", 0, toTake);
1125
1363
  const scannedAs = known.stamps;
1126
1364
  const epoch0 = new Date(0).toISOString();
1365
+ /** One run of a project, written to the store; "stopped" when the import is stopped before it. */
1366
+ const writeRun = async ({ project, line, revisions, seen }, files) => {
1367
+ options.onProgress?.("write", written++, toTake);
1368
+ if (options.signal?.aborted) {
1369
+ report.stopped = true;
1370
+ return "stopped";
1371
+ }
1372
+ const listed = files[0];
1373
+ // A run the store holds already is left as it is: importRun is atomic, so a held run is a whole run.
1374
+ if (held.get(`${listed.source}:${listed.id}`) !== undefined) {
1375
+ line.already += 1;
1376
+ return;
1377
+ }
1378
+ // A run over MAX_RUN_BYTES (found so by the scan above, or grown so since) is left out whole, and said.
1379
+ if (known.large.has(`${listed.source}:${listed.id}`)) {
1380
+ report.skipped.push(tooLarge(listed));
1381
+ return;
1382
+ }
1383
+ const budget = budgetOf();
1384
+ let over = false;
1385
+ // Each of its files, in order. The first's size and time before its read: a file that changes during it is read
1386
+ // again next time.
1387
+ const parts = [];
1388
+ // Every file of it read: one holding only copies adds no records, but its subagents' folder is read with the rest.
1389
+ const searched = [];
1390
+ let read;
1391
+ // The session's own title as the file written last holds it: a moved copy's /rename too, though its turns are
1392
+ // copies the import leaves out.
1393
+ let titled;
1394
+ let changed = false;
1395
+ for (const entry of files) {
1396
+ const { file } = entry;
1397
+ const key = locatorKey(locatorOf(entry));
1398
+ const stats = await sizeOf(entry);
1399
+ if (stats && !fits(budget, stats.bytes)) {
1400
+ over = true;
1401
+ break;
1402
+ }
1403
+ const part = stats ? await readSession(locatorOf(entry), listed.source, { seen: seen(listed.source), lookups: lookupsOf(plan) }).catch((error) => void report.skipped.push(unread(file, error))) : void report.skipped.push({ what: file, why: "gone since it was listed", kind: "vanished" });
1404
+ if (!part || !stats)
1405
+ continue;
1406
+ searched.push(part);
1407
+ if (part.sourceTitle !== undefined && (!titled || stats.mtimeMs >= titled.at))
1408
+ titled = { at: stats.mtimeMs, title: part.sourceTitle };
1409
+ // A file of it holding only copies adds nothing to it.
1410
+ if (ownless(part)) {
1411
+ report.skipped.push({ what: file, why: "holds only records of sessions imported already", kind: "copies" });
1412
+ continue;
1413
+ }
1414
+ read ??= { path_sha256: hash(key), size: stats.bytes, mtime_ms: stats.mtimeMs };
1415
+ parts.push(part);
1416
+ if (scannedAs.get(key) !== stampOf(stats))
1417
+ changed = true;
1418
+ }
1419
+ if (over) {
1420
+ report.skipped.push(tooLarge(listed));
1421
+ return;
1422
+ }
1423
+ if (!read)
1424
+ return;
1425
+ const session = settled(merged(parts), mirrored);
1426
+ if (titled)
1427
+ session.sourceTitle = titled.title;
1428
+ // A file of it changed since the scan above (a session still being written): what it holds now, read through
1429
+ // secretlint again before any of it is cut.
1430
+ if (changed)
1431
+ add(await keysInSessions(parts));
1432
+ // Its id as the plan keeps it (a key in it is one secretlint finds in what was read, the id among it); one
1433
+ // holding a key counts among the keys removed.
1434
+ const keptAs = text(session.id) === session.id ? session.id : redactedId(session.id);
1435
+ session.id = keptAs;
1436
+ const subagents = await readChildren(plan, session, searched, seen(listed.source), budget).catch((error) => {
1437
+ if (!(error instanceof RunTooLarge))
1438
+ throw error;
1439
+ report.skipped.push(tooLarge(listed));
1440
+ });
1441
+ if (!subagents)
1442
+ return;
1443
+ for (const child of subagents)
1444
+ settled(child, mirrored);
1445
+ const moved = await Promise.all(subagents.map(async (child) => scannedAs.get(locatorKey(locatorOf(child))) !== stampOf((await sizeOf(child)) ?? { bytes: -1, mtimeMs: -1 })));
1446
+ if (moved.some(Boolean))
1447
+ add(await keysInSessions(subagents));
1448
+ // The transcript as the store's own write batches, each string cut; its subagents' requests marked after its turns,
1449
+ // so its timeline's usage row counts what its metrics do, one number for the run.
1450
+ const { batches, entries } = transcriptOf(session, json, subagents);
1451
+ const metrics = { ...withChildren(runMetricsOf(entries), subagents.map((child) => runMetricsOf(entriesOf(child)))), activeMs: session.activeMs, ...(session.effort ? { effort: session.effort } : {}) };
1452
+ // Its cost with its subagents' where the source writes theirs apart (withSubagentCosts): unknown when one is.
1453
+ const costUsd = withSubagentCosts(session.source, session.costUsd, subagents.map((child) => child.costUsd));
1454
+ // A session its source did not price: the catalog's estimate, beside its cost (unknown), never written as it.
1455
+ const estimate = costUsd === undefined ? await estimateOf([...entries, ...subagents.flatMap(entriesOf)], catalog) : undefined;
1456
+ if (estimate !== undefined)
1457
+ Object.assign(metrics, { costUsdEst: estimate, costBasis: "catalog" });
1458
+ const answer = session.turns.findLast((t) => t.role === "assistant" && t.text)?.text;
1459
+ // Cut, then put on one line and clipped: a key the clip cut short, or a passphrase whose spaces were changed, would
1460
+ // match no cut.
1461
+ const title = clip(text(runTitleOf(session, text)).replace(/\s+/g, " ").trim(), 120);
1462
+ await store.importRun({
1463
+ id: randomUUID(),
1464
+ agentId: project.agentId,
1465
+ revisionId: revisions.get(session.source),
1466
+ importedFrom: { source: session.source, session: session.id, file: read },
1467
+ launch: { body: launchBody({ input: { content: text(session.firstPrompt ?? "") }, title, place: { mode: "runner" } }) },
1468
+ // An imported session is ended as it ended: a plain completion reads as 'ended', a stop or a failure as its own.
1469
+ state: session.state === "completed" ? "ended" : session.state,
1470
+ ...(costUsd !== undefined ? { costUsd } : {}),
1471
+ ...((answer ?? session.titleText) ? { summary: text(answer ?? session.titleText) } : {}),
1472
+ metrics,
1473
+ startedAt: Date.parse(session.startedAt ?? epoch0),
1474
+ endedAt: Date.parse(session.endedAt ?? session.startedAt ?? epoch0),
1475
+ transcript: batches,
1476
+ });
1477
+ line.runs += 1;
1478
+ // Saved: a request another run leaves to it (`mirrors`) is its from now on.
1479
+ saved.add(`${listed.source}:${listed.id}`);
1480
+ return undefined;
1481
+ };
1482
+ const runs = [];
1127
1483
  for (const project of plan.projects) {
1128
1484
  if (options.signal?.aborted) {
1129
1485
  report.stopped = true;
@@ -1171,117 +1527,21 @@ export async function runImport(store, plan, options) {
1171
1527
  const line = { id: project.agentId, name: project.name, cwd: project.cwd, created, runs: 0, already: 0 };
1172
1528
  // A record or response counted once across the import's files, those its runs here hold already included.
1173
1529
  const seen = await seenIn(store, project.agentId);
1174
- for (const files of byRun(project.sessions)) {
1175
- options.onProgress?.("write", written++, toTake);
1176
- if (options.signal?.aborted) {
1177
- report.stopped = true;
1178
- break;
1179
- }
1180
- const listed = files[0];
1181
- // A run the store holds already is left as it is: importRun is atomic, so a held run is a whole run.
1182
- if (held.get(`${listed.source}:${listed.id}`) !== undefined) {
1183
- line.already += 1;
1184
- continue;
1185
- }
1186
- // A run over MAX_RUN_BYTES (found so by the scan above, or grown so since) is left out whole, and said.
1187
- if (known.large.has(`${listed.source}:${listed.id}`)) {
1188
- report.skipped.push(tooLarge(listed));
1189
- continue;
1190
- }
1191
- const budget = budgetOf();
1192
- let over = false;
1193
- // Each of its files, in order. The first's size and time before its read: a file that changes during it is read
1194
- // again next time.
1195
- const parts = [];
1196
- // Every file of it read: one holding only copies adds no records, but its subagents' folder is read with the rest.
1197
- const searched = [];
1198
- let read;
1199
- // The session's own title as the file written last holds it: a moved copy's /rename too, though its turns are
1200
- // copies the import leaves out.
1201
- let titled;
1202
- let changed = false;
1203
- for (const entry of files) {
1204
- const { file } = entry;
1205
- const key = locatorKey(locatorOf(entry));
1206
- const stats = await stat(file).catch(() => null);
1207
- if (stats && !fits(budget, stats.size)) {
1208
- over = true;
1209
- break;
1210
- }
1211
- const part = stats ? await readSession(locatorOf(entry), listed.source, { seen: seen(listed.source) }).catch((error) => void report.skipped.push(unread(file, error))) : void report.skipped.push({ what: file, why: "gone since it was listed", kind: "vanished" });
1212
- if (!part || !stats)
1213
- continue;
1214
- searched.push(part);
1215
- if (part.sourceTitle !== undefined && (!titled || stats.mtimeMs >= titled.at))
1216
- titled = { at: stats.mtimeMs, title: part.sourceTitle };
1217
- // A file of it holding only copies adds nothing to it.
1218
- if (ownless(part)) {
1219
- report.skipped.push({ what: file, why: "holds only records of sessions imported already", kind: "copies" });
1220
- continue;
1221
- }
1222
- read ??= { path_sha256: hash(key), size: stats.size, mtime_ms: stats.mtimeMs };
1223
- parts.push(part);
1224
- if (scannedAs.get(key) !== stampOf(stats))
1225
- changed = true;
1226
- }
1227
- if (over) {
1228
- report.skipped.push(tooLarge(listed));
1229
- continue;
1230
- }
1231
- if (!read)
1232
- continue;
1233
- const session = merged(parts);
1234
- if (titled)
1235
- session.sourceTitle = titled.title;
1236
- // A file of it changed since the scan above (a session still being written): what it holds now, read through
1237
- // secretlint again before any of it is cut.
1238
- if (changed)
1239
- add(await keysInSessions(parts));
1240
- // Its id as the plan keeps it (a key in it is one secretlint finds in what was read, the id among it); one
1241
- // holding a key counts among the keys removed.
1242
- const keptAs = text(session.id) === session.id ? session.id : redactedId(session.id);
1243
- session.id = keptAs;
1244
- const subagents = await readChildren(plan, session, searched, seen(listed.source), budget).catch((error) => {
1245
- if (!(error instanceof RunTooLarge))
1246
- throw error;
1247
- report.skipped.push(tooLarge(listed));
1248
- });
1249
- if (!subagents)
1250
- continue;
1251
- const moved = await Promise.all(subagents.map(async (child) => scannedAs.get(locatorKey(locatorOf(child))) !== stampOf((await stat(child.file).catch(() => null)) ?? { size: -1, mtimeMs: -1 })));
1252
- if (moved.some(Boolean))
1253
- add(await keysInSessions(subagents));
1254
- // The transcript as the store's own write batches, each string cut; its subagents' requests marked after its turns,
1255
- // so its timeline's usage row counts what its metrics do, one number for the run.
1256
- const { batches, entries } = transcriptOf(session, json, subagents);
1257
- const metrics = { ...withChildren(runMetricsOf(entries), subagents.map((child) => runMetricsOf(entriesOf(child)))), activeMs: session.activeMs, ...(session.effort ? { effort: session.effort } : {}) };
1258
- // A session its source did not price: the catalog's estimate, beside its cost (unknown), never written as it.
1259
- const estimate = session.costUsd === undefined ? await estimateOf([...entries, ...subagents.flatMap(entriesOf)], catalog) : undefined;
1260
- if (estimate !== undefined)
1261
- Object.assign(metrics, { costUsdEst: estimate, costBasis: "catalog" });
1262
- const answer = session.turns.findLast((t) => t.role === "assistant" && t.text)?.text;
1263
- // Cut, then put on one line and clipped: a key the clip cut short, or a passphrase whose spaces were changed, would
1264
- // match no cut.
1265
- const title = clip(text(runTitleOf(session, text)).replace(/\s+/g, " ").trim(), 120);
1266
- await store.importRun({
1267
- id: randomUUID(),
1268
- agentId: project.agentId,
1269
- revisionId: revisions.get(session.source),
1270
- importedFrom: { source: session.source, session: session.id, file: read },
1271
- launch: { body: launchBody({ input: { content: text(session.firstPrompt ?? "") }, title, place: { mode: "runner" } }) },
1272
- // An imported session is ended as it ended: a plain completion reads as 'ended', a stop or a failure as its own.
1273
- state: session.state === "completed" ? "ended" : session.state,
1274
- ...(session.costUsd !== undefined ? { costUsd: session.costUsd } : {}),
1275
- ...((answer ?? session.titleText) ? { summary: text(answer ?? session.titleText) } : {}),
1276
- metrics,
1277
- startedAt: Date.parse(session.startedAt ?? epoch0),
1278
- endedAt: Date.parse(session.endedAt ?? session.startedAt ?? epoch0),
1279
- transcript: batches,
1280
- });
1281
- line.runs += 1;
1282
- }
1530
+ const place = { project, line, revisions, seen };
1531
+ for (const files of byRun(project.sessions))
1532
+ runs.push({ place, files });
1283
1533
  report.agents.push(line);
1284
1534
  }
1535
+ // Claude Code's runs first: a request another run leaves to one of its sessions (`mirrors`, an OpenCode session's own
1536
+ // or a subagent's at any depth) is that session's only once it is saved. Then the rest, each source's in its own
1537
+ // order: an OpenCode session before its later forks, whose copies of its records are its, its subagents read with it.
1538
+ for (const first of [true, false])
1539
+ for (const { place, files } of runs) {
1540
+ if ((files[0].source === "claude-code") !== first)
1541
+ continue;
1542
+ if (report.stopped || (await writeRun(place, files)) === "stopped")
1543
+ break;
1544
+ }
1285
1545
  report.secretsRemoved = text.removed;
1286
1546
  return report;
1287
1547
  }
@@ -1293,6 +1553,7 @@ const LEFT_OUT = {
1293
1553
  live: (n) => `${counted(n, "session")} still being written: ${n === 1 ? "it comes" : "they come"} in next time`,
1294
1554
  "no-words": (n) => `${counted(n, "session")} with no message of yours`,
1295
1555
  "no-project": (n) => `${counted(n, "file")} that ${n === 1 ? "is not a session" : "are not sessions"} (no project folder in ${n === 1 ? "it" : "them"})`,
1556
+ mirror: (n) => `${counted(n, "session")} whose requests ran through a Claude Code session not imported yet: ${n === 1 ? "it comes" : "they come"} in with that session`,
1296
1557
  large: (n) => `${counted(n, "session")} over ${MAX_SESSION_BYTES / 1024 / 1024} MB`,
1297
1558
  unread: (n) => `${counted(n, "session file")} that could not be read`,
1298
1559
  vanished: (n) => `${counted(n, "session file")} gone since ${n === 1 ? "it was" : "they were"} counted`,