@kirkchinese/harness-forge 0.4.0 → 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 (125) hide show
  1. package/README.md +4 -0
  2. package/docs/DETAIL.zh.md +47 -0
  3. package/lib/agents/presets.d.ts +7 -0
  4. package/lib/agents/presets.js +11 -1
  5. package/lib/agents/profiles.js +3 -2
  6. package/lib/agents/row.js +3 -1
  7. package/lib/client/paths.d.ts +12 -0
  8. package/lib/client/paths.js +68 -0
  9. package/lib/client/typert.d.ts +12 -1
  10. package/lib/client/typert.js +54 -6
  11. package/lib/client.js +1593 -270
  12. package/lib/commands/row.js +1 -1
  13. package/lib/context/instructions.js +5 -5
  14. package/lib/dsh/host.d.ts +3 -0
  15. package/lib/dsh/host.js +3 -0
  16. package/lib/forge/contract.d.ts +42 -2
  17. package/lib/forge/contract.js +3 -1
  18. package/lib/forge/follow.d.ts +30 -0
  19. package/lib/forge/follow.js +73 -0
  20. package/lib/forge/ledger.d.ts +70 -7
  21. package/lib/forge/ledger.js +314 -42
  22. package/lib/forge/projects.d.ts +5 -2
  23. package/lib/forge/projects.js +23 -16
  24. package/lib/forge/remote/archive.d.ts +65 -0
  25. package/lib/forge/remote/archive.js +565 -0
  26. package/lib/forge/remote/code-parts.d.ts +18 -0
  27. package/lib/forge/remote/code-parts.js +76 -0
  28. package/lib/forge/remote/fetch.d.ts +265 -0
  29. package/lib/forge/remote/fetch.js +1133 -0
  30. package/lib/forge/remote/service.d.ts +256 -0
  31. package/lib/forge/remote/service.js +868 -0
  32. package/lib/forge/service.d.ts +19 -9
  33. package/lib/forge/service.js +47 -31
  34. package/lib/forge/settings.d.ts +5 -3
  35. package/lib/forge/settings.js +11 -4
  36. package/lib/forge/state.d.ts +60 -0
  37. package/lib/forge/state.js +174 -58
  38. package/lib/hooks/broker/engine.js +2 -8
  39. package/lib/hooks/broker/session-events.d.ts +5 -0
  40. package/lib/hooks/broker/session-events.js +12 -3
  41. package/lib/hooks/broker/types.d.ts +7 -5
  42. package/lib/hooks/condition.d.ts +78 -2
  43. package/lib/hooks/condition.js +494 -73
  44. package/lib/hooks/config.d.ts +1 -1
  45. package/lib/hooks/config.js +4 -0
  46. package/lib/hooks/glob.d.ts +41 -0
  47. package/lib/hooks/glob.js +114 -0
  48. package/lib/hooks/permissions.d.ts +8 -3
  49. package/lib/hooks/permissions.js +119 -26
  50. package/lib/hooks/powershell-aliases.d.ts +19 -0
  51. package/lib/hooks/powershell-aliases.js +58 -0
  52. package/lib/hooks/process.d.ts +17 -0
  53. package/lib/hooks/process.js +156 -1
  54. package/lib/hooks/row.js +2 -0
  55. package/lib/hooks/runner.d.ts +17 -4
  56. package/lib/hooks/runner.js +42 -13
  57. package/lib/hooks/shell-commands.d.ts +10 -1
  58. package/lib/hooks/shell-commands.js +74 -10
  59. package/lib/hooks/shell.d.ts +3 -2
  60. package/lib/hooks/shell.js +5 -2
  61. package/lib/hooks/vocabulary.js +3 -1
  62. package/lib/mcp/catalog.d.ts +5 -2
  63. package/lib/mcp/catalog.js +18 -10
  64. package/lib/mcp/mount.d.ts +40 -2
  65. package/lib/mcp/mount.js +131 -31
  66. package/lib/mcp/policy.d.ts +42 -0
  67. package/lib/mcp/policy.js +43 -0
  68. package/lib/mcp/remote.js +5 -15
  69. package/lib/mcp/row.js +111 -17
  70. package/lib/mods/loader.js +4 -0
  71. package/lib/mods/service/turns.d.ts +8 -7
  72. package/lib/mods/service/turns.js +10 -35
  73. package/lib/opencode/bun.js +14 -2
  74. package/lib/opencode/row.d.ts +14 -1
  75. package/lib/opencode/row.js +38 -20
  76. package/lib/opencode/runtime/server.js +2 -1
  77. package/lib/porting/adapter-paths.d.ts +13 -0
  78. package/lib/porting/adapter-paths.js +120 -0
  79. package/lib/porting/port-gap.d.ts +10 -4
  80. package/lib/porting/port-gap.js +43 -7
  81. package/lib/porting/prompt.js +9 -7
  82. package/lib/porting/row.js +7 -5
  83. package/lib/porting/verify-port.d.ts +3 -10
  84. package/lib/porting/verify-port.js +12 -34
  85. package/lib/sessions/chat-import.d.ts +48 -0
  86. package/lib/sessions/chat-import.js +44 -0
  87. package/lib/sessions/claude.d.ts +16 -10
  88. package/lib/sessions/claude.js +76 -55
  89. package/lib/sessions/codex-discover.d.ts +34 -0
  90. package/lib/sessions/codex-discover.js +205 -0
  91. package/lib/sessions/codex-meta.d.ts +63 -0
  92. package/lib/sessions/codex-meta.js +148 -0
  93. package/lib/sessions/codex-text.d.ts +9 -0
  94. package/lib/sessions/codex-text.js +44 -0
  95. package/lib/sessions/codex.d.ts +34 -22
  96. package/lib/sessions/codex.js +150 -183
  97. package/lib/sessions/opencode.d.ts +15 -9
  98. package/lib/sessions/opencode.js +77 -58
  99. package/lib/sessions/persist.d.ts +162 -0
  100. package/lib/sessions/persist.js +377 -0
  101. package/lib/sessions/row.d.ts +2 -1
  102. package/lib/sessions/row.js +75 -9
  103. package/lib/sessions/turns.d.ts +31 -0
  104. package/lib/sessions/turns.js +63 -0
  105. package/lib/sessions/zstd.d.ts +15 -0
  106. package/lib/sessions/zstd.js +152 -0
  107. package/lib/shared/render.d.ts +30 -1
  108. package/lib/shared/render.js +813 -48
  109. package/lib/skills/provider.d.ts +2 -0
  110. package/lib/skills/provider.js +8 -2
  111. package/lib/skills/row.js +1 -1
  112. package/lib/workbench/adapter-coverage.d.ts +20 -2
  113. package/lib/workbench/adapter-coverage.js +46 -7
  114. package/lib/workbench/overview.d.ts +77 -27
  115. package/lib/workbench/overview.js +99 -12
  116. package/lib/workbench/remote.d.ts +64 -21
  117. package/lib/workbench/remote.js +181 -42
  118. package/lib/workbench/settings.d.ts +5 -1
  119. package/lib/workbench/settings.js +6 -2
  120. package/lib/workbench/workbench.d.ts +34 -4
  121. package/lib/workbench/workbench.js +147 -46
  122. package/locale/zh.json +2 -1
  123. package/package.json +3 -2
  124. package/lib/forge/marketplace-install.d.ts +0 -3
  125. package/lib/forge/marketplace-install.js +0 -64
