@yuriai/web 0.2.31 → 0.2.32-beta.10

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 (201) hide show
  1. package/README.md +19 -0
  2. package/dist/assets/{AgentAvatar-DLAQkFQe.js → AgentAvatar-DLzcNrQ0.js} +1 -1
  3. package/dist/assets/AssistantContactStatus-Bf1yg0yx.js +3 -0
  4. package/dist/assets/{AssistantUnreadBadge-BynxNQMk.js → AssistantUnreadBadge-BUFyxUrT.js} +1 -1
  5. package/dist/assets/{AssistantView-CDZyA9ft.js → AssistantView-CELFybSr.js} +1 -1
  6. package/dist/assets/{DiagramView-DdVFGHQQ.js → DiagramView-DV4P3-Wg.js} +1 -1
  7. package/dist/assets/{FadeInOnReveal-C9a7XnAh.js → FadeInOnReveal-BRrU2ivL.js} +1 -1
  8. package/dist/assets/{GuiPluginSurface-v8r-Hex5.js → GuiPluginSurface-NOHaJGy2.js} +1 -1
  9. package/dist/assets/{GuiPluginWindow-Ba1HfrjQ.js → GuiPluginWindow-BykPaQeY.js} +1 -1
  10. package/dist/assets/Icon-OJf0qBKf.js +1 -0
  11. package/dist/assets/{ImageLoadingPlaceholder-Dcy5lc7F.js → ImageLoadingPlaceholder-DlQbo9CM.js} +1 -1
  12. package/dist/assets/{LoadingImage-BxjJ_Xyj.js → LoadingImage-sZ5omN5L.js} +1 -1
  13. package/dist/assets/MarkdownRenderer-BFR9FWQL.js +2 -0
  14. package/dist/assets/MarkdownRendererImpl-iZFUMI3M.js +10 -0
  15. package/dist/assets/{MarkstreamRendererImpl-EpBnVy9J.css → MarkstreamRendererImpl-C6aiJnjl.css} +1 -1
  16. package/dist/assets/MarkstreamRendererImpl-DjC_Y4LS.js +3 -0
  17. package/dist/assets/{MobileDetailNavigation-o54juFXD.js → MobileDetailNavigation-BOZpHdI2.js} +1 -1
  18. package/dist/assets/{MobileResizableSheet-sV9XR-0k.js → MobileResizableSheet-DuAi_epR.js} +1 -1
  19. package/dist/assets/{MobileShareBridge-oqBZ_f6M.js → MobileShareBridge-D1DrqLWf.js} +1 -1
  20. package/dist/assets/MobileTabPageHeader-BT9gWugr.js +2 -0
  21. package/dist/assets/{MultiRunWindow-7W_86vL6.js → MultiRunWindow-C0GYNaUU.js} +1 -1
  22. package/dist/assets/{OnboardingScreen-CnkijSLE.js → OnboardingScreen-CqsI0632.js} +1 -1
  23. package/dist/assets/{OverlayScrollbar-CCtBTJQj.js → OverlayScrollbar-CZD1yU06.js} +1 -1
  24. package/dist/assets/SettingsView-BYO8LY5A.js +29 -0
  25. package/dist/assets/{SettingsWindow-C0HiNvXh.js → SettingsWindow-CM0Ph9WD.js} +1 -1
  26. package/dist/assets/SetupTourDialog-BYlSBPKZ.js +1 -0
  27. package/dist/assets/SetupTourDialog-DrL_4ODI.css +1 -0
  28. package/dist/assets/{TerminalView-y36H_fIe.js → TerminalView-DnyEAShU.js} +1 -1
  29. package/dist/assets/{ToolOutputDialog-BfjBeqGS.js → ToolOutputDialog-BWONfWze.js} +1 -1
  30. package/dist/assets/{VoiceSettings-BONwzGgR.js → VoiceSettings-Ru_0ySgM.js} +2 -2
  31. package/dist/assets/{YuriLogo-BA5FWp-g.js → YuriLogo-CMUoGUHc.js} +1 -1
  32. package/dist/assets/YuriWordmark-DHYo0FlR.js +1 -0
  33. package/dist/assets/{appThemeRegistry-BsLMp3bc.js → appThemeRegistry-BMlAlm0m.js} +1 -1
  34. package/dist/assets/{button-CBjOhOI0.js → button-C-gRcs_2.js} +1 -1
  35. package/dist/assets/{capgoAdapter-DjlyVxy_.js → capgoAdapter-GdNfjwXs.js} +1 -1
  36. package/dist/assets/checkbox-BrJBzET8.js +1 -0
  37. package/dist/assets/{collapsible-B0j5IQ0T.js → collapsible-B7esGYLd.js} +1 -1
  38. package/dist/assets/{context-menu-C4e_bpls.js → context-menu-DWn1nSZC.js} +1 -1
  39. package/dist/assets/desktopHosts-BLU1tGSX.js +1 -0
  40. package/dist/assets/{desktopRelayRestore-AE3_TnQz.js → desktopRelayRestore-2BIIs8mZ.js} +1 -1
  41. package/dist/assets/{diagram-WPmk0Qh6.js → diagram-Bnra5_6g.js} +1 -1
  42. package/dist/assets/{dialog-Dx3IT7dQ.js → dialog-3UseH0hM.js} +1 -1
  43. package/dist/assets/{es-JU--16Gd.js → es-J7a_sZ1u.js} +2 -2
  44. package/dist/assets/{fileMentionTouchSelection-Bizsisaj.js → fileMentionTouchSelection-ByaQJcTS.js} +1 -1
  45. package/dist/assets/{fr-BUZcRuMk.js → fr-BYxUMKWp.js} +2 -2
  46. package/dist/assets/{gitApi-CNgEj6X5.js → gitApi-BdwvoQFb.js} +1 -1
  47. package/dist/assets/historyImportQueries-C8VK9R5_.js +1 -0
  48. package/dist/assets/host-z9PU8q1e.js +1 -0
  49. package/dist/assets/{input-CEJGM-TS.js → input-CmLlZdeD.js} +1 -1
  50. package/dist/assets/insertionBoundaries-BpQ6nLjP.js +1 -0
  51. package/dist/assets/{ja-BwtVLTXD.js → ja-DCdBiJmD.js} +2 -2
  52. package/dist/assets/{ko--sLsRFpA.js → ko-D-Nb_RJY.js} +2 -2
  53. package/dist/assets/main-Dosy2jXg.js +2 -0
  54. package/dist/assets/main-oBh-dk5-.js +169 -0
  55. package/dist/assets/{markdownHeightCache-D6iSNJG2.js → markdownHeightCache-xNkQdlqi.js} +1 -1
  56. package/dist/assets/{mcpQueries-DVSsZeuk.js → mcpQueries-C8zsTQqJ.js} +1 -1
  57. package/dist/assets/miniChat-CI8ryDGT.js +2 -0
  58. package/dist/assets/mobile-e_mTK3dh.js +2 -0
  59. package/dist/assets/{mobileBackNavigation-Dmbf0kw1.js → mobileBackNavigation-sB7c0Pi4.js} +1 -1
  60. package/dist/assets/multirun-DbmgWrsY.js +3 -0
  61. package/dist/assets/{native-config-BaRHaY4y.js → native-config-C_mwkFzh.js} +1 -1
  62. package/dist/assets/{pl-C4_4J5yA.js → pl-AmU4w3aM.js} +2 -2
  63. package/dist/assets/{projectMeta-rrpZdm8D.js → projectMeta-1iUbVl_M.js} +1 -1
  64. package/dist/assets/{pt-BR-DvNC5K1q.js → pt-BR-BI4ft-Fj.js} +2 -2
  65. package/dist/assets/pwa-BdUAGhLt.js +2 -0
  66. package/dist/assets/{queue-abort-optimistic-CSkERbr4.js → queue-abort-optimistic-BwDsaym5.js} +1 -1
  67. package/dist/assets/react-a6PrrNTm.js +1 -0
  68. package/dist/assets/{readiness-BnO7IaZV.js → readiness-D2N0DtZF.js} +1 -1
  69. package/dist/assets/{renderElectronMiniChatApp-Bq3iNKtr.js → renderElectronMiniChatApp-DV0cNt_O.js} +2 -2
  70. package/dist/assets/{renderMobileApp-DiNeMgwp.js → renderMobileApp-b7--jT5z.js} +7 -7
  71. package/dist/assets/{runtimeConfig-BHOiBANF.js → runtimeConfig-DxmJLWUO.js} +1 -1
  72. package/dist/assets/runtimeEndpointReset-jYAYa3Rh.js +149 -0
  73. package/dist/assets/{select-bKMw5JE8.js → select-J8r9SxHt.js} +1 -1
  74. package/dist/assets/sessionLookup-CUQqj2N4.js +1 -0
  75. package/dist/assets/{sortable-tabs-strip-3sKiA7T1.js → sortable-tabs-strip-CiP6RIQa.js} +1 -1
  76. package/dist/assets/{speechSettingsQueries-BDDxw8LP.js → speechSettingsQueries-B3ziGQvb.js} +1 -1
  77. package/dist/assets/src-GtPQ8f4o.css +2 -0
  78. package/dist/assets/{store-X3lU0obe.js → store-OjrIiXCx.js} +5 -5
  79. package/dist/assets/{textarea-EsaDD051.js → textarea-BHgcxJdC.js} +1 -1
  80. package/dist/assets/{tooltip-LLDL5nIZ.js → tooltip-Degmpxnd.js} +1 -1
  81. package/dist/assets/tour-DDI0Zg7l.js +1 -0
  82. package/dist/assets/types-QETHY-S7.js +2 -0
  83. package/dist/assets/{uk-Dvj0JjiC.js → uk-CbdByxxj.js} +2 -2
  84. package/dist/assets/{useAppFontEffects-wIWWE59b.js → useAppFontEffects-LADr3Zl1.js} +53 -53
  85. package/dist/assets/useDesktopWindowControlsLayout-BVNnRHtc.js +1 -0
  86. package/dist/assets/{useDictation-DlEHSN6P.js → useDictation-DFVJpRbm.js} +1 -1
  87. package/dist/assets/{useEffectiveDirectory-DzqpWUC3.js → useEffectiveDirectory-8tqfGdV5.js} +1 -1
  88. package/dist/assets/{useMobileNavigationStore-BWLhXqci.js → useMobileNavigationStore-CLUFv-TZ.js} +13 -13
  89. package/dist/assets/usePluginsStore-B_SIDwsK.js +1 -0
  90. package/dist/assets/useStreamingTextThrottle-VhgGU_te.js +1 -0
  91. package/dist/assets/{useWorkerHighlightedLines-DMS69wKa.js → useWorkerHighlightedLines-jlxakDGs.js} +1 -1
  92. package/dist/assets/{vendor-markstream-react-DfLaSG3W.js → vendor-markstream-react-6zxyQLCD.js} +1 -1
  93. package/dist/assets/{zh-CN-2Y6u8t24.js → zh-CN-ufEVDbXp.js} +2 -2
  94. package/dist/assets/{zh-TW-Z5wVv4Fb.js → zh-TW-DTBlZ4YC.js} +2 -2
  95. package/dist/index.html +8 -8
  96. package/dist/mini-chat.html +8 -8
  97. package/dist/mobile.html +8 -8
  98. package/package.json +1 -1
  99. package/server/index.js +3 -0
  100. package/server/lib/client-auth/pairing.js +2 -0
  101. package/server/lib/client-auth/pairing.test.js +29 -0
  102. package/server/lib/config-sync/DOCUMENTATION.md +8 -4
  103. package/server/lib/config-sync/index.js +1 -1
  104. package/server/lib/config-sync/magpie-auth.js +10 -4
  105. package/server/lib/config-sync/magpie-auth.test.js +4 -0
  106. package/server/lib/config-sync/magpie.js +28 -22
  107. package/server/lib/config-sync/magpie.test.js +127 -2
  108. package/server/lib/config-sync/plugins.js +44 -0
  109. package/server/lib/config-sync/plugins.test.js +64 -0
  110. package/server/lib/config-sync/tar.js +61 -1
  111. package/server/lib/content-search/DOCUMENTATION.md +9 -0
  112. package/server/lib/content-search/routes.js +18 -1
  113. package/server/lib/content-search/routes.test.js +21 -0
  114. package/server/lib/content-search/runtime.js +7 -3
  115. package/server/lib/content-search/runtime.test.js +26 -0
  116. package/server/lib/gui-customization/DOCUMENTATION.md +21 -1
  117. package/server/lib/gui-customization/session-skill.js +2 -2
  118. package/server/lib/gui-customization/session-skill.test.js +3 -1
  119. package/server/lib/gui-customization/skill/SKILL.md +5 -1
  120. package/server/lib/gui-customization/skill/references/global-pages.md +1 -1
  121. package/server/lib/gui-customization/skill/references/gui-api.md +4 -1
  122. package/server/lib/gui-customization/skill/references/icons.md +134 -0
  123. package/server/lib/gui-customization/skill/references/plugin-styles.md +112 -0
  124. package/server/lib/gui-customization/skill/references/ui-surfaces.md +2 -0
  125. package/server/lib/gui-customization/skill/references/work-status.md +110 -0
  126. package/server/lib/history-import/AGENT_CONNECT_LICENSE +21 -0
  127. package/server/lib/history-import/DOCUMENTATION.md +223 -0
  128. package/server/lib/history-import/dev-proxy.integration.test.js +56 -0
  129. package/server/lib/history-import/events.js +322 -0
  130. package/server/lib/history-import/events.test.js +110 -0
  131. package/server/lib/history-import/installations.js +39 -0
  132. package/server/lib/history-import/installations.test.js +24 -0
  133. package/server/lib/history-import/native.js +49 -0
  134. package/server/lib/history-import/native.test.js +42 -0
  135. package/server/lib/history-import/routes.js +48 -0
  136. package/server/lib/history-import/routes.test.js +55 -0
  137. package/server/lib/history-import/service.js +374 -0
  138. package/server/lib/history-import/service.test.js +538 -0
  139. package/server/lib/history-import/settings.js +146 -0
  140. package/server/lib/history-import/settings.test.js +88 -0
  141. package/server/lib/history-import/sources.js +184 -0
  142. package/server/lib/history-import/sources.test.js +190 -0
  143. package/server/lib/history-import/sqlite.js +187 -0
  144. package/server/lib/history-import/store.js +58 -0
  145. package/server/lib/history-import/store.test.js +84 -0
  146. package/server/lib/history-import/targets.js +24 -0
  147. package/server/lib/host-update/DOCUMENTATION.md +6 -0
  148. package/server/lib/host-update/routes.test.js +1 -1
  149. package/server/lib/notifications/native-stream.relay.test.js +1 -0
  150. package/server/lib/opencode/DOCUMENTATION.md +14 -0
  151. package/server/lib/opencode/core-routes.js +1 -0
  152. package/server/lib/opencode/feature-routes-runtime.js +11 -1
  153. package/server/lib/opencode/plugin-routes.test.js +1 -0
  154. package/server/lib/opencode/plugins.js +1 -1
  155. package/server/lib/opencode/plugins.test.js +3 -2
  156. package/server/lib/opencode/proxy.js +29 -4
  157. package/server/lib/opencode/proxy.test.js +85 -1
  158. package/server/lib/opencode/server-utils-runtime.js +2 -0
  159. package/server/lib/opencode/settings-runtime.js +8 -6
  160. package/server/lib/opencode/settings-runtime.test.js +44 -0
  161. package/server/lib/opencode/yuri-routes.js +1 -1
  162. package/server/lib/relay/DOCUMENTATION.md +1 -1
  163. package/server/lib/relay/host-client.js +3 -1
  164. package/server/lib/relay/host-client.test.js +1 -0
  165. package/server/lib/relay/reasoning-projection.e2e.test.ts +1 -0
  166. package/server/lib/relay/relay-server.e2e.test.ts +32 -17
  167. package/server/lib/relay/service.js +2 -0
  168. package/server/lib/relay/tunnel-host.js +26 -1
  169. package/server/lib/relay/tunnel-host.test.js +27 -3
  170. package/server/lib/remote-desktop/runtime.test.js +2 -2
  171. package/server/lib/ui-auth/DOCUMENTATION.md +3 -0
  172. package/server/lib/ui-auth/ui-auth.js +27 -0
  173. package/server/lib/ui-auth/ui-auth.test.js +42 -1
  174. package/server/plugin-gui-proxy.test.js +1 -1
  175. package/dist/assets/AssistantContactStatus-DZGGspw4.js +0 -3
  176. package/dist/assets/Icon-Bh3TaKoN.js +0 -1
  177. package/dist/assets/MarkdownRenderer-CS6Pia5D.js +0 -2
  178. package/dist/assets/MarkdownRendererImpl-Bdwe3qUr.js +0 -10
  179. package/dist/assets/MarkstreamRendererImpl-CCQj9IkL.js +0 -3
  180. package/dist/assets/MobileTabPageHeader-CptcDWNS.js +0 -2
  181. package/dist/assets/SettingsView-CkJpYIMe.js +0 -29
  182. package/dist/assets/SetupTourDialog-BcEbaEO3.js +0 -1
  183. package/dist/assets/SetupTourDialog-CUzqT2sw.css +0 -1
  184. package/dist/assets/YuriWordmark-Cr1vkcue.js +0 -1
  185. package/dist/assets/desktopHosts-CMglnUdS.js +0 -1
  186. package/dist/assets/host-CBfSyi4l.js +0 -1
  187. package/dist/assets/insertionBoundaries-CgYf6gys.js +0 -1
  188. package/dist/assets/main-B8FcBwPM.js +0 -169
  189. package/dist/assets/main-DrqtyqDc.js +0 -2
  190. package/dist/assets/miniChat-CgeCl4RY.js +0 -2
  191. package/dist/assets/mobile-DAhJKHUq.js +0 -2
  192. package/dist/assets/multirun-BbWnHeaY.js +0 -3
  193. package/dist/assets/pwa-Dm_DJEr9.js +0 -2
  194. package/dist/assets/react-Bwr5-XPi.js +0 -1
  195. package/dist/assets/runtimeEndpointReset-DGxT24oE.js +0 -149
  196. package/dist/assets/sessionLookup-DGNxfDsP.js +0 -1
  197. package/dist/assets/src-PTWgTO6W.css +0 -2
  198. package/dist/assets/tour-Db44qwfs.js +0 -1
  199. package/dist/assets/types-Cl7nTpsb.js +0 -2
  200. package/dist/assets/useDesktopWindowControlsLayout-CdUr9mCZ.js +0 -1
  201. package/dist/assets/usePluginsStore-aZl0WTK8.js +0 -1
