@yuriai/web 0.2.32-beta.5 → 0.2.32-beta.6

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 (170) hide show
  1. package/README.md +18 -0
  2. package/dist/assets/{AgentAvatar-DG1RbFtI.js → AgentAvatar-BPGtFSJl.js} +1 -1
  3. package/dist/assets/{AssistantContactStatus-CzPxX6kn.js → AssistantContactStatus-aUqr2ugb.js} +3 -3
  4. package/dist/assets/{AssistantUnreadBadge-BoimAuZB.js → AssistantUnreadBadge-DrGzknrO.js} +1 -1
  5. package/dist/assets/{AssistantView-DRa5_WqV.js → AssistantView-GTh6h8B4.js} +1 -1
  6. package/dist/assets/{DiagramView-DBNv9eLT.js → DiagramView-CLxCIzOU.js} +1 -1
  7. package/dist/assets/{FadeInOnReveal-Bmxvkrf4.js → FadeInOnReveal-DoQ1DHcy.js} +1 -1
  8. package/dist/assets/{GuiPluginSurface-o7Ay34vJ.js → GuiPluginSurface-Cnyb0Yg6.js} +1 -1
  9. package/dist/assets/{GuiPluginWindow-CwP_vUoC.js → GuiPluginWindow-CWjwMY19.js} +1 -1
  10. package/dist/assets/Icon-wD7peplo.js +1 -0
  11. package/dist/assets/{ImageLoadingPlaceholder-DlosWH_9.js → ImageLoadingPlaceholder-cfSg1uO0.js} +1 -1
  12. package/dist/assets/{LoadingImage-D9r0ukc0.js → LoadingImage-DTlBKb0t.js} +1 -1
  13. package/dist/assets/{MarkdownRenderer-Bq8Gj6CE.js → MarkdownRenderer-QhegFBTR.js} +2 -2
  14. package/dist/assets/{MarkdownRendererImpl-CVRLtLB1.js → MarkdownRendererImpl-rflXjuIs.js} +1 -1
  15. package/dist/assets/{MarkstreamRendererImpl-BOmhW47N.js → MarkstreamRendererImpl-DGuW5ssC.js} +1 -1
  16. package/dist/assets/{MobileDetailNavigation-HZ6caX7w.js → MobileDetailNavigation-DpEvfH1k.js} +1 -1
  17. package/dist/assets/{MobileResizableSheet-vAenroLZ.js → MobileResizableSheet-3pSxhm6y.js} +1 -1
  18. package/dist/assets/{MobileShareBridge-DTCxgcOl.js → MobileShareBridge-DiIVhlyc.js} +1 -1
  19. package/dist/assets/MobileTabPageHeader-eWPfDPR9.js +2 -0
  20. package/dist/assets/{MultiRunWindow-DgpwdrOT.js → MultiRunWindow-ByORgIWm.js} +1 -1
  21. package/dist/assets/{OnboardingScreen-DNlK3zfZ.js → OnboardingScreen-De74T2ws.js} +1 -1
  22. package/dist/assets/{OverlayScrollbar-W17unuIx.js → OverlayScrollbar-C1VJiQk-.js} +1 -1
  23. package/dist/assets/{SettingsView-BCCVFcMo.js → SettingsView-H9vzfUh1.js} +12 -12
  24. package/dist/assets/{SettingsWindow-J6K3qs_9.js → SettingsWindow-CdUQZdrH.js} +1 -1
  25. package/dist/assets/SetupTourDialog-DJQC2v_9.js +1 -0
  26. package/dist/assets/SetupTourDialog-DrL_4ODI.css +1 -0
  27. package/dist/assets/{TerminalView-DvRoa8my.js → TerminalView-X8tMXHjR.js} +1 -1
  28. package/dist/assets/{ToolOutputDialog-cf_VcwJk.js → ToolOutputDialog-DzAxB4FS.js} +1 -1
  29. package/dist/assets/{VoiceSettings-Sm4gB-j5.js → VoiceSettings-CnYY2qY_.js} +2 -2
  30. package/dist/assets/{YuriLogo-XH6UGXtF.js → YuriLogo-kLl6rb2d.js} +1 -1
  31. package/dist/assets/YuriWordmark-DHYo0FlR.js +1 -0
  32. package/dist/assets/{appThemeRegistry-zoeqTiCb.js → appThemeRegistry-DIjRw0x6.js} +1 -1
  33. package/dist/assets/{button-CyJvQsp5.js → button-DSfiaJr4.js} +1 -1
  34. package/dist/assets/{capgoAdapter-Doqr12Eo.js → capgoAdapter-cbndHe7B.js} +1 -1
  35. package/dist/assets/checkbox-cWs92MsM.js +1 -0
  36. package/dist/assets/{collapsible-CXjDO6DW.js → collapsible-AUQp4jpe.js} +1 -1
  37. package/dist/assets/{context-menu-BajfnPcW.js → context-menu-DwQvyFO2.js} +1 -1
  38. package/dist/assets/{diagram-_Js3imTf.js → diagram-BTa5MQro.js} +1 -1
  39. package/dist/assets/{dialog-Bapd6e10.js → dialog-gWs6IrfL.js} +1 -1
  40. package/dist/assets/{es-CBhZ80Z7.js → es-mX3KOqnq.js} +1 -1
  41. package/dist/assets/{fileMentionTouchSelection-BqGxOZhB.js → fileMentionTouchSelection-plcnc8He.js} +1 -1
  42. package/dist/assets/{fr-D9s0sHDF.js → fr-DpWAkfly.js} +1 -1
  43. package/dist/assets/{gitApi-BZT4-6oC.js → gitApi-B9CzBfkU.js} +1 -1
  44. package/dist/assets/historyImportQueries-DXif2xV2.js +1 -0
  45. package/dist/assets/host-z9PU8q1e.js +1 -0
  46. package/dist/assets/{input-SCAHBeSU.js → input-D2qPeIPD.js} +1 -1
  47. package/dist/assets/insertionBoundaries-mB_fOUPv.js +1 -0
  48. package/dist/assets/{ja-BXQ3ox8H.js → ja-BBtK3t8l.js} +1 -1
  49. package/dist/assets/{ko-DlUti1wK.js → ko-Cwp3wC4W.js} +1 -1
  50. package/dist/assets/main-GmcShJwn.js +169 -0
  51. package/dist/assets/main-PMsuxOz8.js +2 -0
  52. package/dist/assets/{markdownHeightCache-B3MTnGA8.js → markdownHeightCache-Cinxvo8I.js} +1 -1
  53. package/dist/assets/{mcpQueries-BV_4aVO7.js → mcpQueries-D4D9YExA.js} +1 -1
  54. package/dist/assets/miniChat-D6sCXrvt.js +2 -0
  55. package/dist/assets/mobile-BT_KeI5P.js +2 -0
  56. package/dist/assets/{mobileBackNavigation-dXm_DT4M.js → mobileBackNavigation-uUEjrscy.js} +1 -1
  57. package/dist/assets/multirun-T_ppFdUy.js +3 -0
  58. package/dist/assets/{native-config-DPhDkRHe.js → native-config-BuFjRBaY.js} +1 -1
  59. package/dist/assets/{pl-B7LIbV2C.js → pl-Ccedjy5w.js} +1 -1
  60. package/dist/assets/{projectMeta-DOi5DwXK.js → projectMeta-FCtpvvba.js} +1 -1
  61. package/dist/assets/{pt-BR-DyusczdZ.js → pt-BR-M2O45bRx.js} +1 -1
  62. package/dist/assets/{pwa-CEIk_CAR.js → pwa-CT5wGYKz.js} +1 -1
  63. package/dist/assets/{queue-abort-optimistic-m5rVgHjT.js → queue-abort-optimistic-Dqb0K-4o.js} +1 -1
  64. package/dist/assets/react-a6PrrNTm.js +1 -0
  65. package/dist/assets/{readiness-DcxDHTFv.js → readiness-B2YFCzzO.js} +1 -1
  66. package/dist/assets/{renderElectronMiniChatApp-DMHtUbjY.js → renderElectronMiniChatApp-oHllm8xZ.js} +2 -2
  67. package/dist/assets/{renderMobileApp-C4tIs0O8.js → renderMobileApp-BHHmg4QP.js} +7 -7
  68. package/dist/assets/{runtimeConfig-zOTrRG4k.js → runtimeConfig-7V2FCxSF.js} +1 -1
  69. package/dist/assets/runtimeEndpointReset-RgJe46-h.js +149 -0
  70. package/dist/assets/{select-CeddPgN5.js → select-BOlDxL_9.js} +1 -1
  71. package/dist/assets/sessionLookup-Fwx-W5l-.js +1 -0
  72. package/dist/assets/{sortable-tabs-strip-D474PwS8.js → sortable-tabs-strip-CtkfOIVC.js} +1 -1
  73. package/dist/assets/{speechSettingsQueries-BnEpSqr1.js → speechSettingsQueries-BjBvcUMN.js} +1 -1
  74. package/dist/assets/src-C5Lsul_L.css +2 -0
  75. package/dist/assets/{store-Diaywtmi.js → store-BMijqCTE.js} +3 -3
  76. package/dist/assets/{textarea-CWQIq-Mn.js → textarea-Cspgldlr.js} +1 -1
  77. package/dist/assets/{tooltip-D3WmiZ7G.js → tooltip-DBb-UCMU.js} +1 -1
  78. package/dist/assets/tour-DzjTres6.js +1 -0
  79. package/dist/assets/{types-C1kMTm4R.js → types-C1fTHpjE.js} +1 -1
  80. package/dist/assets/{uk-BrwM67Dh.js → uk-skNzlwtr.js} +1 -1
  81. package/dist/assets/{useAppFontEffects-C_bov7Lj.js → useAppFontEffects-BIioYkKK.js} +54 -54
  82. package/dist/assets/useDesktopWindowControlsLayout-BO0Lolpp.js +1 -0
  83. package/dist/assets/{useDictation-C-waWdAq.js → useDictation-CwZ6a6i7.js} +1 -1
  84. package/dist/assets/{useEffectiveDirectory-53AP8Okc.js → useEffectiveDirectory-Bqgyt9OS.js} +1 -1
  85. package/dist/assets/{useMobileNavigationStore-B2WlZQtk.js → useMobileNavigationStore-BGHhBg7N.js} +13 -13
  86. package/dist/assets/{usePluginsStore-BB0d0oJj.js → usePluginsStore-DT2-z09d.js} +1 -1
  87. package/dist/assets/{useWorkerHighlightedLines-BfnQF-od.js → useWorkerHighlightedLines-B8ypYliw.js} +1 -1
  88. package/dist/assets/{zh-CN-D9NAFloZ.js → zh-CN-KsbHpHjS.js} +1 -1
  89. package/dist/assets/{zh-TW-tuUKOuhs.js → zh-TW-SdNEiQ7a.js} +1 -1
  90. package/dist/index.html +6 -6
  91. package/dist/mini-chat.html +6 -6
  92. package/dist/mobile.html +6 -6
  93. package/package.json +1 -1
  94. package/server/index.js +2 -0
  95. package/server/lib/client-auth/pairing.js +2 -0
  96. package/server/lib/client-auth/pairing.test.js +29 -0
  97. package/server/lib/content-search/DOCUMENTATION.md +9 -0
  98. package/server/lib/content-search/routes.js +18 -1
  99. package/server/lib/content-search/routes.test.js +21 -0
  100. package/server/lib/content-search/runtime.js +7 -3
  101. package/server/lib/content-search/runtime.test.js +26 -0
  102. package/server/lib/gui-customization/DOCUMENTATION.md +21 -1
  103. package/server/lib/gui-customization/session-skill.js +2 -2
  104. package/server/lib/gui-customization/session-skill.test.js +3 -1
  105. package/server/lib/gui-customization/skill/SKILL.md +5 -1
  106. package/server/lib/gui-customization/skill/references/global-pages.md +1 -1
  107. package/server/lib/gui-customization/skill/references/gui-api.md +4 -1
  108. package/server/lib/gui-customization/skill/references/icons.md +134 -0
  109. package/server/lib/gui-customization/skill/references/plugin-styles.md +112 -0
  110. package/server/lib/gui-customization/skill/references/ui-surfaces.md +2 -0
  111. package/server/lib/gui-customization/skill/references/work-status.md +110 -0
  112. package/server/lib/history-import/AGENT_CONNECT_LICENSE +21 -0
  113. package/server/lib/history-import/DOCUMENTATION.md +214 -0
  114. package/server/lib/history-import/dev-proxy.integration.test.js +56 -0
  115. package/server/lib/history-import/events.js +322 -0
  116. package/server/lib/history-import/events.test.js +110 -0
  117. package/server/lib/history-import/installations.js +39 -0
  118. package/server/lib/history-import/installations.test.js +24 -0
  119. package/server/lib/history-import/native.js +49 -0
  120. package/server/lib/history-import/native.test.js +42 -0
  121. package/server/lib/history-import/routes.js +48 -0
  122. package/server/lib/history-import/routes.test.js +55 -0
  123. package/server/lib/history-import/service.js +374 -0
  124. package/server/lib/history-import/service.test.js +508 -0
  125. package/server/lib/history-import/settings.js +146 -0
  126. package/server/lib/history-import/settings.test.js +88 -0
  127. package/server/lib/history-import/sources.js +184 -0
  128. package/server/lib/history-import/sources.test.js +190 -0
  129. package/server/lib/history-import/sqlite.js +187 -0
  130. package/server/lib/history-import/store.js +58 -0
  131. package/server/lib/history-import/store.test.js +72 -0
  132. package/server/lib/history-import/targets.js +24 -0
  133. package/server/lib/host-update/DOCUMENTATION.md +6 -0
  134. package/server/lib/host-update/routes.test.js +1 -1
  135. package/server/lib/notifications/native-stream.relay.test.js +1 -0
  136. package/server/lib/opencode/DOCUMENTATION.md +3 -0
  137. package/server/lib/opencode/core-routes.js +1 -0
  138. package/server/lib/opencode/feature-routes-runtime.js +11 -1
  139. package/server/lib/opencode/yuri-routes.js +1 -1
  140. package/server/lib/relay/DOCUMENTATION.md +1 -1
  141. package/server/lib/relay/host-client.js +3 -1
  142. package/server/lib/relay/host-client.test.js +1 -0
  143. package/server/lib/relay/reasoning-projection.e2e.test.ts +1 -0
  144. package/server/lib/relay/relay-server.e2e.test.ts +32 -17
  145. package/server/lib/relay/service.js +2 -0
  146. package/server/lib/relay/tunnel-host.js +26 -1
  147. package/server/lib/relay/tunnel-host.test.js +27 -3
  148. package/server/lib/remote-desktop/runtime.test.js +2 -2
  149. package/server/lib/ui-auth/DOCUMENTATION.md +3 -0
  150. package/server/lib/ui-auth/ui-auth.js +27 -0
  151. package/server/lib/ui-auth/ui-auth.test.js +42 -1
  152. package/server/plugin-gui-proxy.test.js +1 -1
  153. package/dist/assets/Icon-BOYrvHyJ.js +0 -1
  154. package/dist/assets/MobileTabPageHeader-B8ywFvz3.js +0 -2
  155. package/dist/assets/SetupTourDialog-CUzqT2sw.css +0 -1
  156. package/dist/assets/SetupTourDialog-D1CePVNG.js +0 -1
  157. package/dist/assets/YuriWordmark-Cr1vkcue.js +0 -1
  158. package/dist/assets/host-CBfSyi4l.js +0 -1
  159. package/dist/assets/insertionBoundaries-B2xOQ5Hz.js +0 -1
  160. package/dist/assets/main-CrVkVfn6.js +0 -169
  161. package/dist/assets/main-DjDRinlx.js +0 -2
  162. package/dist/assets/miniChat-D4MjHmAR.js +0 -2
  163. package/dist/assets/mobile-COK8gAf5.js +0 -2
  164. package/dist/assets/multirun-BZjeyzhb.js +0 -3
  165. package/dist/assets/react-Bwr5-XPi.js +0 -1
  166. package/dist/assets/runtimeEndpointReset-Cv_6vk4X.js +0 -149
  167. package/dist/assets/sessionLookup-SonNO2fE.js +0 -1
  168. package/dist/assets/src-BmVsUiOI.css +0 -2
  169. package/dist/assets/tour-DeA0Ksvj.js +0 -1
  170. package/dist/assets/useDesktopWindowControlsLayout-3tcqC97e.js +0 -1
