dsh-compact-pi 0.2.3-b3 → 0.2.3-b4
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.
- package/CHANGELOG.md +6 -0
- package/README.md +7 -5
- package/bin/dcp-session.ts +25 -18
- package/dist/codec.mjs +45 -9
- package/dist/dcp-session.mjs +1061 -605
- package/dist/index.js +9 -3
- package/docs/compatibility.md +1 -1
- package/docs/help.md +14 -4
- package/docs/publishing.md +4 -4
- package/docs/testing.md +2 -0
- package/package.json +2 -2
- package/skills/dcp-migrate-to-dsh/SKILL.md +10 -8
- package/skills/dcp-migrate-to-dsh/references/commands.md +29 -0
- package/src/codec.ts +40 -6
- package/src/dsh/convert.ts +11 -5
- package/src/dsh/import.ts +53 -24
- package/src/dsh/migration-cli.ts +129 -0
- package/src/dsh/migration-web.ts +44 -0
- package/src/dsh/migration.ts +216 -0
- package/src/dsh/sync.ts +9 -1
- package/test/convert.test.ts +37 -0
- package/test/migration.test.ts +72 -0
package/dist/index.js
CHANGED
|
@@ -30631,8 +30631,8 @@ var SessionProjectionRegistry = class extends Service {
|
|
|
30631
30631
|
// package.json
|
|
30632
30632
|
var package_default = {
|
|
30633
30633
|
name: "dsh-compact-pi",
|
|
30634
|
-
version: "0.2.3-
|
|
30635
|
-
dcpVersion: "0.2.
|
|
30634
|
+
version: "0.2.3-b4",
|
|
30635
|
+
dcpVersion: "0.2.3b4",
|
|
30636
30636
|
type: "module",
|
|
30637
30637
|
description: "DeepSeek Harness context compaction for pi: upstream engine, policy, token meter and pruner",
|
|
30638
30638
|
repository: {
|
|
@@ -34859,13 +34859,14 @@ function dshMessageToPi(message, time3, toolNames, imageToPi) {
|
|
|
34859
34859
|
}
|
|
34860
34860
|
|
|
34861
34861
|
// src/dsh/sync.ts
|
|
34862
|
-
function createSyncState() {
|
|
34862
|
+
function createSyncState({ persistent = false } = {}) {
|
|
34863
34863
|
return {
|
|
34864
34864
|
turn: 1,
|
|
34865
34865
|
step: 0,
|
|
34866
34866
|
turnStarted: false,
|
|
34867
34867
|
systemSeq: void 0,
|
|
34868
34868
|
stepOpen: false,
|
|
34869
|
+
persistent,
|
|
34869
34870
|
seen: /* @__PURE__ */ new Set(),
|
|
34870
34871
|
toolCalls: /* @__PURE__ */ new Map(),
|
|
34871
34872
|
appended: 0
|
|
@@ -34888,6 +34889,11 @@ function ensureTurn(session, state) {
|
|
|
34888
34889
|
function appendSystem(session, state, entry, message, systemPrompt) {
|
|
34889
34890
|
if (state.systemSeq !== void 0) return;
|
|
34890
34891
|
ensureTurn(session, state);
|
|
34892
|
+
if (state.persistent && !state.stepOpen) {
|
|
34893
|
+
state.step += 1;
|
|
34894
|
+
append(session, "step/start", { turn: state.turn, step: state.step });
|
|
34895
|
+
state.stepOpen = true;
|
|
34896
|
+
}
|
|
34891
34897
|
let content = piContentToDsh(
|
|
34892
34898
|
systemPrompt && systemPrompt.trim().length > 0 ? systemPrompt : typeof message.content === "string" ? message.content : []
|
|
34893
34899
|
);
|
package/docs/compatibility.md
CHANGED
package/docs/help.md
CHANGED
|
@@ -9,10 +9,10 @@ pi install npm:dsh-compact-pi@latest
|
|
|
9
9
|
Use the explicit tag while the npm release has a prerelease version. The GitHub tag is also available:
|
|
10
10
|
|
|
11
11
|
```bash
|
|
12
|
-
pi install git:github.com/HanqingTony/dsh-compact-pi@v0.2.3-
|
|
12
|
+
pi install git:github.com/HanqingTony/dsh-compact-pi@v0.2.3-b4
|
|
13
13
|
```
|
|
14
14
|
|
|
15
|
-
Restart pi or run `/reload` while idle. `/dcp-status` should show DCP `0.2.
|
|
15
|
+
Restart pi or run `/reload` while idle. `/dcp-status` should show DCP `0.2.3b4` and DSH `0.2.3-alpha.2`. DCP is tested with pi 1.5.2 and 1.6.1 and needs Node.js `^24.22.3 || >=26.13.1`. Check `pi list` for duplicate installations if commands or warnings appear twice. See the [update instructions](../README.md#updating-an-existing-installation) for pinned tags and branch installs.
|
|
16
16
|
|
|
17
17
|
## Compaction and model selection
|
|
18
18
|
|
|
@@ -25,7 +25,15 @@ If a historical summary model is unavailable in pi, use the picker to select an
|
|
|
25
25
|
|
|
26
26
|
## Move a session between pi and DSH
|
|
27
27
|
|
|
28
|
-
|
|
28
|
+
Run `dcp-session migrate` in a terminal, or ask the `dcp-migrate-to-dsh` skill to guide you. The wizard asks for a source and target, shows the exact output and attachment paths, then waits for confirmation. Agents use `migrate plan` and `migrate apply` so you can review the same information before any session or image is written. See the [command examples](../skills/dcp-migrate-to-dsh/references/commands.md).
|
|
29
|
+
|
|
30
|
+
- **Portable export** writes a new folder under the export directory you choose. Move that whole folder to keep the JSONL and images together.
|
|
31
|
+
- **Direct import** uses the target backend's version, profile, data home, session directory, workspace, and encoding. Run on the target machine. On Windows, use Windows Node.js and Windows paths. On Linux, use the data paths of the backend your desktop client actually connects to.
|
|
32
|
+
- **Conflicts** stop the default plan. You can explicitly choose a new session ID while preserving the existing one, or recover the Pi entries from a recognized mixed log while preserving the original file. Encoding mismatches require a corrected target configuration.
|
|
33
|
+
|
|
34
|
+
The import receipt confirms a write. Open the imported history in the chosen Desktop or TUI, or run `migrate verify-web` to check both the list and history of the approved Web instance.
|
|
35
|
+
|
|
36
|
+
The CLI can also run low-level conversions for scripts. In a checkout use `node dist/dcp-session.mjs --help`. Exit the active source session or work from a copy.
|
|
29
37
|
|
|
30
38
|
```bash
|
|
31
39
|
dcp-session pi2dsh-import session.pi.jsonl
|
|
@@ -36,10 +44,12 @@ pi --session imported.pi.jsonl
|
|
|
36
44
|
|
|
37
45
|
`pi2dsh-import` writes a new session into the DSH 0.2.3-alpha.2 V4 store and prints its ID and working directory. Open it in DSH's session picker or run `dsh-tui --resume <session-id>` from that directory. The default store is `$DSH_HOME/sessions` with Zstandard encoding. Pass the configured session root as the second argument for a custom profile. Add `--plain` for profiles using plaintext JSONL. An existing session with the same ID and workspace is left intact.
|
|
38
46
|
|
|
39
|
-
|
|
47
|
+
In Pi, request a migration or run `/skill:dcp-migrate-to-dsh`. To invoke it from DSH, copy the [skill directory](../skills/dcp-migrate-to-dsh) into `$DSH_HOME/skills` (default `~/.dsh/skills`). Both hosts need access to the converter and source file.
|
|
40
48
|
|
|
41
49
|
The export archives pi entries, including the branch tree, and gives DSH the active compacted context. Reimporting an unchanged export restores the archived pi entries. Reimporting a session after continuing in DSH uses the live DSH context as a linear pi session. Keep the original file for its full history and host-specific metadata.
|
|
42
50
|
|
|
51
|
+
The CLI report counts archived source messages, which may exceed the number shown in DSH. Incomplete tool exchanges are kept in the Pi archive and omitted from the DSH active context.
|
|
52
|
+
|
|
43
53
|
Image references use `DSH_HOME`, which defaults to `~/.dsh`. Keep that attachment store with the logs when moving them across machines. If image import reports a missing object, point `DSH_HOME` at the corresponding store. For compressed DSH input, install the `zstd` command.
|
|
44
54
|
|
|
45
55
|
If old messages seem to disappear after a pi upgrade, confirm that the session path and branch are correct. A standard pi session shows the latest active summary and retained messages while the raw JSONL still holds the earlier entries. Files written by the v0.1 core patch need [legacy migration](native-session-codec.md). A file containing both DSH events and appended pi entries requires separate recovery of each part.
|
package/docs/publishing.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Publishing dsh-compact-pi
|
|
2
2
|
|
|
3
|
-
Use Node.js `^24.22.3 || >=26.13.1`. The package version `0.2.3-
|
|
3
|
+
Use Node.js `^24.22.3 || >=26.13.1`. The package version `0.2.3-b4` corresponds to the displayed version `0.2.3b4`. Keep the upstream DSH base version and increment the DCP build suffix for subsequent releases.
|
|
4
4
|
|
|
5
5
|
## Verify a release
|
|
6
6
|
|
|
@@ -21,13 +21,13 @@ See [testing](testing.md) for the resume and migration matrix. If the source sna
|
|
|
21
21
|
Authenticate interactively with `npm login`, then verify the intended publisher with `npm whoami`. Do not put authentication tokens in this repository.
|
|
22
22
|
|
|
23
23
|
```bash
|
|
24
|
-
npm publish ./dsh-compact-pi-0.2.3-
|
|
24
|
+
npm publish ./dsh-compact-pi-0.2.3-b4.tgz --access public --tag latest
|
|
25
25
|
```
|
|
26
26
|
|
|
27
27
|
The package's `publishConfig` defaults to the public npm registry and the `beta` tag for candidate builds. Use the tested tarball and set `--tag latest` for the public release. Verify with `npm view dsh-compact-pi dist-tags`. Users can install with `pi install npm:dsh-compact-pi@latest` or pin the exact version.
|
|
28
28
|
|
|
29
29
|
```bash
|
|
30
|
-
pi install npm:dsh-compact-pi@0.2.3-
|
|
30
|
+
pi install npm:dsh-compact-pi@0.2.3-b4
|
|
31
31
|
```
|
|
32
32
|
|
|
33
33
|
Restart pi or run `/reload`, then `/dcp-status`. Remove a previous local DCP package entry before loading the published package to avoid registering the extension twice. Run `pi list` to identify the installed source and `pi remove <source>` to remove it.
|
|
@@ -39,7 +39,7 @@ The package is listed in the [Pi package catalog](https://pi.dev/packages/dsh-co
|
|
|
39
39
|
GitHub also hosts tagged releases:
|
|
40
40
|
|
|
41
41
|
```bash
|
|
42
|
-
pi install git:github.com/HanqingTony/dsh-compact-pi@v0.2.3-
|
|
42
|
+
pi install git:github.com/HanqingTony/dsh-compact-pi@v0.2.3-b4
|
|
43
43
|
```
|
|
44
44
|
|
|
45
45
|
A Git release must include `dist/`, `vendor/` and the package manifest so installing it does not require development dependencies or an upstream checkout. Tag only the verified release commit. Keep source provenance and third-party licenses in the repository and tarball.
|
package/docs/testing.md
CHANGED
|
@@ -17,6 +17,8 @@ node --import tsx --test test/images-convert.test.ts test/differential.test.ts
|
|
|
17
17
|
|
|
18
18
|
The resume test installs the built npm tarball in a temporary directory and loads its extension in the candidate pi SDK. It exercises automatic compaction and pi's manual compaction path with a retained PNG. Both paths must save a native compaction checkpoint and image assets, continue with the summary and retained image, and preserve them when the session is reopened.
|
|
19
19
|
|
|
20
|
+
Run `node --import tsx --test test/migration.test.ts` on Windows or Linux to test explicit destination selection, read-only planning, stale plans, duplicate IDs, encoding conflicts, and opt-in recovery of Pi entries. The GitHub Actions matrix runs this test on both hosts. For desktop release checks, also open a synthetic imported session in the target app and verify its history.
|
|
21
|
+
|
|
20
22
|
The test also generates a native pi checkpoint and a separate snapshot cut at the DCP journal commit using an earlier DCP release. On the candidate pi it checks that the next provider request contains the old summary, a retained message and the new user request. It disables fresh summarization during replay so a lost checkpoint fails the test. It runs the CLI in both directions, checking for inactive branch leakage, native context edits, archive fidelity and continued work after adding a message in DSH.
|
|
21
23
|
|
|
22
24
|
The baseline bundle comes from Git commit `1f43099c0273a3edcbe5353a4aaf32884efd1fc9`. The candidate pi package is installed from npm into a temporary directory. If a shallow clone lacks the baseline, fetch the `v0.2.2-b3` tag before running the test. Other builds and the unit suite can run without that Git history.
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-compact-pi",
|
|
3
|
-
"version": "0.2.3-
|
|
4
|
-
"dcpVersion": "0.2.
|
|
3
|
+
"version": "0.2.3-b4",
|
|
4
|
+
"dcpVersion": "0.2.3b4",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "DeepSeek Harness context compaction for pi: upstream engine, policy, token meter and pruner",
|
|
7
7
|
"repository": {
|
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: dcp-migrate-to-dsh
|
|
3
|
-
description:
|
|
3
|
+
description: Guide a user through exporting a selected Pi session or importing it into a confirmed DeepSeek Harness Desktop, Web, or TUI target. Use for Pi-to-DSH session migration and portable exports.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
|
-
# Migrate a
|
|
6
|
+
# Migrate a Pi session to DSH
|
|
7
7
|
|
|
8
|
-
|
|
9
|
-
2. Find the converter. Use `dcp-session` if available, or run `node <dsh-compact-pi-package>/dist/dcp-session.mjs`. When loading this bundled skill, the package root is two directories above this skill folder. In a standard pi npm install it is also under `<pi-agent-dir>/npm/node_modules/dsh-compact-pi`. Check `--help` for `pi2dsh-import` before importing.
|
|
10
|
-
3. Verify the target DSH version and session store. This importer targets the DSH 0.2.3-alpha.2 V4 JSONL layout. Use the target DSH process's `DSH_HOME` for attachments and the target profile's JSONL session root and compression. The defaults are `$DSH_HOME/sessions` (or `~/.dsh/sessions`) and Zstandard. Use `--plain` only when the profile uses plaintext.
|
|
11
|
-
4. Import with `dcp-session pi2dsh-import "<pi-jsonl>"`. Append the configured session root when it differs from the default. Append `--plain` for plaintext. If DCP reports an existing session ID, preserve the existing session and report the conflict. If the target runs on a different machine, run the import there using a securely copied source and a target workspace path valid on that machine. For a portable export, use `dcp-session pi2dsh "<pi-jsonl>" "<new-export.jsonl>"` and keep the corresponding DSH attachment store with it.
|
|
12
|
-
5. Report the returned session ID and project path. Resume from that project using the target UI's session picker or its explicit resume option, for example `dsh-tui --resume "<session-id>"` for the DSH TUI. The import creates a separate DSH session. The current agent session stays open. Ask before sending a first prompt in the imported session.
|
|
8
|
+
Use `dcp-session migrate` or `node <package-root>/dist/dcp-session.mjs migrate`. Check `--help`. The bundled skill is two directories below the package root. When installed under a skill home, resolve its symlink or locate the DCP package from Pi's package list.
|
|
13
9
|
|
|
14
|
-
|
|
10
|
+
1. Ask the user to identify the source and the destination. Use `migrate sources --id <id>` or `migrate sources --cwd <absolute-project>` to show candidate headers when the source path is unclear. Let the user choose when more than one matches.
|
|
11
|
+
2. Confirm the target on the machine that will write it. For a portable export, ask for the export directory. For direct import, ask for Windows Desktop, Linux Desktop, Web, or TUI, the instance or profile name, DSH backend version, DSH home (images), session directory, workspace, and storage encoding. `migrate environment` supplies host information and suggestions to confirm. Run Windows Desktop imports with Windows Node.js. A WSL shell describes a separate environment.
|
|
12
|
+
3. Run `migrate plan` with the confirmed fields and a fresh `--plan-file`. Show the exact output and attachment paths, destination session ID, and any conflict. See [command examples](references/commands.md). For a duplicate, offer to stop or create a separate ID with `--on-conflict copy`. For a mixed Pi/DSH log, offer to stop, select another file, or explicitly recover just the Pi entries with `--recover-pi-entries`. Recovery leaves the original file intact. Encoding and unsupported-format errors need corrected input.
|
|
13
|
+
4. After the user approves the resulting plan, call `migrate apply --plan-file <file> --confirm <code>`. Only use the approved plan and code. If the source or destination changed, rerun the preview and confirm again. For a local interactive terminal, the user can run `dcp-session migrate` and answer the same questions directly.
|
|
14
|
+
5. Report the receipt. For Web, use `migrate verify-web` with an approved launch-URL file when available. For Desktop or TUI, verify that the selected app can open the imported history using its session picker. If app access is unavailable, report the write as complete with UI verification pending. Leave an imported session idle until the user asks to send a prompt.
|
|
15
|
+
|
|
16
|
+
The scripts handle reading, recovery, paths, conflict checks, attachments, and conversion. Keep session contents and Web credentials out of the conversation.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# Migration commands
|
|
2
|
+
|
|
3
|
+
Run from the target OS, using an absolute path to the source copy accessible there. A Windows destination uses Windows paths and Windows Node.js. Quote paths with spaces.
|
|
4
|
+
|
|
5
|
+
## Direct import
|
|
6
|
+
|
|
7
|
+
```text
|
|
8
|
+
dcp-session migrate plan --source "<pi.jsonl>" --target windows-desktop --profile desktop --dsh-version 0.2.2-rc.5 --dsh-home "<DSH home>" --session-root "<session directory>" --workspace "<existing workspace>" --encoding zstd --plan-file "<new plan.json>"
|
|
9
|
+
dcp-session migrate apply --plan-file "<plan.json>" --confirm "<code>"
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Use `linux-desktop` for a Linux desktop client on the same machine as its compatible DSH backend. Use the backend's version and storage settings. For Web or TUI use that instance or profile's settings. Distribution version and backend version can differ.
|
|
13
|
+
|
|
14
|
+
For Desktop and Web, choose a workspace already shown in the target app. Refresh the session list if the app was already open when the file was written.
|
|
15
|
+
|
|
16
|
+
## Portable export
|
|
17
|
+
|
|
18
|
+
```text
|
|
19
|
+
dcp-session migrate plan --source "<pi.jsonl>" --target portable --export-dir "<existing directory>" --plan-file "<new plan.json>"
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
After approval, use the same apply command. Move the complete output folder to keep the DSH JSONL and attachments together. Its directory is the attachment home for that copy.
|
|
23
|
+
|
|
24
|
+
## Checks
|
|
25
|
+
|
|
26
|
+
- `migrate sources` reads only headers. Use `--pi-home` when the source uses a non-default Pi agent directory.
|
|
27
|
+
- `migrate environment` shows the script's current host and paths to use as suggestions.
|
|
28
|
+
- `migrate verify-web --url-file "<launch URL file>" --session-id "<id>" --events <count>` checks the list and history. Use the receipt's event count. The private file contains one launch URL belonging to the confirmed Web instance.
|
|
29
|
+
- `written` confirms the disk write. `verified` confirms both Web reads.
|
package/src/codec.ts
CHANGED
|
@@ -79,6 +79,38 @@ export function projectPiForDsh(entries: readonly SessionEntry[]) {
|
|
|
79
79
|
return convertToLlm(system ? [system, ...conversation] : conversation)
|
|
80
80
|
.map((message, index) => ({ type: 'message', id: `projected-${index}`, message }))
|
|
81
81
|
}
|
|
82
|
+
|
|
83
|
+
/** A native DSH step can only carry tools with both an advertised call and a result. */
|
|
84
|
+
function settledTools(projected: ReturnType<typeof projectPiForDsh>) {
|
|
85
|
+
const result: typeof projected = []
|
|
86
|
+
const pending = new Set<string>()
|
|
87
|
+
for (const [index, entry] of projected.entries()) {
|
|
88
|
+
const { message } = entry
|
|
89
|
+
if (message.role === 'toolResult') {
|
|
90
|
+
if (pending.delete(message.toolCallId)) result.push(entry)
|
|
91
|
+
continue
|
|
92
|
+
}
|
|
93
|
+
pending.clear()
|
|
94
|
+
if (message.role !== 'assistant' || message.stopReason === 'error' || message.stopReason === 'aborted') {
|
|
95
|
+
result.push(entry)
|
|
96
|
+
continue
|
|
97
|
+
}
|
|
98
|
+
const followingResults = new Set<string>()
|
|
99
|
+
for (let next = index + 1; next < projected.length; next++) {
|
|
100
|
+
const following = projected[next]!.message
|
|
101
|
+
if (following.role !== 'toolResult') break
|
|
102
|
+
followingResults.add(following.toolCallId)
|
|
103
|
+
}
|
|
104
|
+
const content = message.content.filter((block) => {
|
|
105
|
+
if (block.type !== 'toolCall') return true
|
|
106
|
+
if (!block.id || !followingResults.delete(block.id)) return false
|
|
107
|
+
pending.add(block.id)
|
|
108
|
+
return true
|
|
109
|
+
})
|
|
110
|
+
if (content.length) result.push({ ...entry, message: { ...message, content } })
|
|
111
|
+
}
|
|
112
|
+
return result
|
|
113
|
+
}
|
|
82
114
|
function piHeader(header: DshHeader): PiHeader {
|
|
83
115
|
return {
|
|
84
116
|
type: 'session',
|
|
@@ -128,21 +160,22 @@ export function dshRowsFromPi(
|
|
|
128
160
|
_file?: string,
|
|
129
161
|
imageToDsh?: (image: any) => any,
|
|
130
162
|
projected = projectPiForDsh(entries),
|
|
163
|
+
destination?: Pick<DshHeader, 'id' | 'cwd'>,
|
|
131
164
|
): string {
|
|
132
165
|
const header: DshHeader = {
|
|
133
166
|
type: 'session',
|
|
134
167
|
version: SESSION_FORMAT_VERSION,
|
|
135
|
-
id: pi.id,
|
|
168
|
+
id: destination?.id ?? pi.id,
|
|
136
169
|
createdAt: Date.parse(pi.timestamp),
|
|
137
|
-
cwd: pi.cwd,
|
|
170
|
+
cwd: destination?.cwd ?? pi.cwd,
|
|
138
171
|
isSeeded: false,
|
|
139
172
|
delegationDepth: 0,
|
|
140
|
-
...(pi.parentSession ? { parentSession: pi.parentSession } : {}),
|
|
173
|
+
...(!destination && pi.parentSession ? { parentSession: pi.parentSession } : {}),
|
|
141
174
|
}
|
|
142
175
|
const session = Session.create(header.id, [], headerForSession(header))
|
|
143
176
|
appendPluginRecord(session, PI_HEADER, JSON.parse(JSON.stringify(pi)))
|
|
144
|
-
const state = createSyncState()
|
|
145
|
-
syncPiEntries(session, projected, state, { imageToDsh })
|
|
177
|
+
const state = createSyncState({ persistent: true })
|
|
178
|
+
syncPiEntries(session, settledTools(projected), state, { imageToDsh })
|
|
146
179
|
closeTurn(session, state)
|
|
147
180
|
// Preserve every entry, its original id, parent and metadata. DSH's message
|
|
148
181
|
// surface is an export view; pi resumes from the lossless archive records.
|
|
@@ -162,9 +195,10 @@ export function writeDshFromPi(
|
|
|
162
195
|
entries: readonly any[],
|
|
163
196
|
imageToDsh?: (image: any) => any,
|
|
164
197
|
projected?: ReturnType<typeof projectPiForDsh>,
|
|
198
|
+
destination?: Pick<DshHeader, 'id' | 'cwd'>,
|
|
165
199
|
): void {
|
|
166
200
|
mkdirSync(path.dirname(file), { recursive: true })
|
|
167
|
-
const body = dshRowsFromPi(header, entries, file, imageToDsh, projected)
|
|
201
|
+
const body = dshRowsFromPi(header, entries, file, imageToDsh, projected, destination)
|
|
168
202
|
const tmp = `${file}.${process.pid}.tmp`
|
|
169
203
|
writeFileSync(tmp, body)
|
|
170
204
|
renameSync(tmp, file)
|
package/src/dsh/convert.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
import { promises as fs } from 'node:fs'
|
|
4
4
|
import * as path from 'node:path'
|
|
5
5
|
import type { Session } from '../../vendor/dsh-runtime.mjs'
|
|
6
|
-
import { createSession, DSH_FORMAT_VERSION, restoreSession } from './session.ts'
|
|
6
|
+
import { createSession, DSH_FORMAT_VERSION, restoreSession, type DshHeader } from './session.ts'
|
|
7
7
|
import { createSyncState, syncPiEntries } from './sync.ts'
|
|
8
8
|
import { openImageBridge } from './images.ts'
|
|
9
9
|
import { projectSurface } from './projection.ts'
|
|
@@ -101,20 +101,26 @@ export async function piToDsh(
|
|
|
101
101
|
if (path.resolve(input) === path.resolve(output))
|
|
102
102
|
throw new Error('Choose a separate output file for session conversion')
|
|
103
103
|
const pi = await readPiSession(input)
|
|
104
|
+
return { input, output, ...await exportPiSession(pi, output) }
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export async function exportPiSession(
|
|
108
|
+
pi: PiSessionFile,
|
|
109
|
+
output: string,
|
|
110
|
+
options: { dshHome?: string; destination?: Pick<DshHeader, 'id' | 'cwd'> } = {},
|
|
111
|
+
) {
|
|
104
112
|
const projected = projectPiForDsh(pi.entries)
|
|
105
|
-
const carrier = await openImageBridge()
|
|
113
|
+
const carrier = await openImageBridge(options.dshHome)
|
|
106
114
|
try {
|
|
107
115
|
await carrier.images.prepare(
|
|
108
116
|
projected.map((entry) => entry.message),
|
|
109
117
|
)
|
|
110
|
-
writeDshFromPi(output, pi.header, pi.entries, carrier.images.toDsh, projected)
|
|
118
|
+
writeDshFromPi(output, pi.header, pi.entries, carrier.images.toDsh, projected, options.destination)
|
|
111
119
|
} finally {
|
|
112
120
|
await carrier.close()
|
|
113
121
|
}
|
|
114
122
|
const parsed = await readDshFile(output)
|
|
115
123
|
return {
|
|
116
|
-
input,
|
|
117
|
-
output,
|
|
118
124
|
messages: pi.entries.filter((entry) => entry.type === 'message').length,
|
|
119
125
|
events: parsed!.events.length,
|
|
120
126
|
}
|
package/src/dsh/import.ts
CHANGED
|
@@ -3,19 +3,52 @@ import { homedir, tmpdir } from 'node:os'
|
|
|
3
3
|
import * as path from 'node:path'
|
|
4
4
|
import { promisify } from 'node:util'
|
|
5
5
|
import { constants, zstdCompress } from 'node:zlib'
|
|
6
|
-
import {
|
|
7
|
-
import { DSH_FORMAT_VERSION
|
|
6
|
+
import { exportPiSession, readPiSession, type PiSessionFile } from './convert.ts'
|
|
7
|
+
import { DSH_FORMAT_VERSION } from './session.ts'
|
|
8
8
|
|
|
9
9
|
const compress = promisify(zstdCompress)
|
|
10
10
|
const zstdOptions = { params: { [constants.ZSTD_c_checksumFlag]: 1 } }
|
|
11
11
|
|
|
12
12
|
// Match the JSONL persistence layout at the vendored DSH revision.
|
|
13
|
-
function escapeSegment(value: string): string {
|
|
13
|
+
export function escapeSegment(value: string): string {
|
|
14
14
|
return value.replace(/[^A-Za-z0-9._-]/g, (char) =>
|
|
15
15
|
'~' + char.charCodeAt(0).toString(16).toUpperCase().padStart(4, '0'),
|
|
16
16
|
)
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
+
export class DestinationConflict extends Error {}
|
|
20
|
+
|
|
21
|
+
export async function nativeDestination(root: string, sessionId: string, cwd: string, plaintext: boolean) {
|
|
22
|
+
try {
|
|
23
|
+
if (!(await fs.stat(root)).isDirectory()) throw new Error(`DSH session root is not a directory: ${root}`)
|
|
24
|
+
} catch (error) {
|
|
25
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
|
|
26
|
+
}
|
|
27
|
+
const id = sessionId === '.' || sessionId === '..'
|
|
28
|
+
? sessionId.replaceAll('.', '~002E')
|
|
29
|
+
: escapeSegment(sessionId)
|
|
30
|
+
const project = path.join(root, projectKey(cwd))
|
|
31
|
+
const destination = path.join(project, id)
|
|
32
|
+
const output = path.join(destination, `session.v${DSH_FORMAT_VERSION}.jsonl${plaintext ? '' : '.zstd'}`)
|
|
33
|
+
let conflict: string | undefined
|
|
34
|
+
for await (const existing of fs.glob('*/*/session{,.v*}.jsonl{,.zstd}', { cwd: root })) {
|
|
35
|
+
const filename = path.basename(existing)
|
|
36
|
+
if (!/^session(?:\.v[1-9]\d*)?\.jsonl(?:\.zstd)?$/.test(filename)) continue
|
|
37
|
+
if (filename.endsWith('.zstd') === plaintext)
|
|
38
|
+
throw new Error(`DSH session root uses a different encoding: ${root}`)
|
|
39
|
+
if (path.basename(path.dirname(existing)) === id) conflict = path.join(root, existing)
|
|
40
|
+
}
|
|
41
|
+
try {
|
|
42
|
+
await fs.lstat(destination)
|
|
43
|
+
conflict ??= destination
|
|
44
|
+
} catch (error) {
|
|
45
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
|
|
46
|
+
}
|
|
47
|
+
if (conflict)
|
|
48
|
+
throw new DestinationConflict(`DSH session already exists: ${sessionId} (${conflict})`)
|
|
49
|
+
return output
|
|
50
|
+
}
|
|
51
|
+
|
|
19
52
|
function projectKey(cwd: string): string {
|
|
20
53
|
const readable = escapeSegment(cwd.replace(/[/\\:]+/g, '-')).replace(/^-+/, '')
|
|
21
54
|
return `--${(readable || 'root').slice(0, 251)}--`
|
|
@@ -25,42 +58,38 @@ export async function importPiToDsh(
|
|
|
25
58
|
input: string,
|
|
26
59
|
root = path.join(process.env.DSH_HOME || path.join(homedir(), '.dsh'), 'sessions'),
|
|
27
60
|
plaintext = false,
|
|
61
|
+
options: { pi?: PiSessionFile; sessionId?: string; cwd?: string; dshHome?: string } = {},
|
|
28
62
|
) {
|
|
29
63
|
root = path.resolve(root)
|
|
64
|
+
const pi = options.pi ?? await readPiSession(input)
|
|
65
|
+
const sessionId = options.sessionId ?? pi.header.id
|
|
66
|
+
const cwd = options.cwd ?? pi.header.cwd
|
|
67
|
+
if (!sessionId || !cwd || !path.isAbsolute(cwd))
|
|
68
|
+
throw new Error('Import requires a native pi session with an ID and an absolute local project path')
|
|
69
|
+
const output = await nativeDestination(root, sessionId, cwd, plaintext)
|
|
70
|
+
const destination = path.dirname(output)
|
|
30
71
|
const stage = await fs.mkdtemp(path.join(tmpdir(), 'dcp-import-'))
|
|
31
72
|
try {
|
|
32
73
|
const raw = path.join(stage, 'session.jsonl')
|
|
33
|
-
const report = await
|
|
74
|
+
const report = await exportPiSession(pi, raw, {
|
|
75
|
+
dshHome: options.dshHome,
|
|
76
|
+
destination: options.sessionId !== undefined || options.cwd !== undefined
|
|
77
|
+
? { id: sessionId, cwd }
|
|
78
|
+
: undefined,
|
|
79
|
+
})
|
|
34
80
|
const bytes = await fs.readFile(raw)
|
|
35
81
|
const headerEnd = bytes.indexOf(0x0a) + 1
|
|
36
|
-
const header = JSON.parse(bytes.subarray(0, headerEnd).toString('utf8')) as DshHeader
|
|
37
|
-
if (header.version !== DSH_FORMAT_VERSION || !header.id || !header.cwd || !path.isAbsolute(header.cwd))
|
|
38
|
-
throw new Error('Import requires a native pi session with an ID and an absolute local project path')
|
|
39
|
-
const id = header.id === '.' || header.id === '..'
|
|
40
|
-
? header.id.replaceAll('.', '~002E')
|
|
41
|
-
: escapeSegment(header.id)
|
|
42
|
-
for await (const existing of fs.glob('*/*/session{,.v*}.jsonl{,.zstd}', { cwd: root })) {
|
|
43
|
-
const filename = path.basename(existing)
|
|
44
|
-
if (!/^session(?:\.v[1-9]\d*)?\.jsonl(?:\.zstd)?$/.test(filename)) continue
|
|
45
|
-
if (filename.endsWith('.zstd') === plaintext)
|
|
46
|
-
throw new Error(`DSH session root uses a different encoding: ${root}`)
|
|
47
|
-
if (path.basename(path.dirname(existing)) === id)
|
|
48
|
-
throw new Error(`DSH session already exists: ${header.id} (${path.join(root, existing)})`)
|
|
49
|
-
}
|
|
50
|
-
const project = path.join(root, projectKey(header.cwd))
|
|
51
|
-
const destination = path.join(project, id)
|
|
52
|
-
const output = path.join(destination, `session.v${header.version}.jsonl${plaintext ? '' : '.zstd'}`)
|
|
53
82
|
// DSH reads the first frame independently when listing session headers.
|
|
54
83
|
const stored = plaintext ? bytes : Buffer.concat(await Promise.all([
|
|
55
84
|
compress(bytes.subarray(0, headerEnd), zstdOptions),
|
|
56
85
|
compress(bytes.subarray(headerEnd), zstdOptions),
|
|
57
86
|
]))
|
|
58
|
-
await fs.mkdir(
|
|
87
|
+
await fs.mkdir(path.dirname(destination), { recursive: true, mode: 0o700 })
|
|
59
88
|
try {
|
|
60
89
|
await fs.mkdir(destination, { mode: 0o700 })
|
|
61
90
|
} catch (error) {
|
|
62
91
|
if ((error as NodeJS.ErrnoException).code === 'EEXIST')
|
|
63
|
-
throw new
|
|
92
|
+
throw new DestinationConflict(`DSH session already exists: ${sessionId} (${destination})`)
|
|
64
93
|
throw error
|
|
65
94
|
}
|
|
66
95
|
const pending = path.join(destination, '.dcp-import.tmp')
|
|
@@ -72,7 +101,7 @@ export async function importPiToDsh(
|
|
|
72
101
|
await fs.rmdir(destination)
|
|
73
102
|
throw error
|
|
74
103
|
}
|
|
75
|
-
return { ...report, output, sessionId
|
|
104
|
+
return { ...report, input, output, sessionId, cwd }
|
|
76
105
|
} finally {
|
|
77
106
|
await fs.rm(stage, { recursive: true, force: true })
|
|
78
107
|
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { promises as fs } from 'node:fs'
|
|
2
|
+
import { createInterface } from 'node:readline/promises'
|
|
3
|
+
import { parseArgs } from 'node:util'
|
|
4
|
+
import { DestinationConflict } from './import.ts'
|
|
5
|
+
import {
|
|
6
|
+
applyMigration, dshVersions, findPiSources, migrationEnvironment, migrationTargets, MixedSession, planMigration,
|
|
7
|
+
type MigrationOptions, type MigrationPlan,
|
|
8
|
+
} from './migration.ts'
|
|
9
|
+
import { verifyWebSession } from './migration-web.ts'
|
|
10
|
+
|
|
11
|
+
const help = `Usage:
|
|
12
|
+
dcp-session migrate [<absolute-pi-session>] Interactive terminal
|
|
13
|
+
dcp-session migrate environment
|
|
14
|
+
dcp-session migrate sources [--pi-home <dir>] [--id <id>] [--cwd <dir>]
|
|
15
|
+
dcp-session migrate plan --source <file> --target <target> --plan-file <file> [options]
|
|
16
|
+
dcp-session migrate apply --plan-file <file> --confirm <code>
|
|
17
|
+
dcp-session migrate verify-web --url-file <file> --session-id <id> --events <count>
|
|
18
|
+
|
|
19
|
+
Targets: ${migrationTargets.join(', ')}
|
|
20
|
+
Portable target: --export-dir <directory>
|
|
21
|
+
Direct targets: --profile <name> --dsh-version <version> --dsh-home <directory>
|
|
22
|
+
--session-root <directory> --workspace <directory> --encoding <zstd|plain>
|
|
23
|
+
Conflict options: --on-conflict <stop|copy>, --recover-pi-entries
|
|
24
|
+
Tested DSH versions: ${dshVersions.join(', ')}
|
|
25
|
+
Plans preview the exact host and paths. Apply rechecks the source and destination before writing.`
|
|
26
|
+
|
|
27
|
+
const print = (value: unknown) => console.log(JSON.stringify(value, null, 2))
|
|
28
|
+
|
|
29
|
+
async function interactive(source?: string) {
|
|
30
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY)
|
|
31
|
+
throw new Error('Interactive mode needs a terminal. Use migrate plan and apply from an agent.')
|
|
32
|
+
const reader = createInterface({ input: process.stdin, output: process.stdout })
|
|
33
|
+
const ask = async (prompt: string) => (await reader.question(prompt + ' ')).trim()
|
|
34
|
+
try {
|
|
35
|
+
const target = await ask(`Target (${migrationTargets.join(', ')}):`) as MigrationOptions['target']
|
|
36
|
+
if (!migrationTargets.includes(target)) throw new Error('Choose a listed target')
|
|
37
|
+
const options: MigrationOptions = { source: source ?? await ask('Absolute Pi session path:'), target }
|
|
38
|
+
if (target === 'portable') options.exportDir = await ask('Absolute export directory:')
|
|
39
|
+
else {
|
|
40
|
+
options.profile = await ask('Target profile or instance name:')
|
|
41
|
+
options.dshVersion = await ask(`Target DSH backend version (${dshVersions.join(', ')}):`)
|
|
42
|
+
options.dshHome = await ask('Absolute target DSH home (attachment store):')
|
|
43
|
+
options.sessionRoot = await ask('Absolute target session directory:')
|
|
44
|
+
options.workspace = await ask('Absolute target workspace:')
|
|
45
|
+
options.encoding = await ask('Target session encoding (zstd or plain):') as MigrationOptions['encoding']
|
|
46
|
+
}
|
|
47
|
+
let plan: MigrationPlan
|
|
48
|
+
for (;;) {
|
|
49
|
+
try {
|
|
50
|
+
plan = await planMigration(options)
|
|
51
|
+
break
|
|
52
|
+
} catch (error) {
|
|
53
|
+
if (error instanceof MixedSession && !options.recoverPiEntries) {
|
|
54
|
+
console.log(error.message)
|
|
55
|
+
if (await ask('Use only the native Pi entries and preserve the source file? Type recover or press Enter to cancel.') !== 'recover') return
|
|
56
|
+
options.recoverPiEntries = true
|
|
57
|
+
} else if (error instanceof DestinationConflict && options.onConflict !== 'copy') {
|
|
58
|
+
console.log(error.message)
|
|
59
|
+
if (await ask('Keep the existing session and use a new ID? Type copy or press Enter to cancel.') !== 'copy') return
|
|
60
|
+
options.onConflict = 'copy'
|
|
61
|
+
} else throw error
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
print(plan)
|
|
65
|
+
const code = await ask('Review the destination above and type the confirmation code to write:')
|
|
66
|
+
if (!code) return
|
|
67
|
+
print(await applyMigration(plan, code))
|
|
68
|
+
} finally {
|
|
69
|
+
reader.close()
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export async function runMigration(args: string[]) {
|
|
74
|
+
const [mode, ...rest] = args
|
|
75
|
+
switch (mode) {
|
|
76
|
+
case '--help': case '-h':
|
|
77
|
+
console.log(help)
|
|
78
|
+
return
|
|
79
|
+
case 'environment':
|
|
80
|
+
if (rest.length) throw new Error('migrate environment takes no arguments')
|
|
81
|
+
print(migrationEnvironment())
|
|
82
|
+
return
|
|
83
|
+
case 'sources': {
|
|
84
|
+
const { values } = parseArgs({ args: rest, options: {
|
|
85
|
+
'pi-home': { type: 'string' }, id: { type: 'string' }, cwd: { type: 'string' },
|
|
86
|
+
} })
|
|
87
|
+
print(await findPiSources({ piHome: values['pi-home'], id: values.id, cwd: values.cwd }))
|
|
88
|
+
return
|
|
89
|
+
}
|
|
90
|
+
case 'plan': {
|
|
91
|
+
const { values: v } = parseArgs({ args: rest, options: {
|
|
92
|
+
source: { type: 'string' }, target: { type: 'string' }, 'plan-file': { type: 'string' },
|
|
93
|
+
'export-dir': { type: 'string' }, profile: { type: 'string' }, 'dsh-version': { type: 'string' },
|
|
94
|
+
'dsh-home': { type: 'string' }, 'session-root': { type: 'string' }, workspace: { type: 'string' },
|
|
95
|
+
encoding: { type: 'string' }, 'on-conflict': { type: 'string' }, 'recover-pi-entries': { type: 'boolean' },
|
|
96
|
+
} })
|
|
97
|
+
if (!v.source || !v.target || !v['plan-file']) throw new Error('Pass --source, --target and --plan-file')
|
|
98
|
+
const plan = await planMigration({
|
|
99
|
+
source: v.source, target: v.target as MigrationOptions['target'], workspace: v.workspace,
|
|
100
|
+
profile: v.profile, dshVersion: v['dsh-version'], dshHome: v['dsh-home'],
|
|
101
|
+
sessionRoot: v['session-root'], exportDir: v['export-dir'], encoding: v.encoding as MigrationOptions['encoding'],
|
|
102
|
+
onConflict: v['on-conflict'] as MigrationOptions['onConflict'], recoverPiEntries: v['recover-pi-entries'],
|
|
103
|
+
})
|
|
104
|
+
await fs.writeFile(v['plan-file'], JSON.stringify(plan, null, 2) + '\n', { mode: 0o600, flag: 'wx' })
|
|
105
|
+
print(plan)
|
|
106
|
+
return
|
|
107
|
+
}
|
|
108
|
+
case 'apply': {
|
|
109
|
+
const { values } = parseArgs({ args: rest, options: {
|
|
110
|
+
'plan-file': { type: 'string' }, confirm: { type: 'string' },
|
|
111
|
+
} })
|
|
112
|
+
if (!values['plan-file'] || !values.confirm) throw new Error('Pass --plan-file and the approved --confirm code')
|
|
113
|
+
print(await applyMigration(JSON.parse(await fs.readFile(values['plan-file'], 'utf8')), values.confirm))
|
|
114
|
+
return
|
|
115
|
+
}
|
|
116
|
+
case 'verify-web': {
|
|
117
|
+
const { values } = parseArgs({ args: rest, options: {
|
|
118
|
+
'url-file': { type: 'string' }, 'session-id': { type: 'string' }, events: { type: 'string' },
|
|
119
|
+
} })
|
|
120
|
+
if (!values['url-file'] || !values['session-id'] || !values.events)
|
|
121
|
+
throw new Error('Pass --url-file, --session-id, and --events from the migration receipt')
|
|
122
|
+
print(await verifyWebSession(values['url-file'], values['session-id'], Number(values.events)))
|
|
123
|
+
return
|
|
124
|
+
}
|
|
125
|
+
default:
|
|
126
|
+
if (rest.length || mode?.startsWith('--')) throw new Error(help)
|
|
127
|
+
await interactive(mode)
|
|
128
|
+
}
|
|
129
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import { promises as fs } from 'node:fs'
|
|
3
|
+
|
|
4
|
+
/** Check the same read endpoints used by the Web UI through its launch URL. */
|
|
5
|
+
export async function verifyWebSession(urlFile: string, sessionId: string, events: number) {
|
|
6
|
+
if (!sessionId || !Number.isSafeInteger(events) || events < 1)
|
|
7
|
+
throw new Error('Pass the sessionId and event count from the migration receipt')
|
|
8
|
+
let url: URL
|
|
9
|
+
try {
|
|
10
|
+
url = new URL((await fs.readFile(urlFile, 'utf8')).trim())
|
|
11
|
+
} catch {
|
|
12
|
+
throw new Error('The URL file must contain one DSH Web launch URL')
|
|
13
|
+
}
|
|
14
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || !url.searchParams.has('token'))
|
|
15
|
+
throw new Error('The URL file must contain one DSH Web launch URL')
|
|
16
|
+
const send = async (target: URL, options: RequestInit) => {
|
|
17
|
+
try {
|
|
18
|
+
return await fetch(target, { ...options, redirect: 'manual', signal: AbortSignal.timeout(20000) })
|
|
19
|
+
} catch {
|
|
20
|
+
throw new Error('The confirmed DSH Web instance is unreachable')
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
const auth = await send(url, {})
|
|
24
|
+
const cookie = auth.headers.get('set-cookie')?.split(';', 1)[0]
|
|
25
|
+
if (!cookie || auth.status !== 303) throw new Error(`DSH Web authentication failed (HTTP ${auth.status})`)
|
|
26
|
+
const headers = { 'content-type': 'application/json', cookie }
|
|
27
|
+
async function rpc(method: string, args: object) {
|
|
28
|
+
const response = await send(new URL(`./api/${method}`, url), {
|
|
29
|
+
method: 'POST',
|
|
30
|
+
headers,
|
|
31
|
+
body: JSON.stringify({ type: 'client-request', rpcId: randomUUID(), method, payload: { args } }),
|
|
32
|
+
})
|
|
33
|
+
const body = await response.json().catch(() => undefined)
|
|
34
|
+
if (!body?.result?.ok) throw new Error(`DSH Web ${method} failed (HTTP ${response.status}, ${body?.result?.error?.code ?? 'no result'})`)
|
|
35
|
+
return body.result.value
|
|
36
|
+
}
|
|
37
|
+
const list = await rpc('session/list', { _request: {} })
|
|
38
|
+
if (!Array.isArray(list?.items) || !list.items.some((item: { sessionId: string }) => item.sessionId === sessionId))
|
|
39
|
+
throw new Error('The imported ID is missing from the target DSH session list')
|
|
40
|
+
await rpc('session/page', {
|
|
41
|
+
request: { address: { kind: 'session', sessionId }, throughSeq: events - 1, maxMessages: 3 },
|
|
42
|
+
})
|
|
43
|
+
return { sessionId, origin: url.origin, status: 'verified', checks: ['session/list', 'session/page'] }
|
|
44
|
+
}
|