@@ -7,16 +7,31 @@
7
7
  * @module @kirkchinese/harness-forge/porting
8
8
  */
9
9
  import { randomUUID } from 'node:crypto';
10
- import { existsSync, readdirSync, statSync } from 'node:fs';
10
+ import { existsSync, mkdirSync, readdirSync, statSync } from 'node:fs';
11
+ import { homedir } from 'node:os';
11
12
  import { dirname, join, resolve } from 'node:path';
12
- import { absolutePath, detectLicense, portBrief } from '@kirkchinese/harness-forge-core';
13
+ import { ADAPTERS_DIR, absolutePath, detectLicense, portBrief } from '@kirkchinese/harness-forge-core';
13
14
  import { dshService } from '../dsh/host.js';
15
+ import { resolveDshHome } from '../forge/state.js';
14
16
  import { portPrompt } from './prompt.js';
15
17
  /** The preset of DSH's creation mode ("Let the agent create a plugin" in the Plugin Manager). */
16
18
  export const CREATOR_PRESET = 'cordis';
17
19
  /** Most files a brief lists for one part. */
18
20
  const FILE_LIMIT = 200;
19
21
  const SKIPPED_DIRS = new Set(['node_modules', '.git']);
22
+ /** The workspace of a directory (made when there is none), or undefined where the host has no workspace registry or refuses. */
23
+ async function workspaceOf(ctx, cwd) {
24
+ const registry = dshService(ctx, 'workspaceRegistry');
25
+ if (typeof registry?.create !== 'function')
26
+ return undefined;
27
+ try {
28
+ const id = (await registry.create(cwd)).id;
29
+ return typeof id === 'string' ? id : undefined;
30
+ }
31
+ catch {
32
+ return undefined;
33
+ }
34
+ }
20
35
  /** The session title for a brief: its heading, without the Markdown marker DSH would otherwise show in the sidebar. */
