@kirkchinese/harness-forge 0.0.0-stage → 0.4.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 (246) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +42 -2
  3. package/assets/icon.svg +12 -0
  4. package/cordis.patch.yml +28 -0
  5. package/lib/agents/presets.d.ts +91 -0
  6. package/lib/agents/presets.js +282 -0
  7. package/lib/agents/profiles.d.ts +58 -0
  8. package/lib/agents/profiles.js +278 -0
  9. package/lib/agents/row.d.ts +17 -0
  10. package/lib/agents/row.js +146 -0
  11. package/lib/client/styles.d.ts +8 -0
  12. package/lib/client/styles.js +89 -0
  13. package/lib/client/typert.d.ts +14 -0
  14. package/lib/client/typert.js +110 -0
  15. package/lib/client.js +22500 -0
  16. package/lib/commands/definition.d.ts +40 -0
  17. package/lib/commands/definition.js +113 -0
  18. package/lib/commands/output-styles.d.ts +42 -0
  19. package/lib/commands/output-styles.js +152 -0
  20. package/lib/commands/row.d.ts +9 -0
  21. package/lib/commands/row.js +157 -0
  22. package/lib/context/instructions.d.ts +32 -0
  23. package/lib/context/instructions.js +88 -0
  24. package/lib/context/row.d.ts +16 -0
  25. package/lib/context/row.js +17 -0
  26. package/lib/dsh/commands.d.ts +30 -0
  27. package/lib/dsh/commands.js +61 -0
  28. package/lib/dsh/host.d.ts +107 -0
  29. package/lib/dsh/host.js +214 -0
  30. package/lib/dsh/model-route.d.ts +21 -0
  31. package/lib/dsh/model-route.js +37 -0
  32. package/lib/dsh/session-records.d.ts +78 -0
  33. package/lib/dsh/session-records.js +36 -0
  34. package/lib/dsh/subagents.d.ts +46 -0
  35. package/lib/dsh/subagents.js +14 -0
  36. package/lib/forge/contract.d.ts +231 -0
  37. package/lib/forge/contract.js +43 -0
  38. package/lib/forge/ledger.d.ts +143 -0
  39. package/lib/forge/ledger.js +733 -0
  40. package/lib/forge/live-mounts.d.ts +45 -0
  41. package/lib/forge/live-mounts.js +78 -0
  42. package/lib/forge/marketplace-install.d.ts +3 -0
  43. package/lib/forge/marketplace-install.js +64 -0
  44. package/lib/forge/npm.d.ts +31 -0
  45. package/lib/forge/npm.js +60 -0
  46. package/lib/forge/projects.d.ts +94 -0
  47. package/lib/forge/projects.js +336 -0
  48. package/lib/forge/receipts.d.ts +5 -0
  49. package/lib/forge/receipts.js +31 -0
  50. package/lib/forge/row.d.ts +32 -0
  51. package/lib/forge/row.js +59 -0
  52. package/lib/forge/service.d.ts +105 -0
  53. package/lib/forge/service.js +274 -0
  54. package/lib/forge/settings.d.ts +41 -0
  55. package/lib/forge/settings.js +115 -0
  56. package/lib/forge/state.d.ts +69 -0
  57. package/lib/forge/state.js +150 -0
  58. package/lib/forge/trust.d.ts +48 -0
  59. package/lib/forge/trust.js +107 -0
  60. package/lib/forge/turns.d.ts +13 -0
  61. package/lib/forge/turns.js +56 -0
  62. package/lib/hooks/broker/engine.d.ts +112 -0
  63. package/lib/hooks/broker/engine.js +728 -0
  64. package/lib/hooks/broker/helpers.d.ts +10 -0
  65. package/lib/hooks/broker/helpers.js +22 -0
  66. package/lib/hooks/broker/lifecycle.d.ts +65 -0
  67. package/lib/hooks/broker/lifecycle.js +342 -0
  68. package/lib/hooks/broker/session-events.d.ts +22 -0
  69. package/lib/hooks/broker/session-events.js +196 -0
  70. package/lib/hooks/broker/tools.d.ts +52 -0
  71. package/lib/hooks/broker/tools.js +424 -0
  72. package/lib/hooks/broker/types.d.ts +262 -0
  73. package/lib/hooks/broker/types.js +1 -0
  74. package/lib/hooks/broker.d.ts +80 -0
  75. package/lib/hooks/broker.js +95 -0
  76. package/lib/hooks/codex-user.d.ts +5 -0
  77. package/lib/hooks/codex-user.js +109 -0
  78. package/lib/hooks/condition.d.ts +11 -0
  79. package/lib/hooks/condition.js +181 -0
  80. package/lib/hooks/config.d.ts +85 -0
  81. package/lib/hooks/config.js +150 -0
  82. package/lib/hooks/matcher.d.ts +20 -0
  83. package/lib/hooks/matcher.js +39 -0
  84. package/lib/hooks/notice.d.ts +17 -0
  85. package/lib/hooks/notice.js +39 -0
  86. package/lib/hooks/output.d.ts +56 -0
  87. package/lib/hooks/output.js +214 -0
  88. package/lib/hooks/permissions.d.ts +14 -0
  89. package/lib/hooks/permissions.js +109 -0
  90. package/lib/hooks/process.d.ts +47 -0
  91. package/lib/hooks/process.js +134 -0
  92. package/lib/hooks/row.d.ts +17 -0
  93. package/lib/hooks/row.js +94 -0
  94. package/lib/hooks/runner.d.ts +85 -0
  95. package/lib/hooks/runner.js +293 -0
  96. package/lib/hooks/shell-commands.d.ts +19 -0
  97. package/lib/hooks/shell-commands.js +177 -0
  98. package/lib/hooks/shell.d.ts +43 -0
  99. package/lib/hooks/shell.js +126 -0
  100. package/lib/hooks/transcript.d.ts +28 -0
  101. package/lib/hooks/transcript.js +141 -0
  102. package/lib/hooks/vocabulary.d.ts +57 -0
  103. package/lib/hooks/vocabulary.js +364 -0
  104. package/lib/index.d.ts +31 -0
  105. package/lib/index.js +287 -0
  106. package/lib/mcp/auth.d.ts +35 -0
  107. package/lib/mcp/auth.js +178 -0
  108. package/lib/mcp/catalog.d.ts +36 -0
  109. package/lib/mcp/catalog.js +61 -0
  110. package/lib/mcp/mount.d.ts +75 -0
  111. package/lib/mcp/mount.js +217 -0
  112. package/lib/mcp/remote.d.ts +45 -0
  113. package/lib/mcp/remote.js +143 -0
  114. package/lib/mcp/row.d.ts +9 -0
  115. package/lib/mcp/row.js +131 -0
  116. package/lib/mods/bundler.d.ts +38 -0
  117. package/lib/mods/bundler.js +157 -0
  118. package/lib/mods/chain.d.ts +103 -0
  119. package/lib/mods/chain.js +436 -0
  120. package/lib/mods/claude.d.ts +27 -0
  121. package/lib/mods/claude.js +56 -0
  122. package/lib/mods/engine.d.ts +160 -0
  123. package/lib/mods/engine.js +701 -0
  124. package/lib/mods/expect.d.ts +8 -0
  125. package/lib/mods/expect.js +248 -0
  126. package/lib/mods/host.d.ts +105 -0
  127. package/lib/mods/host.js +462 -0
  128. package/lib/mods/loader.d.ts +53 -0
  129. package/lib/mods/loader.js +227 -0
  130. package/lib/mods/ops.d.ts +13 -0
  131. package/lib/mods/ops.js +117 -0
  132. package/lib/mods/row.d.ts +9 -0
  133. package/lib/mods/row.js +77 -0
  134. package/lib/mods/runtime.d.ts +60 -0
  135. package/lib/mods/runtime.js +133 -0
  136. package/lib/mods/service/commands.d.ts +17 -0
  137. package/lib/mods/service/commands.js +121 -0
  138. package/lib/mods/service/drawings.d.ts +36 -0
  139. package/lib/mods/service/drawings.js +64 -0
  140. package/lib/mods/service/sessions.d.ts +63 -0
  141. package/lib/mods/service/sessions.js +345 -0
  142. package/lib/mods/service/tools.d.ts +32 -0
  143. package/lib/mods/service/tools.js +253 -0
  144. package/lib/mods/service/turns.d.ts +32 -0
  145. package/lib/mods/service/turns.js +161 -0
  146. package/lib/mods/service/types.d.ts +151 -0
  147. package/lib/mods/service/types.js +1 -0
  148. package/lib/mods/service.d.ts +72 -0
  149. package/lib/mods/service.js +104 -0
  150. package/lib/mods/surfaces.d.ts +93 -0
  151. package/lib/mods/surfaces.js +309 -0
  152. package/lib/mods/values.d.ts +30 -0
  153. package/lib/mods/values.js +95 -0
  154. package/lib/opencode/bun.d.ts +40 -0
  155. package/lib/opencode/bun.js +156 -0
  156. package/lib/opencode/convert.d.ts +53 -0
  157. package/lib/opencode/convert.js +255 -0
  158. package/lib/opencode/row.d.ts +9 -0
  159. package/lib/opencode/row.js +86 -0
  160. package/lib/opencode/runtime/core.d.ts +74 -0
  161. package/lib/opencode/runtime/core.js +249 -0
  162. package/lib/opencode/runtime/events.d.ts +80 -0
  163. package/lib/opencode/runtime/events.js +281 -0
  164. package/lib/opencode/runtime/mount.d.ts +27 -0
  165. package/lib/opencode/runtime/mount.js +283 -0
  166. package/lib/opencode/runtime/server.d.ts +27 -0
  167. package/lib/opencode/runtime/server.js +353 -0
  168. package/lib/opencode/runtime/types.d.ts +109 -0
  169. package/lib/opencode/runtime/types.js +1 -0
  170. package/lib/opencode/runtime.d.ts +55 -0
  171. package/lib/opencode/runtime.js +79 -0
  172. package/lib/porting/port-gap.d.ts +30 -0
  173. package/lib/porting/port-gap.js +122 -0
  174. package/lib/porting/port-sessions.d.ts +41 -0
  175. package/lib/porting/port-sessions.js +98 -0
  176. package/lib/porting/prompt.d.ts +23 -0
  177. package/lib/porting/prompt.js +49 -0
  178. package/lib/porting/row.d.ts +16 -0
  179. package/lib/porting/row.js +25 -0
  180. package/lib/porting/verify-port.d.ts +53 -0
  181. package/lib/porting/verify-port.js +104 -0
  182. package/lib/presets/fs-search.d.ts +25 -0
  183. package/lib/presets/fs-search.js +17 -0
  184. package/lib/presets/tool-filter.d.ts +35 -0
  185. package/lib/presets/tool-filter.js +91 -0
  186. package/lib/sessions/claude.d.ts +29 -0
  187. package/lib/sessions/claude.js +83 -0
  188. package/lib/sessions/codex.d.ts +30 -0
  189. package/lib/sessions/codex.js +303 -0
  190. package/lib/sessions/opencode.d.ts +32 -0
  191. package/lib/sessions/opencode.js +320 -0
  192. package/lib/sessions/row.d.ts +14 -0
  193. package/lib/sessions/row.js +35 -0
  194. package/lib/shared/invocation.d.ts +169 -0
  195. package/lib/shared/invocation.js +325 -0
  196. package/lib/shared/render.d.ts +72 -0
  197. package/lib/shared/render.js +588 -0
  198. package/lib/shared/util.d.ts +21 -0
  199. package/lib/shared/util.js +32 -0
  200. package/lib/skills/bundled.d.ts +3 -0
  201. package/lib/skills/bundled.js +42 -0
  202. package/lib/skills/provider.d.ts +72 -0
  203. package/lib/skills/provider.js +340 -0
  204. package/lib/skills/row.d.ts +22 -0
  205. package/lib/skills/row.js +204 -0
  206. package/lib/workbench/adapter-coverage.d.ts +47 -0
  207. package/lib/workbench/adapter-coverage.js +102 -0
  208. package/lib/workbench/model-tools.d.ts +10 -0
  209. package/lib/workbench/model-tools.js +122 -0
  210. package/lib/workbench/overview.d.ts +103 -0
  211. package/lib/workbench/overview.js +159 -0
  212. package/lib/workbench/remote.d.ts +118 -0
  213. package/lib/workbench/remote.js +422 -0
  214. package/lib/workbench/row.d.ts +15 -0
  215. package/lib/workbench/row.js +16 -0
  216. package/lib/workbench/settings.d.ts +15 -0
  217. package/lib/workbench/settings.js +56 -0
  218. package/lib/workbench/workbench.d.ts +100 -0
  219. package/lib/workbench/workbench.js +260 -0
  220. package/locale/agents/en.json +6 -0
  221. package/locale/agents/zh.json +6 -0
  222. package/locale/commands/en.json +6 -0
  223. package/locale/commands/zh.json +6 -0
  224. package/locale/context/en.json +6 -0
  225. package/locale/context/zh.json +6 -0
  226. package/locale/en.json +6 -0
  227. package/locale/hooks/en.json +6 -0
  228. package/locale/hooks/zh.json +6 -0
  229. package/locale/mcp/en.json +6 -0
  230. package/locale/mcp/zh.json +6 -0
  231. package/locale/mods/en.json +6 -0
  232. package/locale/mods/zh.json +6 -0
  233. package/locale/opencode/en.json +6 -0
  234. package/locale/opencode/zh.json +6 -0
  235. package/locale/porter/en.json +6 -0
  236. package/locale/porter/zh.json +6 -0
  237. package/locale/sessions/en.json +6 -0
  238. package/locale/sessions/zh.json +6 -0
  239. package/locale/skills/en.json +6 -0
  240. package/locale/skills/zh.json +6 -0
  241. package/locale/workbench/en.json +6 -0
  242. package/locale/workbench/zh.json +6 -0
  243. package/locale/zh.json +6 -0
  244. package/package.json +246 -3
  245. package/runtime/opencode-host.mjs +270 -0
  246. package/skills/harness-forge/SKILL.md +47 -0
