@kirkchinese/harness-forge 0.0.0-stage → 0.5.0

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 (279) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +46 -2
  3. package/assets/icon.svg +12 -0
  4. package/cordis.patch.yml +28 -0
  5. package/docs/DETAIL.zh.md +47 -0
  6. package/lib/agents/presets.d.ts +98 -0
  7. package/lib/agents/presets.js +292 -0
  8. package/lib/agents/profiles.d.ts +58 -0
  9. package/lib/agents/profiles.js +279 -0
  10. package/lib/agents/row.d.ts +17 -0
  11. package/lib/agents/row.js +148 -0
  12. package/lib/client/paths.d.ts +12 -0
  13. package/lib/client/paths.js +68 -0
  14. package/lib/client/styles.d.ts +8 -0
  15. package/lib/client/styles.js +89 -0
  16. package/lib/client/typert.d.ts +25 -0
  17. package/lib/client/typert.js +158 -0
  18. package/lib/client.js +23823 -0
  19. package/lib/commands/definition.d.ts +40 -0
  20. package/lib/commands/definition.js +113 -0
  21. package/lib/commands/output-styles.d.ts +42 -0
  22. package/lib/commands/output-styles.js +152 -0
  23. package/lib/commands/row.d.ts +9 -0
  24. package/lib/commands/row.js +157 -0
  25. package/lib/context/instructions.d.ts +32 -0
  26. package/lib/context/instructions.js +88 -0
  27. package/lib/context/row.d.ts +16 -0
  28. package/lib/context/row.js +17 -0
  29. package/lib/dsh/commands.d.ts +30 -0
  30. package/lib/dsh/commands.js +61 -0
  31. package/lib/dsh/host.d.ts +110 -0
  32. package/lib/dsh/host.js +217 -0
  33. package/lib/dsh/model-route.d.ts +21 -0
  34. package/lib/dsh/model-route.js +37 -0
  35. package/lib/dsh/session-records.d.ts +78 -0
  36. package/lib/dsh/session-records.js +36 -0
  37. package/lib/dsh/subagents.d.ts +46 -0
  38. package/lib/dsh/subagents.js +14 -0
  39. package/lib/forge/contract.d.ts +271 -0
  40. package/lib/forge/contract.js +45 -0
  41. package/lib/forge/follow.d.ts +30 -0
  42. package/lib/forge/follow.js +73 -0
  43. package/lib/forge/ledger.d.ts +206 -0
  44. package/lib/forge/ledger.js +1005 -0
  45. package/lib/forge/live-mounts.d.ts +45 -0
  46. package/lib/forge/live-mounts.js +78 -0
  47. package/lib/forge/npm.d.ts +31 -0
  48. package/lib/forge/npm.js +60 -0
  49. package/lib/forge/projects.d.ts +97 -0
  50. package/lib/forge/projects.js +343 -0
  51. package/lib/forge/receipts.d.ts +5 -0
  52. package/lib/forge/receipts.js +31 -0
  53. package/lib/forge/remote/archive.d.ts +65 -0
  54. package/lib/forge/remote/archive.js +565 -0
  55. package/lib/forge/remote/code-parts.d.ts +18 -0
  56. package/lib/forge/remote/code-parts.js +76 -0
  57. package/lib/forge/remote/fetch.d.ts +265 -0
  58. package/lib/forge/remote/fetch.js +1133 -0
  59. package/lib/forge/remote/service.d.ts +256 -0
  60. package/lib/forge/remote/service.js +868 -0
  61. package/lib/forge/row.d.ts +32 -0
  62. package/lib/forge/row.js +59 -0
  63. package/lib/forge/service.d.ts +115 -0
  64. package/lib/forge/service.js +290 -0
  65. package/lib/forge/settings.d.ts +43 -0
  66. package/lib/forge/settings.js +122 -0
  67. package/lib/forge/state.d.ts +129 -0
  68. package/lib/forge/state.js +266 -0
  69. package/lib/forge/trust.d.ts +48 -0
  70. package/lib/forge/trust.js +107 -0
  71. package/lib/forge/turns.d.ts +13 -0
  72. package/lib/forge/turns.js +56 -0
  73. package/lib/hooks/broker/engine.d.ts +112 -0
  74. package/lib/hooks/broker/engine.js +722 -0
  75. package/lib/hooks/broker/helpers.d.ts +10 -0
  76. package/lib/hooks/broker/helpers.js +22 -0
  77. package/lib/hooks/broker/lifecycle.d.ts +65 -0
  78. package/lib/hooks/broker/lifecycle.js +342 -0
  79. package/lib/hooks/broker/session-events.d.ts +27 -0
  80. package/lib/hooks/broker/session-events.js +205 -0
  81. package/lib/hooks/broker/tools.d.ts +52 -0
  82. package/lib/hooks/broker/tools.js +424 -0
  83. package/lib/hooks/broker/types.d.ts +264 -0
  84. package/lib/hooks/broker/types.js +1 -0
  85. package/lib/hooks/broker.d.ts +80 -0
  86. package/lib/hooks/broker.js +95 -0
  87. package/lib/hooks/codex-user.d.ts +5 -0
  88. package/lib/hooks/codex-user.js +109 -0
  89. package/lib/hooks/condition.d.ts +87 -0
  90. package/lib/hooks/condition.js +602 -0
  91. package/lib/hooks/config.d.ts +85 -0
  92. package/lib/hooks/config.js +154 -0
  93. package/lib/hooks/glob.d.ts +41 -0
  94. package/lib/hooks/glob.js +114 -0
  95. package/lib/hooks/matcher.d.ts +20 -0
  96. package/lib/hooks/matcher.js +39 -0
  97. package/lib/hooks/notice.d.ts +17 -0
  98. package/lib/hooks/notice.js +39 -0
  99. package/lib/hooks/output.d.ts +56 -0
  100. package/lib/hooks/output.js +214 -0
  101. package/lib/hooks/permissions.d.ts +19 -0
  102. package/lib/hooks/permissions.js +202 -0
  103. package/lib/hooks/powershell-aliases.d.ts +19 -0
  104. package/lib/hooks/powershell-aliases.js +58 -0
  105. package/lib/hooks/process.d.ts +64 -0
  106. package/lib/hooks/process.js +289 -0
  107. package/lib/hooks/row.d.ts +17 -0
  108. package/lib/hooks/row.js +96 -0
  109. package/lib/hooks/runner.d.ts +98 -0
  110. package/lib/hooks/runner.js +322 -0
  111. package/lib/hooks/shell-commands.d.ts +28 -0
  112. package/lib/hooks/shell-commands.js +241 -0
  113. package/lib/hooks/shell.d.ts +44 -0
  114. package/lib/hooks/shell.js +129 -0
  115. package/lib/hooks/transcript.d.ts +28 -0
  116. package/lib/hooks/transcript.js +141 -0
  117. package/lib/hooks/vocabulary.d.ts +57 -0
  118. package/lib/hooks/vocabulary.js +366 -0
  119. package/lib/index.d.ts +31 -0
  120. package/lib/index.js +287 -0
  121. package/lib/mcp/auth.d.ts +35 -0
  122. package/lib/mcp/auth.js +178 -0
  123. package/lib/mcp/catalog.d.ts +39 -0
  124. package/lib/mcp/catalog.js +69 -0
  125. package/lib/mcp/mount.d.ts +113 -0
  126. package/lib/mcp/mount.js +317 -0
  127. package/lib/mcp/policy.d.ts +42 -0
  128. package/lib/mcp/policy.js +43 -0
  129. package/lib/mcp/remote.d.ts +45 -0
  130. package/lib/mcp/remote.js +133 -0
  131. package/lib/mcp/row.d.ts +9 -0
  132. package/lib/mcp/row.js +225 -0
  133. package/lib/mods/bundler.d.ts +38 -0
  134. package/lib/mods/bundler.js +157 -0
  135. package/lib/mods/chain.d.ts +103 -0
  136. package/lib/mods/chain.js +436 -0
  137. package/lib/mods/claude.d.ts +27 -0
  138. package/lib/mods/claude.js +56 -0
  139. package/lib/mods/engine.d.ts +160 -0
  140. package/lib/mods/engine.js +701 -0
  141. package/lib/mods/expect.d.ts +8 -0
  142. package/lib/mods/expect.js +248 -0
  143. package/lib/mods/host.d.ts +105 -0
  144. package/lib/mods/host.js +462 -0
  145. package/lib/mods/loader.d.ts +53 -0
  146. package/lib/mods/loader.js +231 -0
  147. package/lib/mods/ops.d.ts +13 -0
  148. package/lib/mods/ops.js +117 -0
  149. package/lib/mods/row.d.ts +9 -0
  150. package/lib/mods/row.js +77 -0
  151. package/lib/mods/runtime.d.ts +60 -0
  152. package/lib/mods/runtime.js +133 -0
  153. package/lib/mods/service/commands.d.ts +17 -0
  154. package/lib/mods/service/commands.js +121 -0
  155. package/lib/mods/service/drawings.d.ts +36 -0
  156. package/lib/mods/service/drawings.js +64 -0
  157. package/lib/mods/service/sessions.d.ts +63 -0
  158. package/lib/mods/service/sessions.js +345 -0
  159. package/lib/mods/service/tools.d.ts +32 -0
  160. package/lib/mods/service/tools.js +253 -0
  161. package/lib/mods/service/turns.d.ts +33 -0
  162. package/lib/mods/service/turns.js +136 -0
  163. package/lib/mods/service/types.d.ts +151 -0
  164. package/lib/mods/service/types.js +1 -0
  165. package/lib/mods/service.d.ts +72 -0
  166. package/lib/mods/service.js +104 -0
  167. package/lib/mods/surfaces.d.ts +93 -0
  168. package/lib/mods/surfaces.js +309 -0
  169. package/lib/mods/values.d.ts +30 -0
  170. package/lib/mods/values.js +95 -0
  171. package/lib/opencode/bun.d.ts +40 -0
  172. package/lib/opencode/bun.js +168 -0
  173. package/lib/opencode/convert.d.ts +53 -0
  174. package/lib/opencode/convert.js +255 -0
  175. package/lib/opencode/row.d.ts +22 -0
  176. package/lib/opencode/row.js +104 -0
  177. package/lib/opencode/runtime/core.d.ts +74 -0
  178. package/lib/opencode/runtime/core.js +249 -0
  179. package/lib/opencode/runtime/events.d.ts +80 -0
  180. package/lib/opencode/runtime/events.js +281 -0
  181. package/lib/opencode/runtime/mount.d.ts +27 -0
  182. package/lib/opencode/runtime/mount.js +283 -0
  183. package/lib/opencode/runtime/server.d.ts +27 -0
  184. package/lib/opencode/runtime/server.js +354 -0
  185. package/lib/opencode/runtime/types.d.ts +109 -0
  186. package/lib/opencode/runtime/types.js +1 -0
  187. package/lib/opencode/runtime.d.ts +55 -0
  188. package/lib/opencode/runtime.js +79 -0
  189. package/lib/porting/adapter-paths.d.ts +13 -0
  190. package/lib/porting/adapter-paths.js +120 -0
  191. package/lib/porting/port-gap.d.ts +36 -0
  192. package/lib/porting/port-gap.js +158 -0
  193. package/lib/porting/port-sessions.d.ts +41 -0
  194. package/lib/porting/port-sessions.js +98 -0
  195. package/lib/porting/prompt.d.ts +23 -0
  196. package/lib/porting/prompt.js +51 -0
  197. package/lib/porting/row.d.ts +16 -0
  198. package/lib/porting/row.js +27 -0
  199. package/lib/porting/verify-port.d.ts +46 -0
  200. package/lib/porting/verify-port.js +82 -0
  201. package/lib/presets/fs-search.d.ts +25 -0
  202. package/lib/presets/fs-search.js +17 -0
  203. package/lib/presets/tool-filter.d.ts +35 -0
  204. package/lib/presets/tool-filter.js +91 -0
  205. package/lib/sessions/chat-import.d.ts +48 -0
  206. package/lib/sessions/chat-import.js +44 -0
  207. package/lib/sessions/claude.d.ts +35 -0
  208. package/lib/sessions/claude.js +104 -0
  209. package/lib/sessions/codex-discover.d.ts +34 -0
  210. package/lib/sessions/codex-discover.js +205 -0
  211. package/lib/sessions/codex-meta.d.ts +63 -0
  212. package/lib/sessions/codex-meta.js +148 -0
  213. package/lib/sessions/codex-text.d.ts +9 -0
  214. package/lib/sessions/codex-text.js +44 -0
  215. package/lib/sessions/codex.d.ts +42 -0
  216. package/lib/sessions/codex.js +270 -0
  217. package/lib/sessions/opencode.d.ts +38 -0
  218. package/lib/sessions/opencode.js +339 -0
  219. package/lib/sessions/persist.d.ts +162 -0
  220. package/lib/sessions/persist.js +377 -0
  221. package/lib/sessions/row.d.ts +15 -0
  222. package/lib/sessions/row.js +101 -0
  223. package/lib/sessions/turns.d.ts +31 -0
  224. package/lib/sessions/turns.js +63 -0
  225. package/lib/sessions/zstd.d.ts +15 -0
  226. package/lib/sessions/zstd.js +152 -0
  227. package/lib/shared/invocation.d.ts +169 -0
  228. package/lib/shared/invocation.js +325 -0
  229. package/lib/shared/render.d.ts +101 -0
  230. package/lib/shared/render.js +1353 -0
  231. package/lib/shared/util.d.ts +21 -0
  232. package/lib/shared/util.js +32 -0
  233. package/lib/skills/bundled.d.ts +3 -0
  234. package/lib/skills/bundled.js +42 -0
  235. package/lib/skills/provider.d.ts +74 -0
  236. package/lib/skills/provider.js +346 -0
  237. package/lib/skills/row.d.ts +22 -0
  238. package/lib/skills/row.js +204 -0
  239. package/lib/workbench/adapter-coverage.d.ts +65 -0
  240. package/lib/workbench/adapter-coverage.js +141 -0
  241. package/lib/workbench/model-tools.d.ts +10 -0
  242. package/lib/workbench/model-tools.js +122 -0
  243. package/lib/workbench/overview.d.ts +153 -0
  244. package/lib/workbench/overview.js +246 -0
  245. package/lib/workbench/remote.d.ts +161 -0
  246. package/lib/workbench/remote.js +561 -0
  247. package/lib/workbench/row.d.ts +15 -0
  248. package/lib/workbench/row.js +16 -0
  249. package/lib/workbench/settings.d.ts +19 -0
  250. package/lib/workbench/settings.js +60 -0
  251. package/lib/workbench/workbench.d.ts +130 -0
  252. package/lib/workbench/workbench.js +361 -0
  253. package/locale/agents/en.json +6 -0
  254. package/locale/agents/zh.json +6 -0
  255. package/locale/commands/en.json +6 -0
  256. package/locale/commands/zh.json +6 -0
  257. package/locale/context/en.json +6 -0
  258. package/locale/context/zh.json +6 -0
  259. package/locale/en.json +6 -0
  260. package/locale/hooks/en.json +6 -0
  261. package/locale/hooks/zh.json +6 -0
  262. package/locale/mcp/en.json +6 -0
  263. package/locale/mcp/zh.json +6 -0
  264. package/locale/mods/en.json +6 -0
  265. package/locale/mods/zh.json +6 -0
  266. package/locale/opencode/en.json +6 -0
  267. package/locale/opencode/zh.json +6 -0
  268. package/locale/porter/en.json +6 -0
  269. package/locale/porter/zh.json +6 -0
  270. package/locale/sessions/en.json +6 -0
  271. package/locale/sessions/zh.json +6 -0
  272. package/locale/skills/en.json +6 -0
  273. package/locale/skills/zh.json +6 -0
  274. package/locale/workbench/en.json +6 -0
  275. package/locale/workbench/zh.json +6 -0
  276. package/locale/zh.json +7 -0
  277. package/package.json +247 -3
  278. package/runtime/opencode-host.mjs +270 -0
  279. package/skills/harness-forge/SKILL.md +47 -0