21
36
  export function briefTitle(brief) {
22
37
  return (brief.split('\n', 1)[0] ?? '').replace(/^#+\s*/u, '').trim();
@@ -83,17 +98,31 @@ export function partFiles(plugin, component) {
83
98
  out.push(plugin.ref.manifestPath);
84
99
  return out;
85
100
  }
101
+ /**
102
+ * The DSH home and profile this Harness Forge runs in, resolved as DSH does:
103
+ * `$DSH_HOME` (a blank value is unset), else `~/.dsh`; the profile from the
104
+ * `profileContext` service, which only a profile-launched DSH composes.
105
+ */
106
+ export function portRuntime(ctx, env = process.env) {
107
+ const profile = dshService(ctx, 'profileContext');
108
+ const named = typeof profile?.name === 'string' && profile.name.length > 0 && typeof profile.dir === 'string' && profile.dir.length > 0;
109
+ return {
110
+ dshHome: resolveDshHome(env),
111
+ dshHomeFromEnv: (env.DSH_HOME?.trim() ?? '').length > 0,
112
+ ...(named ? { profile: { name: profile.name, dir: profile.dir } } : {}),
113
+ };
114
+ }
86
115
  /** The brief for one part of a plugin, or a failure naming what is missing. */
87
- export function briefFor(plugin, gaps, componentId) {
116
+ export function briefFor(plugin, gaps, componentId, runtime) {
88
117
  const component = plugin.components.find(item => item.id === componentId);
89
118
  if (component === undefined)
90
119
  throw new Error(`${plugin.name} has no part ${componentId}`);
91
120
  const license = plugin.license ?? detectLicense(plugin.root);
92
- return portBrief({ plugin, component, gaps, files: partFiles(plugin, component), ...(license !== undefined ? { license } : {}) });
121
+ return portBrief({ plugin, component, gaps, files: partFiles(plugin, component), ...(license !== undefined ? { license } : {}), ...(runtime !== undefined ? { runtime } : {}) });
93
122
  }
94
123
  /** The first message of a part's port session: the protocol, then the brief (see `prompt.ts`). */
95
- export function taskFor(plugin, gaps, componentId, language) {
96
- const brief = briefFor(plugin, gaps, componentId);
124
+ export function taskFor(plugin, gaps, componentId, language, runtime) {
125
+ const brief = briefFor(plugin, gaps, componentId, runtime);
97
126
  const component = plugin.components.find(item => item.id === componentId);
98
127
  return portPrompt({ plugin, component, brief, ...(language !== undefined && language.length > 0 ? { language } : {}) });
99
128
  }
@@ -112,7 +141,14 @@ export async function startCreatorSession(ctx, task, location = {}, title = brie
112
141
  if (presets?.list !== undefined && (creator === undefined || creator.broken !== undefined)) {
113
142
  throw new Error(`creation mode (agent preset "${CREATOR_PRESET}") is ${creator === undefined ? 'not in this DSH profile' : 'unavailable in this DSH profile'}; copy the brief into a session instead`);
114
143
  }
115
- const where = location.workspaceId !== undefined ? { workspaceId: location.workspaceId } : location.cwd !== undefined ? { cwd: location.cwd } : {};
144
+ const cwd = location.cwd ?? join(homedir(), ADAPTERS_DIR);
145
+ if (location.workspaceId === undefined && location.cwd === undefined)
146
+ mkdirSync(cwd, { recursive: true });
147
+ // DSH groups a session under the workspace whose path is its directory; without one the session lands in
148
+ // "Ungrouped" among the person's own. The adapters directory gets a workspace named after the folder, reused by
149
+ // every creation session.
150
+ const workspaceId = location.workspaceId ?? await workspaceOf(ctx, cwd);
151
+ const where = workspaceId !== undefined ? { workspaceId } : { cwd };
116
152
  const { sessionId } = await controller.create({ ...where, agentPreset: CREATOR_PRESET });
117
153
  // Named before the task is sent, so the sidebar shows the brief's heading rather than the protocol's first line. A title the host refuses only leaves DSH's own.
118
154
  if (title.length > 0)
@@ -29,18 +29,20 @@ export function portPrompt(input) {
29
29
  '',
30
30
  '## Protocol',
31
31
  '',
32
- '1. **Ask once, first.** Read the brief and the original\'s files, then send the user ONE concise message with numbered questions, each with a default so they can just reply "ok". Ask:',
33
- ` - where to put the adapter's source; default \`${defaultAdapterDir(packageName)}\`, because it is outside every workspace and the original plugin, so neither a workspace cleanup nor an update of the original touches it, and the local install keeps pointing at it;`,
34
- ' - each question under "Questions for the user" in the brief that reading the files did not settle.',
35
- ' Never ask what you can look up (DSH APIs, slot names, file contents): look it up. Write no file before the answer.',
36
- '2. **Build without further questions.** Load the `dsh-doc` skill and follow it. Scaffold the package in the agreed directory, implement it reusing the original\'s code and data where possible, install it into the current profile with `plugin_manager` `install_bundle` (absolute directory) and make sure it is enabled. Ask again only when blocked on a choice only the user can make.',
32
+ '1. **Ask once, first.** Your first reply is ONE concise message with numbered questions, each with a default so the user can just reply "ok". Use only the brief: do not call tools, inspect files or the runtime, or plan the implementation before the answer. Ask:',
33
+ ` - where to put the adapter's source; default \`${defaultAdapterDir(packageName)}\`, under the creation session's default working directory and separate from the original plugin;`,
34
+ ' - each user choice under "Questions for the user" in the brief; describe placement and other choices in user-facing terms, not API names.',
35
+ ' Never ask what you can look up (DSH APIs, slot names, file contents). Write no file before the answer.',
36
+ '2. **Build without further questions.** Now read the original files and load the `dsh-doc` skill. If the skill tool is unavailable, find and read the installed dsh-doc references directly. Confirm the DSH APIs and slot names with runtime inspection. Scaffold the package in the agreed directory, implement it reusing the original\'s code and data where possible, install it into the current profile with `plugin_manager` `install_bundle` (absolute directory) and make sure it is enabled. Ask again only when blocked on a choice only the user can make.',
37
+ ' Follow the brief\'s "Data access rules" without exception: take session and profile data from DSH\'s runtime services and the context the adapter receives; resolve any DSH path at run time from `$DSH_HOME` (default `~/.dsh`) and the running profile, never from a home path written into the source; never read or iterate other profiles; read no private file of DSH or another harness beyond what the part needs. The profile and home under "Where DSH keeps its data" are for your checks, not for the source.',
37
38
  ' Fallback: should `install_bundle` come back `"application": "failed"` with "pnpm printed nothing … and was terminated", call it once more with the same directory (a pnpm that did not exit; the second call completes). Do not run pnpm or `dsh plugin` from the shell on the running profile instead.',
38
39
  '3. **Verify before you report.** All of these must pass:',
39
40
  ' a. The adapter loaded without errors: `plugin_manager` `list_bundles` shows it enabled with no `error`, and `cordis_inspect_*` shows what it registered.',
40
41
  ' b. Each behaviour the acceptance criteria name happens: exercise it and observe the result (the tool\'s answer, the command\'s output, the hook acting, the surface\'s value).',
41
- ` c. \`${VERIFY_TOOL}\` with \`${verifyArgs}\` answers \`"covered": true\`.`,
42
+ ` c. \`${VERIFY_TOOL}\` with \`${verifyArgs}\` answers \`"covered": true\`, its \`paths\` check included.`,
42
43
  ' When a check fails, fix the cause and run all three again.',
43
- '4. **Report.** Only after 3 passed: say what now works, with the evidence (what each check showed, including the `' + VERIFY_TOOL + '` answer), where the source is, and what still differs from the original. If you cannot close the gap, say exactly what blocks it, what you tried, and what the user can do.',
44
+ ' To check what the page shows, use runtime inspection: `cordis_inspect_list`, then `cordis_inspect_query` on the Client `Slots.listSubTree` (the live slot tree and props, when a page is connected); if that cannot show it, ask the user to look and confirm. Never read DSH\'s access token or logs, `/proc` of another process, or another process\'s files, and never drive a browser with credentials taken from them.',
45
+ '4. **Report immediately when step 3 passes.** Do not start or wait for optional reviews before sending the final report; give the result first, then mention any review still running. Say what now works, with the evidence (what each check showed, including the `' + VERIFY_TOOL + '` answer), where the source is, and what still differs from the original. If you cannot close the gap, say exactly what blocks it, what you tried, and what the user can do.',
44
46
  '',
45
47
  '---',
46
48
  '',
@@ -1,5 +1,5 @@
1
1
  import { FORGE_SERVICE } from '../forge/service.js';
2
- import { briefFor, briefTitle, startCreatorSession, taskFor } from './port-gap.js';
2
+ import { briefFor, briefTitle, portRuntime, startCreatorSession, taskFor } from './port-gap.js';
3
3
  import { PortSessions } from './port-sessions.js';
4
4
  import { rowEffect } from '../forge/row.js';
5
5
  export const name = 'harness-forge-porter';
@@ -12,11 +12,13 @@ export function apply(ctx) {
12
12
  export function startPorter(ctx, forge) {
13
13
  const sessions = new PortSessions(forge.statePath);
14
14
  const api = {
15
- brief: (plugin, gaps, componentId) => briefFor(plugin, gaps, componentId),
16
- task: (plugin, gaps, componentId, language) => taskFor(plugin, gaps, componentId, language),
15
+ // Read for each brief: the facts are the profile and home of the session that asks.
16
+ brief: (plugin, gaps, componentId) => briefFor(plugin, gaps, componentId, portRuntime(ctx)),
17
+ task: (plugin, gaps, componentId, language) => taskFor(plugin, gaps, componentId, language, portRuntime(ctx)),
17
18
  port: async (plugin, gaps, componentId, location, language) => {
18
- const task = taskFor(plugin, gaps, componentId, language);
19
- const started = await startCreatorSession(ctx, task, location, briefTitle(briefFor(plugin, gaps, componentId)));
19
+ const runtime = portRuntime(ctx);
20
+ const task = taskFor(plugin, gaps, componentId, language, runtime);
21
+ const started = await startCreatorSession(ctx, task, location, briefTitle(briefFor(plugin, gaps, componentId, runtime)));
20
22
  sessions.started(plugin.id, componentId, started.sessionId);
21
23
  return started;
22
24
  },
@@ -1,14 +1,6 @@
1
- /**
2
- * `harness_verify_port`: whether an installed adapter now covers a plugin
3
- * part. It reads the adapter packages again, asks DSH's plugin manager whether
4
- * that package is enabled and its plugins started without a fault, and records
5
- * the answer for the Gaps screen ("Done — verified", or back to in progress).
6
- * The creation-mode agent calls it before it reports a port done.
7
- * @module @kirkchinese/harness-forge/porting
8
- */
9
1
  import { type ForeignPlugin } from '@kirkchinese/harness-forge-core';
10
2
  import { type AdapterCoverage } from '../workbench/overview.js';
11
- import { type PluginManagerLike } from '../workbench/adapter-coverage.js';
3
+ import { type PluginManagerLike, type ReadinessCheck } from '../workbench/adapter-coverage.js';
12
4
  import { PortSessions, type PortRecord } from './port-sessions.js';
13
5
  import type { HarnessForge } from '../forge/service.js';
14
6
  import type { Workbench } from '../workbench/workbench.js';
@@ -23,8 +15,9 @@ export interface VerifyDeps {
23
15
  readonly pluginManager: PluginManagerLike | undefined;
24
16
  readonly sessions: PortSessions;
25
17
  }
18
+ /** One check of the answer: the adapter's readiness, then its source's paths. */
26
19
  export interface PortCheck {
27
- readonly check: 'declared' | 'enabled' | 'loaded';
20
+ readonly check: ReadinessCheck['check'] | 'paths';
28
21
  readonly ok: boolean;
29
22
  readonly detail: string;
30
23
  }
@@ -3,36 +3,19 @@
3
3
  * part. It reads the adapter packages again, asks DSH's plugin manager whether
4
4
  * that package is enabled and its plugins started without a fault, and records
5
5
  * the answer for the Gaps screen ("Done — verified", or back to in progress).
6
+ * It also reads the adapter's source for a hard-coded DSH home or a listing of
7
+ * profiles (`adapter-paths.ts`), the brief's data access rules.
6
8
  * The creation-mode agent calls it before it reports a port done.
7
9
  * @module @kirkchinese/harness-forge/porting
8
10
  */
11
+ import { existsSync } from 'node:fs';
9
12
  import { adapterPackageName } from '@kirkchinese/harness-forge-core';
10
13
  import { coveringAdapter } from '../workbench/overview.js';
11
- import { bundleState } from '../workbench/adapter-coverage.js';
14
+ import { adapterReadiness, managerSnapshot } from '../workbench/adapter-coverage.js';
12
15
  import { PortSessions } from './port-sessions.js';
16
+ import { hardCodedPaths, pathsDetail } from './adapter-paths.js';
13
17
  import { dshService } from '../dsh/host.js';
14
18
  const check = (name, ok, detail) => ({ check: name, ok, detail });
15
- /** Whether the package's plugins started: every row it declares has a live entry, active, without a startup failure. */
16
- async function loaded(manager, rows) {
17
- if (rows.length === 0)
18
- return check('loaded', true, 'its bundle declares no plugin rows, so nothing has to start');
19
- const entries = new Map((await manager.listPlugins()).map(entry => [entry.entryId, entry]));
20
- const problems = [];
21
- for (const row of rows) {
22
- const entry = row.entryId === undefined ? undefined : entries.get(row.entryId);
23
- if (entry === undefined)
24
- problems.push(`row "${row.rowId}" has no running entry`);
25
- else if (entry.diagnostic !== undefined)
26
- problems.push(`row "${row.rowId}" failed to start: ${entry.diagnostic}`);
27
- else if (!entry.enabled)
28
- problems.push(`row "${row.rowId}" is disabled`);
29
- else if (entry.fiberPhase !== 'active')
30
- problems.push(`row "${row.rowId}" is ${entry.fiberPhase ?? 'not running'}`);
31
- }
32
- return problems.length === 0
33
- ? check('loaded', true, `all ${String(rows.length)} plugin row(s) of its bundle are active, without startup failures`)
34
- : check('loaded', false, problems.join('; '));
35
- }
36
19
  /**
37
20
  * Verify that an adapter covers one part, and record the answer.
38
21
  * @param callerSession - the session that asked, linked to the part when no port session was recorded for it.
@@ -56,18 +39,13 @@ export async function verifyPort(deps, pluginId, componentId, callerSession) {
56
39
  checks.push(check('enabled', false, 'this DSH profile composes no plugin manager, so whether the adapter is enabled cannot be checked'));
57
40
  }
58
41
  else {
59
- // The criterion the workbench overview counts an adapter by (`bundleState`).
60
- const status = bundleState(name, await deps.pluginManager.listBundles());
61
- if (status.state === 'unlisted')
62
- checks.push(check('enabled', false, `${name} is on disk but DSH does not list it as an installed bundle: install it with plugin_manager install_bundle (a link left by a failed install does not count), and check that its package.json declares a bundle (dsh-doc references/host-plugin.md)`));
63
- else if (status.state === 'off')
64
- checks.push(check('enabled', false, `${name} is installed but switched off: enable it with plugin_manager set_bundle`));
65
- else if (status.state === 'broken')
66
- checks.push(check('enabled', false, `${name} is enabled but its bundle cannot load: ${status.error.code}${status.error.diagnostic !== undefined ? ` — ${status.error.diagnostic}` : ''}`));
67
- else {
68
- checks.push(check('enabled', true, `${name} is enabled`));
69
- checks.push(await loaded(deps.pluginManager, status.bundle.rows));
70
- }
42
+ // The decision the workbench overview counts an adapter by.
43
+ checks.push(...adapterReadiness(name, await managerSnapshot(deps.pluginManager)));
44
+ }
45
+ // Only a package whose files are here can be read; an adapter DSH installed always has them.
46
+ if (dir !== undefined && existsSync(dir)) {
47
+ const findings = hardCodedPaths(dir);
48
+ checks.push(check('paths', findings.length === 0, pathsDetail(findings)));
71
49
  }
72
50
  }
73
51
  const covered = checks.every(item => item.ok);
@@ -0,0 +1,48 @@
1
+ /**
2
+ * dsh-chat-import, the dedicated session importer for DSH (Claude Code, Codex, OpenCode and 40+ other agents):
3
+ * Harness Forge recommends it, installs it on request through DSH's plugin manager, and yields its own import
4
+ * to it while it runs. Detected by the service it provides (`chatImport`); Harness Forge does not depend on it.
5
+ * @module @kirkchinese/harness-forge
6
+ */
7
+ import type { Context } from '@deepseek-ai/cordis';
8
+ /** Its npm package, which is also its bundle name. */
9
+ export declare const CHAT_IMPORT_PACKAGE = "dsh-chat-import";
10
+ /** The command that installs it into the web profile when the plugin manager is not reachable. */
11
+ export declare const CHAT_IMPORT_COMMAND = "dsh plugin --profile web add dsh-chat-import";
12
+ /** What Harness Forge's import answers while dsh-chat-import runs. */
13
+ export declare const YIELD_MESSAGE = "Session import is provided by dsh-chat-import: use its Import sessions button in the sidebar.";
14
+ /** Whether dsh-chat-import runs in this DSH. */
15
+ export declare function chatImportRunning(ctx: object): boolean;
16
+ /** Where session import stands, for the workbench. */
17
+ export interface SessionImportStatus {
18
+ /** Who imports sessions: Harness Forge, or dsh-chat-import while it runs. */
19
+ readonly provider: 'harness-forge' | 'dsh-chat-import';
20
+ /** Whether Harness Forge can install dsh-chat-import itself (DSH's plugin manager is there). */
21
+ readonly canInstall: boolean;
22
+ readonly command: string;
23
+ }
24
+ export declare function sessionImportStatus(ctx: object): SessionImportStatus;
25
+ interface ChangeResult {
26
+ readonly changed: boolean;
27
+ readonly application: 'applied' | 'restart-required' | 'overridden' | 'failed' | 'cancelled';
28
+ readonly error?: {
29
+ readonly code: string;
30
+ readonly diagnostic?: string;
31
+ };
32
+ readonly pendingBuilds?: readonly string[];
33
+ /** The bundle an installation added. */
34
+ readonly bundle?: string;
35
+ }
36
+ /** How an installation ended. */
37
+ export interface ChatImportInstall {
38
+ /** `applied`: it runs now; `restart-required`: it runs after DSH restarts. */
39
+ readonly application: ChangeResult['application'];
40
+ readonly running: boolean;
41
+ }
42
+ /**
43
+ * Install dsh-chat-import from npm and enable it, through DSH's plugin manager, the way the Plugins page does; an
44
+ * installed but disabled copy is enabled. The browser asks the person first. Throws with the reason, and the
45
+ * command to run instead, when it cannot.
46
+ */
47
+ export declare function installChatImport(ctx: Context): Promise<ChatImportInstall>;
48
+ export {};
@@ -0,0 +1,44 @@
1
+ import { dshService } from '../dsh/host.js';
2
+ /** Its npm package, which is also its bundle name. */
3
+ export const CHAT_IMPORT_PACKAGE = 'dsh-chat-import';
4
+ /** The command that installs it into the web profile when the plugin manager is not reachable. */
5
+ export const CHAT_IMPORT_COMMAND = `dsh plugin --profile web add ${CHAT_IMPORT_PACKAGE}`;
6
+ /** What Harness Forge's import answers while dsh-chat-import runs. */
7
+ export const YIELD_MESSAGE = 'Session import is provided by dsh-chat-import: use its Import sessions button in the sidebar.';
8
+ /** Whether dsh-chat-import runs in this DSH. */
9
+ export function chatImportRunning(ctx) {
10
+ return dshService(ctx, 'chatImport') !== undefined;
11
+ }
12
+ export function sessionImportStatus(ctx) {
13
+ const manager = dshService(ctx, 'pluginManager');
14
+ return {
15
+ provider: chatImportRunning(ctx) ? 'dsh-chat-import' : 'harness-forge',
16
+ canInstall: typeof manager?.installBundle === 'function',
17
+ command: CHAT_IMPORT_COMMAND,
18
+ };
19
+ }
20
+ /**
21
+ * Install dsh-chat-import from npm and enable it, through DSH's plugin manager, the way the Plugins page does; an
22
+ * installed but disabled copy is enabled. The browser asks the person first. Throws with the reason, and the
23
+ * command to run instead, when it cannot.
24
+ */
25
+ export async function installChatImport(ctx) {
26
+ const manager = dshService(ctx, 'pluginManager');
27
+ if (typeof manager?.installBundle !== 'function')
28
+ throw new Error(`DSH's plugin manager is not available here; install dsh-chat-import from the Plugins page, or run: ${CHAT_IMPORT_COMMAND}`);
29
+ if (chatImportRunning(ctx))
30
+ return { application: 'applied', running: true };
31
+ const listed = typeof manager.listBundles === 'function' ? (await manager.listBundles()).find(bundle => bundle.name === CHAT_IMPORT_PACKAGE) : undefined;
32
+ const result = listed !== undefined && listed.installed !== false && typeof manager.setBundleEnabled === 'function'
33
+ ? await manager.setBundleEnabled(CHAT_IMPORT_PACKAGE, true)
34
+ : await manager.installBundle(CHAT_IMPORT_PACKAGE, { enabled: true });
35
+ // A profile whose other entries fail to activate reports that as the change's error too; dsh-chat-import itself
36
+ // was added when the manager names it as the bundle, or when its service runs.
37
+ const added = result.bundle === CHAT_IMPORT_PACKAGE || chatImportRunning(ctx);
38
+ if (result.application === 'failed' || result.application === 'cancelled' || (result.error !== undefined && !added)) {
39
+ const builds = result.pendingBuilds !== undefined && result.pendingBuilds.length > 0 ? ` (its install scripts wait for approval: ${result.pendingBuilds.join(', ')})` : '';
40
+ const reason = result.error?.diagnostic ?? result.error?.code ?? result.application;
41
+ throw new Error(`dsh-chat-import was not installed: ${reason}${builds}. Install it from the Plugins page, or run: ${CHAT_IMPORT_COMMAND}`);
42
+ }
43
+ return { application: result.application, running: chatImportRunning(ctx) };
44
+ }
@@ -1,4 +1,6 @@
1
1
  import type { Context } from '@deepseek-ai/cordis';
2
+ import { type SessionPage, type SessionPageRequest } from '../forge/contract.js';
3
+ import { type ImportIdentity, type ImportReport } from './persist.js';
2
4
  /** One discoverable Claude Code transcript. */
3
5
  export interface SessionCandidate {
4
6
  readonly path: string;
@@ -7,21 +9,25 @@ export interface SessionCandidate {
7
9
  readonly title?: string;
8
10
  readonly cwd?: string;
9
11
  readonly createdAt?: number;
12
+ /** When the transcript was last written. */
13
+ readonly updatedAt?: number;
14
+ /** The transcript's size in bytes. */
15
+ readonly bytes?: number;
10
16
  readonly origin?: 'subagent';
11
17
  }
12
18
  /** Result of one session import. */
13
- export interface SessionImportReport {
14
- readonly id: string;
15
- readonly sourcePath: string;
16
- readonly title?: string;
17
- readonly turns: number;
18
- readonly events: number;
19
- readonly stats: Record<string, number>;
20
- }
19
+ export type SessionImportReport = ImportReport;
21
20
  /** Default Claude Code projects directory. */
22
21
  export declare function defaultClaudeProjectsRoot(home?: string): string;
23
- /** Discover Claude Code main transcripts under a root. */
24
- export declare function discoverClaudeSessions(root?: string, limit?: number): Promise<SessionCandidate[]>;
22
+ /** The id an import gives a Claude Code session (the core mints it the same way: `claude-<session id>`). */
23
+ export declare function claudeSessionId(sourceId: string): string;
24
+ /** How an import finds the DSH session holding a Claude Code session: earlier versions used the bare id. */
25
+ export declare function claudeIdentity(sourceId: string): ImportIdentity;
26
+ /**
27
+ * One page of the Claude Code main transcripts under a root, newest first. The files are only listed and dated;
28
+ * the page's transcripts are the ones opened, so a long history costs no more than a short one.
29
+ */
30
+ export declare function discoverClaudeSessions(root?: string, page?: SessionPageRequest): Promise<SessionPage<SessionCandidate>>;
25
31
  /** Import one Claude Code transcript into DSH session persistence. */
26
32
  export declare function importClaudeSession(ctx: Context, sourcePath: string, options?: {
27
33
  readonly includeSubagents?: boolean;
@@ -4,38 +4,89 @@
4
4
  * the persistence hand-off so the UI never writes session storage directly.
5
5
  * @module @kirkchinese/harness-forge
6
6
  */
7
+ import { readdir, stat } from 'node:fs/promises';
7
8
  import { homedir } from 'node:os';
8
9
  import { join } from 'node:path';
9
- import { claudeCodeAdapter, synthesizeDshSession } from '@kirkchinese/harness-forge-core';
10
- import { dshService } from '../dsh/host.js';
10
+ import { claudeCodeAdapter, discoverClaudeCodeSessions } from '@kirkchinese/harness-forge-core';
11
+ import { SESSION_PAGE_SIZE } from '../forge/contract.js';
12
+ import { importReport, persistImported, targetIdentity } from './persist.js';
11
13
  /** Default Claude Code projects directory. */
12
14
  export function defaultClaudeProjectsRoot(home = homedir()) {
13
15
  return join(home, '.claude', 'projects');
14
16
  }
15
- /** Discover Claude Code main transcripts under a root. */
16
- export async function discoverClaudeSessions(root = defaultClaudeProjectsRoot(), limit = 200) {
17
- const out = [];
18
- for await (const item of claudeCodeAdapter.discover(root, { recursive: true })) {
19
- out.push({
20
- path: item.ref,
21
- sourceId: item.sourceId ?? item.ref,
22
- source: 'claude-code',
23
- ...(item.title !== undefined ? { title: item.title } : {}),
24
- ...(item.cwd !== undefined ? { cwd: item.cwd } : {}),
25
- ...(item.createdAt !== undefined ? { createdAt: item.createdAt } : {}),
26
- ...(item.origin !== undefined ? { origin: item.origin } : {}),
27
- });
28
- if (out.length >= limit)
29
- break;
17
+ /** The id an import gives a Claude Code session (the core mints it the same way: `claude-<session id>`). */
18
+ export function claudeSessionId(sourceId) {
19
+ return `claude-${sourceId.trim()}`;
20
+ }
21
+ /** How an import finds the DSH session holding a Claude Code session: earlier versions used the bare id. */
22
+ export function claudeIdentity(sourceId) {
23
+ return { id: claudeSessionId(sourceId), legacyIds: [sourceId.trim()] };
24
+ }
25
+ /** Directories of a project that hold sidecars, not main transcripts. */
26
+ const SIDECAR_DIRS = new Set(['subagents', 'workflows', 'tool-results']);
27
+ /**
28
+ * One page of the Claude Code main transcripts under a root, newest first. The files are only listed and dated;
29
+ * the page's transcripts are the ones opened, so a long history costs no more than a short one.
30
+ */
31
+ export async function discoverClaudeSessions(root = defaultClaudeProjectsRoot(), page = {}) {
32
+ const limit = Math.max(1, page.limit ?? SESSION_PAGE_SIZE);
33
+ const files = await listTranscripts(root);
34
+ const sessions = [];
35
+ let at = Math.max(0, page.cursor ?? 0);
36
+ for (; at < files.length && sessions.length < limit; at++) {
37
+ const file = files[at];
38
+ try {
39
+ for await (const item of discoverClaudeCodeSessions(file.path)) {
40
+ sessions.push({
41
+ path: item.ref,
42
+ sourceId: item.sourceId ?? item.ref,
43
+ source: 'claude-code',
44
+ ...(item.title !== undefined ? { title: item.title } : {}),
45
+ ...(item.cwd !== undefined ? { cwd: item.cwd } : {}),
46
+ ...(item.createdAt !== undefined ? { createdAt: item.createdAt } : {}),
47
+ updatedAt: file.updatedAt,
48
+ bytes: file.bytes,
49
+ ...(item.origin !== undefined ? { origin: item.origin } : {}),
50
+ });
51
+ }
52
+ }
53
+ catch {
54
+ // A transcript that cannot be read is not offered.
55
+ }
30
56
  }
31
- out.sort((a, b) => (b.createdAt ?? 0) - (a.createdAt ?? 0));
32
- return out;
57
+ return { sessions, ...(at < files.length ? { next: at } : {}) };
58
+ }
59
+ async function listTranscripts(root) {
60
+ const found = [];
61
+ const walk = async (dir) => {
62
+ let entries;
63
+ try {
64
+ entries = await readdir(dir, { withFileTypes: true });
65
+ }
66
+ catch {
67
+ return;
68
+ }
69
+ for (const entry of entries) {
70
+ const path = join(dir, entry.name);
71
+ if (entry.isDirectory()) {
72
+ if (!SIDECAR_DIRS.has(entry.name))
73
+ await walk(path);
74
+ }
75
+ else if (entry.isFile() && /\.jsonl$/iu.test(entry.name) && !/^journal\.jsonl$/iu.test(entry.name)) {
76
+ const info = await stat(path).catch(() => undefined);
77
+ if (info !== undefined)
78
+ found.push({ path, updatedAt: info.mtimeMs, bytes: info.size });
79
+ }
80
+ }
81
+ };
82
+ const info = await stat(root).catch(() => undefined);
83
+ if (info?.isFile() === true)
84
+ return [{ path: root, updatedAt: info.mtimeMs, bytes: info.size }];
85
+ await walk(root);
86
+ return found.sort((a, b) => b.updatedAt - a.updatedAt || b.path.localeCompare(a.path));
33
87
  }
34
88
  /** Import one Claude Code transcript into DSH session persistence. */
35
89
  export async function importClaudeSession(ctx, sourcePath, options = {}) {
36
- const persistence = dshService(ctx, 'sessionPersistence');
37
- if (persistence === undefined)
38
- throw new Error('sessionPersistence service is not available');
39
90
  const candidate = {
40
91
  ref: sourcePath,
41
92
  sourceId: sourcePath,
@@ -47,37 +98,7 @@ export async function importClaudeSession(ctx, sourcePath, options = {}) {
47
98
  // A transcript with no conversation on its main chain would become an empty session: say why instead.
48
99
  if (parsed.session.turns.length === 0)
49
100
  throw new Error(`nothing to import from ${sourcePath}: ${parsed.stats.reasons.join('; ') || 'no conversation in the transcript'}`);
50
- const synthesized = synthesizeDshSession(parsed.session);
51
- const events = synthesized.events;
52
- const handle = await persistence.create({
53
- version: 4,
54
- id: synthesized.meta.id,
55
- createdAt: synthesized.meta.createdAt,
56
- isSeeded: false,
57
- ...(synthesized.meta.cwd !== undefined ? { cwd: synthesized.meta.cwd } : {}),
58
- delegationDepth: synthesized.meta.delegationDepth,
59
- ...(synthesized.meta.origin !== undefined ? { origin: synthesized.meta.origin } : {}),
60
- ...(synthesized.meta.parentSession !== undefined ? { parentSession: synthesized.meta.parentSession } : {}),
61
- });
62
- try {
63
- await handle.append(events);
64
- await handle.flush();
65
- }
66
- finally {
67
- await handle.close();
68
- }
69
- return {
70
- id: synthesized.meta.id,
71
- sourcePath,
72
- ...(parsed.session.title !== undefined ? { title: parsed.session.title } : {}),
73
- turns: synthesized.stats.turns,
74
- events: events.length,
75
- stats: {
76
- steps: synthesized.stats.steps,
77
- messages: synthesized.stats.messages,
78
- toolCalls: synthesized.stats.toolCalls,
79
- toolResults: synthesized.stats.toolResults,
80
- synthesizedToolResults: synthesized.stats.synthesizedToolResults,
81
- },
82
- };
101
+ const sourceId = parsed.session.source.sessionId;
102
+ const identity = options.targetId !== undefined ? targetIdentity(options.targetId) : sourceId !== undefined ? claudeIdentity(sourceId) : targetIdentity(parsed.session.id);
103
+ return importReport(sourcePath, parsed.session.title, await persistImported(ctx, parsed.session, identity));
83
104
  }
@@ -0,0 +1,34 @@
1
+ import { type SessionPage, type SessionPageRequest } from '../forge/contract.js';
2
+ import { type IndexedThread } from './codex-meta.js';
3
+ export interface CodexSessionCandidate {
4
+ readonly path: string;
5
+ /** The thread. */
6
+ readonly sourceId: string;
7
+ /** The session a forked thread belongs to (its parent's), when it is not the thread itself. */
8
+ readonly parentId?: string;
9
+ readonly title?: string;
10
+ readonly cwd?: string;
11
+ /** When the thread was created (as an import stores it). */
12
+ readonly createdAt?: number;
13
+ /** When the rollout was last written. */
14
+ readonly updatedAt?: number;
15
+ /** The rollout file's size in bytes (compressed, for a `.zst`). */
16
+ readonly bytes?: number;
17
+ /** Codex archived the thread (it is in `archived_sessions`). */
18
+ readonly archived?: boolean;
19
+ /** A subagent's thread: part of the session that spawned it, listed only when an import of it is stored. */
20
+ readonly subagent?: boolean;
21
+ }
22
+ /**
23
+ * One page of the Codex sessions under `root` (`~/.codex/sessions`; the archive and the thread names are read from
24
+ * its siblings), newest first: every `rollout-*.jsonl` and `.jsonl.zst`, a thread once. A subagent's thread is part
25
+ * of the session that spawned it and left out, unless `isImported` says an import of it is stored: an earlier
26
+ * version imported those, and the copy has to stay reachable.
27
+ */
28
+ export declare function discoverCodexSessions(root: string, page?: SessionPageRequest, isImported?: (subagent: CodexSessionCandidate) => Promise<boolean>): Promise<SessionPage<CodexSessionCandidate>>;
29
+ /**
30
+ * Every thread the rollouts under `root` hold, subagent threads included (an earlier version imported those too):
31
+ * what tells whether an id an earlier version gave a thread was given to others. Each file's `session_meta` is read
32
+ * once, until the file changes.
33
+ */
34
+ export declare function codexThreads(root: string): Promise<IndexedThread[]>;