@@ -0,0 +1,320 @@
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 { synthesizeDshSession } from '@kirkchinese/harness-forge-core';
12
+ import { dshService } from '../dsh/host.js';
13
+ /** Default OpenCode database path (the desktop build uses ~/.local/share). */
14
+ export function defaultOpenCodeDatabase(home = homedir()) {
15
+ const xdg = join(home, '.local', 'share', 'opencode', 'opencode.db');
16
+ if (existsSync(xdg))
17
+ return xdg;
18
+ const local = process.env.LOCALAPPDATA === undefined ? undefined : join(process.env.LOCALAPPDATA, 'opencode', 'opencode.db');
19
+ return local ?? xdg;
20
+ }
21
+ /** Discover top-level OpenCode sessions (subagent sessions are excluded). */
22
+ export async function discoverOpenCodeSessions(path = defaultOpenCodeDatabase(), limit = 200) {
23
+ const db = await openDatabase(path);
24
+ try {
25
+ const schema = schemaKind(db);
26
+ const rows = schema === 'v2'
27
+ ? db.prepare('select id, title, directory, time_created from session_v2 where parent_id is null order by time_updated desc limit ?').all(limit)
28
+ : db.prepare('select id, title, directory, time_created from session where parent_id is null order by time_updated desc limit ?').all(limit);
29
+ return rows.map((row) => {
30
+ const title = stringField(row['title']);
31
+ const cwd = stringField(row['directory']);
32
+ const createdAt = numberField(row['time_created']);
33
+ return {
34
+ path,
35
+ sourceId: String(row['id']),
36
+ source: 'opencode',
37
+ ...(title !== undefined ? { title } : {}),
38
+ ...(cwd !== undefined ? { cwd } : {}),
39
+ ...(createdAt !== undefined ? { createdAt } : {}),
40
+ };
41
+ });
42
+ }
43
+ finally {
44
+ db.close();
45
+ }
46
+ }
47
+ /** Read one OpenCode session into the shared normalized model. */
48
+ export async function readOpenCodeSession(path, sourceId, targetId) {
49
+ const db = await openDatabase(path);
50
+ try {
51
+ if (schemaKind(db) === 'v2')
52
+ return readOpenCodeV2(db, path, sourceId, targetId);
53
+ const row = db.prepare('select id, title, directory, time_created from session where id = ?').get(sourceId);
54
+ if (row === undefined)
55
+ throw new Error(`OpenCode session not found: ${sourceId}`);
56
+ const messages = db.prepare('select id, data from message where session_id = ? order by time_created').all(sourceId);
57
+ const turns = [];
58
+ let current;
59
+ let step;
60
+ const startTurn = (prompt, at) => {
61
+ current = { number: turns.length + 1, prompt, ...(at !== undefined ? { timestamp: at } : {}), steps: [] };
62
+ turns.push(current);
63
+ step = undefined;
64
+ };
65
+ const ensureStep = (at) => {
66
+ if (current === undefined)
67
+ startTurn('', at);
68
+ if (step === undefined) {
69
+ step = { number: current.steps.length + 1, ...(at !== undefined ? { timestamp: at } : {}), content: [], toolCalls: [], toolResults: [] };
70
+ current.steps.push(step);
71
+ }
72
+ return step;
73
+ };
74
+ for (const message of messages) {
75
+ const data = parseRecord(message['data']);
76
+ if (data === undefined)
77
+ continue;
78
+ const created = numberField(asRecord(data['time'])?.['created']);
79
+ const role = data['role'];
80
+ const parts = db.prepare('select data from part where message_id = ? order by time_created').all(String(message['id']));
81
+ if (role === 'user') {
82
+ const prompt = parts.map(part => parseRecord(part['data'])).filter(isTextPart).map(part => part['text']).join('\n');
83
+ startTurn(prompt, created);
84
+ continue;
85
+ }
86
+ if (role !== 'assistant')
87
+ continue;
88
+ for (const partRow of parts) {
89
+ const part = parseRecord(partRow['data']);
90
+ if (part === undefined)
91
+ continue;
92
+ if (part['type'] === 'text') {
93
+ const text = stringField(part['text']);
94
+ if (text !== undefined)
95
+ ensureStep(created).content.push({ type: 'text', text });
96
+ continue;
97
+ }
98
+ if (part['type'] === 'reasoning') {
99
+ const text = stringField(part['text']);
100
+ if (text !== undefined)
101
+ ensureStep(created).content.push({ type: 'reasoning', text });
102
+ continue;
103
+ }
104
+ if (part['type'] !== 'tool')
105
+ continue;
106
+ const callId = stringField(part['callID']) ?? stringField(part['id']);
107
+ const name = stringField(part['tool']) ?? 'tool';
108
+ if (callId === undefined)
109
+ continue;
110
+ const state = asRecord(part['state']);
111
+ const args = state?.['input'] ?? {};
112
+ const call = { type: 'tool-call', id: callId, name, arguments: args };
113
+ const target = ensureStep(created);
114
+ target.content.push(call);
115
+ target.toolCalls.push({ id: callId, name, arguments: args });
116
+ const output = state?.['output'];
117
+ if (output !== undefined || state?.['status'] === 'completed') {
118
+ target.toolResults.push({
119
+ toolCallId: callId,
120
+ content: [{ type: 'text', text: typeof output === 'string' ? output : JSON.stringify(output ?? '') }],
121
+ ...(created !== undefined ? { timestamp: created } : {}),
122
+ ...(state?.['status'] === 'error' ? { isError: true } : {}),
123
+ });
124
+ }
125
+ }
126
+ }
127
+ const title = stringField(row['title']);
128
+ const cwd = stringField(row['directory']);
129
+ const createdAt = numberField(row['time_created']) ?? 0;
130
+ return {
131
+ session: {
132
+ id: targetId ?? sourceId,
133
+ source: { tool: 'opencode', path, sessionId: sourceId },
134
+ createdAt,
135
+ ...(cwd !== undefined ? { cwd } : {}),
136
+ ...(title !== undefined ? { title } : {}),
137
+ turns: turns,
138
+ },
139
+ ...(title !== undefined ? { title } : {}),
140
+ };
141
+ }
142
+ finally {
143
+ db.close();
144
+ }
145
+ }
146
+ /** Import one OpenCode session into DSH session persistence. */
147
+ export async function importOpenCodeSession(ctx, path, sourceId, options = {}) {
148
+ const persistence = dshService(ctx, 'sessionPersistence');
149
+ if (persistence === undefined)
150
+ throw new Error('sessionPersistence service is not available');
151
+ const parsed = await readOpenCodeSession(path, sourceId, options.targetId);
152
+ if (parsed.session.turns.length === 0)
153
+ throw new Error(`nothing to import from OpenCode session ${sourceId}: it has no conversation`);
154
+ const synthesized = synthesizeDshSession(parsed.session);
155
+ const events = synthesized.events;
156
+ const handle = await persistence.create({
157
+ version: 4,
158
+ id: synthesized.meta.id,
159
+ createdAt: synthesized.meta.createdAt,
160
+ isSeeded: false,
161
+ ...(synthesized.meta.cwd !== undefined ? { cwd: synthesized.meta.cwd } : {}),
162
+ delegationDepth: synthesized.meta.delegationDepth,
163
+ ...(synthesized.meta.origin !== undefined ? { origin: synthesized.meta.origin } : {}),
164
+ ...(synthesized.meta.parentSession !== undefined ? { parentSession: synthesized.meta.parentSession } : {}),
165
+ });
166
+ try {
167
+ await handle.append(events);
168
+ await handle.flush();
169
+ }
170
+ finally {
171
+ await handle.close();
172
+ }
173
+ return {
174
+ id: synthesized.meta.id,
175
+ sourcePath: path,
176
+ ...(parsed.title !== undefined ? { title: parsed.title } : {}),
177
+ turns: synthesized.stats.turns,
178
+ events: events.length,
179
+ stats: {
180
+ steps: synthesized.stats.steps,
181
+ messages: synthesized.stats.messages,
182
+ toolCalls: synthesized.stats.toolCalls,
183
+ toolResults: synthesized.stats.toolResults,
184
+ synthesizedToolResults: synthesized.stats.synthesizedToolResults,
185
+ },
186
+ };
187
+ }
188
+ async function openDatabase(path) {
189
+ const { DatabaseSync } = await import('node:sqlite');
190
+ return new DatabaseSync(path, { readOnly: true });
191
+ }
192
+ function schemaKind(db) {
193
+ const names = new Set(db.prepare("select name from sqlite_master where type='table'").all().map(row => String(row['name'])));
194
+ return names.has('session_v2') ? 'v2' : 'v1';
195
+ }
196
+ function readOpenCodeV2(db, path, sourceId, targetId) {
197
+ const row = db.prepare('select id, title, directory, time_created from session_v2 where id = ?').get(sourceId);
198
+ if (row === undefined)
199
+ throw new Error(`OpenCode session not found: ${sourceId}`);
200
+ const messages = db.prepare('select id, type, data, time_created from session_message where session_id = ? order by seq, time_created').all(sourceId);
201
+ const turns = [];
202
+ let current;
203
+ let step;
204
+ const startTurn = (prompt, at) => {
205
+ current = { number: turns.length + 1, prompt, ...(at !== undefined ? { timestamp: at } : {}), steps: [] };
206
+ turns.push(current);
207
+ step = undefined;
208
+ };
209
+ const ensureStep = (at) => {
210
+ if (current === undefined)
211
+ startTurn('', at);
212
+ if (step === undefined) {
213
+ step = { number: current.steps.length + 1, ...(at !== undefined ? { timestamp: at } : {}), content: [], toolCalls: [], toolResults: [] };
214
+ current.steps.push(step);
215
+ }
216
+ return step;
217
+ };
218
+ for (const message of messages) {
219
+ const data = parseRecord(message['data']);
220
+ if (data === undefined)
221
+ continue;
222
+ const messageTime = numberField(message['time_created']);
223
+ const created = numberField(asRecord(data['time'])?.['created']) ?? messageTime;
224
+ if (message['type'] === 'user') {
225
+ const prompt = stringField(data['text']) ?? contentText(data['content']);
226
+ startTurn(prompt, created);
227
+ continue;
228
+ }
229
+ if (message['type'] !== 'assistant')
230
+ continue;
231
+ const blocks = Array.isArray(data['content']) ? data['content'] : [];
232
+ for (const value of blocks) {
233
+ const block = asRecord(value);
234
+ if (block === undefined)
235
+ continue;
236
+ if (block['type'] === 'text') {
237
+ const text = stringField(block['text']);
238
+ if (text !== undefined)
239
+ ensureStep(created).content.push({ type: 'text', text });
240
+ continue;
241
+ }
242
+ if (block['type'] === 'reasoning') {
243
+ const text = stringField(block['text']);
244
+ if (text !== undefined)
245
+ ensureStep(created).content.push({ type: 'reasoning', text });
246
+ continue;
247
+ }
248
+ if (block['type'] !== 'tool')
249
+ continue;
250
+ const callId = stringField(block['callID']) ?? stringField(block['id']);
251
+ const name = stringField(block['tool']) ?? stringField(block['name']) ?? 'tool';
252
+ if (callId === undefined)
253
+ continue;
254
+ const state = asRecord(block['state']);
255
+ const args = state?.['input'] ?? {};
256
+ const target = ensureStep(created);
257
+ target.content.push({ type: 'tool-call', id: callId, name, arguments: args });
258
+ target.toolCalls.push({ id: callId, name, arguments: args });
259
+ const output = state?.['output'] ?? contentText(state?.['content']);
260
+ if (output !== undefined || state?.['status'] === 'completed') {
261
+ target.toolResults.push({
262
+ toolCallId: callId,
263
+ content: [{ type: 'text', text: typeof output === 'string' ? output : JSON.stringify(output ?? '') }],
264
+ ...(created !== undefined ? { timestamp: created } : {}),
265
+ ...(state?.['status'] === 'error' ? { isError: true } : {}),
266
+ });
267
+ }
268
+ }
269
+ }
270
+ const title = stringField(row['title']);
271
+ const cwd = stringField(row['directory']);
272
+ const createdAt = numberField(row['time_created']) ?? 0;
273
+ return {
274
+ session: {
275
+ id: targetId ?? sourceId,
276
+ source: { tool: 'opencode', path, sessionId: sourceId },
277
+ createdAt,
278
+ ...(cwd !== undefined ? { cwd } : {}),
279
+ ...(title !== undefined ? { title } : {}),
280
+ turns: turns,
281
+ },
282
+ ...(title !== undefined ? { title } : {}),
283
+ };
284
+ }
285
+ function contentText(value) {
286
+ if (!Array.isArray(value))
287
+ return typeof value === 'string' ? value : '';
288
+ return value
289
+ .map((item) => {
290
+ const block = asRecord(item);
291
+ return block?.['type'] === 'text' && typeof block['text'] === 'string' ? block['text'] : '';
292
+ })
293
+ .filter(Boolean)
294
+ .join('\n');
295
+ }
296
+ function parseRecord(value) {
297
+ if (typeof value !== 'string')
298
+ return undefined;
299
+ try {
300
+ const parsed = JSON.parse(value);
301
+ return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)
302
+ ? parsed
303
+ : undefined;
304
+ }
305
+ catch {
306
+ return undefined;
307
+ }
308
+ }
309
+ function isTextPart(part) {
310
+ return part !== undefined && part['type'] === 'text' && typeof part['text'] === 'string';
311
+ }
312
+ function asRecord(value) {
313
+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : undefined;
314
+ }
315
+ function stringField(value) {
316
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
317
+ }
318
+ function numberField(value) {
319
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
320
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The sessions row: Claude Code, Codex and OpenCode sessions imported into
3
+ * DSH on demand, from the workbench. It holds no listener.
4
+ * @module @kirkchinese/harness-forge/sessions
5
+ */
6
+ import type { Context } from '@deepseek-ai/cordis';
7
+ import type { Disposer } from '../forge/contract.js';
8
+ import { type HarnessForge } from '../forge/service.js';
9
+ export declare const name = "harness-forge-sessions";
10
+ export declare const inject: string[];
11
+ /** The sessions row. */
12
+ export declare function apply(ctx: Context): void;
13
+ /** Start the sessions row on the shared service. Returns its teardown. */
14
+ export declare function startSessions(ctx: Context, forge: HarnessForge): Disposer;
@@ -0,0 +1,35 @@
1
+ import { discoverCodexSessions, importCodexSession } from './codex.js';
2
+ import { FORGE_SERVICE } from '../forge/service.js';
3
+ import { discoverOpenCodeSessions, importOpenCodeSession } from './opencode.js';
4
+ import { discoverClaudeSessions, importClaudeSession } from './claude.js';
5
+ import { rowEffect } from '../forge/row.js';
6
+ export const name = 'harness-forge-sessions';
7
+ export const inject = [FORGE_SERVICE];
8
+ /** The sessions row. */
9
+ export function apply(ctx) {
10
+ rowEffect(ctx, 'sessions', forge => startSessions(ctx, forge));
11
+ }
12
+ /** Start the sessions row on the shared service. Returns its teardown. */
13
+ export function startSessions(ctx, forge) {
14
+ const api = {
15
+ sessions: async (root, source) => {
16
+ if (source === 'codex')
17
+ return (await discoverCodexSessions(root)).map(session => ({ ...session, source: 'codex' }));
18
+ if (source === 'opencode')
19
+ return (await discoverOpenCodeSessions(root)).map(session => ({ ...session, source: 'opencode' }));
20
+ return discoverClaudeSessions(root);
21
+ },
22
+ importSession: (path, targetId, source, sourceId) => {
23
+ const options = targetId === undefined ? {} : { targetId };
24
+ if (source === 'codex')
25
+ return importCodexSession(ctx, path, options);
26
+ if (source === 'opencode') {
27
+ if (sourceId === undefined)
28
+ throw new Error('OpenCode import requires a sourceId');
29
+ return importOpenCodeSession(ctx, path, sourceId, options);
30
+ }
31
+ return importClaudeSession(ctx, path, options);
32
+ },
33
+ };
34
+ return forge.provide('sessions', api);
35
+ }
@@ -0,0 +1,169 @@
1
+ /**
2
+ * What a skill's or command's frontmatter asks of the turn that invokes it,
3
+ * as Claude Code applies it (commands and skills share the fields):
4
+ *
5
+ * - `allowed-tools`: allow rules for that turn; deny and ask rules still win.
6
+ * `${CLAUDE_SKILL_DIR}`, `${CLAUDE_PROJECT_DIR}`, `${CLAUDE_PLUGIN_ROOT}`
7
+ * and `${CLAUDE_PLUGIN_DATA}` expand inside the rules.
8
+ * - `disallowed-tools`: the tools are refused while the skill is active.
9
+ * - `model` / `effort`: the rest of the turn runs on that model and effort.
10
+ * A value naming no model DSH has (a Claude alias such as `opus`) keeps the
11
+ * session's model, and the session records why.
12
+ * - `context: fork`: the rendered content runs as the task of a new delegated
13
+ * agent (`agent` names its type, `general-purpose` by default) and its
14
+ * result comes back; `background: false` waits for it in the invoking turn,
15
+ * otherwise the result arrives as a message when the agent finishes.
16
+ *
17
+ * Everything clears when the user sends the next message.
18
+ * @module @kirkchinese/harness-forge
19
+ */
20
+ import type { Context } from '@deepseek-ai/cordis';
21
+ /** Where a skill or command lives, for the variables its rules may name. */
22
+ export interface InvocationPlaces {
23
+ readonly skillDir?: string;
24
+ readonly pluginRoot?: string;
25
+ readonly dataDir?: string;
26
+ }
27
+ /** One skill's or command's invocation frontmatter. */
28
+ export interface InvocationSpec {
29
+ /** The DSH name: the skill name, or the command name. */
30
+ readonly name: string;
31
+ readonly kind: 'skill' | 'command';
32
+ /** The name its own harness invokes it by (`plugin:skill`, or bare for the user's own). */
33
+ readonly foreignName?: string;
34
+ /** `plugin`, `user` or `project`, as `UserPromptExpansion` reports `command_source`. */
35
+ readonly source?: string;
36
+ readonly pluginId: string;
37
+ readonly componentId: string;
38
+ readonly frontmatter: Readonly<Record<string, unknown>>;
39
+ readonly places: InvocationPlaces;
40
+ }
41
+ /** The parsed directives of a spec. */
42
+ export interface Directives {
43
+ readonly allowedTools: readonly string[];
44
+ readonly disallowedTools: readonly string[];
45
+ readonly model?: string;
46
+ readonly effort?: string;
47
+ readonly fork?: {
48
+ readonly agent?: string;
49
+ readonly background: boolean;
50
+ };
51
+ }
52
+ /** Read the invocation fields of a frontmatter. */
53
+ export declare function directivesOf(frontmatter: Readonly<Record<string, unknown>>): Directives;
54
+ /** Expand the path variables a rule may name. */
55
+ export declare function expandRule(rule: string, places: InvocationPlaces & {
56
+ readonly projectDir: string;
57
+ }): string;
58
+ interface AgentLike {
59
+ readonly id?: string;
60
+ readonly options?: {
61
+ readonly provider?: string;
62
+ readonly model?: string;
63
+ readonly reasoningEffort?: string;
64
+ };
65
+ readonly session: {
66
+ readonly header: {
67
+ readonly id: string;
68
+ readonly cwd?: string;
69
+ };
70
+ };
71
+ followup(message: unknown): void;
72
+ }
73
+ /** Per-session invocation state of foreign skills and commands. */
74
+ export declare class Invocations {
75
+ private readonly ctx;
76
+ private readonly presetOf;
77
+ private readonly directory;
78
+ private readonly specs;
79
+ private readonly turns;
80
+ private readonly pending;
81
+ /**
82
+ * A command submitted its prompt: its frontmatter takes effect in the turn
83
+ * that prompt starts, after that turn clears the previous grants.
84
+ */
85
+ queue(sessionId: string, spec: InvocationSpec): void;
86
+ /** Withdraw a spec queued for a session's next turn (its prompt was not submitted after all). */
87
+ unqueue(sessionId: string, spec: InvocationSpec): void;
88
+ /** Take the specs queued for a session's next turn. */
89
+ takeQueued(sessionId: string): InvocationSpec[];
90
+ /**
91
+ * @param presetOf - the DSH preset of a foreign agent name, for `agent`.
92
+ * @param directory - the session's working directory.
93
+ */
94
+ constructor(ctx: Context, presetOf: (foreignName: string) => string | undefined, directory: (agent: AgentLike, signal: AbortSignal) => Promise<string>);
95
+ /** Make a skill's frontmatter take effect when the skill is invoked. Returns the withdrawal. */
96
+ registerSkill(spec: InvocationSpec): () => void;
97
+ /** The registered spec of a skill name. */
98
+ skill(name: string): InvocationSpec | undefined;
99
+ /** The turn's tool grants of a session, as allow and deny rules. */
100
+ rules(sessionId: string): {
101
+ allow: readonly string[];
102
+ deny: readonly string[];
103
+ };
104
+ /** The skills and commands active in a session's turn. */
105
+ active(sessionId: string): readonly string[];
106
+ /** The user sent a new message: grants and overrides end. */
107
+ clear(sessionId: string): void;
108
+ /**
109
+ * DSH 0.2.2 fixes a step's route before `agent/pre-step`, so a route is selected on the agent ahead of the step
110
+ * that must run on it: a typed command's or skill's when the line is dispatched (its turn has not begun), a
111
+ * model-invoked skill's during the step that loads it. The route the agent had is put back when that turn ends.
112
+ */
113
+ private readonly selected;
114
+ private applyRoute;
115
+ /** A typed command or skill line is about to run: its frontmatter route is selected for the turn it starts. */
116
+ preselect(agent: AgentLike, spec: InvocationSpec, signal: AbortSignal): Promise<void>;
117
+ /** A session's turn started: a route selected ahead of it now belongs to it. */
118
+ turnStarted(sessionId: string): void;
119
+ /**
120
+ * A session's turn ended: the route it ran on is put back. Called from a `session/event` listener, which runs
121
+ * while DSH publishes the event and may not append (selecting a route appends `model/selection`), so the
122
+ * selection is put back right after; the next step reads the route only later.
123
+ */
124
+ turnEnded(sessionId: string): void;
125
+ /** A typed line was answered without starting a turn: the route it selected is put back now. */
126
+ release(sessionId: string): void;
127
+ /** Apply a spec's grants and overrides to the agent's current turn. */
128
+ activate(agent: AgentLike, spec: InvocationSpec, signal: AbortSignal): Promise<Directives>;
129
+ /**
130
+ * Run rendered content in a forked agent. With `background`, return at once
131
+ * and deliver the result to the parent when the agent finishes.
132
+ * @returns the result text, or the launch note in the background case.
133
+ */
134
+ fork(agent: AgentLike, spec: InvocationSpec, directives: Directives, content: string, signal: AbortSignal): Promise<string>;
135
+ private expandedRules;
136
+ /**
137
+ * Resolve a frontmatter `model` and `effort` to a DSH route: an exact
138
+ * `provider/model`, a model id or name one provider lists (the current
139
+ * provider first), and an effort the model offers by name or, failing that,
140
+ * by rank.
141
+ */
142
+ private route;
143
+ }
144
+ /** A requested model and effort resolved against what DSH serves. */
145
+ export interface RouteResolution {
146
+ readonly route?: {
147
+ provider?: string;
148
+ model?: string;
149
+ reasoningEffort?: string;
150
+ };
151
+ /** Why a requested value was not applied. */
152
+ readonly note?: string;
153
+ }
154
+ /**
155
+ * Resolve a Claude `model` and `effort` to a DSH route: an exact
156
+ * `provider/model`, else a model id or name one provider lists (the current
157
+ * provider first); an effort the model offers by id or name, else by rank
158
+ * among Claude's `low`…`max`. `inherit` keeps the current model.
159
+ */
160
+ export declare function resolveRoute(ctx: Context, current: {
161
+ readonly provider?: string;
162
+ readonly model?: string;
163
+ }, wantedModel: string | undefined, wantedEffort: string | undefined, signal: AbortSignal): Promise<RouteResolution>;
164
+ /** The Claude family a `model` value names: an alias (`haiku`, `sonnet`, `opus`, `opusplan`) or a `claude-…` id. */
165
+ export declare function claudeFamily(wanted: string): ClaudeFamily | undefined;
166
+ export type ClaudeFamily = 'haiku' | 'sonnet' | 'opus';
167
+ /** The person's mapping of Claude aliases to served models (Harness Forge's `modelAliases` config). */
168
+ export declare function setModelAliases(aliases: Readonly<Partial<Record<ClaudeFamily, string>>> | undefined): void;
169
+ export {};