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

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 (375) hide show
  1. package/CHANGELOG.md +325 -1
  2. package/README.md +332 -88
  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/agents-store.js +1 -1
  8. package/dist/answer-text.d.ts +3 -0
  9. package/dist/answer-text.js +22 -0
  10. package/dist/attach-conformance.js +5 -4
  11. package/dist/box-paths.d.ts +3 -2
  12. package/dist/box-paths.js +5 -4
  13. package/dist/browser-computer.d.ts +3 -8
  14. package/dist/browser-computer.js +12 -35
  15. package/dist/browser-cost.js +94 -20
  16. package/dist/capacity.d.ts +1 -1
  17. package/dist/capacity.js +3 -3
  18. package/dist/chatgpt-plan.d.ts +5 -0
  19. package/dist/chatgpt-plan.js +25 -11
  20. package/dist/claude-login-token.d.ts +15 -11
  21. package/dist/claude-login-token.js +167 -107
  22. package/dist/claude-login.d.ts +76 -31
  23. package/dist/claude-login.js +426 -79
  24. package/dist/claude-sign-in.d.ts +3 -0
  25. package/dist/claude-sign-in.js +10 -1
  26. package/dist/cli.js +323 -292
  27. package/dist/composio-made.d.ts +1 -6
  28. package/dist/composio-made.js +1 -6
  29. package/dist/composio-owners.d.ts +26 -0
  30. package/dist/composio-owners.js +36 -0
  31. package/dist/composio-preset.d.ts +56 -23
  32. package/dist/composio-preset.js +173 -77
  33. package/dist/composio-triggers.d.ts +4 -4
  34. package/dist/composio-triggers.js +6 -7
  35. package/dist/compute-cost.js +11 -2
  36. package/dist/computer-attach.d.ts +6 -3
  37. package/dist/computer-attach.js +41 -29
  38. package/dist/computer-held-routes.d.ts +1 -1
  39. package/dist/computer-held-routes.js +9 -4
  40. package/dist/computer-keys.d.ts +11 -1
  41. package/dist/computer-keys.js +26 -1
  42. package/dist/computer-record.js +3 -1
  43. package/dist/computer-view.d.ts +5 -3
  44. package/dist/computer-view.js +10 -6
  45. package/dist/computer-viewer.js +36 -7
  46. package/dist/computers.d.ts +2 -1
  47. package/dist/computers.js +6 -3
  48. package/dist/console/THIRD-PARTY-NOTICES.txt +50 -0
  49. package/dist/console/assets/backend-BztxEAvb.js +166 -0
  50. package/dist/console/assets/index-LwNL4L9q.js +619 -0
  51. package/dist/console/assets/share-L84tlUDW.js +6 -0
  52. package/dist/console/assets/styles-CaRKlHke.js +291 -0
  53. package/dist/console/assets/styles-DQo8rzY-.css +1 -0
  54. package/dist/console/index.html +4 -3
  55. package/dist/console/share.html +17 -0
  56. package/dist/decisions.d.ts +17 -7
  57. package/dist/decisions.js +41 -15
  58. package/dist/dial-relay.js +10 -4
  59. package/dist/docker-daemon.js +4 -5
  60. package/dist/docker-host-addresses.js +29 -11
  61. package/dist/email/account.d.ts +6 -0
  62. package/dist/email/account.js +6 -0
  63. package/dist/email/authentication.d.ts +21 -0
  64. package/dist/email/authentication.js +106 -0
  65. package/dist/email/email-faux.d.ts +11 -2
  66. package/dist/email/email-faux.js +21 -5
  67. package/dist/email/mail.d.ts +25 -0
  68. package/dist/email/mail.js +58 -2
  69. package/dist/email/names.js +2 -2
  70. package/dist/email/tools.d.ts +9 -4
  71. package/dist/email/tools.js +95 -13
  72. package/dist/env-switch.d.ts +12 -2
  73. package/dist/env-switch.js +23 -3
  74. package/dist/errors.d.ts +1 -0
  75. package/dist/errors.js +2 -0
  76. package/dist/fal-price.d.ts +11 -1
  77. package/dist/fal-price.js +33 -0
  78. package/dist/faux-computers.js +1 -1
  79. package/dist/filed-answer.d.ts +2 -2
  80. package/dist/filed-answer.js +2 -2
  81. package/dist/graph-served.d.ts +10 -5
  82. package/dist/graph-served.js +40 -10
  83. package/dist/handed-values.js +1 -2
  84. package/dist/harness-check.d.ts +2 -1
  85. package/dist/harness-check.js +45 -12
  86. package/dist/harness-keys.js +9 -6
  87. package/dist/harness-opencode/facts.js +2 -0
  88. package/dist/harness-recipe-entry.d.ts +9 -3
  89. package/dist/harness-recipe-entry.js +18 -9
  90. package/dist/harness-recipe.d.ts +21 -0
  91. package/dist/harness-recipe.js +25 -3
  92. package/dist/harness-table.d.ts +8 -0
  93. package/dist/harness-table.js +17 -6
  94. package/dist/helper-env.d.ts +4 -1
  95. package/dist/helper-env.js +4 -1
  96. package/dist/host-check.d.ts +2 -3
  97. package/dist/host-check.js +13 -7
  98. package/dist/hosted-search.js +1 -1
  99. package/dist/import.d.ts +11 -8
  100. package/dist/import.js +437 -186
  101. package/dist/key-refusal.d.ts +9 -2
  102. package/dist/key-refusal.js +86 -32
  103. package/dist/learn/audit.d.ts +8 -5
  104. package/dist/learn/audit.js +15 -7
  105. package/dist/learn/compile.d.ts +5 -2
  106. package/dist/learn/compile.js +45 -21
  107. package/dist/learn/field-check.d.ts +111 -0
  108. package/dist/learn/field-check.js +174 -0
  109. package/dist/learn/ledger.d.ts +32 -29
  110. package/dist/learn/ledger.js +26 -19
  111. package/dist/learn/promote.d.ts +79 -36
  112. package/dist/learn/promote.js +60 -65
  113. package/dist/learn/secrets.d.ts +4 -0
  114. package/dist/learn/secrets.js +12 -0
  115. package/dist/learned-nodes.d.ts +8 -5
  116. package/dist/learned-nodes.js +8 -5
  117. package/dist/learned-workflow.d.ts +2 -1
  118. package/dist/learned-workflow.js +13 -10
  119. package/dist/learning-cost.d.ts +25 -8
  120. package/dist/learning-cost.js +23 -8
  121. package/dist/learning-setting.d.ts +6 -0
  122. package/dist/learning-setting.js +11 -1
  123. package/dist/listen-first.d.ts +5 -4
  124. package/dist/listen-first.js +4 -5
  125. package/dist/live-reach.d.ts +7 -0
  126. package/dist/live-reach.js +7 -0
  127. package/dist/mcp-api-only-origins.d.ts +15 -0
  128. package/dist/mcp-api-only-origins.js +40 -0
  129. package/dist/mcp-gateway.d.ts +16 -2
  130. package/dist/mcp-gateway.js +41 -3
  131. package/dist/mcp-oauth.d.ts +1 -1
  132. package/dist/mcp-oauth.js +3 -2
  133. package/dist/mcp-probe.d.ts +3 -0
  134. package/dist/mcp-probe.js +3 -0
  135. package/dist/mcp-secret-writes.d.ts +24 -2
  136. package/dist/mcp-secret-writes.js +30 -2
  137. package/dist/mcp-servers-store.d.ts +52 -14
  138. package/dist/mcp-servers-store.js +165 -61
  139. package/dist/mcp-sources.d.ts +1 -2
  140. package/dist/mcp-sources.js +1 -2
  141. package/dist/mcp-store.d.ts +5 -5
  142. package/dist/mcp-store.js +3 -3
  143. package/dist/mcp.js +1 -1
  144. package/dist/model-gateway.d.ts +1 -1
  145. package/dist/model-gateway.js +20 -36
  146. package/dist/ollama-provider.d.ts +23 -9
  147. package/dist/ollama-provider.js +49 -20
  148. package/dist/openapi.js +202 -51
  149. package/dist/otel/genai.d.ts +83 -7
  150. package/dist/otel/genai.js +69 -9
  151. package/dist/otel/tracer.d.ts +42 -13
  152. package/dist/otel/tracer.js +241 -56
  153. package/dist/page.d.ts +7 -1
  154. package/dist/page.js +76 -22
  155. package/dist/paid-calls.d.ts +6 -4
  156. package/dist/paid-calls.js +15 -7
  157. package/dist/place-offers.d.ts +55 -34
  158. package/dist/place-offers.js +93 -54
  159. package/dist/place.d.ts +13 -14
  160. package/dist/place.js +56 -41
  161. package/dist/print.js +1 -1
  162. package/dist/provider.d.ts +3 -2
  163. package/dist/provider.js +17 -8
  164. package/dist/redact/match.d.ts +27 -9
  165. package/dist/redact/match.js +266 -57
  166. package/dist/run-census.d.ts +1 -1
  167. package/dist/run-census.js +4 -5
  168. package/dist/run-cut.js +4 -5
  169. package/dist/run-export-store.d.ts +15 -0
  170. package/dist/run-export-store.js +30 -0
  171. package/dist/run-export.d.ts +139 -0
  172. package/dist/run-export.js +379 -0
  173. package/dist/run-file-cut.d.ts +5 -0
  174. package/dist/run-file-cut.js +13 -0
  175. package/dist/run-launch.js +16 -3
  176. package/dist/run-model-key.d.ts +15 -6
  177. package/dist/run-model-key.js +30 -31
  178. package/dist/run-reads-over-store.js +4 -4
  179. package/dist/run-secrets.js +3 -5
  180. package/dist/run-timeline-served.js +3 -1
  181. package/dist/runnable.js +2 -2
  182. package/dist/runner/adapter-loop.d.ts +35 -18
  183. package/dist/runner/adapter-loop.js +94 -47
  184. package/dist/runner/adapter-run-spec.d.ts +14 -1
  185. package/dist/runner/adapter-run-spec.js +64 -28
  186. package/dist/runner/adapters/pi.js +4 -2
  187. package/dist/runner/audit.d.ts +8 -5
  188. package/dist/runner/audit.js +37 -17
  189. package/dist/runner/beside.js +5 -6
  190. package/dist/runner/claim-secrets.d.ts +10 -3
  191. package/dist/runner/claim-secrets.js +29 -13
  192. package/dist/runner/cli-run-spec.d.ts +18 -0
  193. package/dist/runner/cli-run-spec.js +81 -46
  194. package/dist/runner/compare-end.d.ts +2 -1
  195. package/dist/runner/compare-end.js +25 -10
  196. package/dist/runner/conformance/harness.js +2 -3
  197. package/dist/runner/conformance/subject.d.ts +4 -1
  198. package/dist/runner/harness-loops.js +3 -3
  199. package/dist/runner/held.d.ts +5 -2
  200. package/dist/runner/journal-kinds.d.ts +4 -1
  201. package/dist/runner/journal-kinds.js +22 -4
  202. package/dist/runner/learned-first.js +20 -4
  203. package/dist/runner/learning-end.d.ts +2 -8
  204. package/dist/runner/learning-end.js +11 -19
  205. package/dist/runner/live-ticker.js +7 -5
  206. package/dist/runner/loop-contract.d.ts +0 -2
  207. package/dist/runner/loop.d.ts +7 -0
  208. package/dist/runner/loop.js +1 -0
  209. package/dist/runner/main.js +12 -11
  210. package/dist/runner/mcp-claim.js +21 -5
  211. package/dist/runner/meta-tools.js +3 -2
  212. package/dist/runner/metrics.d.ts +7 -0
  213. package/dist/runner/metrics.js +19 -0
  214. package/dist/runner/model-route.d.ts +10 -7
  215. package/dist/runner/model-route.js +79 -15
  216. package/dist/runner/native-loop.js +10 -8
  217. package/dist/runner/presence.d.ts +1 -4
  218. package/dist/runner/presence.js +6 -8
  219. package/dist/runner/promotion.d.ts +25 -13
  220. package/dist/runner/promotion.js +125 -50
  221. package/dist/runner/redact.d.ts +3 -1
  222. package/dist/runner/redact.js +5 -3
  223. package/dist/runner/responses-fetch.d.ts +36 -0
  224. package/dist/runner/responses-fetch.js +511 -0
  225. package/dist/runner/run-child-host.d.ts +20 -5
  226. package/dist/runner/run-child-host.js +179 -77
  227. package/dist/runner/run-child.js +11 -4
  228. package/dist/runner/runner-check.js +5 -1
  229. package/dist/runner/runner.d.ts +2 -3
  230. package/dist/runner/runner.js +13 -9
  231. package/dist/runner/sdk-loop.js +8 -8
  232. package/dist/runner/spec-holds.d.ts +8 -1
  233. package/dist/runner/spec-holds.js +9 -4
  234. package/dist/runner/workflow-calls.d.ts +9 -0
  235. package/dist/runner/workflow-calls.js +150 -0
  236. package/dist/runner/workflow-first.d.ts +120 -32
  237. package/dist/runner/workflow-first.js +218 -94
  238. package/dist/runner/workflow-spec.js +1 -1
  239. package/dist/runs-over-store.js +8 -7
  240. package/dist/save-once.d.ts +14 -0
  241. package/dist/save-once.js +31 -0
  242. package/dist/scrub-command.d.ts +34 -31
  243. package/dist/scrub-command.js +116 -147
  244. package/dist/sdk/runs.d.ts +6 -0
  245. package/dist/sdk/runs.js +89 -10
  246. package/dist/seal-key.js +4 -4
  247. package/dist/secret-cut.d.ts +3 -0
  248. package/dist/secret-cut.js +7 -1
  249. package/dist/secret-rules.d.ts +8 -1
  250. package/dist/secret-rules.js +482 -53
  251. package/dist/secrets.d.ts +51 -9
  252. package/dist/secrets.js +311 -21
  253. package/dist/server-keys.d.ts +4 -3
  254. package/dist/server-keys.js +4 -3
  255. package/dist/server-secrets-store.js +2 -4
  256. package/dist/server.d.ts +15 -3
  257. package/dist/server.js +312 -80
  258. package/dist/share-context.d.ts +22 -0
  259. package/dist/share-context.js +76 -0
  260. package/dist/shell-lex.d.ts +105 -0
  261. package/dist/shell-lex.js +646 -0
  262. package/dist/sign-ins-store.d.ts +5 -7
  263. package/dist/sign-ins-store.js +12 -16
  264. package/dist/sign-ins.d.ts +7 -11
  265. package/dist/sign-ins.js +40 -41
  266. package/dist/skills/agentrun-serve/SKILL.md +5 -2
  267. package/dist/start-switches.d.ts +6 -5
  268. package/dist/start-switches.js +8 -4
  269. package/dist/stats.d.ts +5 -1
  270. package/dist/stats.js +1 -1
  271. package/dist/store/agent-body.js +2 -2
  272. package/dist/store/dialect.d.ts +4 -0
  273. package/dist/store/dialect.js +1 -0
  274. package/dist/store/index.d.ts +2 -2
  275. package/dist/store/index.js +1 -1
  276. package/dist/store/mcp-record-keys.d.ts +10 -0
  277. package/dist/store/mcp-record-keys.js +13 -0
  278. package/dist/store/postgres/dialect.js +2 -0
  279. package/dist/store/postgres/migrations/0029_run_launch_census_settle.sql +28 -0
  280. package/dist/store/postgres/migrations/0030_learning_ledger_epoch.sql +40 -0
  281. package/dist/store/postgres/migrations/0031_learning_ledger_calls.sql +12 -0
  282. package/dist/store/postgres/store.js +4 -0
  283. package/dist/store/schema.d.ts +33 -10
  284. package/dist/store/schema.js +70 -16
  285. package/dist/store/seal.d.ts +4 -1
  286. package/dist/store/sqlite/run-launch.d.ts +3 -10
  287. package/dist/store/sqlite/run-launch.js +12 -23
  288. package/dist/store/sqlite/run-patch.d.ts +17 -10
  289. package/dist/store/sqlite/run-patch.js +50 -13
  290. package/dist/store/sqlite/store.d.ts +3 -0
  291. package/dist/store/sqlite/store.js +116 -34
  292. package/dist/store/store-schema.js +3 -4
  293. package/dist/store/store.d.ts +67 -32
  294. package/dist/store/store.js +14 -11
  295. package/dist/store-reads/analytics.d.ts +2 -1
  296. package/dist/store-reads/analytics.js +7 -5
  297. package/dist/store-reads/learning.d.ts +35 -26
  298. package/dist/store-reads/learning.js +120 -92
  299. package/dist/store-reads/stats.d.ts +2 -2
  300. package/dist/store-reads/stats.js +13 -7
  301. package/dist/store-view.js +10 -7
  302. package/dist/suggestions.d.ts +1 -1
  303. package/dist/suggestions.js +29 -13
  304. package/dist/template-eval.d.ts +72 -9
  305. package/dist/template-eval.js +358 -64
  306. package/dist/timeline/labels.d.ts +1 -1
  307. package/dist/timeline/labels.js +4 -3
  308. package/dist/timeline/timeline.d.ts +23 -11
  309. package/dist/timeline/timeline.js +115 -31
  310. package/dist/timeline/web-calls.d.ts +8 -6
  311. package/dist/timeline/web-calls.js +10 -6
  312. package/dist/tool-gate.d.ts +13 -1
  313. package/dist/tool-gate.js +43 -3
  314. package/dist/tool-keys-store.js +2 -4
  315. package/dist/tool-keys.d.ts +11 -0
  316. package/dist/tool-keys.js +16 -0
  317. package/dist/tool-plane.d.ts +50 -11
  318. package/dist/tool-plane.js +94 -30
  319. package/dist/tools.d.ts +5 -1
  320. package/dist/tools.js +7 -7
  321. package/dist/trigger-email.js +12 -6
  322. package/dist/triggers.d.ts +15 -34
  323. package/dist/triggers.js +119 -126
  324. package/dist/validate.d.ts +8 -1
  325. package/dist/validate.js +163 -23
  326. package/dist/web-fake.d.ts +2 -1
  327. package/dist/web-fake.js +8 -6
  328. package/dist/web-fetch.d.ts +8 -6
  329. package/dist/web-fetch.js +13 -11
  330. package/dist/web-holds.d.ts +32 -0
  331. package/dist/web-holds.js +86 -0
  332. package/dist/web-run.d.ts +32 -5
  333. package/dist/web-run.js +75 -28
  334. package/dist/web-save.js +23 -12
  335. package/dist/web-search.js +14 -25
  336. package/dist/wires.d.ts +4 -3
  337. package/dist/wires.js +5 -4
  338. package/dist/workspace/archil-claim.d.ts +12 -5
  339. package/dist/workspace/archil-claim.js +45 -5
  340. package/dist/workspace/attach.js +52 -19
  341. package/dist/workspace/attached-computers.d.ts +6 -2
  342. package/dist/workspace/attached-computers.js +5 -4
  343. package/dist/workspace/computer-deps.d.ts +23 -6
  344. package/dist/workspace/computer-deps.js +35 -17
  345. package/dist/workspace/computer-for-claim.d.ts +21 -4
  346. package/dist/workspace/computer-for-claim.js +160 -54
  347. package/dist/workspace/computer-intervals.d.ts +2 -0
  348. package/dist/workspace/computer-intervals.js +1 -1
  349. package/dist/workspace/computer-janitor.d.ts +48 -14
  350. package/dist/workspace/computer-janitor.js +153 -44
  351. package/dist/workspace/computer-kept.d.ts +158 -32
  352. package/dist/workspace/computer-kept.js +288 -63
  353. package/dist/workspace/computer-providers.d.ts +8 -3
  354. package/dist/workspace/computer-providers.js +12 -5
  355. package/dist/workspace/index.d.ts +1 -1
  356. package/dist/workspace/index.js +1 -1
  357. package/dist/workspace/local.js +41 -1
  358. package/dist/workspace/mount-revoke-left.d.ts +31 -0
  359. package/dist/workspace/mount-revoke-left.js +72 -0
  360. package/dist/workspace/paired-route.js +4 -5
  361. package/dist/workspace/resolve-computer.d.ts +5 -2
  362. package/dist/workspace/resolve-computer.js +9 -3
  363. package/dist/workspace/run-end-computers.d.ts +11 -5
  364. package/dist/workspace/run-end-computers.js +153 -28
  365. package/dist/workspace/run-tools.d.ts +22 -3
  366. package/dist/workspace/run-tools.js +17 -5
  367. package/dist/workspace/run-workspace.d.ts +14 -1
  368. package/dist/workspace/run-workspace.js +34 -1
  369. package/dist/workspace/workspace.d.ts +6 -0
  370. package/package.json +12 -13
  371. package/skills/agentrun-serve/SKILL.md +5 -2
  372. package/templates/README.md +22 -6
  373. package/dist/console/assets/backend-CSAWUqtZ.js +0 -166
  374. package/dist/console/assets/index-Bwn1oTem.css +0 -1
  375. package/dist/console/assets/index-DPh29cyz.js +0 -747
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.
@@ -14,7 +14,7 @@ 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;
@@ -237,12 +249,16 @@ export const MAX_CANDIDATES = 500;
237
249
  /** The most of one instructions or skill file read, and of one agent's skill files together. */
