dsh-compact-pi 0.2.3-b2 → 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 +12 -0
- package/README.md +18 -5
- package/bin/dcp-session.ts +33 -14
- package/dist/codec.mjs +45 -9
- package/dist/dcp-session.mjs +969 -436
- package/dist/index.js +12 -4
- package/docs/compatibility.md +1 -1
- package/docs/help.md +25 -4
- package/docs/publishing.md +9 -9
- package/docs/testing.md +7 -4
- package/package.json +5 -3
- package/scripts/test-resume.mjs +96 -31
- package/skills/dcp-migrate-to-dsh/SKILL.md +16 -0
- 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 +108 -0
- 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 +63 -1
- package/test/migration.test.ts +72 -0
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
|
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { promises as fs } from 'node:fs'
|
|
2
|
+
import { homedir, tmpdir } from 'node:os'
|
|
3
|
+
import * as path from 'node:path'
|
|
4
|
+
import { promisify } from 'node:util'
|
|
5
|
+
import { constants, zstdCompress } from 'node:zlib'
|
|
6
|
+
import { exportPiSession, readPiSession, type PiSessionFile } from './convert.ts'
|
|
7
|
+
import { DSH_FORMAT_VERSION } from './session.ts'
|
|
8
|
+
|
|
9
|
+
const compress = promisify(zstdCompress)
|
|
10
|
+
const zstdOptions = { params: { [constants.ZSTD_c_checksumFlag]: 1 } }
|
|
11
|
+
|
|
12
|
+
// Match the JSONL persistence layout at the vendored DSH revision.
|
|
13
|
+
export function escapeSegment(value: string): string {
|
|
14
|
+
return value.replace(/[^A-Za-z0-9._-]/g, (char) =>
|
|
15
|
+
'~' + char.charCodeAt(0).toString(16).toUpperCase().padStart(4, '0'),
|
|
16
|
+
)
|
|
17
|
+
}
|
|
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
|
+
|
|
52
|
+
function projectKey(cwd: string): string {
|
|
53
|
+
const readable = escapeSegment(cwd.replace(/[/\\:]+/g, '-')).replace(/^-+/, '')
|
|
54
|
+
return `--${(readable || 'root').slice(0, 251)}--`
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export async function importPiToDsh(
|
|
58
|
+
input: string,
|
|
59
|
+
root = path.join(process.env.DSH_HOME || path.join(homedir(), '.dsh'), 'sessions'),
|
|
60
|
+
plaintext = false,
|
|
61
|
+
options: { pi?: PiSessionFile; sessionId?: string; cwd?: string; dshHome?: string } = {},
|
|
62
|
+
) {
|
|
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)
|
|
71
|
+
const stage = await fs.mkdtemp(path.join(tmpdir(), 'dcp-import-'))
|
|
72
|
+
try {
|
|
73
|
+
const raw = path.join(stage, 'session.jsonl')
|
|
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
|
+
})
|
|
80
|
+
const bytes = await fs.readFile(raw)
|
|
81
|
+
const headerEnd = bytes.indexOf(0x0a) + 1
|
|
82
|
+
// DSH reads the first frame independently when listing session headers.
|
|
83
|
+
const stored = plaintext ? bytes : Buffer.concat(await Promise.all([
|
|
84
|
+
compress(bytes.subarray(0, headerEnd), zstdOptions),
|
|
85
|
+
compress(bytes.subarray(headerEnd), zstdOptions),
|
|
86
|
+
]))
|
|
87
|
+
await fs.mkdir(path.dirname(destination), { recursive: true, mode: 0o700 })
|
|
88
|
+
try {
|
|
89
|
+
await fs.mkdir(destination, { mode: 0o700 })
|
|
90
|
+
} catch (error) {
|
|
91
|
+
if ((error as NodeJS.ErrnoException).code === 'EEXIST')
|
|
92
|
+
throw new DestinationConflict(`DSH session already exists: ${sessionId} (${destination})`)
|
|
93
|
+
throw error
|
|
94
|
+
}
|
|
95
|
+
const pending = path.join(destination, '.dcp-import.tmp')
|
|
96
|
+
try {
|
|
97
|
+
await fs.writeFile(pending, stored, { flag: 'wx', mode: 0o600 })
|
|
98
|
+
await fs.rename(pending, output)
|
|
99
|
+
} catch (error) {
|
|
100
|
+
await fs.rm(pending, { force: true })
|
|
101
|
+
await fs.rmdir(destination)
|
|
102
|
+
throw error
|
|
103
|
+
}
|
|
104
|
+
return { ...report, input, output, sessionId, cwd }
|
|
105
|
+
} finally {
|
|
106
|
+
await fs.rm(stage, { recursive: true, force: true })
|
|
107
|
+
}
|
|
108
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
2
|
+
import { promises as fs } from 'node:fs'
|
|
3
|
+
import { homedir, hostname } from 'node:os'
|
|
4
|
+
import path from 'node:path'
|
|
5
|
+
import { exportPiSession, type PiSessionFile } from './convert.ts'
|
|
6
|
+
import { DestinationConflict, escapeSegment, importPiToDsh, nativeDestination } from './import.ts'
|
|
7
|
+
|
|
8
|
+
export const migrationTargets = ['portable', 'windows-desktop', 'linux-desktop', 'web', 'tui'] as const
|
|
9
|
+
export const dshVersions = ['0.2.2-rc.1', '0.2.2-rc.5', '0.2.3-alpha.2'] as readonly string[]
|
|
10
|
+
|
|
11
|
+
export function migrationEnvironment() {
|
|
12
|
+
const piHome = path.resolve(process.env.PI_CODING_AGENT_DIR ?? path.join(homedir(), '.pi', 'agent'))
|
|
13
|
+
const dshHome = path.resolve(process.env.DSH_HOME ?? path.join(homedir(), '.dsh'))
|
|
14
|
+
return { host: hostname(), platform: process.platform, piHome, suggestedDshHome: dshHome, suggestedSessionRoot: path.join(dshHome, 'sessions') }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
type Target = typeof migrationTargets[number]
|
|
18
|
+
type Encoding = 'zstd' | 'plain'
|
|
19
|
+
export interface MigrationOptions {
|
|
20
|
+
source: string
|
|
21
|
+
target: Target
|
|
22
|
+
workspace?: string
|
|
23
|
+
profile?: string
|
|
24
|
+
dshVersion?: string
|
|
25
|
+
dshHome?: string
|
|
26
|
+
sessionRoot?: string
|
|
27
|
+
encoding?: Encoding
|
|
28
|
+
exportDir?: string
|
|
29
|
+
recoverPiEntries?: boolean
|
|
30
|
+
onConflict?: 'stop' | 'copy'
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export class MixedSession extends Error {}
|
|
34
|
+
|
|
35
|
+
const piEntryTypes = new Set([
|
|
36
|
+
'message', 'model_change', 'thinking_level_change', 'custom', 'custom_message',
|
|
37
|
+
'context_edit', 'compaction', 'branch_summary', 'session_info', 'label',
|
|
38
|
+
])
|
|
39
|
+
|
|
40
|
+
function absolute(value: string | undefined, label: string): string {
|
|
41
|
+
if (!value || !path.isAbsolute(value)) throw new Error(`${label} must be an absolute path on this host`)
|
|
42
|
+
return path.resolve(value)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function directory(value: string | undefined, label: string): Promise<string> {
|
|
46
|
+
const dir = absolute(value, label)
|
|
47
|
+
if (!(await fs.stat(dir)).isDirectory()) throw new Error(`${label} must be a directory: ${dir}`)
|
|
48
|
+
return fs.realpath(dir)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function targetRoot(value: string | undefined): Promise<string> {
|
|
52
|
+
const root = absolute(value, 'Target session root')
|
|
53
|
+
const remaining: string[] = []
|
|
54
|
+
for (let current = root;; current = path.dirname(current)) {
|
|
55
|
+
try {
|
|
56
|
+
return path.join(await directory(current, 'Target session root'), ...remaining)
|
|
57
|
+
} catch (error) {
|
|
58
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || current === path.dirname(current)) throw error
|
|
59
|
+
remaining.unshift(path.basename(current))
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function digest(value: string | Buffer): string {
|
|
65
|
+
return createHash('sha256').update(value).digest('hex')
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export async function findPiSources({ piHome, cwd, id }: { piHome?: string; cwd?: string; id?: string }) {
|
|
69
|
+
if (!cwd && !id) throw new Error('Pass --cwd or --id to select Pi sessions')
|
|
70
|
+
const root = path.join(absolute(piHome ?? process.env.PI_CODING_AGENT_DIR ?? path.join(homedir(), '.pi', 'agent'), 'Pi agent directory'), 'sessions')
|
|
71
|
+
const matches = []
|
|
72
|
+
for await (const file of fs.glob('*/*.jsonl', { cwd: root })) {
|
|
73
|
+
const input = path.join(root, file)
|
|
74
|
+
const handle = await fs.open(input, 'r')
|
|
75
|
+
try {
|
|
76
|
+
const buffer = Buffer.alloc(65536)
|
|
77
|
+
const { bytesRead } = await handle.read(buffer)
|
|
78
|
+
const header = JSON.parse(buffer.subarray(0, bytesRead).toString('utf8').split('\n', 1)[0]!)
|
|
79
|
+
if (header.type !== 'session' || !header.id || (id && header.id !== id) || (cwd && header.cwd !== cwd)) continue
|
|
80
|
+
matches.push({ path: input, id: header.id, cwd: header.cwd, timestamp: header.timestamp ?? header.createdAt, updated: (await handle.stat()).mtimeMs })
|
|
81
|
+
} catch (error) {
|
|
82
|
+
if (!(error instanceof SyntaxError)) throw error
|
|
83
|
+
} finally {
|
|
84
|
+
await handle.close()
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return matches.sort((a, b) => b.updated - a.updated)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function loadSource(input: string, recover: boolean) {
|
|
91
|
+
const bytes = await fs.readFile(input)
|
|
92
|
+
const [header, ...entries] = bytes.toString('utf8').split('\n').filter(line => line.trim()).map(line => JSON.parse(line))
|
|
93
|
+
if (header?.type !== 'session' || typeof header.id !== 'string' || !header.id)
|
|
94
|
+
throw new Error('Source must have a session header with an ID')
|
|
95
|
+
if (entries.some(row => !row || typeof row !== 'object' || Array.isArray(row)))
|
|
96
|
+
throw new Error('Source contains an invalid session row')
|
|
97
|
+
const mirrors = entries.filter(row => 'seq' in row)
|
|
98
|
+
if (mirrors.length && !recover) throw new MixedSession(
|
|
99
|
+
`Source contains ${mirrors.length} DSH event rows. Choose a native Pi file or explicitly approve --recover-pi-entries.`,
|
|
100
|
+
)
|
|
101
|
+
const native = entries.filter(row => !('seq' in row))
|
|
102
|
+
if (!mirrors.length && header.version !== 3)
|
|
103
|
+
throw new Error('This workflow requires a Pi v3 header or a supported mixed log')
|
|
104
|
+
if (mirrors.length && (header.version !== 4 || !mirrors.every(row =>
|
|
105
|
+
Number.isSafeInteger(row.seq) && row.seq >= 0 && typeof row.type === 'string' && ('data' in row),
|
|
106
|
+
))) throw new Error('Mixed source has an unsupported header or event shapes')
|
|
107
|
+
const ids = new Set()
|
|
108
|
+
for (const row of native) {
|
|
109
|
+
// A known mixed-log writer omitted parentId on its initial model entry.
|
|
110
|
+
const legacyRoot = mirrors.length && ids.size === 0 && row.type === 'model_change' && row.parentId === undefined
|
|
111
|
+
if (!piEntryTypes.has(row.type) || typeof row.id !== 'string' || !row.id || ids.has(row.id)
|
|
112
|
+
|| (!legacyRoot && row.parentId !== null && !ids.has(row.parentId)))
|
|
113
|
+
throw new Error('Source has ambiguous Pi entries or parent links')
|
|
114
|
+
ids.add(row.id)
|
|
115
|
+
}
|
|
116
|
+
if (!native.some(row => row.type === 'message')) throw new Error('Source has no native Pi messages')
|
|
117
|
+
const timestamp = header.timestamp ?? (mirrors.length && Number.isFinite(header.createdAt) ? new Date(header.createdAt).toISOString() : undefined)
|
|
118
|
+
if (typeof timestamp !== 'string' || !Number.isFinite(Date.parse(timestamp))) throw new Error('Source has no valid creation time')
|
|
119
|
+
const pi: PiSessionFile = {
|
|
120
|
+
header: mirrors.length
|
|
121
|
+
? { type: 'session', version: 3, id: header.id, timestamp, cwd: header.cwd }
|
|
122
|
+
: header,
|
|
123
|
+
entries: native,
|
|
124
|
+
}
|
|
125
|
+
return { pi, sha256: digest(bytes), mirrorRows: mirrors.length }
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async function portableOutput(dir: string, sessionId: string) {
|
|
129
|
+
const folder = path.join(dir, 'dcp-' + escapeSegment(sessionId))
|
|
130
|
+
try {
|
|
131
|
+
await fs.lstat(folder)
|
|
132
|
+
throw new DestinationConflict(`Export directory already exists: ${folder}`)
|
|
133
|
+
} catch (error) {
|
|
134
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
|
|
135
|
+
}
|
|
136
|
+
return path.join(folder, 'session.dsh.jsonl')
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async function prepare(options: MigrationOptions, copyId?: string) {
|
|
140
|
+
const { target, dshVersion, profile, encoding } = options
|
|
141
|
+
if (!migrationTargets.includes(target)) throw new Error('Choose an explicit migration target')
|
|
142
|
+
if ((target === 'windows-desktop' && process.platform !== 'win32') ||
|
|
143
|
+
(target === 'linux-desktop' && process.platform !== 'linux'))
|
|
144
|
+
throw new Error(`Run this migration on the native host for ${target}`)
|
|
145
|
+
const source = await fs.realpath(absolute(options.source, 'Pi source'))
|
|
146
|
+
const { pi, sha256, mirrorRows } = await loadSource(source, options.recoverPiEntries === true)
|
|
147
|
+
const portable = target === 'portable'
|
|
148
|
+
if (portable && [dshVersion, profile, encoding, options.dshHome, options.sessionRoot, options.workspace].some(Boolean))
|
|
149
|
+
throw new Error('A portable export only takes --export-dir for its target')
|
|
150
|
+
if (!portable && options.exportDir) throw new Error('Use --session-root for a direct import')
|
|
151
|
+
if (!portable && (!dshVersion || !dshVersions.includes(dshVersion)))
|
|
152
|
+
throw new Error(`Confirm an exact tested DSH backend version: ${dshVersions.join(', ')}`)
|
|
153
|
+
if (!portable && (!profile?.trim() || (encoding !== 'zstd' && encoding !== 'plain')))
|
|
154
|
+
throw new Error('Confirm the target profile or instance and its encoding (zstd or plain)')
|
|
155
|
+
if (options.onConflict && options.onConflict !== 'stop' && options.onConflict !== 'copy')
|
|
156
|
+
throw new Error('Choose a conflict policy of stop or copy')
|
|
157
|
+
const cwd = portable ? pi.header.cwd : await directory(options.workspace, 'Target workspace')
|
|
158
|
+
if (typeof cwd !== 'string' || !cwd) throw new Error('Source does not name a project directory')
|
|
159
|
+
const dshHome = portable ? undefined : await directory(options.dshHome, 'Target DSH home')
|
|
160
|
+
const sessionRoot = portable ? undefined : await targetRoot(options.sessionRoot)
|
|
161
|
+
const exportDir = portable ? await directory(options.exportDir, 'Export directory') : undefined
|
|
162
|
+
const resolveOutput = (id: string) => portable
|
|
163
|
+
? portableOutput(exportDir!, id)
|
|
164
|
+
: nativeDestination(sessionRoot!, id, cwd, encoding === 'plain')
|
|
165
|
+
let sessionId = pi.header.id
|
|
166
|
+
let output
|
|
167
|
+
let conflict
|
|
168
|
+
try {
|
|
169
|
+
output = await resolveOutput(sessionId)
|
|
170
|
+
} catch (error) {
|
|
171
|
+
if (!(error instanceof DestinationConflict) || options.onConflict !== 'copy') throw error
|
|
172
|
+
conflict = error.message
|
|
173
|
+
sessionId = copyId ?? randomUUID()
|
|
174
|
+
if (!/^[0-9a-f-]{36}$/i.test(sessionId) || sessionId === pi.header.id)
|
|
175
|
+
throw new Error('Invalid new session ID in the migration plan')
|
|
176
|
+
output = await resolveOutput(sessionId)
|
|
177
|
+
}
|
|
178
|
+
const plan = {
|
|
179
|
+
host: hostname(), platform: process.platform, source, sourceSessionId: pi.header.id, sourceCwd: pi.header.cwd,
|
|
180
|
+
sha256, sourceMessages: pi.entries.filter(row => row.type === 'message').length, mirrorRows,
|
|
181
|
+
target, dshVersion, profile, encoding, dshHome, sessionRoot, exportDir,
|
|
182
|
+
sessionId, cwd, output, conflict,
|
|
183
|
+
attachmentHome: dshHome ?? path.dirname(output),
|
|
184
|
+
}
|
|
185
|
+
return { pi, plan }
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export async function planMigration(options: MigrationOptions) {
|
|
189
|
+
const { plan } = await prepare(options)
|
|
190
|
+
return { schema: 1, options, ...plan, confirmation: digest(JSON.stringify(plan)).slice(0, 12) }
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export type MigrationPlan = Awaited<ReturnType<typeof planMigration>>
|
|
194
|
+
|
|
195
|
+
export async function applyMigration(saved: MigrationPlan, confirmation: string) {
|
|
196
|
+
if (saved.schema !== 1 || !confirmation || confirmation !== saved.confirmation)
|
|
197
|
+
throw new Error('Apply requires the confirmation code from the approved plan')
|
|
198
|
+
const { plan, pi } = await prepare(saved.options, saved.sessionId)
|
|
199
|
+
if (digest(JSON.stringify(plan)).slice(0, 12) !== confirmation)
|
|
200
|
+
throw new Error('The source, target, or conflict changed. Generate and confirm a new plan.')
|
|
201
|
+
const { source, sessionId, cwd, output, dshHome, sessionRoot, encoding } = plan
|
|
202
|
+
const destination = { id: sessionId, cwd }
|
|
203
|
+
if (sessionRoot && dshHome) {
|
|
204
|
+
const report = await importPiToDsh(source, sessionRoot, encoding === 'plain', { pi, sessionId, cwd, dshHome })
|
|
205
|
+
return { ...report, target: plan.target, attachmentHome: plan.attachmentHome, status: 'written', verification: 'open-and-check-target-history' }
|
|
206
|
+
}
|
|
207
|
+
const folder = path.dirname(output)
|
|
208
|
+
await fs.mkdir(folder, { mode: 0o700 })
|
|
209
|
+
try {
|
|
210
|
+
const report = await exportPiSession(pi, output, { dshHome: folder, destination })
|
|
211
|
+
return { ...report, output, sessionId, cwd, target: plan.target, attachmentHome: folder, status: 'exported' }
|
|
212
|
+
} catch (error) {
|
|
213
|
+
await fs.rm(folder, { recursive: true, force: true })
|
|
214
|
+
throw error
|
|
215
|
+
}
|
|
216
|
+
}
|
package/src/dsh/sync.ts
CHANGED
|
@@ -10,18 +10,20 @@ export interface SyncState {
|
|
|
10
10
|
turnStarted: boolean
|
|
11
11
|
systemSeq: number | undefined
|
|
12
12
|
stepOpen: boolean
|
|
13
|
+
persistent: boolean
|
|
13
14
|
seen: Set<string>
|
|
14
15
|
toolCalls: Map<string, number>
|
|
15
16
|
appended: number
|
|
16
17
|
}
|
|
17
18
|
|
|
18
|
-
export function createSyncState(): SyncState {
|
|
19
|
+
export function createSyncState({ persistent = false }: { persistent?: boolean } = {}): SyncState {
|
|
19
20
|
return {
|
|
20
21
|
turn: 1,
|
|
21
22
|
step: 0,
|
|
22
23
|
turnStarted: false,
|
|
23
24
|
systemSeq: undefined,
|
|
24
25
|
stepOpen: false,
|
|
26
|
+
persistent,
|
|
25
27
|
seen: new Set(),
|
|
26
28
|
toolCalls: new Map(),
|
|
27
29
|
appended: 0,
|
|
@@ -58,6 +60,12 @@ function appendSystem(
|
|
|
58
60
|
): void {
|
|
59
61
|
if (state.systemSeq !== undefined) return
|
|
60
62
|
ensureTurn(session, state)
|
|
63
|
+
// Persisted V4 system messages must belong to an open step.
|
|
64
|
+
if (state.persistent && !state.stepOpen) {
|
|
65
|
+
state.step += 1
|
|
66
|
+
append(session, 'step/start', { turn: state.turn, step: state.step })
|
|
67
|
+
state.stepOpen = true
|
|
68
|
+
}
|
|
61
69
|
let content = piContentToDsh(
|
|
62
70
|
systemPrompt && systemPrompt.trim().length > 0
|
|
63
71
|
? systemPrompt
|
package/test/convert.test.ts
CHANGED
|
@@ -4,7 +4,10 @@ import assert from 'node:assert/strict'
|
|
|
4
4
|
import { promises as fs } from 'node:fs'
|
|
5
5
|
import os from 'node:os'
|
|
6
6
|
import path from 'node:path'
|
|
7
|
+
import { zstdDecompressSync } from 'node:zlib'
|
|
8
|
+
import { dshRowsFromPi, archivedPi } from '../src/codec.ts'
|
|
7
9
|
import { dshToPi, piToDsh, readPiSession } from '../src/dsh/convert.ts'
|
|
10
|
+
import { importPiToDsh } from '../src/dsh/import.ts'
|
|
8
11
|
import { readDshFile } from '../src/dsh/store.ts'
|
|
9
12
|
|
|
10
13
|
const long = (label: string) => `${label} `.repeat(200)
|
|
@@ -19,7 +22,7 @@ const piRows = [
|
|
|
19
22
|
version: 3,
|
|
20
23
|
id: 'convert-test',
|
|
21
24
|
timestamp: new Date().toISOString(),
|
|
22
|
-
cwd: '
|
|
25
|
+
cwd: path.join(dir, '项目'),
|
|
23
26
|
},
|
|
24
27
|
{
|
|
25
28
|
type: 'message',
|
|
@@ -71,6 +74,65 @@ assert.equal(back.entries.length, 2)
|
|
|
71
74
|
assert.equal(back.entries[0].message.role, 'user')
|
|
72
75
|
assert.equal(back.entries[1].message.role, 'assistant')
|
|
73
76
|
|
|
77
|
+
function sessionRows(bytes: Buffer) {
|
|
78
|
+
return bytes.toString('utf8').trimEnd().split('\n').map((line) => {
|
|
79
|
+
const { time: _time, ...row } = JSON.parse(line)
|
|
80
|
+
return row
|
|
81
|
+
})
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
for (const plain of [false, true]) {
|
|
85
|
+
const root = path.join(dir, plain ? 'plain' : 'zstd')
|
|
86
|
+
const imported = await importPiToDsh(piFile, root, plain)
|
|
87
|
+
assert.equal(imported.sessionId, piRows[0].id)
|
|
88
|
+
assert.equal(imported.cwd, piRows[0].cwd)
|
|
89
|
+
assert.match(path.basename(path.dirname(path.dirname(imported.output))), /~9879~76EE--$/)
|
|
90
|
+
const bytes = await fs.readFile(imported.output)
|
|
91
|
+
assert.deepEqual(
|
|
92
|
+
sessionRows(plain ? bytes : zstdDecompressSync(bytes)),
|
|
93
|
+
sessionRows(await fs.readFile(dshFile)),
|
|
94
|
+
)
|
|
95
|
+
await assert.rejects(importPiToDsh(piFile, root, plain), /session already exists/)
|
|
96
|
+
await assert.rejects(importPiToDsh(piFile, root, !plain), /different encoding/)
|
|
97
|
+
assert.deepEqual(await fs.readFile(imported.output), bytes)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const [header, user, assistant] = piRows
|
|
101
|
+
const system = {
|
|
102
|
+
...user, id: 'system', message: { role: 'system', content: 'Historical system prompt' },
|
|
103
|
+
}
|
|
104
|
+
const withTools = {
|
|
105
|
+
...assistant,
|
|
106
|
+
message: {
|
|
107
|
+
...assistant!.message,
|
|
108
|
+
stopReason: 'toolUse',
|
|
109
|
+
content: [
|
|
110
|
+
{ type: 'text', text: 'Still visible' },
|
|
111
|
+
{ type: 'toolCall', id: 'finished', name: 'read', arguments: {} },
|
|
112
|
+
{ type: 'toolCall', id: 'unfinished', name: 'read', arguments: {} },
|
|
113
|
+
],
|
|
114
|
+
},
|
|
115
|
+
}
|
|
116
|
+
const toolResult = {
|
|
117
|
+
...assistant, id: 'result', parentId: assistant!.id,
|
|
118
|
+
message: { role: 'toolResult', toolCallId: 'finished', toolName: 'read', content: [{ type: 'text', text: 'OK' }] },
|
|
119
|
+
}
|
|
120
|
+
const entries = [
|
|
121
|
+
system, { ...user, parentId: system.id }, withTools, toolResult,
|
|
122
|
+
{ ...toolResult, id: 'orphan', parentId: toolResult.id, message: { ...toolResult.message, toolCallId: 'missing' } },
|
|
123
|
+
]
|
|
124
|
+
const [dshHeader, ...log] = sessionRows(Buffer.from(
|
|
125
|
+
dshRowsFromPi(header as Parameters<typeof dshRowsFromPi>[0], entries),
|
|
126
|
+
))
|
|
127
|
+
const systemIndex = log.findIndex((event) => event.type === 'system/message')
|
|
128
|
+
assert.ok(systemIndex > 0)
|
|
129
|
+
assert.equal(log[systemIndex - 1].type, 'step/start')
|
|
130
|
+
for (const coordinate of ['turn', 'step'])
|
|
131
|
+
assert.equal(log[systemIndex].data[coordinate], log[systemIndex - 1].data[coordinate])
|
|
132
|
+
assert.deepEqual(log.filter((e) => e.type === 'tool/call').map((e) => e.data.callId), ['finished'])
|
|
133
|
+
assert.deepEqual(log.filter((e) => e.type === 'tool/result').map((e) => e.data.message.toolCallId), ['finished'])
|
|
134
|
+
assert.deepEqual(archivedPi(dshHeader, log)?.entries, JSON.parse(JSON.stringify(entries)))
|
|
135
|
+
|
|
74
136
|
console.log('convert ok', {
|
|
75
137
|
dshEvents: dsh!.events.length,
|
|
76
138
|
backEntries: back.entries.length,
|