@@ -0,0 +1,214 @@
1
+ # Cross-agent history import
2
+
3
+ This Host-owned module reads source histories and project instruction text,
4
+ normalizes them, and writes new conversations through official OpenCode
5
+ `session.import`. It does not write OpenCode databases or run historical prompts.
6
+ Agent Connect reader/normalization adaptations use fixed commit
7
+ `42287c14a8fd381bc7ef7a96076a5cba5b4d75f6`; its MIT notice is in
8
+ `AGENT_CONNECT_LICENSE`. No Agent Connect process or new dependency is installed.
9
+
10
+ ## Ownership and routes
11
+
12
+ - `sources.js`: default/custom Host roots, bounded traversal, JSONL/Zstandard,
13
+ source identities and revision fingerprints.
14
+ - `native.js`: current OpenCode instance metadata inventory and bounded message
15
+ excerpts; existing sessions are attached in place, never copied.
16
+ - `installations.js`: connected-Host executable/application detection, without
17
+ launching agents. Scan returns per-source `true`, `false` (not detected), or
18
+ `null` (unknown); leftover history directories are not installation evidence.
19
+ Installation status never filters readable histories or authorizes writes.
20
+ - `sqlite.js`: Cursor editor KV and CLI protobuf/blob readers, using private
21
+ DB+WAL snapshots. Original databases and SHM are never opened by SQLite.
22
+ - `events.js`: active transcript normalization and native transfer projection.
23
+ - `settings.js`: project-only rule/skill plans, conflicts, fingerprints, backups
24
+ and JSONC-preserving writes through the existing config owner.
25
+ - `service.js`: scan/preview lifetimes, explicit confirmation, parent ordering,
26
+ idempotency, cancellation and independent-item failures.
27
+ - `store.js`: SQLite job/receipt persistence; no transcript or rule content.
28
+ - `targets.js`: read-only canonical destination resolution, then confirmed missing-directory creation and revalidation.
29
+ - `routes.js`: authenticated, no-store HTTP boundary registered before the proxy.
30
+
31
+ POST `scan`, `imported`, `preview`, `start`, `resume`, `dismiss`, `cancel` and GET `job`, `jobs` live under
32
+ `/api/yuri/history-import/`. The existing Host UI/client gate authenticates them;
33
+ URL-token authentication is not accepted here. Plans and jobs additionally belong
34
+ to the authenticated client/owner and upstream runtime identity. Start requires
35
+ `confirm: true`; the same plan returns the same job on retry. Scans/plans expire
36
+ after 30 minutes and are bounded to eight retained entries each. A Host serializes
37
+ imports; closing the UI does not cancel confirmed work. Cancellation is
38
+ cooperative between items, not a rollback of already committed data.
39
+
40
+ Web, Electron, hosted mobile and Capacitor read files on the **connected Host**,
41
+ never on the browser/phone. There is no upload flow. Standalone VS Code returns
42
+ 501 `history_import_unsupported` instead of forwarding these routes to OpenCode.
43
+ The setup tour sends `start({ sources, directory, confirm: true })` on “Next”.
44
+ It immediately accepts a Host-owned job; full discovery, per-item validation and
45
+ fingerprint-bound planning run in the background, without another confirmation page.
46
+ Settings conflicts keep existing files. The explicit `planID` start API remains
47
+ available with keep-both/replace decisions. Closing a client does not cancel either flow.
48
+ `progress` describes `scanning`, `validating` or `importing` with phase-local
49
+ `completed`/`total`; zero total means unknown, not 0% progress. The receipt total
50
+ is finalized after planning, including scan/validation failures. An additive SQLite
51
+ column migration persists progress. Restart marks unfinished jobs interrupted;
52
+ it does not replay executable plans. Internal scans/plans are released after each
53
+ background job. Failed items do not block unrelated projects.
54
+
55
+ `jobs` returns all unfinished jobs for the authenticated owner/runtime, oldest
56
+ first, using summary counts (including failures) without transcript/receipt bodies.
57
+ New source jobs durably retain only their source IDs and fallback destination in a
58
+ private SQLite `request` column; responses expose only `resumable`. `resume` needs
59
+ `{ id, confirm: true }`, reuses the same job ID, and merges duplicate active retries.
60
+ Another active import rejects with `import_busy`. A transaction resets only that
61
+ job's attempt receipts/progress, never imported sessions, project registrations or
62
+ source files. Discovery/validation is repeated; deterministic revision IDs and
63
+ authoritative provenance readback skip committed sessions. Index callbacks and
64
+ project registration are retried independently. Settings retain the keep-existing
65
+ conflict policy. This is an idempotent retry, not a byte/file-offset resume.
66
+ Continue always uses the stored original source intent; the resume payload cannot
67
+ replace it with new sources or destinations. Legacy/explicit-plan jobs without
68
+ stored intent return `resume_request_missing` without resetting receipts or
69
+ starting a new import. The popup reports this limitation, never asks for a new
70
+ selection or silently selects all sources. Missing historical selections, merge
71
+ decisions and replace decisions cannot be reconstructed from result receipts.
72
+ After a failed Continue attempt the popup changes that import row's action to
73
+ Remove. `dismiss({ id })` durably marks only the authenticated owner/runtime's
74
+ inactive job as dismissed, excluding it from `jobs` and latest `job` results.
75
+ Running jobs reject dismissal with `import_busy`. Receipts and imported
76
+ conversations/projects/files remain untouched; repeated dismissal is idempotent.
77
+ Explicit historical job reads retain the receipt, but dismissed jobs cannot resume.
78
+
79
+ Discovery accepts optional `limitPerSource` (integer 1–10). This is a fast,
80
+ non-exhaustive sample: traversal/reads stop when that source reaches the limit,
81
+ including across roots, and Cursor editor bounds its composer-header SQL query.
82
+ With `includeCounts: true`, metadata traversal continues, but remaining transcript
83
+ bodies are not parsed. Candidate files are counted once per physical path;
84
+ Cursor editor combines `COUNT(*)` with bounded sample reads in the same private
85
+ snapshot, or reads only the count when enough examples were found elsewhere.
86
+ Counts are `{ value, approximate }` per source: positive values are estimates,
87
+ since duplicates/empty/malformed histories were not validated. Metadata-read or
88
+ traversal failure returns `value: null`, not a misleading partial/zero success.
89
+ The enumeration remains bounded to 20,000 entries; original DBs stay untouched.
90
+ Sample order is not a claim of catalog-wide recency.
91
+ Scan responses expose `sampled`; plans reject sampled scans with `incomplete_scan`.
92
+ The tour asks for five examples and metadata counts per tool, then scans selected tools fully only
93
+ on “Next”, preserving full-history import rather than importing just examples.
94
+ Scan summaries include a whitespace-normalized excerpt of up to 180 characters
95
+ from assistant text (falling back to user text), never tool records or reasoning.
96
+ OpenCode inventory pages official `session.list` metadata (100 per page, at most
97
+ 5,000 sessions, 10-second request budget). A complete inventory gives an exact
98
+ count; failed/incomplete inventory gives an unknown count, while readable samples
99
+ remain visible. Only sampled OpenCode sessions request message projection (one
100
+ 10-message page per example); full registration jobs never read message bodies.
101
+ This source is the connected instance, not an alternate database or export file.
102
+ Combined native/external discoveries retain the existing 5,000-session bound;
103
+ overflow is reported per omitted source without discarding readable retained
104
+ sessions. As before, this is a bounded import, not an unbounded catalog migration.
105
+
106
+ `imported({ scanID, directory })` is a separate read-only badge query for sampled
107
+ scans only. The scan retains already-computed source revisions, never rereads
108
+ transcript bodies for badges. It uses the same deterministic IDs/provenance as
109
+ separate imports, canonical destinations and parent revisions, with at most four
110
+ concurrent `session.get` calls, 50 examples and a shared five-second timeout.
111
+ Exact existing targets report `imported`; authoritative 404 reports `available`;
112
+ query failure, conflicts or a parent outside the sample report `unknown`, never
113
+ an invented unimported state. Badges are conservative, not catalog-wide totals.
114
+ Checks retain owner/runtime fencing and do not trust persisted receipts alone.
115
+
116
+ ## Supported sources and conversion
117
+
118
+ | Source | Reader behavior |
119
+ | --- | --- |
120
+ | Claude Code | projects JSONL, active UUID parent chain, compaction/snips, parallel assistant tool fragments and subagents |
121
+ | Codex | sessions and archived_sessions JSONL, paired event/response user tracks, rollbacks, tool call/output pairs |
122
+ | Cursor | agent-transcripts JSONL; editor state.vscdb composer/bubble KV; CLI chats store.db meta, ordered protobuf message references and archives |
123
+ | DeepSeek Harness | session JSONL or concatenated Zstandard frames, latest physical generation, versions 0–4, sequenced surface replacement and tool/result pairing |
124
+ | OpenCode | current instance official session inventory; “Next” registers original projects and refreshes existing session index entries without `session.import` |
125
+
126
+ Known defaults respect the source-specific HOME/config environment overrides.
127
+ Explicit roots must be absolute Host paths. Sources remain untouched; unreadable
128
+ files are reported independently, not interpreted as an authoritative empty scan.
129
+ Symlink entries are skipped, and project rule/destination symlinks fail closed.
130
+ JSONL is capped at 64 MiB decompressed, 8 MiB per line and 100,000 records;
131
+ traversal at 20,000 entries and 5,000 sessions. SQLite snapshots are capped at
132
+ 1 GiB. Missing Zstandard support is an explicit per-source error, not a Host
133
+ startup failure. Discovery deduplicates source identity across scan entry paths
134
+ and active/archive copies, preferring the more recently modified file.
135
+
136
+ This is not lossless native-runtime migration: tools/results become inert text,
137
+ reasoning remains reasoning text, and only available user inline image bytes are
138
+ retained. Missing/local-file attachments, runtime state, provider replay data,
139
+ permissions and historical usage are not reconstructed. Imported metadata marks
140
+ usage unknown; schema-required counters are zero, not recovered usage evidence.
141
+
142
+ ## Merge, revisions and retry
143
+
144
+ Destination paths must be absolute and resolve through canonical existing ancestors.
145
+ Preview/validation never creates a directory. Confirmed execution creates missing
146
+ project directories and checks their canonical identity again, then uses the shared
147
+ project registry before importing a session. Registration failure prevents session
148
+ and settings writes for that project. Created directories/projects are not removed
149
+ on later failure, to preserve concurrent user work. Multiple source paths
150
+ may map to one destination project. Separate imports preserve selected parent/
151
+ child relationships with parents imported first. An unselected parent produces
152
+ an explicit detached-child warning. Parent failure blocks that subtree only.
153
+ Child target IDs incorporate the selected parent's revision ID.
154
+ Impossible self-parent metadata is normalized to a detached root with a
155
+ `parent_detached` warning; transcript contents are retained. Other parent cycles
156
+ fail their own entries with `invalid_parent_graph`, and descendants report
157
+ `parent_failed`; independent conversations continue. Parent ordering is iterative
158
+ and linear rather than recursive. Explicit merges flatten selected source
159
+ histories and do not depend on their original parent graph.
160
+ OpenCode entries retain their original IDs and locations. They cannot be merged
161
+ or redirected to another project; missing/deleted locations or sessions fail
162
+ independently. Registration/index failures remain retryable without copies.
163
+ Their existing project configuration is already native and is not rewritten.
164
+
165
+ Conversation merge is explicit, requires one destination and follows the scan
166
+ list/selection order. It creates a new session, removes only an exactly matching
167
+ shared prefix, inserts source boundary markers, and preserves repeated genuine
168
+ messages. It never appends to or overwrites existing OpenCode conversations.
169
+
170
+ Target IDs encode source installation/session identities, normalized revision,
171
+ destination, mode and parent revision. Exact repeat imports verify authoritative
172
+ metadata and skip; changed source content creates a new revision. Lost write
173
+ responses recover only through an exact authoritative read, never merely a 409.
174
+ Every successful import is read back through `session.get` and checked against
175
+ the expected ID, provenance and destination; a write acknowledgment alone is not
176
+ success. The session index receives that verified record. Index failure is
177
+ reported separately and retryable without duplicating the conversation.
178
+ Full receipts are durable; polled status returns
179
+ at most 80 recent/failed results plus the total completed count.
180
+
181
+ ## Project settings
182
+
183
+ Selected histories identify source project roots. Root CLAUDE.md/AGENTS.md,
184
+ source rule folders, .cursorrules, and Markdown skill definitions are eligible.
185
+ Native in-place root instructions are skipped. Other unconditional rules go to
186
+ `.opencode/imported-rules/` and are added to effective instructions through the
187
+ existing JSONC config owner, preserving inherited instructions and comments.
188
+ Rules with `globs`, `paths` or `alwaysApply` metadata remain archived, not globally
189
+ enabled. Skills copy **SKILL.md only** to namespaced directories under
190
+ `.opencode/skills/`; supporting scripts and resources are not copied, so such
191
+ skills may need manual repair. This limit is disclosed before confirmation.
192
+ Global credentials, provider/auth settings, hooks, permissions, MCP and plugins
193
+ are excluded.
194
+ For source-based background jobs, settings planning failures (including symlinked
195
+ rule/skill roots) are recorded once per source project/destination as failed
196
+ settings items, without excluding readable conversations from that project. No
197
+ unsafe settings are read through symlinks or written. Explicit settings previews
198
+ still reject unsafe paths so callers can resolve them before confirming.
199
+
200
+ Conflicts default to keep existing; explicit keep-both uses a separate path;
201
+ replace backs up existing content first. Preview binds source/target/config
202
+ fingerprints. Changed data fails instead of silently overwriting. Failed config
203
+ activation compensates only the unchanged rule file written by this operation;
204
+ concurrent user edits are retained. Plans permit at most 200 rule/skill files,
205
+ 512 KiB each and 4 MiB total. Partial failures leave unrelated successes valid;
206
+ re-preview and retry, rather than restarting a persisted executable plan.
207
+
208
+ ## Verification
209
+
210
+ Focused Vitest tests cover format normalization, official transfer schema,
211
+ SQLite source immutability, repeat/lost-response imports, source changes,
212
+ ownership, runtime fencing, parent failures, merge, cancellation, receipts,
213
+ JSONC merging, conflict policies and unsafe paths. Real OpenCode smoke validation
214
+ must use synthetic sources and isolated HOME/XDG roots, never user histories.
@@ -0,0 +1,56 @@
1
+ import fs from 'node:fs/promises';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import http from 'node:http';
5
+ import { once } from 'node:events';
6
+ import express from 'express';
7
+ import { createServer } from 'vite';
8
+ import { expect, test } from 'vitest';
9
+ import createConfig from '../../../vite.config.ts';
10
+ import { createHistoryImportService } from './service.js';
11
+ import { createImportStore } from './store.js';
12
+ import { registerHistoryImportRoutes } from './routes.js';
13
+ import { digest } from './events.js';
14
+
15
+ test('real development proxy preserves browser origin for resume and durable task dismissal', async () => {
16
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yuri-import-proxy-'));
17
+ const store = createImportStore(path.join(directory, 'receipts.sqlite'));
18
+ store.create('interrupted', 'owner', digest('fixture'), 357);
19
+ store.append('interrupted', 0, { key: 'saved', status: 'imported', sessionID: 'existing' });
20
+ store.finish('interrupted', 'interrupted');
21
+ const service = createHistoryImportService({ store, getRuntimeIdentity: () => 'fixture', createClient: () => { throw new Error('must not touch imported content'); } });
22
+ const backend = express();
23
+ registerHistoryImportRoutes(backend, { express, service, uiAuthController: { resolveAuthContext: async () => ({ type: 'session' }) } });
24
+ const api = http.createServer(backend); const ui = http.createServer();
25
+ let vite;
26
+ try {
27
+ api.listen(0, '127.0.0.1'); await once(api, 'listening');
28
+ const config = createConfig({ command: 'serve', mode: 'development' });
29
+ vite = await createServer({ configFile: false, root: directory, cacheDir: path.join(directory, '.vite'), appType: 'custom', logLevel: 'silent',
30
+ optimizeDeps: { noDiscovery: true, include: [] },
31
+ server: { middlewareMode: { server: ui }, hmr: false,
32
+ proxy: { '/api': { ...config.server.proxy['/api'], target: `http://127.0.0.1:${api.address().port}` } },
33
+ },
34
+ });
35
+ ui.on('request', vite.middlewares); ui.listen(0, '127.0.0.1'); await once(ui, 'listening');
36
+ const origin = `http://127.0.0.1:${ui.address().port}`;
37
+ const call = (route, body, requestOrigin = origin) => fetch(`${origin}/api/yuri/history-import/${route}`, {
38
+ method: 'POST', headers: { 'Content-Type': 'application/json', Origin: requestOrigin, 'Sec-Fetch-Site': 'same-origin' }, body: JSON.stringify(body),
39
+ });
40
+ const resume = await call('resume', { id: 'interrupted', confirm: true });
41
+ expect({ status: resume.status, body: await resume.json() }).toEqual({ status: 400, body: { code: 'resume_request_missing' } });
42
+ const forbidden = await call('dismiss', { id: 'interrupted' }, 'https://attacker.example');
43
+ expect(forbidden.status).toBe(403);
44
+ const dismiss = await call('dismiss', { id: 'interrupted' });
45
+ expect({ status: dismiss.status, body: await dismiss.json() }).toEqual({ status: 200, body: { id: 'interrupted' } });
46
+ expect(await (await fetch(`${origin}/api/yuri/history-import/jobs`)).json()).toEqual([]);
47
+ expect(service.status('interrupted', 'owner')).toMatchObject({ dismissed: true, completed: 1, results: [{ sessionID: 'existing' }] });
48
+ } finally {
49
+ await vite?.close();
50
+ for (const server of [ui, api]) {
51
+ server.closeAllConnections();
52
+ if (server.listening) await new Promise(resolve => server.close(resolve));
53
+ }
54
+ await service.close(); await fs.rm(directory, { recursive: true, force: true });
55
+ }
56
+ });
@@ -0,0 +1,322 @@
1
+ // Reader/normalization adaptations from Agent Connect (MIT), commit
2
+ // 42287c14a8fd381bc7ef7a96076a5cba5b4d75f6. See AGENT_CONNECT_LICENSE.
3
+ import { createHash } from 'node:crypto';
4
+
5
+ export const digest = (value) => createHash('sha256').update(typeof value === 'string' ? value : JSON.stringify(value)).digest('hex');
6
+ export const fail = (code) => { throw Object.assign(new Error(code), { code }); };
7
+ export const timestamp = (value, fallback = 0) => {
8
+ const number = typeof value === 'number' ? value : Date.parse(value);
9
+ return Number.isFinite(number) && number >= 0 ? number : fallback;
10
+ };
11
+ export const textOf = (value) => {
12
+ if (typeof value === 'string') return value;
13
+ if (Array.isArray(value)) return value.map((part) => textOf(part?.text ?? part?.content ?? '')).filter(Boolean).join('\n');
14
+ return value == null ? '' : JSON.stringify(value);
15
+ };
16
+
17
+ // Preserve repeated genuine messages. Only source-specific duplicate encodings
18
+ // and the explicitly shared prefix of selected conversations are deduplicated.
19
+ export function combineSessions(sessions) {
20
+ if (sessions.length < 2) fail('merge_requires_sessions');
21
+ const events = [...sessions[0].events];
22
+ const signatures = sessions[0].events.map(eventSignature);
23
+ for (const session of sessions.slice(1)) {
24
+ let common = 0;
25
+ while (common < signatures.length && common < session.events.length && signatures[common] === eventSignature(session.events[common])) common++;
26
+ const remainder = session.events.slice(common);
27
+ if (!remainder.length) continue;
28
+ events.push({ kind: 'marker', text: `[Imported conversation: ${session.title}]`, time: remainder[0].time });
29
+ events.push(...remainder);
30
+ }
31
+ return events;
32
+ }
33
+ const eventSignature = ({ kind, text, name, input, output, files }) => digest({ kind, text, name, input, output, files });
34
+
35
+ function activeClaudeChain(entries, warnings) {
36
+ const messages = new Map();
37
+ const progress = new Map();
38
+ for (const entry of entries) {
39
+ if (entry.type === 'progress' && entry.uuid) {
40
+ progress.set(entry.uuid, progress.get(entry.parentUuid) ?? entry.parentUuid);
41
+ } else if (['user', 'assistant', 'system', 'attachment'].includes(entry.type) && entry.uuid) {
42
+ messages.set(entry.uuid, { ...entry, parentUuid: progress.get(entry.parentUuid) ?? entry.parentUuid });
43
+ }
44
+ }
45
+ if (!messages.size) return entries.filter((entry) => !entry.isSidechain);
46
+ // Relink compact's retained segment before removing snipped messages.
47
+ const values = [...messages.values()];
48
+ const lastBoundary = values.findLastIndex((entry) => entry.type === 'system' && entry.subtype === 'compact_boundary');
49
+ const boundary = values[lastBoundary];
50
+ const segment = boundary?.compactMetadata?.preservedSegment;
51
+ if (segment) {
52
+ const kept = new Set();
53
+ let current = messages.get(segment.tailUuid);
54
+ while (current && !kept.has(current.uuid)) {
55
+ kept.add(current.uuid);
56
+ if (current.uuid === segment.headUuid) break;
57
+ current = messages.get(current.parentUuid);
58
+ }
59
+ const anchor = messages.get(segment.anchorUuid);
60
+ const anchorIndex = values.findIndex((entry) => entry.uuid === segment.anchorUuid);
61
+ const anchorSeen = new Set();
62
+ let cursor = anchor;
63
+ let valid = true;
64
+ while (cursor) {
65
+ if (kept.has(cursor.uuid) || anchorSeen.has(cursor.uuid)) { valid = false; break; }
66
+ anchorSeen.add(cursor.uuid);
67
+ if (cursor.parentUuid && !messages.has(cursor.parentUuid)) { valid = false; break; }
68
+ cursor = messages.get(cursor.parentUuid);
69
+ }
70
+ if (current?.uuid === segment.headUuid && anchor && anchorIndex >= lastBoundary && valid) {
71
+ messages.get(segment.headUuid).parentUuid = segment.anchorUuid;
72
+ for (const entry of messages.values()) {
73
+ if (entry.parentUuid === segment.anchorUuid && entry.uuid !== segment.headUuid) entry.parentUuid = segment.tailUuid;
74
+ }
75
+ for (const entry of values.slice(0, lastBoundary)) if (!kept.has(entry.uuid)) messages.delete(entry.uuid);
76
+ } else warnings.add('branch_incomplete');
77
+ }
78
+ const deleted = new Map();
79
+ for (const entry of messages.values()) {
80
+ for (const id of entry.snipMetadata?.removedUuids ?? []) if (messages.has(id)) deleted.set(id, messages.get(id).parentUuid);
81
+ }
82
+ for (const id of deleted.keys()) messages.delete(id);
83
+ for (const entry of messages.values()) {
84
+ const seen = new Set();
85
+ while (deleted.has(entry.parentUuid) && !seen.has(entry.parentUuid)) {
86
+ seen.add(entry.parentUuid); entry.parentUuid = deleted.get(entry.parentUuid);
87
+ }
88
+ }
89
+ let leaf;
90
+ for (const entry of messages.values()) {
91
+ if (!entry.isSidechain && (!leaf || timestamp(entry.timestamp) > timestamp(leaf.timestamp))) leaf = entry;
92
+ }
93
+ const chain = [];
94
+ const seen = new Set();
95
+ while (leaf && !seen.has(leaf.uuid)) {
96
+ seen.add(leaf.uuid); chain.push(leaf);
97
+ if (leaf.parentUuid && !messages.has(leaf.parentUuid)) warnings.add('branch_incomplete');
98
+ leaf = messages.get(leaf.parentUuid);
99
+ }
100
+ chain.reverse();
101
+ // Parallel assistant fragments share one provider message ID, even when only
102
+ // one fragment is on the parent chain. Recover siblings and their tool results.
103
+ const providerIDs = new Set(chain.filter((entry) => entry.type === 'assistant').map((entry) => entry.message?.id).filter(Boolean));
104
+ const siblings = new Map();
105
+ for (const entry of messages.values()) {
106
+ if (entry.type === 'assistant' && providerIDs.has(entry.message?.id) && !entry.isSidechain) {
107
+ const group = siblings.get(entry.message.id) ?? []; group.push(entry); siblings.set(entry.message.id, group);
108
+ }
109
+ }
110
+ const results = new Map();
111
+ for (const entry of messages.values()) {
112
+ if (entry.type === 'user' && Array.isArray(entry.message?.content) && entry.message.content.some((part) => part.type === 'tool_result')) {
113
+ const group = results.get(entry.parentUuid) ?? []; group.push(entry); results.set(entry.parentUuid, group);
114
+ }
115
+ }
116
+ const recovered = [];
117
+ for (const entry of chain) {
118
+ recovered.push(entry);
119
+ if (entry.type !== 'assistant') continue;
120
+ for (const sibling of siblings.get(entry.message?.id) ?? []) {
121
+ if (!seen.has(sibling.uuid)) { recovered.push(sibling); seen.add(sibling.uuid); }
122
+ for (const result of results.get(sibling.uuid) ?? []) if (!seen.has(result.uuid)) { recovered.push(result); seen.add(result.uuid); }
123
+ }
124
+ }
125
+ if (messages.size > seen.size || deleted.size) warnings.add('inactive_branches_omitted');
126
+ return recovered;
127
+ }
128
+
129
+ const contextPrefixes = ['# agents.md instructions', '<user_instructions', '<environment_context', '<additional_context', '<skill', '<system-reminder', '<permissions instructions', '<turn_aborted', '<subagent_notification', '<internal_model_context', '<user_shell_command'];
130
+ function codexUser(entry) {
131
+ const payload = entry.payload;
132
+ if (entry.type === 'event_msg' && payload?.type === 'user_message') return { kind: 'event', text: textOf(payload.message) };
133
+ if (entry.type === 'event_msg' && payload?.type === 'item_completed' && payload.item?.type === 'UserMessage') return { kind: 'event', text: textOf(payload.item.content) };
134
+ if (entry.type === 'response_item' && payload?.type === 'message' && payload.role === 'user') {
135
+ const text = textOf(payload.content);
136
+ if (!contextPrefixes.some((prefix) => text.trimStart().toLowerCase().startsWith(prefix))) return { kind: 'response', text };
137
+ }
138
+ return null;
139
+ }
140
+ function codexBoundaries(lines) {
141
+ const boundaries = []; let pending;
142
+ for (let index = 0; index < lines.length; index++) {
143
+ const line = lines[index]; const user = codexUser(line);
144
+ if (user) {
145
+ if (pending && user.kind !== pending.kind && (!user.text.trim() || !pending.text.trim() || user.text.trim() === pending.text.trim())) {
146
+ boundaries.push({ ...pending, secondary: index, text: user.kind === 'event' ? user.text || pending.text : pending.text || user.text }); pending = undefined;
147
+ } else { if (pending) boundaries.push(pending); pending = { ...user, index }; }
148
+ } else if (line.type === 'response_item' && line.payload?.role !== 'user' || line.type === 'compacted' || line.type === 'event_msg' && ['agent_message', 'agent_reasoning', 'turn_started', 'turn_complete', 'turn_aborted'].includes(line.payload?.type)) {
149
+ if (pending) boundaries.push(pending); pending = undefined;
150
+ }
151
+ }
152
+ if (pending) boundaries.push(pending);
153
+ return boundaries;
154
+ }
155
+
156
+ export function parseTranscript(source, entries, fallbackID, fallbackTime = 0) {
157
+ const warnings = new Set(['tools_archived', 'usage_unknown']);
158
+ const head = source === 'codex' ? entries.find((entry) => entry.type === 'session_meta')?.payload ?? {} : entries[0] ?? {};
159
+ let id = head.sessionId ?? head.session_id ?? head.id ?? fallbackID;
160
+ let directory = head.cwd ?? '';
161
+ let title = '';
162
+ const events = [];
163
+ const add = (kind, text, entry, extra = {}) => {
164
+ if (!text && !extra.files?.length && kind !== 'tool') return;
165
+ events.push({ kind, text, time: timestamp(entry.timestamp ?? entry.time ?? entry.createdAt, fallbackTime), ...extra });
166
+ };
167
+ const blocks = (content, role, entry, results = new Map()) => {
168
+ if (typeof content === 'string') { add(role, content, entry); return; }
169
+ if (!Array.isArray(content)) return;
170
+ let text = ''; let files = [];
171
+ const flush = () => { add(role, text, entry, files.length ? { files } : {}); text = ''; files = []; };
172
+ for (const part of content) {
173
+ if (['text', 'input_text', 'output_text'].includes(part.type)) text += `${text ? '\n' : ''}${part.text ?? ''}`;
174
+ else if (part.type === 'thinking' || part.type === 'reasoning') { flush(); add('thinking', part.thinking ?? part.text ?? '', entry); }
175
+ else if (part.type === 'tool_use' || part.type === 'tool-call') {
176
+ flush();
177
+ const result = results.get(part.id ?? part.toolCallId);
178
+ add('tool', '', entry, { name: part.name ?? part.toolName, input: part.input ?? part.args ?? part.arguments ?? {}, output: textOf(result?.content ?? result?.result), incomplete: !result, isError: result?.is_error === true || result?.isError === true });
179
+ if (!result) warnings.add('unfinished_tools');
180
+ } else if (role === 'user' && part.type === 'image' && part.source?.type === 'base64') {
181
+ files.push({ data: part.source.data, mime: part.source.media_type, source: { type: 'inline' } });
182
+ } else if (!['tool_result', 'tool-result'].includes(part.type)) warnings.add('attachments_omitted');
183
+ }
184
+ flush();
185
+ };
186
+ if (source === 'claude') {
187
+ const messages = activeClaudeChain(entries, warnings);
188
+ const results = new Map();
189
+ for (const entry of messages) for (const part of Array.isArray(entry.message?.content) ? entry.message.content : []) if (part.type === 'tool_result') results.set(part.tool_use_id, part);
190
+ for (const entry of entries) {
191
+ if (entry.type === 'custom-title') title = entry.customTitle ?? title;
192
+ else if (entry.type === 'ai-title' && !title) title = entry.aiTitle ?? '';
193
+ directory ||= entry.cwd ?? ''; id = entry.sessionId ?? id;
194
+ }
195
+ for (const entry of messages) {
196
+ if (entry.type === 'user' || entry.type === 'assistant') blocks(entry.message?.content, entry.isMeta ? 'marker' : entry.type === 'assistant' ? 'assistant-text' : 'user', entry, results);
197
+ else if (entry.subtype === 'compact_boundary') add('marker', '[Claude Code context compaction]', entry);
198
+ }
199
+ } else if (source === 'codex') {
200
+ const lines = [];
201
+ for (const entry of entries) {
202
+ if (entry.type === 'event_msg' && entry.payload?.type === 'thread_rolled_back') {
203
+ const count = entry.payload.num_turns;
204
+ if (!Number.isInteger(count) || count < 1) fail('invalid_source');
205
+ const boundaries = codexBoundaries(lines);
206
+ if (boundaries.length) lines.length = boundaries[Math.max(0, boundaries.length - count)].index;
207
+ warnings.add('inactive_branches_omitted');
208
+ } else lines.push(entry);
209
+ }
210
+ const boundaries = codexBoundaries(lines); const users = new Map(boundaries.map((boundary) => [boundary.index, boundary]));
211
+ const secondary = new Set(boundaries.map((boundary) => boundary.secondary)); const outputs = new Map();
212
+ for (const entry of lines) if (entry.type === 'response_item' && ['function_call_output', 'custom_tool_call_output'].includes(entry.payload?.type)) outputs.set(entry.payload.call_id, entry.payload);
213
+ const nativeCopies = new Map(); let segment = 0;
214
+ const copyKey = (kind, text) => JSON.stringify([segment, kind, text]);
215
+ for (let index = 0; index < lines.length; index++) {
216
+ const entry = lines[index]; const payload = entry.payload;
217
+ if (users.has(index) || entry.type === 'compacted') segment++;
218
+ const kind = payload?.type === 'reasoning' ? 'thinking' : payload?.type === 'message' && payload.role === 'assistant' ? 'assistant-text' : undefined;
219
+ if (entry.type !== 'response_item' || !kind) continue;
220
+ const text = textOf(kind === 'thinking' ? payload.summary : payload.content);
221
+ const key = copyKey(kind, text);
222
+ nativeCopies.set(key, (nativeCopies.get(key) ?? 0) + 1);
223
+ }
224
+ segment = 0;
225
+ for (let index = 0; index < lines.length; index++) {
226
+ const entry = lines[index]; const payload = entry.payload;
227
+ if (users.has(index) || entry.type === 'compacted') segment++;
228
+ if (users.has(index)) add('user', users.get(index).text, entry);
229
+ else if (secondary.has(index)) continue;
230
+ else if (entry.type === 'response_item') {
231
+ if (payload?.type === 'message' && payload.role === 'assistant') blocks(payload.content, 'assistant-text', entry);
232
+ else if (payload?.type === 'reasoning') add('thinking', textOf(payload.summary), entry);
233
+ else if (['function_call', 'custom_tool_call'].includes(payload?.type)) {
234
+ const result = outputs.get(payload.call_id);
235
+ add('tool', '', entry, { name: payload.name, input: payload.arguments ?? payload.input ?? {}, output: textOf(result?.output), incomplete: !result });
236
+ if (!result) warnings.add('unfinished_tools');
237
+ }
238
+ } else if (entry.type === 'event_msg' && ['agent_message', 'agent_reasoning'].includes(payload?.type)) {
239
+ const kind = payload.type === 'agent_message' ? 'assistant-text' : 'thinking';
240
+ const text = textOf(payload.message ?? payload.text);
241
+ const key = copyKey(kind, text); const copies = nativeCopies.get(key) ?? 0;
242
+ if (copies) nativeCopies.set(key, copies - 1);
243
+ else add(kind, text, entry);
244
+ } else if (entry.type === 'compacted') add('marker', `[Codex context compaction]\n${payload?.message ?? entry.message ?? ''}`, entry);
245
+ }
246
+ } else if (source === 'dsh') {
247
+ if (head.type !== 'session' || !head.id || head.version != null && ![0, 1, 2, 3, 4].includes(head.version)) fail('unsupported_source_version');
248
+ const surface = []; const surfaceTypes = ['system/message', 'developer/message', 'user/message', 'assistant/message', 'tool/result'];
249
+ let expectedSeq = 0;
250
+ for (const entry of entries.slice(1)) {
251
+ if (entry.seq !== undefined && entry.seq !== expectedSeq) fail('invalid_source');
252
+ expectedSeq++;
253
+ if (!surfaceTypes.includes(entry.type)) continue;
254
+ if (entry.surfaceOp && entry.surfaceOp !== 'append') {
255
+ const op = entry.surfaceOp;
256
+ if (op.op !== 'replace') fail('unsupported_source_version');
257
+ const start = surface.findIndex((item) => item.seq === op.startSeq);
258
+ const end = surface.findIndex((item) => item.seq === op.endSeq);
259
+ if (start < 0 || end < start) fail('invalid_source');
260
+ surface.splice(start, end - start + 1, entry); warnings.add('inactive_branches_omitted');
261
+ } else surface.push(entry);
262
+ }
263
+ const results = new Map();
264
+ const calls = new Set();
265
+ for (const entry of surface) {
266
+ if (entry.type === 'tool/result') {
267
+ const message = entry.data?.message;
268
+ const result = message?.content?.find((part) => part.type === 'tool-result');
269
+ results.set(result?.toolCallId ?? message?.source?.callId ?? message?.callId, result ?? message);
270
+ }
271
+ if (entry.type === 'assistant/message') for (const part of entry.data?.message?.content ?? []) if (part.type === 'tool-call') calls.add(part.id);
272
+ }
273
+ for (const entry of entries) if (entry.type === 'session/title') title = entry.data?.title ?? entry.data?.value ?? title;
274
+ for (const entry of surface) {
275
+ const data = entry.data ?? {};
276
+ if (entry.type === 'user/message') blocks(data.content, data.source?.kind === 'user' ? 'user' : 'marker', entry);
277
+ else if (entry.type === 'assistant/message') {
278
+ const message = data.message ?? {};
279
+ blocks(message.content, 'assistant-text', entry, results);
280
+ } else if (entry.type === 'system/message' || entry.type === 'developer/message') blocks(data.message?.content, 'marker', entry);
281
+ else if (entry.type === 'tool/result') {
282
+ const message = data.message; const result = message?.content?.find((part) => part.type === 'tool-result');
283
+ const callID = result?.toolCallId ?? message?.source?.callId ?? message?.callId;
284
+ if (!calls.has(callID)) add('marker', `[Historical tool result]\n${textOf(result?.content ?? message?.content)}`, entry);
285
+ }
286
+ }
287
+ if (head.parentSession) warnings.add('fork_archived');
288
+ } else if (source === 'cursor') {
289
+ for (const entry of entries) {
290
+ const role = entry.role ?? entry.message?.role;
291
+ if (role === 'user' || role === 'assistant') blocks(entry.message?.content ?? entry.content ?? entry.text, role === 'user' ? 'user' : 'assistant-text', entry);
292
+ directory ||= entry.cwd ?? '';
293
+ }
294
+ } else fail('invalid_source');
295
+ if (!events.length) fail('empty_transcript');
296
+ title ||= events.find((event) => event.kind === 'user')?.text?.replace(/\s+/g, ' ').slice(0, 100) ?? String(id);
297
+ let parentID = source === 'codex' ? head.source?.subagent?.thread_spawn?.parent_thread_id ?? head.parent_thread_id
298
+ : head.origin === 'subagent' || head.delegationDepth > 0 ? head.parentSession : undefined;
299
+ if (parentID != null && String(parentID) === String(id)) { parentID = undefined; warnings.add('parent_detached'); }
300
+ return { id: String(id), title: String(title).slice(0, 200), directory, parentID, events, warnings: [...warnings] };
301
+ }
302
+
303
+ export function toNativeTransfer(session, directory, sessionID, provenance, parentID) {
304
+ const model = { providerID: 'imported', id: 'historical' };
305
+ const messages = session.events.map((event, index) => {
306
+ const id = `msg_${digest(`${sessionID}:${index}`).slice(0, 32)}`;
307
+ const time = { created: event.time };
308
+ if (event.kind === 'user') return { type: 'user', id, time, text: event.text ?? '', ...(event.files?.length ? { files: event.files } : {}) };
309
+ const text = event.kind === 'tool' ? `[Historical tool: ${event.name ?? 'unknown'}${event.incomplete ? ' — unfinished' : ''}]\nInput: ${textOf(event.input)}\nOutput: ${event.output ?? ''}` : event.text ?? '';
310
+ return { type: 'assistant', id, time: { ...time, completed: event.time }, agent: 'build', model,
311
+ content: [{ type: event.kind === 'thinking' ? 'reasoning' : 'text', text }], finish: 'stop' };
312
+ });
313
+ const created = session.events[0]?.time ?? 0;
314
+ const updated = session.events.reduce((latest, event) => Math.max(latest, event.time), created);
315
+ return {
316
+ location: { directory },
317
+ info: { id: sessionID, projectID: 'imported', location: { directory }, title: session.title,
318
+ ...(parentID ? { parentID } : {}), cost: 0, tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
319
+ time: { created, updated }, metadata: { historyImport: provenance } },
320
+ messages,
321
+ };
322
+ }