238
250
  export const MAX_FILE_BYTES = 256 * 1024;
239
251
  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"];
252
+ /** The project's skill folders, each `<dir>/<name>/` with its SKILL.md, by where each harness keeps them. OpenCode reads
253
+ * `skill/` and `skills/` in each of its config folders, the project's `.opencode` among them. A home's own folders (its
254
+ * ~/.config/opencode, ~/.claude) are no project's, and none is read. */
255
+ export const SKILL_DIRS = [".agents/skills", ".claude/skills", ".codex/skills", ".pi/skills", ".opencode/skills", ".opencode/skill"];
242
256
  const INSTRUCTIONS = {
243
257
  "claude-agent": ["CLAUDE.md", "AGENTS.md"],
244
258
  codex: ["AGENTS.md", "CLAUDE.md"],
245
259
  pi: ["AGENTS.md", "CLAUDE.md"],
260
+ // OpenCode's rules file is AGENTS.md, CLAUDE.md where there is none.
261
+ opencode: ["AGENTS.md", "CLAUDE.md"],
246
262
  };
247
263
  const hash = (text) => createHash("sha256").update(text).digest("hex");
248
264
  /** A run's files and its subagents' are over MAX_RUN_BYTES together: the run is left out. */
@@ -269,7 +285,13 @@ export function candidatesOf(plan, env) {
269
285
  * import keep it from the same keys, or a later import would not find the run an earlier one made. */
270
286
  const redactedId = (id) => `redacted-${hash(id).slice(0, 16)}`;
271
287
  /** 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}`;
288
+ const stampOf = (size) => `${size.bytes}:${size.mtimeMs}`;
289
+ /** A listed session's own size and last write (locatorSize): its file's, or its own rows' in a database of many. What
290
+ * LIVE_MS, MAX_SESSION_BYTES, MAX_RUN_BYTES and an unchanged session go by. */
291
+ const sizeOf = (listed) => sizeNow(locatorOf(listed), listed.source);
292
+ /** locatorSize after the plan: none when it cannot be had now, as when the session is gone (the read that follows, if
293
+ * any, says why). */
294
+ const sizeNow = (locator, source) => locatorSize(locator, source).catch(() => null);
273
295
  /** Bind remote consent to the enumerated source, including archive replacements that preserve size and mtime. */
274
296
  const remoteHistoryStamp = (stats) => `${stats.dev}:${stats.ino}:${stats.size}:${stats.mtimeMs}:${stats.ctimeMs}`;
275
297
  const keptId = (envs, own = []) => {
@@ -340,12 +362,12 @@ async function findKeys(plan, add, cut, held, signal, onProgress) {
340
362
  const budget = budgetOf();
341
363
  let over = false;
342
364
  for (const entry of files) {
343
- const stats = await stat(entry.file).catch(() => null);
344
- if (stats && !fits(budget, stats.size)) {
365
+ const stats = await sizeOf(entry);
366
+ if (stats && !fits(budget, stats.bytes)) {
345
367
  over = true;
346
368
  break;
347
369
  }
348
- const part = stats ? await readSession(locatorOf(entry), listed.source, { seen }).catch(() => undefined) : undefined;
370
+ const part = stats ? await readSession(locatorOf(entry), listed.source, { seen, lookups: lookupsOf(plan) }).catch(() => undefined) : undefined;
349
371
  if (!part || !stats)
350
372
  continue;
351
373
  stamps.set(locatorKey(locatorOf(entry)), stampOf(stats));
@@ -367,7 +389,7 @@ async function findKeys(plan, add, cut, held, signal, onProgress) {
367
389
  if (!subagents)
368
390
  continue;
369
391
  for (const child of subagents) {
370
- const stats = await stat(child.file).catch(() => null);
392
+ const stats = await sizeOf(child);
371
393
  if (stats)
372
394
  stamps.set(locatorKey(locatorOf(child)), stampOf(stats));
373
395
  }
@@ -382,7 +404,7 @@ export const agentIdOf = (cwd) => `imp-${hash(`dir:${cwd}`).slice(0, 32)}`;
382
404
  /** The sessions the store holds already, as `source:session`, to their run's id: a purged run's too, so a session its
383
405
  * owner purged is never imported again. */
384
406
  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;
407
+ const sameFile = (seen, size) => seen !== undefined && seen.size === size.bytes && seen.mtime_ms === size.mtimeMs;
386
408
  /** The session files the store's imports read whole, by their path's sha256, with their run: the file stamp an import kept
387
409
  * on the run's `imported_from`, so an unchanged file is not parsed again. */
388
410
  async function filesIn(store) {
@@ -399,10 +421,15 @@ const clip = (text, max) => (text.length > max ? `${text.slice(0, max - 1)}…`
399
421
  /** What an import would take: the sessions under `home`, by project, with what it leaves out and why. Keeps no turns
400
422
  * (with `measure`, only until each session is measured), and reads no file `store`'s imports already read whole and
401
423
  * that has not changed since. */
424
+ /** What an import's reads look up once for all its files (readSession's `lookups`: a Codex fork's parent anywhere in
425
+ * its sessions), one map per plan: the one planImport read with, carried to the plan it returns. */
426
+ const planLookups = new WeakMap();
427
+ const lookupsOf = (plan) => planLookups.get(plan) ?? planLookups.set(plan, new Map()).get(plan);
402
428
  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
429
  // 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
430
  // import's run then goes by the id as kept.
405
431
  const idOf = keptId([env, stored ?? {}], own);
432
+ const lookups = new Map();
406
433
  const skipped = [];
407
434
  // Each file left out here, with the project folder its read gave, if it was read that far: what `only` goes by.
408
435
  const leftFrom = new Map();
@@ -418,30 +445,51 @@ export async function planImport({ home, sources = SOURCES, all = false, deleted
418
445
  let stopped = false;
419
446
  // Each listed session's place in the import's order (inOrder).
420
447
  const rank = new Map();
448
+ // Each subagent read here, by locatorKey, as its own subagents name it (`source:id`): what holdBack walks down.
449
+ const childIds = new Map();
450
+ // Each subagent read here whose requests name another source's session (`mirrors`), with those sessions: its run
451
+ // waits for a Claude Code session it names that is on disk but not imported now.
452
+ const mirroring = new Map();
453
+ const tie = async (locator, source, size) => {
454
+ const listed = size.bytes > MAX_SESSION_BYTES ? undefined : await readSession(locator, source, { turns: false, lookups }).catch(() => undefined);
455
+ // One over the cap is not read: its parent is what its reader tells without reading it (an OpenCode row's, a Codex
456
+ // rollout's first line).
457
+ const parent = listed ? (listed.child ? listed.parent : undefined) : (size.parent ?? (await locatorParent(locator, source)));
458
+ if (parent)
459
+ child(`${source}:${await idOf(parent, scan)}`, locator);
460
+ };
421
461
  const temps = [...new Set([tempDir, await realpath(tempDir).catch(() => tempDir)])];
422
462
  for (const source of sources) {
423
- for (const { locator, stats } of await inOrder(await sessionLocators(home, source), source)) {
463
+ // Each source's own folders where `env` puts them (CLAUDE_CONFIG_DIR, CODEX_HOME, XDG_DATA_HOME, OPENCODE_DB).
464
+ for (const { locator, size, failed } of await inOrder(await sessionLocators(home, source, { env }), source)) {
424
465
  const { file } = locator;
425
466
  if (signal?.aborted) {
426
467
  stopped = true;
427
468
  break;
428
469
  }
470
+ // One whose own size cannot be had (a database locked or damaged since it was listed) is named and passed over.
471
+ if (failed !== undefined) {
472
+ leave(unread(locatorKey(locator), failed), source);
473
+ continue;
474
+ }
429
475
  const known = seen.get(hash(locatorKey(locator)));
430
- if (sameFile(known, stats)) {
476
+ if (sameFile(known, size)) {
431
477
  already += 1;
432
478
  held.push(known.run);
433
479
  continue;
434
480
  }
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);
481
+ // The session's own last write and size (a database's sessions each their own): one live session, or a large
482
+ // database, leaves the rest of its file importable.
483
+ // Either one, when it is a subagent's, holds its run back (holdBack): the subagent is tied to its run as one read
484
+ // would tie it, by its listing while it is written, by the parent its source's stat names when it is over the cap.
485
+ const unreadAs = leftUnread(locator, size, now);
486
+ if (unreadAs) {
487
+ leave(unreadAs, source);
488
+ await tie(locator, source, size);
441
489
  continue;
442
490
  }
443
491
  // 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));
492
+ const session = await readSession(locator, source, { turns: false, lookups }).catch((error) => leave(unread(file, error), source));
445
493
  if (!session)
446
494
  continue;
447
495
  session.id = await idOf(session.id, scan);
@@ -451,29 +499,17 @@ export async function planImport({ home, sources = SOURCES, all = false, deleted
451
499
  // thread's, whichever of its files); else it counts in the totals alone, where its project would.
452
500
  if (session.child && session.parent) {
453
501
  child(`${source}:${session.parent}`, locator);
502
+ childIds.set(locatorKey(locator), `${source}:${session.id}`);
503
+ if (session.mirrors?.length)
504
+ mirroring.set(locatorKey(locator), session.mirrors);
454
505
  continue;
455
506
  }
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);
507
+ const readAs = await leftRead(session, file, temps, all, deleted);
508
+ if (readAs) {
509
+ leave(readAs, source, session.cwd);
462
510
  continue;
463
511
  }
464
512
  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
513
  if (session.child) {
478
514
  untied.push({ locator, source });
479
515
  continue;
@@ -489,12 +525,76 @@ export async function planImport({ home, sources = SOURCES, all = false, deleted
489
525
  rank.set(session, rank.size);
490
526
  project.sessions.push(session);
491
527
  }
492
- for (const { locator, of } of await childrenOf(home, source))
528
+ for (const { locator, of } of await childrenOf(home, source, { env }))
493
529
  child(locatorKey(of), locator);
494
530
  }
531
+ // A run imports only when every subagent it has, whatever its source, can be read now: one still written or over the
532
+ // cap leaves the run out with it, said, and the run comes in whole, its subagents' usage with it, once each can be.
533
+ const holds = new Map();
534
+ for (const project of projects.values()) {
535
+ const runs = new Map();
536
+ for (const session of project.sessions)
537
+ runs.set(`${session.source}:${session.id}`, [...(runs.get(`${session.source}:${session.id}`) ?? []), session]);
538
+ for (const [key, parts] of runs) {
539
+ if (!holds.has(key))
540
+ holds.set(key, await holdBack(children, parts, childIds, now));
541
+ const why = holds.get(key);
542
+ if (why)
543
+ leave({ what: locatorKey(locatorOf(parts[0])), ...why, session: key }, parts[0].source, project.cwd);
544
+ }
545
+ project.sessions = project.sessions.filter((session) => !holds.get(`${session.source}:${session.id}`));
546
+ if (!project.sessions.length)
547
+ projects.delete(project.cwd);
548
+ }
495
549
  ownRuns(projects, rank);
496
550
  // The owner's choice, once each session has its one project: a project not chosen is no part of the plan.
497
551
  const chosen = only === undefined ? undefined : new Set(only);
552
+ // A run that leaves a request to a Claude Code session (`mirrors`, its own or a subagent's) counts it there only once
553
+ // that session is saved: saved by a later import, the request would count in both. So a run whose Claude Code session
554
+ // is on disk but not imported now (still written, held back with a live subagent, in a project not chosen, or of a
555
+ // source this import does not read) waits for it, said. One whose session no import brings in as it is (over the cap,
556
+ // unreadable, a temp or gone folder, no message of the person's), or that is no file here, imports now: the request is
557
+ // its own.
558
+ const targetsOf = (parts) => [...parts.flatMap((part) => part.mirrors ?? []), ...subagentsOf(children, parts, childIds).flatMap((locator) => mirroring.get(locatorKey(locator)) ?? [])].filter((link) => link.source === "claude-code");
559
+ const waiting = [...projects.values()].flatMap((project) => byRun(project.sessions).flatMap((parts) => (targetsOf(parts).length ? [{ project, parts }] : [])));
560
+ if (waiting.length) {
561
+ const stored = store ? await importedIn(store) : new Map();
562
+ 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)));
563
+ 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"))));
564
+ const claude = await sessionLocators(home, "claude-code", { env }).catch(() => []);
565
+ const listed = new Set(claude.map((locator) => basename(locator.file, ".jsonl")));
566
+ // An import that reads no Claude Code left none of it out above: each Claude Code session a run's request ran
567
+ // through goes by the same rules here, so one no import brings in leaves the request the run's own, not a wait.
568
+ if (!sources.includes("claude-code")) {
569
+ // A target the store holds, or one of a run the store holds, decides nothing (the loop below): it is not read.
570
+ const targets = new Set(waiting.filter(({ parts }) => !stored.has(`${parts[0].source}:${parts[0].id}`)).flatMap(({ parts }) => targetsOf(parts).map((link) => link.sessionId)));
571
+ for (const locator of claude) {
572
+ const id = basename(locator.file, ".jsonl");
573
+ if (!targets.has(id) || stored.has(`claude-code:${await idOf(id, scan)}`))
574
+ continue;
575
+ const kind = await neverKind(locator, now, temps, all, deleted);
576
+ if (kind && NEVER_IN.has(kind))
577
+ never.add(id);
578
+ }
579
+ }
580
+ for (const { project, parts } of waiting) {
581
+ const key = `${parts[0].source}:${parts[0].id}`;
582
+ if (stored.has(key))
583
+ continue;
584
+ let target;
585
+ for (const link of targetsOf(parts)) {
586
+ const kept = await idOf(link.sessionId, scan);
587
+ if (listed.has(link.sessionId) && !comingIn.has(kept) && !stored.has(`claude-code:${kept}`) && !never.has(kept) && !never.has(link.sessionId))
588
+ target = kept;
589
+ }
590
+ if (target === undefined)
591
+ continue;
592
+ 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);
593
+ project.sessions = project.sessions.filter((session) => `${session.source}:${session.id}` !== key);
594
+ if (!project.sessions.length)
595
+ projects.delete(project.cwd);
596
+ }
597
+ }
498
598
  // 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
599
  // for a file left out unread (still written, over the cap, unreadable), as its first records say. A file that names
500
600
  // no folder is no chosen project's.
@@ -510,7 +610,17 @@ export async function planImport({ home, sources = SOURCES, all = false, deleted
510
610
  }
511
611
  skipped.splice(0, skipped.length, ...ofChosen);
512
612
  }
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 } : {}) };
613
+ // Each Claude Code session a request names, by the id the import keeps it as, where that is another.
614
+ const mirrorIds = new Map();
615
+ for (const project of projects.values())
616
+ for (const parts of byRun(project.sessions))
617
+ for (const { sessionId } of targetsOf(parts)) {
618
+ const kept = await idOf(sessionId, scan);
619
+ if (kept !== sessionId)
620
+ mirrorIds.set(sessionId, kept);
621
+ }
622
+ 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 } : {}) };
623
+ planLookups.set(plan, lookups);
514
624
  if (!measure)
515
625
  return plan;
516
626
  const counting = secretCut(env, SECRET_NAMES);
@@ -520,6 +630,7 @@ export async function planImport({ home, sources = SOURCES, all = false, deleted
520
630
  // This server's own secrets first, as the import takes them.
521
631
  foundKeys(own);
522
632
  const { large } = await findKeys(plan, foundKeys, counting.text, (listed) => heldBy?.get(`${listed.source}:${listed.id}`) !== undefined, signal);
633
+ const mirrored = mirrorsOf(plan, heldBy, large);
523
634
  // Measured in the import's own order, a record or response counted once across files, each session with its
524
635
  // subagents; a session the store holds already from its run, as the import counts it, not from its file now.
525
636
  for (const project of plan.projects) {
@@ -541,13 +652,13 @@ export async function planImport({ home, sources = SOURCES, all = false, deleted
541
652
  const budget = budgetOf();
542
653
  let over = false;
543
654
  for (const listed of files) {
544
- const stats = await stat(listed.file).catch(() => null);
655
+ const stats = await sizeOf(listed);
545
656
  // 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)) {
657
+ if (stats && !fits(budget, stats.bytes)) {
547
658
  over = true;
548
659
  break;
549
660
  }
550
- const part = await readSession(locatorOf(listed), listed.source, { seen: seen(listed.source) }).catch(() => undefined);
661
+ const part = await readSession(locatorOf(listed), listed.source, { seen: seen(listed.source), lookups }).catch(() => undefined);
551
662
  if (part)
552
663
  read.push(part);
553
664
  }
@@ -558,7 +669,7 @@ export async function planImport({ home, sources = SOURCES, all = false, deleted
558
669
  const parts = read.filter((part) => !ownless(part));
559
670
  if (!parts.length)
560
671
  continue;
561
- const session = merged(parts);
672
+ const session = settled(merged(parts), mirrored);
562
673
  // What the import's cut would take out of it (its turns, its first message): the dry run's count.
563
674
  counting.json(session.turns);
564
675
  if (session.firstPrompt)
@@ -570,7 +681,7 @@ export async function planImport({ home, sources = SOURCES, all = false, deleted
570
681
  });
571
682
  if (!subagents)
572
683
  continue;
573
- found.push({ source: session.source, agent: project.agentId, ...measured(session, subagents) });
684
+ found.push({ source: session.source, agent: project.agentId, ...measured(session, subagents.map((child) => settled(child, mirrored))) });
574
685
  }
575
686
  }
576
687
  // 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 +698,35 @@ export async function planImport({ home, sources = SOURCES, all = false, deleted
587
698
  for (const [path, text] of Object.entries(files.skills))
588
699
  (counting.text(path), counting.text(text));
589
700
  }
590
- return { ...plan, found, secretsFound: counting.text.removed };
701
+ const withFound = { ...plan, found, secretsFound: counting.text.removed };
702
+ planLookups.set(withFound, lookups);
703
+ return withFound;
591
704
  }
592
705
  /** The subagents tied to no session: each one's tokens and tool calls, for a summary's totals, each response once. */
593
706
  export async function untiedFound(plan) {
707
+ const mirrored = mirrorsOf(plan);
594
708
  const seen = new Map();
595
709
  const counted = (source) => seen.get(source) ?? seen.set(source, new Set()).get(source);
596
710
  // A thread resumed in a second file of the same id is one: its own subagents, which name it, count once with it.
597
711
  const threads = new Map();
598
712
  for (const { locator, source } of plan.untied) {
599
- const stats = await stat(locator.file).catch(() => null);
600
- if (!stats || stats.size > MAX_SESSION_BYTES)
713
+ const stats = await sizeNow(locator, source);
714
+ if (!stats || stats.bytes > MAX_SESSION_BYTES)
601
715
  continue;
602
- const session = await readSession(locator, source, { seen: counted(source) }).catch(() => undefined);
716
+ const session = await readSession(locator, source, { seen: counted(source), lookups: lookupsOf(plan) }).catch(() => undefined);
603
717
  if (session)
604
718
  threads.set(`${source}:${session.id}`, [...(threads.get(`${source}:${session.id}`) ?? []), session]);
605
719
  }
606
720
  const found = [];
607
721
  for (const parts of threads.values()) {
608
- const session = merged(parts);
722
+ const session = settled(merged(parts), mirrored);
609
723
  // One whose own subagents are over the cap together counts for itself alone: the totals never hold more than a run.
610
724
  const children = await readChildren(plan, session, parts, counted(session.source), budgetOf()).catch((error) => {
611
725
  if (!(error instanceof RunTooLarge))
612
726
  throw error;
613
727
  return [];
614
728
  });
615
- found.push({ source: session.source, agent: "", untied: true, metrics: metricsOf(session, children) });
729
+ found.push({ source: session.source, agent: "", untied: true, metrics: metricsOf(session, children.map((child) => settled(child, mirrored))) });
616
730
  }
617
731
  return found;
618
732
  }
@@ -696,33 +810,124 @@ function merged(parts) {
696
810
  /** A session that holds only records an earlier file of the import holds (a resumed session's copy of them). */
697
811
  const ownless = (session) => session.copies > 0 && !session.turns.some((turn) => turn.role !== "note");
698
812
  /** 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. */
813
+ * already (each answer's response id and its later parts', and each entry's record ids, as its transcript keeps them:
814
+ * Claude Code's and Copilot's; an OpenCode answer's fingerprint and its prompts', what a 1.x fork's copies of them are
815
+ * keyed by), then each file's as it is read. */
701
816
  async function seenIn(store, agentId) {
702
817
  const bySource = new Map();
703
818
  const seen = (source) => bySource.get(source) ?? bySource.set(source, new Set()).get(source);
704
819
  if (!store || !(await store.agents.get(agentId)))
705
820
  return seen;
706
821
  for (const run of await store.runs.list({ agentId })) {
707
- if (run.importedFrom?.source !== "claude-code")
822
+ const source = run.importedFrom?.source;
823
+ if (source !== "claude-code" && source !== "opencode" && source !== "copilot")
708
824
  continue;
709
825
  for (const entry of (await journalEntries(store.readJournal(run.id), ctx))) {
710
826
  const id = entry.model?.[0]?.responseId;
827
+ const { record_uuids: uuids, record_keys: keys } = (entry.data ?? {});
828
+ if (source === "opencode") {
829
+ // A request's fingerprint is its answer's response id; a prompt's, its record id.
830
+ for (const key of [id, ...(Array.isArray(uuids) ? uuids : [])])
831
+ if (typeof key === "string" && key.startsWith("o:"))
832
+ seen("opencode").add(key);
833
+ continue;
834
+ }
835
+ const into = seen(source);
711
836
  if (typeof id === "string" && id)
712
- seen("claude-code").add(`m:${id}`);
837
+ into.add(`m:${id}`);
713
838
  // A run imported before a request's key held its request id (message id:request id) keeps the bare message id:
714
839
  // 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;
840
+ if (source === "claude-code" && typeof id === "string" && id && !id.includes(":"))
841
+ into.add(`l:${id}`);
718
842
  if (Array.isArray(uuids))
719
843
  for (const uuid of uuids)
720
844
  if (typeof uuid === "string")
721
- seen("claude-code").add(`u:${uuid}`);
845
+ into.add(`u:${uuid}`);
846
+ if (Array.isArray(keys))
847
+ for (const key of keys)
848
+ if (typeof key === "string" && key)
849
+ into.add(`m:${key}`);
722
850
  }
723
851
  }
724
852
  return seen;
725
853
  }
854
+ /** Why a session is left out before it is read, if it is: still written (live), or over the cap (large). */
855
+ 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;
856
+ /** Why a session read (turns: false) is no project's run, if it is not: no project folder, no message of the person's
857
+ * (but with `all`), its project a temp folder (first, gone or not: only `all` brings it in, as the left-out line says)
858
+ * or gone (but with `all` or `deleted`). */
859
+ async function leftRead(session, file, temps, all, deleted) {
860
+ const { cwd, source, id } = session;
861
+ if (!cwd)
862
+ return { what: file, why: "no project directory in it", kind: "no-project" };
863
+ if (!all && session.users === 0 && !session.child)
864
+ return { what: file, why: "no message of the person's", kind: "no-words", session: `${source}:${id}` };
865
+ if (all)
866
+ return undefined;
867
+ if (temps.some((temp) => cwd === temp || cwd.startsWith(temp + sep)))
868
+ return { what: file, why: `its project ${cwd} is a temp directory`, kind: "temp", session: `${source}:${id}` };
869
+ const there = await lstat(cwd).catch(() => null);
870
+ if (!there?.isDirectory() && !deleted)
871
+ return { what: file, why: `its project ${cwd} is gone`, kind: "gone", session: `${source}:${id}` };
872
+ return undefined;
873
+ }
874
+ /** How planImport would leave a Claude Code session out, by the same rules (leftUnread, unread, leftRead), when it is
875
+ * not one of the sources it reads: none when it would be a run, or a subagent's part of one. */
876
+ async function neverKind(locator, now, temps, all, deleted) {
877
+ const size = await locatorSize(locator, "claude-code").catch(() => undefined);
878
+ if (size === null)
879
+ return undefined;
880
+ if (size === undefined)
881
+ return "unread";
882
+ const unreadAs = leftUnread(locator, size, now);
883
+ if (unreadAs)
884
+ return unreadAs.kind;
885
+ const session = await readSession(locator, "claude-code", { turns: false }).catch(() => undefined);
886
+ if (!session)
887
+ return "unread";
888
+ if (session.child && session.parent)
889
+ return undefined;
890
+ return (await leftRead(session, locator.file, temps, all, deleted))?.kind;
891
+ }
892
+ /** Why a Claude Code session is left out that no later import changes as it is: a request another run leaves to it
893
+ * (`mirrors`) counts in that run. */
894
+ const NEVER_IN = new Set(["large", "unread", "no-words", "temp", "gone", "no-project"]);
895
+ const LIVE_CHILD = { why: "a subagent of it was written in the last 10 minutes: it comes in with it", kind: "live" };
896
+ const LARGE_CHILD = { why: `a subagent of it is over ${MAX_SESSION_BYTES} bytes`, kind: "large" };
897
+ /** A run's subagents, theirs, and so on down, each once (the import's children relation, as readChildren walks it):
898
+ * `childIds` names each subagent the plan read, so its own subagents are found. */
899
+ function subagentsOf(children, parts, childIds) {
900
+ const out = [];
901
+ const visited = new Set();
902
+ const under = (owner) => {
903
+ for (const locator of children.get(owner) ?? []) {
904
+ const key = locatorKey(locator);
905
+ if (visited.has(key))
906
+ continue;
907
+ visited.add(key);
908
+ out.push(locator);
909
+ const id = childIds.get(key);
910
+ if (id !== undefined)
911
+ under(id);
912
+ }
913
+ };
914
+ for (const part of parts)
915
+ under(locatorKey(locatorOf(part)));
916
+ under(`${parts[0].source}:${parts[0].id}`);
917
+ return out;
918
+ }
919
+ /** Why a run waits, if it does: the first of its subagents (subagentsOf) that cannot be read now by its size now: still
920
+ * written, or over the cap. */
921
+ async function holdBack(children, parts, childIds, now) {
922
+ for (const locator of subagentsOf(children, parts, childIds)) {
923
+ const size = await sizeNow(locator, parts[0].source);
924
+ if (size && size.bytes > MAX_SESSION_BYTES)
925
+ return LARGE_CHILD;
926
+ if (size && now - size.mtimeMs < LIVE_MS)
927
+ return LIVE_CHILD;
928
+ }
929
+ return undefined;
930
+ }
726
931
  /** A run's subagents, theirs, and so on down, each file once, read with the import's `seen`: those beside each of its
727
932
  * files (Claude Code's), and those naming its thread (Codex's, whichever of its files they ran under). One gone or
728
933
  * 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 +941,14 @@ async function readChildren(plan, session, parts, seen, budget) {
736
941
  if (visited.has(key))
737
942
  continue;
738
943
  visited.add(key);
739
- const stats = await stat(locator.file).catch(() => null);
944
+ const stats = await sizeNow(locator, session.source);
740
945
  if (!stats)
741
946
  continue;
742
947
  // 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
948
  // No subagent is passed over for its size: the run would be kept without its usage.
744
- if (!fits(budget, stats.size))
949
+ if (!fits(budget, stats.bytes))
745
950
  throw new RunTooLarge();
746
- const child = await readSession(locator, session.source, { seen }).catch(() => undefined);
951
+ const child = await readSession(locator, session.source, { seen, lookups: lookupsOf(plan) }).catch(() => undefined);
747
952
  if (!child)
748
953
  continue;
749
954
  out.push(child);
@@ -760,12 +965,26 @@ async function readChildren(plan, session, parts, seen, budget) {
760
965
  * its cost (none known: null), as a request's cost is written with no answer (REQUEST_COST). The timeline shows none of
761
966
  * them, and its usage row, the run's cost and runMetricsOf all count each one. */
762
967
  const subagentMarks = (children) => children.flatMap((child) => child.turns.flatMap((turn) => {
763
- if (turn.role !== "assistant")
968
+ if (turn.role !== "assistant" || turn.mirrors)
764
969
  return [];
765
970
  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 } : {}) } }];
971
+ // A failed request's counts are its own, zeros included, as its answer's are (entryOf); so are a folded one's.
972
+ 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
973
  }));
974
+ /** The sessions a request may be counted in instead of its own (mirroredIn): each the plan imports (but those over the
975
+ * run's cap, `large`), and each the store holds already. A request OpenCode ran through Claude Code is that Claude Code
976
+ * session's when either holds it. */
977
+ 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);
978
+ /** A session as a run counts it, read whole: a turn whose request `mirrored` gives to another session keeps its `mirrors`
979
+ * (shown, counted nothing: entryOf), any other loses it; its cost is its own requests' (ownRequests). */
980
+ function settled(session, mirrored) {
981
+ const answers = session.turns.filter((turn) => turn.role === "assistant");
982
+ for (const answer of answers)
983
+ if (answer.mirrors && !mirrored(answer))
984
+ delete answer.mirrors;
985
+ session.costUsd = ownRequests(answers, session.costUsd, mirrored).cost;
986
+ return session;
987
+ }
769
988
  /** A session's entries as its transcript holds them, its subagents' requests with them (subagentMarks). */
770
989
  const runEntries = (session, children) => [...entriesOf(session), ...subagentMarks(children)];
771
990
  /** What a session used, its subagents' requests with it: runMetricsOf of its entries, and its subagents' models and tool
@@ -919,11 +1138,12 @@ export async function projectFiles(cwd, skipped) {
919
1138
  }
920
1139
  return { instructions, skills };
921
1140
  }
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. */
1141
+ /** A turn's transcript entry, with the source's ids of the records it was read from (`record_uuids`) and of a request's
1142
+ * later parts (`record_keys`, Turn.keys): a later import counts a copy of them once. */
924
1143
  const message = (turn, model) => {
925
1144
  const written = entryOf(turn, model);
926
- return turn.uuids?.length ? { ...written, data: { ...written.data, record_uuids: turn.uuids } } : written;
1145
+ const ids = { ...(turn.uuids?.length ? { record_uuids: turn.uuids } : {}), ...(turn.role === "assistant" && turn.keys?.length ? { record_keys: turn.keys } : {}) };
1146
+ return Object.keys(ids).length ? { ...written, data: { ...written.data, ...ids } } : written;
927
1147
  };
928
1148
  const entryOf = (turn, model) => {
929
1149
  if (turn.role === "user")
@@ -978,11 +1198,15 @@ const entryOf = (turn, model) => {
978
1198
  ...(cacheWrite1h !== undefined ? { cacheWrite1h } : {}),
979
1199
  totalTokens: input + output + cacheRead + cacheWrite,
980
1200
  cost: cost === undefined ? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } : { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: cost },
1201
+ // Its zeros are counted in a later request of the session (the source wrote a total): known, never unmetered.
1202
+ ...(turn.folded ? { folded: true } : {}),
981
1203
  },
982
1204
  // A failed request's zero counts are its counts, as a live run's failed request's are.
983
1205
  ...(turn.error !== undefined ? { stopReason: "error", errorMessage: turn.error } : { stopReason: turn.calls.length ? "toolUse" : "stop" }),
984
1206
  timestamp: turn.at,
985
1207
  },
1208
+ // A request another run of the import counts (settled kept its `mirrors`): shown here, counted there.
1209
+ ...(turn.mirrors ? { data: { mirrors: { source: turn.mirrors.source, session: turn.mirrors.sessionId } } } : {}),
986
1210
  };
987
1211
  };