@@ -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
+ }
@@ -0,0 +1,110 @@
1
+ import { describe, expect, test } from 'vitest';
2
+ import { Schema } from 'effect';
3
+ import { SessionMessage } from '@opencode/schema/session-message';
4
+ import { SessionTransfer } from '@opencode/schema/session-transfer';
5
+ import { combineSessions, parseTranscript, toNativeTransfer } from './events.js';
6
+
7
+ const at = '2026-01-01T00:00:00.000Z';
8
+ const claude = (id, parent, type, content, extra = {}) => ({ uuid: id, parentUuid: parent, type, timestamp: at, sessionId: 'chat', cwd: '/project', message: { content }, ...extra });
9
+
10
+ describe('source readers', () => {
11
+ test.each(['parent_thread_id', 'thread_spawn'])('Codex self-parent metadata is detached without losing the transcript (%s)', (field) => {
12
+ const parent = field === 'parent_thread_id' ? { parent_thread_id: 'same-thread' }
13
+ : { source: { subagent: { thread_spawn: { parent_thread_id: 'same-thread' } } } };
14
+ const result = parseTranscript('codex', [
15
+ { type: 'session_meta', payload: { id: 'same-thread', ...parent } },
16
+ { type: 'event_msg', payload: { type: 'user_message', message: 'Keep this conversation' } },
17
+ ], 'fallback');
18
+ expect(result.parentID).toBeUndefined();
19
+ expect(result.events.map((event) => event.text)).toEqual(['Keep this conversation']);
20
+ expect(result.warnings).toContain('parent_detached');
21
+ });
22
+ test('Claude follows the active branch and preserves genuine repeated messages', () => {
23
+ const entries = [claude('u1', null, 'user', 'continue'), claude('a1', 'u1', 'assistant', [{ type: 'text', text: 'old' }]),
24
+ claude('a2', 'u1', 'assistant', [{ type: 'text', text: 'new' }], { timestamp: '2026-01-01T00:00:01Z' }),
25
+ claude('u2', 'a2', 'user', 'continue', { timestamp: '2026-01-01T00:00:02Z' })];
26
+ const result = parseTranscript('claude', entries, 'fallback');
27
+ expect(result.events.map((event) => event.text)).toEqual(['continue', 'new', 'continue']);
28
+ expect(result.warnings).toContain('inactive_branches_omitted');
29
+ });
30
+ test('Claude keeps ordered text/tool/results and never fabricates tool completion', () => {
31
+ const entries = [claude('u', null, 'user', 'hello'), claude('a', 'u', 'assistant', [
32
+ { type: 'text', text: 'before' }, { type: 'tool_use', id: 'call', name: 'Read', input: { file_path: 'x' } }, { type: 'text', text: 'after' },
33
+ { type: 'tool_use', id: 'missing', name: 'Bash', input: { command: 'never run' } },
34
+ ]), claude('r', 'a', 'user', [{ type: 'tool_result', tool_use_id: 'call', content: 'full result' }], { timestamp: '2026-01-01T00:00:02Z' })];
35
+ const result = parseTranscript('claude', entries, 'fallback');
36
+ expect(result.events.map((event) => event.kind)).toEqual(['user', 'assistant-text', 'tool', 'assistant-text', 'tool']);
37
+ expect(result.events[2]).toMatchObject({ output: 'full result', incomplete: false });
38
+ expect(result.events[4]).toMatchObject({ incomplete: true });
39
+ });
40
+ test('parallel Claude tool fragments and snip relinks survive chain recovery', () => {
41
+ const entries = [claude('u', null, 'user', 'hello'),
42
+ claude('a1', 'u', 'assistant', [{ type: 'tool_use', id: 'one', name: 'Read' }], { message: { id: 'shared', content: [{ type: 'tool_use', id: 'one', name: 'Read' }] } }),
43
+ claude('a2', 'u', 'assistant', [], { message: { id: 'shared', content: [{ type: 'tool_use', id: 'two', name: 'Read' }] }, timestamp: '2026-01-01T00:00:01Z' }),
44
+ claude('r1', 'a1', 'user', [{ type: 'tool_result', tool_use_id: 'one', content: 'one' }]),
45
+ claude('r2', 'a2', 'user', [{ type: 'tool_result', tool_use_id: 'two', content: 'two' }], { timestamp: '2026-01-01T00:00:02Z' })];
46
+ expect(parseTranscript('claude', entries, 'fallback').events.filter((event) => event.kind === 'tool').map((event) => event.output).sort()).toEqual(['one', 'two']);
47
+ });
48
+ test.each([false, true])('Codex pairs both dual-track orders without removing repeated turns (%s)', (reverse) => {
49
+ const event = (text) => ({ type: 'event_msg', timestamp: at, payload: { type: 'user_message', message: text } });
50
+ const response = (text) => ({ type: 'response_item', timestamp: at, payload: { type: 'message', role: 'user', content: [{ type: 'input_text', text }] } });
51
+ const pair = (text) => reverse ? [event(text), response(text)] : [response(text), event(text)];
52
+ const assistant = { type: 'response_item', timestamp: at, payload: { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'answer' }] } };
53
+ const entries = [{ type: 'session_meta', payload: { id: 'codex', cwd: '/project' } }, ...pair('continue'), assistant, ...pair('continue'), assistant,
54
+ { type: 'event_msg', payload: { type: 'thread_rolled_back', num_turns: 1 } }, ...pair('replacement')];
55
+ const result = parseTranscript('codex', entries, 'fallback');
56
+ expect(result.events.map((item) => item.text)).toEqual(['continue', 'answer', 'replacement']);
57
+ });
58
+ test('Codex includes complete tool outputs without replay payloads', () => {
59
+ const result = parseTranscript('codex', [{ type: 'session_meta', payload: { id: 'id' } },
60
+ { type: 'response_item', payload: { type: 'function_call', call_id: 'c', name: 'shell', arguments: '{"cmd":"echo test"}' } },
61
+ { type: 'response_item', payload: { type: 'function_call_output', call_id: 'c', output: 'x'.repeat(100000) } }], 'fallback');
62
+ expect(result.events[0].output).toHaveLength(100000);
63
+ expect(result.events[0].incomplete).toBe(false);
64
+ });
65
+ test('Codex event-only assistant output survives without duplicating its native encoding or a later repeated turn', () => {
66
+ const user = { type: 'event_msg', payload: { type: 'user_message', message: 'continue' } };
67
+ const answer = { type: 'event_msg', payload: { type: 'agent_message', message: 'answer' } };
68
+ const native = { type: 'response_item', payload: { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'answer' }] } };
69
+ const reasoning = { type: 'event_msg', payload: { type: 'agent_reasoning', text: 'historical reasoning' } };
70
+ const result = parseTranscript('codex', [user, answer, native, user, answer, reasoning], 'fixture');
71
+ expect(result.events.map((event) => event.text)).toEqual(['continue', 'answer', 'continue', 'answer', 'historical reasoning']);
72
+ });
73
+ test('DSH surface replacements exclude superseded history and pair tool blocks only once', () => {
74
+ const entries = [{ type: 'session', version: 4, id: 'dsh', cwd: '/project', parentSession: 'parent' },
75
+ { type: 'user/message', seq: 0, time: 1, surfaceOp: 'append', data: { source: { kind: 'user' }, content: [{ type: 'text', text: 'old' }] } },
76
+ { type: 'user/message', seq: 1, time: 2, surfaceOp: { op: 'replace', startSeq: 0, endSeq: 0 }, data: { source: { kind: 'user' }, content: [{ type: 'text', text: 'summary' }] } },
77
+ { type: 'assistant/message', seq: 2, time: 3, surfaceOp: 'append', data: { message: { content: [{ type: 'tool-call', id: 'c', name: 'read', arguments: '{}' }] } } },
78
+ { type: 'tool/call', seq: 3, time: 3, data: { callId: 'c', name: 'read', arguments: '{}' } },
79
+ { type: 'tool/result', seq: 4, time: 4, surfaceOp: 'append', data: { message: { source: { callId: 'c' }, content: [{ type: 'tool-result', toolCallId: 'c', content: [{ type: 'text', text: 'result' }] }] } } }];
80
+ const result = parseTranscript('dsh', entries, 'fallback');
81
+ expect(result.events).toHaveLength(2);
82
+ expect(result.events[0].text).toBe('summary');
83
+ expect(result.events[1]).toMatchObject({ kind: 'tool', name: 'read', input: '{}', output: 'result', incomplete: false });
84
+ expect(result.parentID).toBeUndefined();
85
+ expect(result.warnings).toContain('fork_archived');
86
+ });
87
+ test('DSH unknown versions and broken sequences are explicit errors', () => {
88
+ expect(() => parseTranscript('dsh', [{ type: 'session', version: 99, id: 'd' }], 'fallback')).toThrow('unsupported_source_version');
89
+ expect(() => parseTranscript('dsh', [{ type: 'session', version: 4, id: 'd' }, { type: 'user/message', seq: 10 }], 'fallback')).toThrow('invalid_source');
90
+ });
91
+ });
92
+
93
+ test('native transfer round-trips the installed official schemas, with no permissions or native replay data', () => {
94
+ const session = parseTranscript('claude', [claude('u', null, 'user', [{ type: 'text', text: 'hello' }, { type: 'image', source: { type: 'base64', data: 'aGVsbG8=', media_type: 'image/png' } }]),
95
+ claude('a', 'u', 'assistant', [{ type: 'thinking', thinking: 'historical reasoning' }, { type: 'text', text: 'answer' }], { timestamp: '2026-01-01T00:00:01Z' })], 'fallback');
96
+ const transfer = toNativeTransfer(session, '/project', 'ses_import', { version: 1 });
97
+ const decoded = Schema.decodeUnknownSync(SessionTransfer.Data)({ info: transfer.info, messages: transfer.messages });
98
+ expect(decoded.messages).toHaveLength(3);
99
+ for (const message of transfer.messages) expect(() => Schema.decodeUnknownSync(SessionMessage.Info)(message)).not.toThrow();
100
+ expect(transfer.info.permissions).toBeUndefined();
101
+ expect(transfer.info.model).toBeUndefined();
102
+ expect(transfer.messages[0].files[0].source).toEqual({ type: 'inline' });
103
+ expect(transfer.info.time.updated).toBe(Date.parse('2026-01-01T00:00:01Z'));
104
+ });
105
+
106
+ test('explicit merge deduplicates only a shared prefix and preserves continuation order', () => {
107
+ const u = (text) => ({ kind: 'user', text, time: 1 });
108
+ const result = combineSessions([{ title: 'a', events: [u('hello'), u('continue')] }, { title: 'b', events: [u('hello'), u('different'), u('continue'), u('continue')] }]);
109
+ expect(result.filter((event) => event.kind === 'user').map((event) => event.text)).toEqual(['hello', 'continue', 'different', 'continue', 'continue']);
110
+ });
@@ -0,0 +1,39 @@
1
+ import fs from 'node:fs/promises';
2
+ import { constants } from 'node:fs';
3
+ import path from 'node:path';
4
+ import os from 'node:os';
5
+
6
+ const commands = { claude: ['claude'], codex: ['codex'], cursor: ['cursor', 'cursor-agent'], dsh: ['dsh'] };
7
+
8
+ // Installation evidence is an executable/app binary, never a leftover history
9
+ // directory. Probes do not launch source agents or read their configuration.
10
+ export async function detectSourceInstallations(sources = Object.keys(commands), { home = os.homedir(), env = process.env, platform = process.platform } = {}) {
11
+ const windows = platform === 'win32';
12
+ const paths = [...new Set([...(env.PATH || '').split(windows ? ';' : path.delimiter).filter(Boolean),
13
+ path.join(home, '.local', 'bin'), path.join(home, '.bun', 'bin'), path.join(home, '.npm-global', 'bin')])];
14
+ const extensions = windows ? ['', '.exe', '.cmd', '.bat', '.com'] : [''];
15
+ return Object.fromEntries(await Promise.all(sources.map(async (source) => {
16
+ if (!commands[source]) return [source, null];
17
+ const candidates = paths.flatMap((directory) => commands[source].flatMap((command) => extensions.map((extension) => path.join(directory, `${command}${extension}`))));
18
+ if (source === 'claude') candidates.push(path.join(home, '.claude', 'local', 'claude'));
19
+ if (platform === 'darwin' && ['cursor', 'codex'].includes(source)) {
20
+ const name = source === 'cursor' ? 'Cursor' : 'Codex';
21
+ for (const applications of ['/Applications', path.join(home, 'Applications')]) candidates.push(path.join(applications, `${name}.app`, 'Contents', 'MacOS', name));
22
+ }
23
+ if (windows && source === 'cursor') {
24
+ if (env.LOCALAPPDATA) candidates.push(path.join(env.LOCALAPPDATA, 'Programs', 'cursor', 'Cursor.exe'));
25
+ if (env.ProgramFiles) candidates.push(path.join(env.ProgramFiles, 'Cursor', 'Cursor.exe'));
26
+ }
27
+ let unknown = false;
28
+ for (const candidate of candidates) {
29
+ try {
30
+ if (!(await fs.stat(candidate)).isFile()) continue;
31
+ await fs.access(candidate, windows ? constants.F_OK : constants.X_OK);
32
+ return [source, true];
33
+ } catch (error) {
34
+ if (!['ENOENT', 'ENOTDIR'].includes(error.code)) unknown = true;
35
+ }
36
+ }
37
+ return [source, unknown ? null : false];
38
+ })));
39
+ }
@@ -0,0 +1,24 @@
1
+ import { afterEach, beforeEach, expect, test } from 'vitest';
2
+ import fs from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { detectSourceInstallations } from './installations.js';
6
+
7
+ let home;
8
+ beforeEach(async () => { home = await fs.mkdtemp(path.join(os.tmpdir(), 'yuri-installation-test-')); });
9
+ afterEach(async () => { await fs.rm(home, { recursive: true, force: true }); });
10
+
11
+ test('installation is detected from executables without executing them; history folders alone are not evidence', async () => {
12
+ const bin = path.join(home, 'bin'); await fs.mkdir(bin);
13
+ await fs.writeFile(path.join(bin, 'claude'), 'this fixture must never execute', { mode: 0o700 });
14
+ await fs.mkdir(path.join(home, '.codex', 'sessions'), { recursive: true });
15
+ await fs.mkdir(path.join(home, '.cursor'), { recursive: true });
16
+ expect(await detectSourceInstallations(undefined, { home, env: { PATH: bin }, platform: 'linux' })).toEqual({ claude: true, codex: false, cursor: false, dsh: false });
17
+ });
18
+ test('user-local executable symlinks count as installed; denied probes remain unknown', async () => {
19
+ const bin = path.join(home, '.local', 'bin'); await fs.mkdir(bin, { recursive: true });
20
+ await fs.writeFile(path.join(home, 'dsh'), 'fixture', { mode: 0o700 });
21
+ await fs.symlink(path.join(home, 'dsh'), path.join(bin, 'dsh'));
22
+ await fs.writeFile(path.join(bin, 'codex'), 'not executable', { mode: 0o600 });
23
+ expect(await detectSourceInstallations(['dsh', 'codex'], { home, env: { PATH: '' }, platform: 'linux' })).toEqual({ dsh: true, codex: null });
24
+ });
@@ -0,0 +1,49 @@
1
+ import { digest, fail } from './events.js';
2
+
3
+ const directoryOf = (session) => session.location?.directory;
4
+ export const nativeRevision = (session, namespace) => ({ source: 'opencode', namespace, id: session.id,
5
+ hash: digest({ id: session.id, directory: directoryOf(session) }), directory: directoryOf(session) });
6
+
7
+ // Only metadata is paged for inventory. Message projection is limited to the
8
+ // visible examples and never used by the in-place project registration job.
9
+ export async function discoverNative(client, namespace, { limitPerSource, includeCounts = false } = {}) {
10
+ const sessions = []; const descriptors = new Map(); const errors = [];
11
+ const seen = new Set(); const cursors = new Set(); const signal = AbortSignal.timeout(10000);
12
+ let cursor; let complete = false;
13
+ try {
14
+ do {
15
+ const page = await client.session.list({ limit: 100, ...(cursor ? { cursor } : { order: 'desc' }) }, { signal });
16
+ if (!Array.isArray(page.data)) fail('invalid_source');
17
+ for (const info of page.data) {
18
+ if (seen.has(info.id)) continue;
19
+ if (seen.size >= 5000) fail('too_many_sessions');
20
+ seen.add(info.id);
21
+ if (limitPerSource !== undefined && sessions.length >= limitPerSource) continue;
22
+ const key = digest(`opencode:${namespace}:${info.id}`);
23
+ const revision = nativeRevision(info, namespace);
24
+ descriptors.set(key, { source: 'opencode', format: 'opencode', sessionID: info.id, namespace, revision });
25
+ sessions.push({ key, source: 'opencode', id: info.id, title: info.title || info.id,
26
+ directory: directoryOf(info) || '', messages: 0, warnings: [], updated: info.time?.updated });
27
+ }
28
+ cursor = page.cursor?.next;
29
+ complete = !cursor;
30
+ if (cursor && cursors.has(cursor)) fail('invalid_source');
31
+ if (cursor) cursors.add(cursor);
32
+ } while (cursor && (limitPerSource === undefined || includeCounts));
33
+ } catch (error) { errors.push({ source: 'opencode', code: error.code ?? 'source_unreadable' }); }
34
+ if (limitPerSource !== undefined) {
35
+ await Promise.all(sessions.map(async (session) => {
36
+ try {
37
+ const page = await client.message.list({ sessionID: session.id, limit: 10, order: 'desc' }, { signal });
38
+ const text = (message) => message.type === 'assistant' ? message.content?.filter((part) => part.type === 'text').map((part) => part.text).join(' ') : message.type === 'user' ? message.text : '';
39
+ const messages = page.data;
40
+ if (!Array.isArray(messages)) fail('invalid_source');
41
+ const excerpt = messages.find((message) => message.type === 'assistant' && text(message)?.trim())
42
+ ?? messages.find((message) => message.type === 'user' && text(message)?.trim());
43
+ session.excerpt = text(excerpt ?? {})?.slice(0, 512).replace(/\s+/g, ' ').trim().slice(0, 180) || '';
44
+ } catch { session.warnings.push('preview_unavailable'); }
45
+ }));
46
+ }
47
+ return { sessions, descriptors, errors,
48
+ counts: includeCounts ? { opencode: { value: complete ? seen.size : null, approximate: false } } : undefined };
49
+ }
@@ -0,0 +1,42 @@
1
+ import { expect, test, vi } from 'vitest';
2
+ import { discoverNative } from './native.js';
3
+
4
+ const info = (id) => ({ id: `ses_${id}`, title: `Conversation ${id}`, location: { directory: '/workspace/example' }, time: { updated: id } });
5
+ const clientFor = (size) => ({ session: { list: vi.fn(async ({ cursor, limit }) => {
6
+ const offset = Number(cursor || 0); const end = Math.min(size, offset + limit);
7
+ return { data: Array.from({ length: end - offset }, (_, index) => info(offset + index)), cursor: end < size ? { next: String(end) } : {} };
8
+ }) }, message: { list: vi.fn(async () => ({ data: [
9
+ { type: 'assistant', content: [{ type: 'reasoning', text: 'private reasoning' }, { type: 'tool', text: 'tool output' }, { type: 'text', text: 'Real\n assistant answer' }] },
10
+ ], cursor: {} })) } });
11
+
12
+ test('5000 native sessions count only metadata, with five bounded message pages and no writes', async () => {
13
+ const client = clientFor(5000);
14
+ const result = await discoverNative(client, 'runtime', { limitPerSource: 5, includeCounts: true });
15
+ expect(result.counts.opencode).toEqual({ value: 5000, approximate: false });
16
+ expect(result.sessions).toHaveLength(5); expect(result.errors).toEqual([]);
17
+ expect(client.session.list).toHaveBeenCalledTimes(50);
18
+ expect(client.message.list).toHaveBeenCalledTimes(5);
19
+ expect(client.message.list.mock.calls.every(([query]) => query.limit === 10)).toBe(true);
20
+ expect(result.sessions[0].excerpt).toBe('Real assistant answer');
21
+ expect(result.descriptors.size).toBe(5);
22
+ });
23
+
24
+ test('full native discovery never reads messages; failed pagination does not claim a partial count', async () => {
25
+ const client = clientFor(101);
26
+ const full = await discoverNative(client, 'runtime');
27
+ expect(full.sessions).toHaveLength(101); expect(client.message.list).not.toHaveBeenCalled();
28
+ client.session.list.mockRejectedValueOnce(new Error('offline'));
29
+ const failed = await discoverNative(client, 'runtime', { limitPerSource: 5, includeCounts: true });
30
+ expect(failed.counts.opencode.value).toBeNull(); expect(failed.errors).toHaveLength(1);
31
+ });
32
+
33
+ test('counting failure keeps readable examples; repeated cursors and oversized catalogs stay bounded', async () => {
34
+ const client = clientFor(5001);
35
+ const result = await discoverNative(client, 'runtime', { limitPerSource: 5, includeCounts: true });
36
+ expect(result.sessions).toHaveLength(5); expect(result.counts.opencode.value).toBeNull();
37
+ expect(result.errors[0].code).toBe('too_many_sessions');
38
+ client.session.list.mockResolvedValue({ data: [info(1)], cursor: { next: 'same' } });
39
+ const repeated = await discoverNative(client, 'runtime', { limitPerSource: 5, includeCounts: true });
40
+ expect(repeated.errors[0].code).toBe('invalid_source');
41
+ expect(repeated.counts.opencode.value).toBeNull();
42
+ });