@@ -0,0 +1,270 @@
1
+ import { homedir } from 'node:os';
2
+ import { dirname, join } from 'node:path';
3
+ import { assertFileImportable, fileLines, limitBytes, MAX_LINE_BYTES, splitLines } from '@kirkchinese/harness-forge-core';
4
+ import { zstdChunks } from './zstd.js';
5
+ import { stringField, textOf, timestamp, usablePrompt } from './codex-text.js';
6
+ import { codexHomeOf, codexIdentity, codexSessionId, CodexTitle, rolloutCreatedAt, rolloutThread, threadNames } from './codex-meta.js';
7
+ import { importReport, persistImported, targetIdentity } from './persist.js';
8
+ import { replyText, turnReader, turnText } from './turns.js';
9
+ import { codexThreads } from './codex-discover.js';
10
+ export { discoverCodexSessions } from './codex-discover.js';
11
+ export { codexSessionId } from './codex-meta.js';
12
+ /** Default Codex rollout directory. */
13
+ export function defaultCodexSessionsRoot(home = homedir()) {
14
+ return join(home, '.codex', 'sessions');
15
+ }
16
+ /** Parse one Codex rollout into the shared normalized model. */
17
+ export async function readCodexSession(path, targetId) {
18
+ const turns = [];
19
+ const parts = rolloutTurns(path);
20
+ let next = await parts.next();
21
+ for (; next.done !== true; next = await parts.next())
22
+ turns.push(next.value);
23
+ const { meta, firstTimestamp, title } = next.value;
24
+ if (meta === undefined)
25
+ throw new Error(`Codex rollout has no session_meta: ${path}`);
26
+ const thread = rolloutThread(meta);
27
+ if (thread === undefined)
28
+ throw new Error(`Codex rollout has no session id: ${path}`);
29
+ const id = targetId ?? codexSessionId(thread.id);
30
+ const createdAt = rolloutCreatedAt(meta, firstTimestamp);
31
+ const cwd = stringField(meta['cwd']);
32
+ const named = title?.title;
33
+ return {
34
+ session: {
35
+ id,
36
+ source: { tool: 'codex', path, sessionId: id },
37
+ createdAt,
38
+ ...(cwd !== undefined ? { cwd } : {}),
39
+ ...(named !== undefined ? { title: named } : {}),
40
+ turns: turns,
41
+ },
42
+ ...(named !== undefined ? { title: named } : {}),
43
+ thread,
44
+ };
45
+ }
46
+ /**
47
+ * The turns of a rollout, each as soon as the next one starts (what is said in a turn is then complete; a tool
48
+ * result may still reach one of its steps), and then what else the rollout says. Read only as far as it is asked.
49
+ */
50
+ async function* rolloutTurns(path) {
51
+ /** Turns the record just read completed, to hand out before the next one is read. */
52
+ const closed = [];
53
+ let count = 0;
54
+ let meta;
55
+ let firstTimestamp;
56
+ let seen = false;
57
+ /** The first thing the person said, when no `user_message` event carries it (used only if no turn starts). */
58
+ let fallback;
59
+ let turn;
60
+ let step;
61
+ const pending = new Map();
62
+ let title;
63
+ const names = threadNames(codexHomeOf(path));
64
+ const startTurn = (prompt, at) => {
65
+ if (turn !== undefined)
66
+ closed.push(turn);
67
+ count += 1;
68
+ turn = { number: count, prompt, ...(at !== undefined ? { timestamp: at } : {}), steps: [] };
69
+ step = undefined;
70
+ };
71
+ const ensureTurn = () => {
72
+ if (turn === undefined)
73
+ startTurn('');
74
+ return turn;
75
+ };
76
+ const ensureStep = (at) => {
77
+ const owner = ensureTurn();
78
+ if (step === undefined) {
79
+ step = { number: owner.steps.length + 1, ...(at !== undefined ? { timestamp: at } : {}), content: [], toolCalls: [], toolResults: [] };
80
+ owner.steps = [...owner.steps, step];
81
+ }
82
+ return step;
83
+ };
84
+ // Text after a tool call opens the next step: in one step it would part the call from its result.
85
+ const bodyStep = (at) => {
86
+ if (step !== undefined && step.toolCalls.length > 0)
87
+ step = undefined;
88
+ return ensureStep(at);
89
+ };
90
+ // One record at a time: a rollout is not held, and what a continued session cannot use (reasoning blobs, image
91
+ // data, token counts) is read past and gone as soon as its line is.
92
+ for await (const record of readRecords(path)) {
93
+ yield* closed.splice(0);
94
+ if (!seen) {
95
+ seen = true;
96
+ firstTimestamp = record.timestamp;
97
+ }
98
+ const payload = record.payload;
99
+ if (payload === undefined)
100
+ continue;
101
+ if (record.type === 'session_meta' && meta === undefined) {
102
+ meta = payload;
103
+ const thread = rolloutThread(payload);
104
+ title = new CodexTitle(thread === undefined ? undefined : (await names).get(thread.id));
105
+ }
106
+ title?.observe(record);
107
+ if (fallback === undefined && record.type === 'response_item' && payload['type'] === 'message' && payload['role'] === 'user') {
108
+ const text = textOf(payload['content']);
109
+ if (text.trim().length > 0 && !text.trimStart().startsWith('<'))
110
+ fallback = text;
111
+ }
112
+ const at = timestamp(record.timestamp) ?? timestamp(payload['timestamp']);
113
+ if (record.type === 'event_msg' && payload['type'] === 'user_message') {
114
+ const prompt = stringField(payload['message']);
115
+ if (prompt !== undefined && turn?.prompt !== prompt)
116
+ startTurn(prompt, at);
117
+ continue;
118
+ }
119
+ if (record.type !== 'response_item')
120
+ continue;
121
+ const kind = payload['type'];
122
+ if (kind === 'message') {
123
+ const role = payload['role'];
124
+ const text = textOf(payload['content']);
125
+ if (role === 'assistant') {
126
+ const current = text.length > 0 ? bodyStep(at) : ensureStep(at);
127
+ if (text.length > 0)
128
+ current.content = [...current.content, { type: 'text', text }];
129
+ }
130
+ else if (role === 'user' && usablePrompt(text) && (turn === undefined || turn.prompt.length === 0 || step !== undefined)) {
131
+ if (turn?.prompt !== text)
132
+ startTurn(text, at);
133
+ }
134
+ continue;
135
+ }
136
+ if (kind === 'reasoning') {
137
+ const text = textOf(payload['summary']) || textOf(payload['content']);
138
+ if (text.length > 0) {
139
+ const current = bodyStep(at);
140
+ current.content = [...current.content, { type: 'reasoning', text }];
141
+ }
142
+ continue;
143
+ }
144
+ const callId = stringField(payload['call_id']);
145
+ if (kind === 'function_call' || kind === 'custom_tool_call') {
146
+ if (callId === undefined)
147
+ continue;
148
+ const name = stringField(payload['name']) ?? 'tool';
149
+ const raw = kind === 'function_call' ? parseJson(stringField(payload['arguments'])) : stringField(payload['input']);
150
+ const call = { type: 'tool-call', id: callId, name, arguments: raw ?? {} };
151
+ const current = ensureStep(at);
152
+ current.content = [...current.content, call];
153
+ current.toolCalls = [...current.toolCalls, { id: callId, name, arguments: raw ?? {} }];
154
+ pending.set(callId, { call, step: current });
155
+ continue;
156
+ }
157
+ if (kind === 'function_call_output' || kind === 'custom_tool_call_output') {
158
+ if (callId === undefined)
159
+ continue;
160
+ const owner = pending.get(callId);
161
+ if (owner === undefined)
162
+ continue;
163
+ const result = {
164
+ toolCallId: callId,
165
+ content: [{ type: 'text', text: outputText(payload['output']) }],
166
+ ...(at !== undefined ? { timestamp: at } : {}),
167
+ };
168
+ owner.step.toolResults = [...owner.step.toolResults, result];
169
+ pending.delete(callId);
170
+ }
171
+ }
172
+ if (count === 0 && fallback !== undefined)
173
+ startTurn(fallback);
174
+ yield* closed.splice(0);
175
+ if (turn !== undefined)
176
+ yield turn;
177
+ return { meta, firstTimestamp, title };
178
+ }
179
+ /**
180
+ * Import one Codex rollout into DSH session persistence: into the session that already holds its thread, else a new
181
+ * one. A stored session that may or may not hold it (nothing tells) is not guessed at: the import is refused, and
182
+ * the list offers both. `targetId` imports into that session, the way "Import as new" does.
183
+ */
184
+ export async function importCodexSession(ctx, sourcePath, options = {}) {
185
+ const parsed = await readCodexSession(sourcePath, options.targetId);
186
+ if (parsed.session.turns.length === 0)
187
+ throw new Error(`nothing to import from ${sourcePath}: no conversation in the rollout`);
188
+ const identity = options.targetId !== undefined
189
+ ? targetIdentity(options.targetId)
190
+ : rolloutIdentity(sourcePath, parsed.thread, parsed.session.createdAt, { session: parsed.session });
191
+ return importReport(sourcePath, parsed.title, await persistImported(ctx, parsed.session, identity));
192
+ }
193
+ /** The identity of the thread a rollout holds: the one the list shows and the import uses. */
194
+ export function rolloutIdentity(path, thread, createdAt, known = {}) {
195
+ const home = codexHomeOf(path);
196
+ const root = home !== undefined ? join(home, 'sessions') : dirname(path);
197
+ const session = known.session;
198
+ return codexIdentity(thread, createdAt, {
199
+ threads: () => (known.threads ?? codexThreads)(root),
200
+ turns: () => session !== undefined ? turnReader(sessionTurns(session.turns)) : rolloutTurnReader(path),
201
+ turnsOf: rolloutTurnReader,
202
+ });
203
+ }
204
+ /** A reader of a rollout's turns: the rollout is read as far as the turns asked for. */
205
+ function rolloutTurnReader(path) {
206
+ return turnReader(sessionTurns(rolloutTurns(path)));
207
+ }
208
+ /** Turns as compared ({@link turnText}): the same for a rollout being read and one already read. */
209
+ async function* sessionTurns(turns) {
210
+ for await (const turn of turns)
211
+ yield turnText(turn.prompt, turn.steps.flatMap(step => replyText(step.content)));
212
+ }
213
+ /**
214
+ * The lines of a rollout, plain or compressed, streamed: what the import reads. The size is checked before the file
215
+ * is read (a compressed one, as its decoded bytes stream by), so a rollout that is too large costs nothing.
216
+ * `observer` sees how much the line splitter holds at once.
217
+ */
218
+ export async function* rolloutLines(path, observer) {
219
+ await assertFileImportable(path);
220
+ yield* path.endsWith('.zst')
221
+ ? splitLines(limitBytes(zstdChunks(path)), MAX_LINE_BYTES, observer)
222
+ : fileLines(path, observer !== undefined ? { observer } : {});
223
+ }
224
+ /** The records of a rollout, one at a time. */
225
+ async function* readRecords(path) {
226
+ for await (const line of rolloutLines(path)) {
227
+ if (line.oversized || line.text.trim().length === 0)
228
+ continue;
229
+ try {
230
+ const value = JSON.parse(line.text);
231
+ if (typeof value === 'object' && value !== null)
232
+ yield value;
233
+ }
234
+ catch {
235
+ // A partially written rollout line is ignored; the rest remains readable.
236
+ }
237
+ }
238
+ }
239
+ /**
240
+ * A function call's output text. Codex wraps the output of its shell tools as `{"output": …, "metadata": …}`
241
+ * (exit code, duration); the model saw the output, so that is what the result holds.
242
+ */
243
+ function outputText(value) {
244
+ const text = textOf(value) || stringField(value) || '';
245
+ const trimmed = text.trimStart();
246
+ if (!trimmed.startsWith('{'))
247
+ return text;
248
+ try {
249
+ const parsed = JSON.parse(trimmed);
250
+ if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {
251
+ const output = parsed['output'];
252
+ if (typeof output === 'string')
253
+ return output;
254
+ }
255
+ }
256
+ catch {
257
+ // Not the wrapper: the output itself is JSON or starts like it.
258
+ }
259
+ return text;
260
+ }
261
+ function parseJson(value) {
262
+ if (value === undefined)
263
+ return undefined;
264
+ try {
265
+ return JSON.parse(value);
266
+ }
267
+ catch {
268
+ return value;
269
+ }
270
+ }
@@ -0,0 +1,38 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { NormalizedSession } from '@kirkchinese/harness-forge-core';
3
+ import { type SessionPage, type SessionPageRequest } from '../forge/contract.js';
4
+ import { type ImportIdentity, type ImportReport } from './persist.js';
5
+ /** One discoverable OpenCode session in its shared database. */
6
+ export interface OpenCodeSessionCandidate {
7
+ readonly path: string;
8
+ readonly sourceId: string;
9
+ readonly source: 'opencode';
10
+ readonly title?: string;
11
+ readonly cwd?: string;
12
+ readonly createdAt?: number;
13
+ readonly updatedAt?: number;
14
+ /** The size of the session's messages and parts, in bytes; absent when the database does not say. */
15
+ readonly bytes?: number;
16
+ }
17
+ export type OpenCodeImportReport = ImportReport;
18
+ /** Default OpenCode database path (the desktop build uses ~/.local/share). */
19
+ export declare function defaultOpenCodeDatabase(home?: string): string;
20
+ /** Discover top-level OpenCode sessions (subagent sessions are excluded). */
21
+ export declare function discoverOpenCodeSessions(path?: string, page?: SessionPageRequest): Promise<SessionPage<OpenCodeSessionCandidate>>;
22
+ /** Read one OpenCode session into the shared normalized model. */
23
+ export declare function readOpenCodeSession(path: string, sourceId: string, targetId?: string): Promise<{
24
+ session: NormalizedSession;
25
+ title?: string;
26
+ }>;
27
+ /**
28
+ * The DSH id of an imported OpenCode session. Prefixed, so it never equals the OpenCode id: a session under the
29
+ * source's own id reads as native to other importers (dsh-chat-import hides those sources). Imports by earlier
30
+ * versions used the bare id; they are still found and reused.
31
+ */
32
+ export declare function openCodeSessionId(sourceId: string): string;
33
+ /** How an import finds the DSH session holding an OpenCode session: earlier versions used the bare id. */
34
+ export declare function openCodeIdentity(sourceId: string): ImportIdentity;
35
+ /** Import one OpenCode session into DSH session persistence. */
36
+ export declare function importOpenCodeSession(ctx: Context, path: string, sourceId: string, options?: {
37
+ readonly targetId?: string;
38
+ }): Promise<OpenCodeImportReport>;
@@ -0,0 +1,339 @@
1
+ /**
2
+ * OpenCode session migration. OpenCode stores sessions/messages/parts in a
3
+ * SQLite database; this adapter reads a snapshot through `node:sqlite`, reduces
4
+ * the rows to the shared NormalizedSession model, and lets the existing
5
+ * DSH synthesizer emit v4 events. The database is opened read-only.
6
+ * @module @kirkchinese/harness-forge
7
+ */
8
+ import { existsSync } from 'node:fs';
9
+ import { homedir } from 'node:os';
10
+ import { join } from 'node:path';
11
+ import { assertSessionSize } from '@kirkchinese/harness-forge-core';
12
+ import { SESSION_PAGE_SIZE } from '../forge/contract.js';
13
+ import { importReport, persistImported, targetIdentity } from './persist.js';
14
+ /** Default OpenCode database path (the desktop build uses ~/.local/share). */
15
+ export function defaultOpenCodeDatabase(home = homedir()) {
16
+ const xdg = join(home, '.local', 'share', 'opencode', 'opencode.db');
17
+ if (existsSync(xdg))
18
+ return xdg;
19
+ const local = process.env.LOCALAPPDATA === undefined ? undefined : join(process.env.LOCALAPPDATA, 'opencode', 'opencode.db');
20
+ return local ?? xdg;
21
+ }
22
+ /** Discover top-level OpenCode sessions (subagent sessions are excluded). */
23
+ export async function discoverOpenCodeSessions(path = defaultOpenCodeDatabase(), page = {}) {
24
+ const limit = Math.max(1, page.limit ?? SESSION_PAGE_SIZE);
25
+ const offset = Math.max(0, page.cursor ?? 0);
26
+ const db = await openDatabase(path);
27
+ try {
28
+ const table = schemaKind(db) === 'v2' ? 'session_v2' : 'session';
29
+ // One more than a page, to know whether another page follows.
30
+ const rows = db.prepare(`select id, title, directory, time_created, time_updated from ${table} where parent_id is null order by time_updated desc limit ? offset ?`).all(limit + 1, offset);
31
+ const sessions = rows.slice(0, limit).map((row) => {
32
+ const title = stringField(row['title']);
33
+ const cwd = stringField(row['directory']);
34
+ const createdAt = numberField(row['time_created']);
35
+ const updatedAt = numberField(row['time_updated']);
36
+ const bytes = sessionBytes(db, String(row['id']));
37
+ return {
38
+ path,
39
+ sourceId: String(row['id']),
40
+ source: 'opencode',
41
+ ...(title !== undefined ? { title } : {}),
42
+ ...(cwd !== undefined ? { cwd } : {}),
43
+ ...(createdAt !== undefined ? { createdAt } : {}),
44
+ ...(updatedAt !== undefined ? { updatedAt } : {}),
45
+ ...(bytes !== undefined ? { bytes } : {}),
46
+ };
47
+ });
48
+ return { sessions, ...(rows.length > limit ? { next: offset + limit } : {}) };
49
+ }
50
+ finally {
51
+ db.close();
52
+ }
53
+ }
54
+ /** Read one OpenCode session into the shared normalized model. */
55
+ export async function readOpenCodeSession(path, sourceId, targetId) {
56
+ const db = await openDatabase(path);
57
+ try {
58
+ // Before any message is read: a session is rows, not a file, and its size is what they add up to.
59
+ const bytes = sessionBytes(db, sourceId);
60
+ if (bytes !== undefined)
61
+ assertSessionSize(bytes);
62
+ if (schemaKind(db) === 'v2')
63
+ return readOpenCodeV2(db, path, sourceId, targetId);
64
+ const row = db.prepare('select id, title, directory, time_created from session where id = ?').get(sourceId);
65
+ if (row === undefined)
66
+ throw new Error(`OpenCode session not found: ${sourceId}`);
67
+ const messages = db.prepare('select id, data from message where session_id = ? order by time_created').iterate(sourceId);
68
+ const parts = db.prepare('select data from part where message_id = ? order by time_created');
69
+ const turns = [];
70
+ let current;
71
+ let step;
72
+ const startTurn = (prompt, at) => {
73
+ current = { number: turns.length + 1, prompt, ...(at !== undefined ? { timestamp: at } : {}), steps: [] };
74
+ turns.push(current);
75
+ step = undefined;
76
+ };
77
+ const ensureStep = (at) => {
78
+ if (current === undefined)
79
+ startTurn('', at);
80
+ if (step === undefined) {
81
+ step = { number: current.steps.length + 1, ...(at !== undefined ? { timestamp: at } : {}), content: [], toolCalls: [], toolResults: [] };
82
+ current.steps.push(step);
83
+ }
84
+ return step;
85
+ };
86
+ // Text after a tool call opens the next step: in one step it would part the call from its result.
87
+ const bodyStep = (at) => {
88
+ if (step !== undefined && step.toolCalls.length > 0)
89
+ step = undefined;
90
+ return ensureStep(at);
91
+ };
92
+ for (const message of messages) {
93
+ const data = parseRecord(message['data']);
94
+ if (data === undefined)
95
+ continue;
96
+ const created = numberField(asRecord(data['time'])?.['created']);
97
+ const role = data['role'];
98
+ if (role !== 'user' && role !== 'assistant')
99
+ continue;
100
+ const rows = parts.iterate(String(message['id']));
101
+ if (role === 'user') {
102
+ const texts = [];
103
+ for (const part of rows) {
104
+ const data = parseRecord(part['data']);
105
+ if (isTextPart(data))
106
+ texts.push(data['text']);
107
+ }
108
+ startTurn(texts.join('\n'), created);
109
+ continue;
110
+ }
111
+ for (const partRow of rows) {
112
+ const part = parseRecord(partRow['data']);
113
+ if (part === undefined)
114
+ continue;
115
+ if (part['type'] === 'text') {
116
+ const text = stringField(part['text']);
117
+ if (text !== undefined)
118
+ bodyStep(created).content.push({ type: 'text', text });
119
+ continue;
120
+ }
121
+ if (part['type'] === 'reasoning') {
122
+ const text = stringField(part['text']);
123
+ if (text !== undefined)
124
+ bodyStep(created).content.push({ type: 'reasoning', text });
125
+ continue;
126
+ }
127
+ if (part['type'] !== 'tool')
128
+ continue;
129
+ const callId = stringField(part['callID']) ?? stringField(part['id']);
130
+ const name = stringField(part['tool']) ?? 'tool';
131
+ if (callId === undefined)
132
+ continue;
133
+ const state = asRecord(part['state']);
134
+ const args = state?.['input'] ?? {};
135
+ const call = { type: 'tool-call', id: callId, name, arguments: args };
136
+ const target = ensureStep(created);
137
+ target.content.push(call);
138
+ target.toolCalls.push({ id: callId, name, arguments: args });
139
+ const output = state?.['output'];
140
+ if (output !== undefined || state?.['status'] === 'completed') {
141
+ target.toolResults.push({
142
+ toolCallId: callId,
143
+ content: [{ type: 'text', text: typeof output === 'string' ? output : JSON.stringify(output ?? '') }],
144
+ ...(created !== undefined ? { timestamp: created } : {}),
145
+ ...(state?.['status'] === 'error' ? { isError: true } : {}),
146
+ });
147
+ }
148
+ }
149
+ }
150
+ const title = stringField(row['title']);
151
+ const cwd = stringField(row['directory']);
152
+ const createdAt = numberField(row['time_created']) ?? 0;
153
+ return {
154
+ session: {
155
+ id: targetId ?? openCodeSessionId(sourceId),
156
+ source: { tool: 'opencode', path, sessionId: sourceId },
157
+ createdAt,
158
+ ...(cwd !== undefined ? { cwd } : {}),
159
+ ...(title !== undefined ? { title } : {}),
160
+ turns: turns,
161
+ },
162
+ ...(title !== undefined ? { title } : {}),
163
+ };
164
+ }
165
+ finally {
166
+ db.close();
167
+ }
168
+ }
169
+ /**
170
+ * The DSH id of an imported OpenCode session. Prefixed, so it never equals the OpenCode id: a session under the
171
+ * source's own id reads as native to other importers (dsh-chat-import hides those sources). Imports by earlier
172
+ * versions used the bare id; they are still found and reused.
173
+ */
174
+ export function openCodeSessionId(sourceId) {
175
+ return `opencode-${sourceId}`;
176
+ }
177
+ /** How an import finds the DSH session holding an OpenCode session: earlier versions used the bare id. */
178
+ export function openCodeIdentity(sourceId) {
179
+ return { id: openCodeSessionId(sourceId), legacyIds: [sourceId] };
180
+ }
181
+ /** Import one OpenCode session into DSH session persistence. */
182
+ export async function importOpenCodeSession(ctx, path, sourceId, options = {}) {
183
+ const parsed = await readOpenCodeSession(path, sourceId, options.targetId);
184
+ if (parsed.session.turns.length === 0)
185
+ throw new Error(`nothing to import from OpenCode session ${sourceId}: it has no conversation`);
186
+ const identity = options.targetId !== undefined ? targetIdentity(options.targetId) : openCodeIdentity(sourceId);
187
+ return importReport(path, parsed.title, await persistImported(ctx, parsed.session, identity));
188
+ }
189
+ async function openDatabase(path) {
190
+ const { DatabaseSync } = await import('node:sqlite');
191
+ return new DatabaseSync(path, { readOnly: true });
192
+ }
193
+ /** What one session's message and part rows add up to, in bytes; `undefined` when the schema is not one this knows. */
194
+ function sessionBytes(db, sourceId) {
195
+ const sum = (sql) => Number(db.prepare(sql).get(sourceId)?.['bytes'] ?? 0);
196
+ try {
197
+ if (schemaKind(db) === 'v2')
198
+ return sum('select coalesce(sum(length(cast(data as blob))), 0) as bytes from session_message where session_id = ?');
199
+ return sum('select coalesce(sum(length(cast(data as blob))), 0) as bytes from message where session_id = ?')
200
+ + sum('select coalesce(sum(length(cast(p.data as blob))), 0) as bytes from part p join message m on m.id = p.message_id where m.session_id = ?');
201
+ }
202
+ catch {
203
+ return undefined;
204
+ }
205
+ }
206
+ function schemaKind(db) {
207
+ const names = new Set(db.prepare("select name from sqlite_master where type='table'").all().map(row => String(row['name'])));
208
+ return names.has('session_v2') ? 'v2' : 'v1';
209
+ }
210
+ function readOpenCodeV2(db, path, sourceId, targetId) {
211
+ const row = db.prepare('select id, title, directory, time_created from session_v2 where id = ?').get(sourceId);
212
+ if (row === undefined)
213
+ throw new Error(`OpenCode session not found: ${sourceId}`);
214
+ const messages = db.prepare('select id, type, data, time_created from session_message where session_id = ? order by seq, time_created').iterate(sourceId);
215
+ const turns = [];
216
+ let current;
217
+ let step;
218
+ const startTurn = (prompt, at) => {
219
+ current = { number: turns.length + 1, prompt, ...(at !== undefined ? { timestamp: at } : {}), steps: [] };
220
+ turns.push(current);
221
+ step = undefined;
222
+ };
223
+ const ensureStep = (at) => {
224
+ if (current === undefined)
225
+ startTurn('', at);
226
+ if (step === undefined) {
227
+ step = { number: current.steps.length + 1, ...(at !== undefined ? { timestamp: at } : {}), content: [], toolCalls: [], toolResults: [] };
228
+ current.steps.push(step);
229
+ }
230
+ return step;
231
+ };
232
+ const bodyStep = (at) => {
233
+ if (step !== undefined && step.toolCalls.length > 0)
234
+ step = undefined;
235
+ return ensureStep(at);
236
+ };
237
+ for (const message of messages) {
238
+ const data = parseRecord(message['data']);
239
+ if (data === undefined)
240
+ continue;
241
+ const messageTime = numberField(message['time_created']);
242
+ const created = numberField(asRecord(data['time'])?.['created']) ?? messageTime;
243
+ if (message['type'] === 'user') {
244
+ const prompt = stringField(data['text']) ?? contentText(data['content']);
245
+ startTurn(prompt, created);
246
+ continue;
247
+ }
248
+ if (message['type'] !== 'assistant')
249
+ continue;
250
+ const blocks = Array.isArray(data['content']) ? data['content'] : [];
251
+ for (const value of blocks) {
252
+ const block = asRecord(value);
253
+ if (block === undefined)
254
+ continue;
255
+ if (block['type'] === 'text') {
256
+ const text = stringField(block['text']);
257
+ if (text !== undefined)
258
+ bodyStep(created).content.push({ type: 'text', text });
259
+ continue;
260
+ }
261
+ if (block['type'] === 'reasoning') {
262
+ const text = stringField(block['text']);
263
+ if (text !== undefined)
264
+ bodyStep(created).content.push({ type: 'reasoning', text });
265
+ continue;
266
+ }
267
+ if (block['type'] !== 'tool')
268
+ continue;
269
+ const callId = stringField(block['callID']) ?? stringField(block['id']);
270
+ const name = stringField(block['tool']) ?? stringField(block['name']) ?? 'tool';
271
+ if (callId === undefined)
272
+ continue;
273
+ const state = asRecord(block['state']);
274
+ const args = state?.['input'] ?? {};
275
+ const target = ensureStep(created);
276
+ target.content.push({ type: 'tool-call', id: callId, name, arguments: args });
277
+ target.toolCalls.push({ id: callId, name, arguments: args });
278
+ const output = state?.['output'] ?? contentText(state?.['content']);
279
+ if (output !== undefined || state?.['status'] === 'completed') {
280
+ target.toolResults.push({
281
+ toolCallId: callId,
282
+ content: [{ type: 'text', text: typeof output === 'string' ? output : JSON.stringify(output ?? '') }],
283
+ ...(created !== undefined ? { timestamp: created } : {}),
284
+ ...(state?.['status'] === 'error' ? { isError: true } : {}),
285
+ });
286
+ }
287
+ }
288
+ }
289
+ const title = stringField(row['title']);
290
+ const cwd = stringField(row['directory']);
291
+ const createdAt = numberField(row['time_created']) ?? 0;
292
+ return {
293
+ session: {
294
+ id: targetId ?? openCodeSessionId(sourceId),
295
+ source: { tool: 'opencode', path, sessionId: sourceId },
296
+ createdAt,
297
+ ...(cwd !== undefined ? { cwd } : {}),
298
+ ...(title !== undefined ? { title } : {}),
299
+ turns: turns,
300
+ },
301
+ ...(title !== undefined ? { title } : {}),
302
+ };
303
+ }
304
+ function contentText(value) {
305
+ if (!Array.isArray(value))
306
+ return typeof value === 'string' ? value : '';
307
+ return value
308
+ .map((item) => {
309
+ const block = asRecord(item);
310
+ return block?.['type'] === 'text' && typeof block['text'] === 'string' ? block['text'] : '';
311
+ })
312
+ .filter(Boolean)
313
+ .join('\n');
314
+ }
315
+ function parseRecord(value) {
316
+ if (typeof value !== 'string')
317
+ return undefined;
318
+ try {
319
+ const parsed = JSON.parse(value);
320
+ return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)
321
+ ? parsed
322
+ : undefined;
323
+ }
324
+ catch {
325
+ return undefined;
326
+ }
327
+ }
328
+ function isTextPart(part) {
329
+ return part !== undefined && part['type'] === 'text' && typeof part['text'] === 'string';
330
+ }
331
+ function asRecord(value) {
332
+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : undefined;
333
+ }
334
+ function stringField(value) {
335
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
336
+ }
337
+ function numberField(value) {
338
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
339
+ }