988
1212
  /** The entries `message` makes of a session's turns, as a transcript holds them. */
@@ -1032,7 +1256,7 @@ async function estimateOf(entries, catalog) {
1032
1256
  return undefined;
1033
1257
  // Each answer's request at its own provider's entry, as @parcha/agentrun-import prices a session's totals.
1034
1258
  const requests = entries.flatMap((entry) => {
1035
- const answer = entry.kind === "pi.assistant" ? entry.model?.[0] : undefined;
1259
+ const answer = entry.kind === "pi.assistant" && entry.data?.mirrors === undefined ? entry.model?.[0] : undefined;
1036
1260
  if (!answer?.usage)
1037
1261
  return [];
1038
1262
  const { input = 0, output = 0, cacheRead = 0, cacheWrite = 0, cacheWrite1h } = answer.usage;
@@ -1093,8 +1317,8 @@ function runTitleOf(session, cut) {
1093
1317
  * `whsec_` from elsewhere). The per-run door token is gone (the runner cutover deleted it). A sealed value that does not
1094
1318
  * open is said to `say` (the webhook's secret once, naming the data directory): the import goes on, and does not cut it. */
1095
1319
  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`);
1320
+ // An import and a scrub run offline: they open the key from the server's data directory, so that is where they point.
1321
+ 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
1322
  return (await openServerSecretsOverStore(store, data, env, TRIGGER_ADAPTERS, say)).secrets.values();
1099
1323
  }
1100
1324
  /** 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 +1342,134 @@ export async function runImport(store, plan, options) {
1118
1342
  };
1119
1343
  // Every key of the import is known before anything of it is written.
1120
1344
  const known = await findKeys(plan, add, text, (listed) => held.get(`${listed.source}:${listed.id}`) !== undefined, options.signal, options.onProgress);
1345
+ // A request another session counts (one the store holds, or one this import has saved) counts there, not again here:
1346
+ // one whose session is not saved (unreadable, too large, stopped before it) counts in its own run.
1347
+ const saved = new Set(held.keys());
1348
+ const mirrored = mirroredIn(saved, plan.mirrorIds);
1121
1349
  const toTake = options.onProgress ? plan.projects.reduce((n, p) => n + byRun(p.sessions).length, 0) : 0;
1122
1350
  let written = 0;
1123
1351
  if (!options.signal?.aborted)
1124
1352
  options.onProgress?.("write", 0, toTake);
1125
1353
  const scannedAs = known.stamps;
1126
1354
  const epoch0 = new Date(0).toISOString();
1355
+ /** One run of a project, written to the store; "stopped" when the import is stopped before it. */
1356
+ const writeRun = async ({ project, line, revisions, seen }, files) => {
1357
+ options.onProgress?.("write", written++, toTake);
1358
+ if (options.signal?.aborted) {
1359
+ report.stopped = true;
1360
+ return "stopped";
1361
+ }
1362
+ const listed = files[0];
1363
+ // A run the store holds already is left as it is: importRun is atomic, so a held run is a whole run.
1364
+ if (held.get(`${listed.source}:${listed.id}`) !== undefined) {
1365
+ line.already += 1;
1366
+ return;
1367
+ }
1368
+ // A run over MAX_RUN_BYTES (found so by the scan above, or grown so since) is left out whole, and said.
1369
+ if (known.large.has(`${listed.source}:${listed.id}`)) {
1370
+ report.skipped.push(tooLarge(listed));
1371
+ return;
1372
+ }
1373
+ const budget = budgetOf();
1374
+ let over = false;
1375
+ // Each of its files, in order. The first's size and time before its read: a file that changes during it is read
1376
+ // again next time.
1377
+ const parts = [];
1378
+ // Every file of it read: one holding only copies adds no records, but its subagents' folder is read with the rest.
1379
+ const searched = [];
1380
+ let read;
1381
+ // The session's own title as the file written last holds it: a moved copy's /rename too, though its turns are
1382
+ // copies the import leaves out.
1383
+ let titled;
1384
+ let changed = false;
1385
+ for (const entry of files) {
1386
+ const { file } = entry;
1387
+ const key = locatorKey(locatorOf(entry));
1388
+ const stats = await sizeOf(entry);
1389
+ if (stats && !fits(budget, stats.bytes)) {
1390
+ over = true;
1391
+ break;
1392
+ }
1393
+ 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" });
1394
+ if (!part || !stats)
1395
+ continue;
1396
+ searched.push(part);
1397
+ if (part.sourceTitle !== undefined && (!titled || stats.mtimeMs >= titled.at))
1398
+ titled = { at: stats.mtimeMs, title: part.sourceTitle };
1399
+ // A file of it holding only copies adds nothing to it.
1400
+ if (ownless(part)) {
1401
+ report.skipped.push({ what: file, why: "holds only records of sessions imported already", kind: "copies" });
1402
+ continue;
1403
+ }
1404
+ read ??= { path_sha256: hash(key), size: stats.bytes, mtime_ms: stats.mtimeMs };
1405
+ parts.push(part);
1406
+ if (scannedAs.get(key) !== stampOf(stats))
1407
+ changed = true;
1408
+ }
1409
+ if (over) {
1410
+ report.skipped.push(tooLarge(listed));
1411
+ return;
1412
+ }
1413
+ if (!read)
1414
+ return;
1415
+ const session = settled(merged(parts), mirrored);
1416
+ if (titled)
1417
+ session.sourceTitle = titled.title;
1418
+ // A file of it changed since the scan above (a session still being written): what it holds now, read through
1419
+ // secretlint again before any of it is cut.
1420
+ if (changed)
1421
+ add(await keysInSessions(parts));
1422
+ // Its id as the plan keeps it (a key in it is one secretlint finds in what was read, the id among it); one
1423
+ // holding a key counts among the keys removed.
1424
+ const keptAs = text(session.id) === session.id ? session.id : redactedId(session.id);
1425
+ session.id = keptAs;
1426
+ const subagents = await readChildren(plan, session, searched, seen(listed.source), budget).catch((error) => {
1427
+ if (!(error instanceof RunTooLarge))
1428
+ throw error;
1429
+ report.skipped.push(tooLarge(listed));
1430
+ });
1431
+ if (!subagents)
1432
+ return;
1433
+ for (const child of subagents)
1434
+ settled(child, mirrored);
1435
+ const moved = await Promise.all(subagents.map(async (child) => scannedAs.get(locatorKey(locatorOf(child))) !== stampOf((await sizeOf(child)) ?? { bytes: -1, mtimeMs: -1 })));
1436
+ if (moved.some(Boolean))
1437
+ add(await keysInSessions(subagents));
1438
+ // The transcript as the store's own write batches, each string cut; its subagents' requests marked after its turns,
1439
+ // so its timeline's usage row counts what its metrics do, one number for the run.
1440
+ const { batches, entries } = transcriptOf(session, json, subagents);
1441
+ const metrics = { ...withChildren(runMetricsOf(entries), subagents.map((child) => runMetricsOf(entriesOf(child)))), activeMs: session.activeMs, ...(session.effort ? { effort: session.effort } : {}) };
1442
+ // Its cost with its subagents' where the source writes theirs apart (withSubagentCosts): unknown when one is.
1443
+ const costUsd = withSubagentCosts(session.source, session.costUsd, subagents.map((child) => child.costUsd));
1444
+ // A session its source did not price: the catalog's estimate, beside its cost (unknown), never written as it.
1445
+ const estimate = costUsd === undefined ? await estimateOf([...entries, ...subagents.flatMap(entriesOf)], catalog) : undefined;
1446
+ if (estimate !== undefined)
1447
+ Object.assign(metrics, { costUsdEst: estimate, costBasis: "catalog" });
1448
+ const answer = session.turns.findLast((t) => t.role === "assistant" && t.text)?.text;
1449
+ // Cut, then put on one line and clipped: a key the clip cut short, or a passphrase whose spaces were changed, would
1450
+ // match no cut.
1451
+ const title = clip(text(runTitleOf(session, text)).replace(/\s+/g, " ").trim(), 120);
1452
+ await store.importRun({
1453
+ id: randomUUID(),
1454
+ agentId: project.agentId,
1455
+ revisionId: revisions.get(session.source),
1456
+ importedFrom: { source: session.source, session: session.id, file: read },
1457
+ launch: { body: launchBody({ input: { content: text(session.firstPrompt ?? "") }, title, place: { mode: "runner" } }) },
1458
+ // An imported session is ended as it ended: a plain completion reads as 'ended', a stop or a failure as its own.
1459
+ state: session.state === "completed" ? "ended" : session.state,
1460
+ ...(costUsd !== undefined ? { costUsd } : {}),
1461
+ ...((answer ?? session.titleText) ? { summary: text(answer ?? session.titleText) } : {}),
1462
+ metrics,
1463
+ startedAt: Date.parse(session.startedAt ?? epoch0),
1464
+ endedAt: Date.parse(session.endedAt ?? session.startedAt ?? epoch0),
1465
+ transcript: batches,
1466
+ });
1467
+ line.runs += 1;
1468
+ // Saved: a request another run leaves to it (`mirrors`) is its from now on.
1469
+ saved.add(`${listed.source}:${listed.id}`);
1470
+ return undefined;
1471
+ };
1472
+ const runs = [];
1127
1473
  for (const project of plan.projects) {
1128
1474
  if (options.signal?.aborted) {
1129
1475
  report.stopped = true;
@@ -1171,117 +1517,21 @@ export async function runImport(store, plan, options) {
1171
1517
  const line = { id: project.agentId, name: project.name, cwd: project.cwd, created, runs: 0, already: 0 };
1172
1518
  // A record or response counted once across the import's files, those its runs here hold already included.
1173
1519
  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
- }
1520
+ const place = { project, line, revisions, seen };
1521
+ for (const files of byRun(project.sessions))
1522
+ runs.push({ place, files });
1283
1523
  report.agents.push(line);
1284
1524
  }
1525
+ // Claude Code's runs first: a request another run leaves to one of its sessions (`mirrors`, an OpenCode session's own
1526
+ // 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
1527
+ // order: an OpenCode session before its later forks, whose copies of its records are its, its subagents read with it.
1528
+ for (const first of [true, false])
1529
+ for (const { place, files } of runs) {
1530
+ if ((files[0].source === "claude-code") !== first)
1531
+ continue;
1532
+ if (report.stopped || (await writeRun(place, files)) === "stopped")
1533
+ break;
1534
+ }
1285
1535
  report.secretsRemoved = text.removed;
1286
1536
  return report;
1287
1537
  }
@@ -1293,6 +1543,7 @@ const LEFT_OUT = {
1293
1543
  live: (n) => `${counted(n, "session")} still being written: ${n === 1 ? "it comes" : "they come"} in next time`,
1294
1544
  "no-words": (n) => `${counted(n, "session")} with no message of yours`,
1295
1545
  "no-project": (n) => `${counted(n, "file")} that ${n === 1 ? "is not a session" : "are not sessions"} (no project folder in ${n === 1 ? "it" : "them"})`,
1546
+ 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
1547
  large: (n) => `${counted(n, "session")} over ${MAX_SESSION_BYTES / 1024 / 1024} MB`,
1297
1548
  unread: (n) => `${counted(n, "session file")} that could not be read`,
1298
1549
  vanished: (n) => `${counted(n, "session file")} gone since ${n === 1 ? "it was" : "they were"} counted`,