dsh-compact-pi 0.2.3-b4 → 0.2.3-b6
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 +28 -5
- package/bin/dcp-session.ts +4 -1
- package/dist/dcp-session.mjs +619 -157
- package/dist/dcp.mjs +23 -18
- package/dist/index.js +70 -15
- package/docs/compatibility.md +1 -1
- package/docs/help.md +22 -3
- package/docs/publishing.md +4 -4
- package/docs/testing.md +17 -0
- package/package.json +2 -2
- package/scripts/smoke-package.mjs +4 -0
- package/scripts/test-correction-scope.ts +187 -0
- package/scripts/test-resume.mjs +1 -1
- package/skills/dcp-import-from-dsh/SKILL.md +17 -0
- package/skills/dcp-migrate-to-dsh/SKILL.md +10 -5
- package/skills/dcp-migrate-to-dsh/references/commands.md +4 -0
- package/src/bridge.ts +2 -1
- package/src/config.ts +61 -4
- package/src/dsh/convert.ts +14 -14
- package/src/dsh/engine.ts +3 -1
- package/src/dsh/llm.ts +29 -4
- package/src/dsh/migration-cli.ts +10 -2
- package/src/dsh/migration.ts +4 -4
- package/src/dsh/pi-destination.ts +75 -0
- package/src/dsh/reverse-migration-cli.ts +71 -0
- package/src/dsh/reverse-migration.ts +244 -0
- package/src/dsh/store.ts +14 -8
- package/src/index.ts +2 -2
- package/test/cancellation.test.ts +1 -0
- package/test/config.test.ts +33 -0
- package/test/host.test.ts +56 -0
- package/test/integration.test.ts +2 -0
- package/test/migration.test.ts +73 -0
|
@@ -7,10 +7,15 @@ description: Guide a user through exporting a selected Pi session or importing i
|
|
|
7
7
|
|
|
8
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.
|
|
9
9
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
10
|
+
## Ask one question and wait for the answer
|
|
11
|
+
|
|
12
|
+
Ask in the user's language. Use the host's user-input tool when available, or ask in chat and end the turn. Offer short choices when known. Never present a configuration table, a questionnaire covering multiple decisions, or raw plan JSON to the user. Skip questions whose answers the user already provided explicitly. Detection and defaults supply suggestions. A missing or ambiguous answer stays unresolved until the user answers.
|
|
13
|
+
|
|
14
|
+
1. **Source.** Ask which Pi session to use if it is unclear. Use `migrate sources --id <id>` or `migrate sources --cwd <absolute-project>` to find candidates. Even a single match is a suggestion when the user has only named the project.
|
|
15
|
+
2. **Destination.** Ask whether to export a portable folder or import directly. For portable export, ask where to put the folder. For direct import, ask which machine and DSH instance to use. If that still leaves the profile or client ambiguous, ask which one. Confirm the destination workspace, then ask separately about each unresolved storage detail. Use [target details](references/commands.md#target-details) to identify what needs verification.
|
|
16
|
+
3. **Conflict.** Run `migrate plan` with the confirmed selection and a fresh `--plan-file`. Ask about one conflict at a time. For a duplicate, ask whether to stop or use a separate ID (`--on-conflict copy`). For a mixed log, ask whether to stop, choose another file, or recover only the Pi entries (`--recover-pi-entries`). Recovery leaves the source intact. Ask for corrected input on an encoding or format mismatch. Rerun the plan only after the user decides.
|
|
17
|
+
4. **Write approval.** Show the source session, target and exact output path in a short sentence or a few lines. Include the separate attachment location, new ID or recovery choice only when relevant. Ask a single question, such as “现在写入这个位置吗?” Wait for explicit approval of this plan. Then run `migrate apply --plan-file <file> --confirm <code>` using the saved plan and its code. If the plan becomes stale, preview it again and ask for fresh approval.
|
|
18
|
+
|
|
19
|
+
Report the receipt. For Web, use `migrate verify-web` with an approved launch-URL file when available. For Desktop or TUI, verify the imported history using the session picker. If app access is unavailable, report the write with UI verification pending. Leave the imported session idle until the user asks to send a prompt.
|
|
15
20
|
|
|
16
21
|
The scripts handle reading, recovery, paths, conflict checks, attachments, and conversion. Keep session contents and Web credentials out of the conversation.
|
|
@@ -13,6 +13,10 @@ Use `linux-desktop` for a Linux desktop client on the same machine as its compat
|
|
|
13
13
|
|
|
14
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
15
|
|
|
16
|
+
## Target details
|
|
17
|
+
|
|
18
|
+
The direct-import plan needs the target machine and client, instance or profile, backend version, DSH home for attachments, session root, workspace, and encoding. Read the selected instance's settings when available. Use `migrate environment` to identify the current host and suggest paths. Ask separately before using any unresolved value. A Windows Desktop import runs under Windows Node.js. WSL is a separate environment, even on the same machine.
|
|
19
|
+
|
|
16
20
|
## Portable export
|
|
17
21
|
|
|
18
22
|
```text
|
package/src/bridge.ts
CHANGED
|
@@ -224,6 +224,7 @@ export class DshBridge {
|
|
|
224
224
|
const bundle = await (this.bundle ??= createEngine(
|
|
225
225
|
host,
|
|
226
226
|
this.config.policy,
|
|
227
|
+
this.config.summaryPrompt,
|
|
227
228
|
).catch((error) => {
|
|
228
229
|
this.running = false
|
|
229
230
|
this.bundle = undefined
|
|
@@ -748,6 +749,6 @@ export class DshBridge {
|
|
|
748
749
|
} catch (error) {
|
|
749
750
|
policy = `policy unavailable: ${String(error)}; configure .pi/dcp.json for this model`
|
|
750
751
|
}
|
|
751
|
-
return `dcp v${packageInfo.dcpVersion} (dsh-compact-pi) | DSH ${dshInfo.version} (${dshInfo.commit.slice(0, 12)})\ncheckpoints=${this.records().length}; tokens~${this.lastTokens}\n${policy}\n${this.summaryModelStatus()}\nCompatibility: fixed model; text/tools/images; no input during compaction\nHost: real Cordis plugins, unmodified source snapshot\nPersistence: pi append-only log (current branch)`
|
|
752
|
+
return `dcp v${packageInfo.dcpVersion} (dsh-compact-pi) | DSH ${dshInfo.version} (${dshInfo.commit.slice(0, 12)})\ncheckpoints=${this.records().length}; tokens~${this.lastTokens}\n${policy}\n${this.summaryModelStatus()}\nSummary prompt: ${this.config.summaryPrompt?.mode ?? 'native'}\nCompatibility: fixed model; text/tools/images; no input during compaction\nHost: real Cordis plugins, unmodified source snapshot\nPersistence: pi append-only log (current branch)`
|
|
752
753
|
}
|
|
753
754
|
}
|
package/src/config.ts
CHANGED
|
@@ -1,12 +1,23 @@
|
|
|
1
1
|
/** Project-local settings for the DSH policy. */
|
|
2
2
|
import { randomUUID } from 'node:crypto'
|
|
3
3
|
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
|
|
4
|
+
import { homedir } from 'node:os'
|
|
4
5
|
import path from 'node:path'
|
|
5
6
|
import { resolveConfig, type Policy } from '../vendor/dsh-runtime.mjs'
|
|
6
7
|
export interface DcpConfig {
|
|
7
8
|
policy: Policy
|
|
8
9
|
audit: boolean
|
|
10
|
+
summaryPrompt?: SummaryPrompt
|
|
11
|
+
dshBackends?: Record<string, DshBackend>
|
|
9
12
|
}
|
|
13
|
+
export interface DshBackend {
|
|
14
|
+
home: string
|
|
15
|
+
sessionRoot?: string
|
|
16
|
+
}
|
|
17
|
+
export type SummaryPrompt =
|
|
18
|
+
| { mode: 'native' }
|
|
19
|
+
| { mode: 'override' | 'append'; text: string }
|
|
20
|
+
|
|
10
21
|
type SummaryModel = { provider: string; id: string }
|
|
11
22
|
|
|
12
23
|
async function readConfig(cwd: string): Promise<unknown> {
|
|
@@ -25,7 +36,7 @@ function validateConfig(value: unknown): Partial<DcpConfig> {
|
|
|
25
36
|
throw new Error('dcp.json must be an object')
|
|
26
37
|
const record = value as Record<string, unknown>
|
|
27
38
|
for (const key of Object.keys(record))
|
|
28
|
-
if (!['policy', 'audit'].includes(key))
|
|
39
|
+
if (!['policy', 'audit', 'summaryPrompt', 'dshBackends'].includes(key))
|
|
29
40
|
throw new Error(`dcp.json: unknown setting ${key}`)
|
|
30
41
|
if (record.audit !== undefined && typeof record.audit !== 'boolean')
|
|
31
42
|
throw new Error('dcp.json: audit must be boolean')
|
|
@@ -38,12 +49,58 @@ function validateConfig(value: unknown): Partial<DcpConfig> {
|
|
|
38
49
|
throw new Error('dcp.json: policy must be an object')
|
|
39
50
|
const policy = (record.policy ?? {}) as Policy
|
|
40
51
|
resolveConfig(policy)
|
|
52
|
+
if (record.summaryPrompt !== undefined) {
|
|
53
|
+
const value = record.summaryPrompt
|
|
54
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
55
|
+
throw new Error('dcp.json: summaryPrompt must be an object')
|
|
56
|
+
const prompt = value as Record<string, unknown>
|
|
57
|
+
for (const key of Object.keys(prompt))
|
|
58
|
+
if (!['mode', 'text'].includes(key))
|
|
59
|
+
throw new Error(`dcp.json: unknown summaryPrompt setting ${key}`)
|
|
60
|
+
if (prompt.mode === 'native') {
|
|
61
|
+
if (prompt.text !== undefined)
|
|
62
|
+
throw new Error('dcp.json: summaryPrompt.text is only used with override or append')
|
|
63
|
+
} else {
|
|
64
|
+
if (prompt.mode !== 'override' && prompt.mode !== 'append')
|
|
65
|
+
throw new Error('dcp.json: summaryPrompt.mode must be native, override, or append')
|
|
66
|
+
if (typeof prompt.text !== 'string' || !prompt.text.trim())
|
|
67
|
+
throw new Error('dcp.json: summaryPrompt.text must be a non-empty string')
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (record.dshBackends !== undefined) {
|
|
71
|
+
const backends = record.dshBackends
|
|
72
|
+
if (!backends || typeof backends !== 'object' || Array.isArray(backends))
|
|
73
|
+
throw new Error('dcp.json: dshBackends must be an object of named local backends')
|
|
74
|
+
for (const [name, backend] of Object.entries(backends)) {
|
|
75
|
+
if (!name.trim() || !backend || typeof backend !== 'object' || Array.isArray(backend)
|
|
76
|
+
|| Object.keys(backend).some(key => key !== 'home' && key !== 'sessionRoot')
|
|
77
|
+
|| typeof backend.home !== 'string' || !path.isAbsolute(backend.home)
|
|
78
|
+
|| (backend.sessionRoot !== undefined &&
|
|
79
|
+
(typeof backend.sessionRoot !== 'string' || !path.isAbsolute(backend.sessionRoot))))
|
|
80
|
+
throw new Error(`dcp.json: dshBackends.${name} requires an absolute local home and optional absolute sessionRoot`)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
41
83
|
return record as Partial<DcpConfig>
|
|
42
84
|
}
|
|
43
85
|
|
|
44
|
-
export async function loadConfig(cwd: string): Promise<DcpConfig> {
|
|
45
|
-
const { policy
|
|
46
|
-
|
|
86
|
+
export async function loadConfig(cwd: string, agentDir?: string): Promise<DcpConfig> {
|
|
87
|
+
const config = { policy: {}, audit: true, ...validateConfig(await readConfig(cwd)) }
|
|
88
|
+
if (agentDir && !config.summaryPrompt) {
|
|
89
|
+
const file = path.join(agentDir, 'dcp.json')
|
|
90
|
+
try {
|
|
91
|
+
const userConfig = validateConfig(JSON.parse(await readFile(file, 'utf8')))
|
|
92
|
+
if (userConfig.summaryPrompt) config.summaryPrompt = userConfig.summaryPrompt
|
|
93
|
+
} catch (error) {
|
|
94
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT')
|
|
95
|
+
throw new Error(`${file}: ${(error as Error).message}`, { cause: error })
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return config
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function loadCompactionConfig(cwd: string): Promise<DcpConfig> {
|
|
102
|
+
const agentDir = process.env.PI_CODING_AGENT_DIR || path.join(homedir(), '.pi', 'agent')
|
|
103
|
+
return loadConfig(cwd, agentDir.replace(/^~(?=[/\\]|$)/, homedir()))
|
|
47
104
|
}
|
|
48
105
|
|
|
49
106
|
export function summaryModelLabel(policy: Policy): string {
|
package/src/dsh/convert.ts
CHANGED
|
@@ -7,7 +7,7 @@ import { createSession, DSH_FORMAT_VERSION, restoreSession, type DshHeader } fro
|
|
|
7
7
|
import { createSyncState, syncPiEntries } from './sync.ts'
|
|
8
8
|
import { openImageBridge } from './images.ts'
|
|
9
9
|
import { projectSurface } from './projection.ts'
|
|
10
|
-
import { readDshFile } from './store.ts'
|
|
10
|
+
import { readDshFile, type DshFile } from './store.ts'
|
|
11
11
|
import { writeDshFromPi, archivedPi, projectPiForDsh } from '../codec.ts'
|
|
12
12
|
import type { PiMessage } from './messages.ts'
|
|
13
13
|
|
|
@@ -134,19 +134,20 @@ export async function dshToPi(
|
|
|
134
134
|
throw new Error('Choose a separate output file for session conversion')
|
|
135
135
|
const dsh = await readDshFile(input)
|
|
136
136
|
if (!dsh) throw new Error(`${input}: not a DSH session file`)
|
|
137
|
-
const
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
messages: archived.entries.filter((entry) => entry.type === 'message')
|
|
144
|
-
.length,
|
|
145
|
-
events: dsh.events.length,
|
|
146
|
-
}
|
|
137
|
+
const { header, entries } = await convertDshSession(dsh)
|
|
138
|
+
await writePiSession(output, header, entries)
|
|
139
|
+
return {
|
|
140
|
+
input, output,
|
|
141
|
+
messages: entries.filter(entry => entry.type === 'message').length,
|
|
142
|
+
events: dsh.events.length,
|
|
147
143
|
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export async function convertDshSession(dsh: DshFile, dshHome?: string): Promise<PiSessionFile> {
|
|
147
|
+
const archived = archivedPi(dsh.header, dsh.events)
|
|
148
|
+
if (archived) return archived
|
|
148
149
|
const session = restoreSession(dsh.header, dsh.events)
|
|
149
|
-
const carrier = await openImageBridge()
|
|
150
|
+
const carrier = await openImageBridge(dshHome)
|
|
150
151
|
let messages: PiMessage[]
|
|
151
152
|
try {
|
|
152
153
|
await carrier.images.hydrate(
|
|
@@ -174,8 +175,7 @@ export async function dshToPi(
|
|
|
174
175
|
)
|
|
175
176
|
parentId = id
|
|
176
177
|
}
|
|
177
|
-
|
|
178
|
-
return { input, output, messages: messages.length, events: dsh.events.length }
|
|
178
|
+
return { header, entries }
|
|
179
179
|
}
|
|
180
180
|
|
|
181
181
|
export async function dshSessionFromPiFile(input: string): Promise<Session> {
|
package/src/dsh/engine.ts
CHANGED
|
@@ -16,6 +16,7 @@ import {
|
|
|
16
16
|
type Policy,
|
|
17
17
|
} from '../../vendor/dsh-runtime.mjs'
|
|
18
18
|
import { createLlm, type PiHost } from './llm.ts'
|
|
19
|
+
import type { SummaryPrompt } from '../config.ts'
|
|
19
20
|
import { ImageBridge } from './images.ts'
|
|
20
21
|
import { homedir } from 'node:os'
|
|
21
22
|
import path from 'node:path'
|
|
@@ -38,6 +39,7 @@ export interface EngineBundle {
|
|
|
38
39
|
export async function createEngine(
|
|
39
40
|
host: PiHost,
|
|
40
41
|
config: Policy = {},
|
|
42
|
+
summaryPrompt?: SummaryPrompt,
|
|
41
43
|
): Promise<EngineBundle> {
|
|
42
44
|
const ctx = new Context()
|
|
43
45
|
try {
|
|
@@ -64,7 +66,7 @@ export async function createEngine(
|
|
|
64
66
|
await ctx.plugin({
|
|
65
67
|
name: 'pi-compaction-llm',
|
|
66
68
|
apply: (service: Context) =>
|
|
67
|
-
service.provide('llm', createLlm(host, images)),
|
|
69
|
+
service.provide('llm', createLlm(host, images, summaryPrompt)),
|
|
68
70
|
})
|
|
69
71
|
await ctx.plugin(SessionStore)
|
|
70
72
|
await ctx.plugin(SessionProjectionRegistry)
|
package/src/dsh/llm.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import { dshMessageToPi as mapMessage } from './messages.ts'
|
|
4
4
|
import { LlmError } from '../../vendor/dsh-runtime.mjs'
|
|
5
5
|
import type { ImageBridge } from './images.ts'
|
|
6
|
+
import type { SummaryPrompt } from '../config.ts'
|
|
6
7
|
|
|
7
8
|
export interface PiHost {
|
|
8
9
|
attachmentHome?(): string
|
|
@@ -38,9 +39,13 @@ function usageToDsh(usage: any): any {
|
|
|
38
39
|
* DSH `ctx.llm.stream(options)` replacement. The compaction backend calls it
|
|
39
40
|
* with the replayed prefix + instruction; we forward the conversation to pi's
|
|
40
41
|
* model registry and re-emit the answer as DSH stream chunks so the real
|
|
41
|
-
* `summarizeWithLlm` code path (
|
|
42
|
+
* `summarizeWithLlm` code path (framing, text projection) is preserved.
|
|
42
43
|
*/
|
|
43
|
-
export function createLlm(
|
|
44
|
+
export function createLlm(
|
|
45
|
+
host: PiHost,
|
|
46
|
+
images?: ImageBridge,
|
|
47
|
+
summaryPrompt?: SummaryPrompt,
|
|
48
|
+
): any {
|
|
44
49
|
return {
|
|
45
50
|
imageRequestPricing: () => undefined,
|
|
46
51
|
async *stream(options: any): AsyncGenerator<any> {
|
|
@@ -54,16 +59,36 @@ export function createLlm(host: PiHost, images?: ImageBridge): any {
|
|
|
54
59
|
throw new Error('dcp: no pi model available for summarization')
|
|
55
60
|
|
|
56
61
|
options.signal?.throwIfAborted()
|
|
62
|
+
let requestMessages = options.messages ?? []
|
|
63
|
+
if (options.purpose === 'compaction' && summaryPrompt && summaryPrompt.mode !== 'native') {
|
|
64
|
+
// Upstream appends a single text-only user directive after the replayed prefix.
|
|
65
|
+
const directive = requestMessages.at(-1)
|
|
66
|
+
if (
|
|
67
|
+
directive?.role !== 'user' ||
|
|
68
|
+
!Array.isArray(directive.content) ||
|
|
69
|
+
directive.content.length !== 1 ||
|
|
70
|
+
directive.content[0]?.type !== 'text' ||
|
|
71
|
+
typeof directive.content[0].text !== 'string'
|
|
72
|
+
)
|
|
73
|
+
throw new Error('dcp: unexpected DSH compaction directive format')
|
|
74
|
+
const text = summaryPrompt.mode === 'append'
|
|
75
|
+
? directive.content[0].text + '\n\n' + summaryPrompt.text
|
|
76
|
+
: summaryPrompt.text
|
|
77
|
+
requestMessages = [
|
|
78
|
+
...requestMessages.slice(0, -1),
|
|
79
|
+
{ ...directive, content: [{ type: 'text', text }] },
|
|
80
|
+
]
|
|
81
|
+
}
|
|
57
82
|
const imageToPi = images
|
|
58
83
|
? await images.requestMapper(
|
|
59
|
-
|
|
84
|
+
requestMessages,
|
|
60
85
|
model,
|
|
61
86
|
options.signal,
|
|
62
87
|
)
|
|
63
88
|
: undefined
|
|
64
89
|
const messages: any[] = []
|
|
65
90
|
const systemPrompts: string[] = []
|
|
66
|
-
for (const message of
|
|
91
|
+
for (const message of requestMessages) {
|
|
67
92
|
if (message.role === 'system') {
|
|
68
93
|
systemPrompts.push(textOf(message.content))
|
|
69
94
|
continue
|
package/src/dsh/migration-cli.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { promises as fs } from 'node:fs'
|
|
2
2
|
import { createInterface } from 'node:readline/promises'
|
|
3
|
+
import path from 'node:path'
|
|
3
4
|
import { parseArgs } from 'node:util'
|
|
4
5
|
import { DestinationConflict } from './import.ts'
|
|
5
6
|
import {
|
|
@@ -61,8 +62,15 @@ async function interactive(source?: string) {
|
|
|
61
62
|
} else throw error
|
|
62
63
|
}
|
|
63
64
|
}
|
|
64
|
-
|
|
65
|
-
|
|
65
|
+
console.log(`Session ${plan.sourceSessionId} → ${plan.target} on ${plan.host}`)
|
|
66
|
+
console.log(`Output: ${plan.output}`)
|
|
67
|
+
if (plan.attachmentHome !== path.dirname(plan.output))
|
|
68
|
+
console.log(`Attachments: ${plan.attachmentHome}`)
|
|
69
|
+
if (plan.sessionId !== plan.sourceSessionId)
|
|
70
|
+
console.log(`New session ID: ${plan.sessionId}`)
|
|
71
|
+
if (plan.mirrorRows)
|
|
72
|
+
console.log(`Recover Pi entries only, leaving ${plan.mirrorRows} DSH rows in the source.`)
|
|
73
|
+
const code = await ask(`Write to this location? Enter ${plan.confirmation} to confirm, or press Enter to cancel.`)
|
|
66
74
|
if (!code) return
|
|
67
75
|
print(await applyMigration(plan, code))
|
|
68
76
|
} finally {
|
package/src/dsh/migration.ts
CHANGED
|
@@ -37,18 +37,18 @@ const piEntryTypes = new Set([
|
|
|
37
37
|
'context_edit', 'compaction', 'branch_summary', 'session_info', 'label',
|
|
38
38
|
])
|
|
39
39
|
|
|
40
|
-
function absolute(value: string | undefined, label: string): string {
|
|
40
|
+
export function absolute(value: string | undefined, label: string): string {
|
|
41
41
|
if (!value || !path.isAbsolute(value)) throw new Error(`${label} must be an absolute path on this host`)
|
|
42
42
|
return path.resolve(value)
|
|
43
43
|
}
|
|
44
44
|
|
|
45
|
-
async function directory(value: string | undefined, label: string): Promise<string> {
|
|
45
|
+
export async function directory(value: string | undefined, label: string): Promise<string> {
|
|
46
46
|
const dir = absolute(value, label)
|
|
47
47
|
if (!(await fs.stat(dir)).isDirectory()) throw new Error(`${label} must be a directory: ${dir}`)
|
|
48
48
|
return fs.realpath(dir)
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
-
async function targetRoot(value: string | undefined): Promise<string> {
|
|
51
|
+
export async function targetRoot(value: string | undefined): Promise<string> {
|
|
52
52
|
const root = absolute(value, 'Target session root')
|
|
53
53
|
const remaining: string[] = []
|
|
54
54
|
for (let current = root;; current = path.dirname(current)) {
|
|
@@ -61,7 +61,7 @@ async function targetRoot(value: string | undefined): Promise<string> {
|
|
|
61
61
|
}
|
|
62
62
|
}
|
|
63
63
|
|
|
64
|
-
function digest(value: string | Buffer): string {
|
|
64
|
+
export function digest(value: string | Buffer): string {
|
|
65
65
|
return createHash('sha256').update(value).digest('hex')
|
|
66
66
|
}
|
|
67
67
|
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { promises as fs } from 'node:fs'
|
|
2
|
+
import { homedir } from 'node:os'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import { pathToFileURL } from 'node:url'
|
|
5
|
+
import { absolute, directory, targetRoot } from './migration.ts'
|
|
6
|
+
|
|
7
|
+
type PiSdk = typeof import('@earendil-works/pi-coding-agent')
|
|
8
|
+
const piPackage = '@earendil-works/pi-coding-agent'
|
|
9
|
+
|
|
10
|
+
async function installedPi(): Promise<PiSdk> {
|
|
11
|
+
// CLI installation and Pi can live in separate npm/pnpm prefixes.
|
|
12
|
+
for (const folder of (process.env.PATH ?? '').split(path.delimiter).filter(Boolean)) {
|
|
13
|
+
const command = path.resolve(folder, 'pi')
|
|
14
|
+
const entrypoints = [path.join(folder, 'node_modules', piPackage, 'dist', 'index.js')]
|
|
15
|
+
try {
|
|
16
|
+
const real = await fs.realpath(command)
|
|
17
|
+
const dist = path.dirname(real)
|
|
18
|
+
if (real.endsWith('.js')) entrypoints.push(path.join(dist, 'index.js'), path.join(dist, '..', 'index.js'))
|
|
19
|
+
else {
|
|
20
|
+
const handle = await fs.open(real, 'r')
|
|
21
|
+
try {
|
|
22
|
+
const buffer = Buffer.alloc(16384)
|
|
23
|
+
const { bytesRead } = await handle.read(buffer)
|
|
24
|
+
const target = /^# cmd-shim-target=(.+)$/m.exec(buffer.subarray(0, bytesRead).toString())?.[1]?.trim()
|
|
25
|
+
if (target && path.isAbsolute(target))
|
|
26
|
+
entrypoints.unshift(path.join(path.dirname(target), '..', 'index.js'), path.join(path.dirname(target), 'index.js'))
|
|
27
|
+
} finally {
|
|
28
|
+
await handle.close()
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
} catch (error) {
|
|
32
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
|
|
33
|
+
}
|
|
34
|
+
for (const file of entrypoints) {
|
|
35
|
+
try {
|
|
36
|
+
if (!(await fs.stat(file)).isFile()) continue
|
|
37
|
+
} catch (error) {
|
|
38
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue
|
|
39
|
+
throw error
|
|
40
|
+
}
|
|
41
|
+
const sdk = await import(pathToFileURL(file).href)
|
|
42
|
+
if (sdk.SessionManager && sdk.SettingsManager) return sdk
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
const sdk = await import(piPackage).catch(() => undefined)
|
|
46
|
+
if (sdk) return sdk
|
|
47
|
+
throw new Error('Cannot load the local Pi session manager. Run with Pi installed on this host and on PATH.')
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function resolvePiDestination(options: { workspace: string; piHome?: string; sessionDir?: string }) {
|
|
51
|
+
const workspace = await directory(options.workspace, 'Pi workspace')
|
|
52
|
+
const sdk = await installedPi()
|
|
53
|
+
const piHome = absolute(options.piHome ?? sdk.getAgentDir(), 'Pi agent home')
|
|
54
|
+
const sessionDirectory = options.sessionDir ?? (process.env.PI_CODING_AGENT_SESSION_DIR ||
|
|
55
|
+
sdk.SettingsManager.create(workspace, piHome).getSessionDir())
|
|
56
|
+
// Pi derives this project key from the absolute cwd. Its internal helper also
|
|
57
|
+
// creates the directory, so use the same key without writing during preview.
|
|
58
|
+
const key = `--${workspace.replace(/^[/\\]/, '').replace(/[/\\:]/g, '-')}--`
|
|
59
|
+
const configuredDir = sessionDirectory && !options.sessionDir
|
|
60
|
+
? path.resolve(workspace, sessionDirectory.replace(/^~(?=[/\\]|$)/, homedir()))
|
|
61
|
+
: sessionDirectory
|
|
62
|
+
const sessionDir = await targetRoot(configuredDir ?? path.join(piHome, 'sessions', key))
|
|
63
|
+
let parent = sessionDir
|
|
64
|
+
for (;;) {
|
|
65
|
+
try {
|
|
66
|
+
await fs.access(parent, fs.constants.W_OK | fs.constants.X_OK)
|
|
67
|
+
break
|
|
68
|
+
} catch (error) {
|
|
69
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || parent === path.dirname(parent)) throw error
|
|
70
|
+
parent = path.dirname(parent)
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
const launchArgs = options.sessionDir ? ['--session-dir', sessionDir] : []
|
|
74
|
+
return { workspace, piHome, sessionDir, sessionDirSource: options.sessionDir ? 'explicit' : configuredDir ? 'configured' : 'project', launchArgs, sdk }
|
|
75
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { promises as fs } from 'node:fs'
|
|
2
|
+
import { parseArgs } from 'node:util'
|
|
3
|
+
import { resolvePiDestination } from './pi-destination.ts'
|
|
4
|
+
import {
|
|
5
|
+
applyReverseMigration, listDshSessions, planReverseMigration, probeDshBackends,
|
|
6
|
+
type ReverseOptions,
|
|
7
|
+
} from './reverse-migration.ts'
|
|
8
|
+
|
|
9
|
+
const help = `Usage:
|
|
10
|
+
dcp-session import-dsh probe [--project <dir>]
|
|
11
|
+
dcp-session import-dsh sessions [--project <dir>] <backend> [--cwd <source-project>] [--limit <n>] [--offset <n>]
|
|
12
|
+
dcp-session import-dsh destination [--workspace <dir>] [--pi-home <dir>] [--session-dir <dir>]
|
|
13
|
+
dcp-session import-dsh plan [--project <dir>] <backend> --id <session-id> --workspace <dir> --plan-file <file>
|
|
14
|
+
[--pi-home <dir>] [--session-dir <dir>] [--on-conflict copy]
|
|
15
|
+
dcp-session import-dsh apply --plan-file <file> --confirm <code>
|
|
16
|
+
|
|
17
|
+
Backend: --backend <name> from probe, or --dsh-home <dir> [--session-root <dir>].
|
|
18
|
+
Use native paths on the host that runs Pi. Only apply writes a Pi session.
|
|
19
|
+
Confirm the selected workspace, session directory and exact output before apply.`
|
|
20
|
+
|
|
21
|
+
const string = { type: 'string' } as const
|
|
22
|
+
const backendOptions = { project: string, backend: string, 'dsh-home': string, 'session-root': string }
|
|
23
|
+
const destinationOptions = { workspace: string, 'pi-home': string, 'session-dir': string }
|
|
24
|
+
const print = (value: unknown) => console.log(JSON.stringify(value, null, 2))
|
|
25
|
+
|
|
26
|
+
export async function runReverseMigration([command, ...args]: string[]) {
|
|
27
|
+
if (!command || command === '--help' || command === '-h') {
|
|
28
|
+
console.log(help)
|
|
29
|
+
return
|
|
30
|
+
}
|
|
31
|
+
if (command === 'probe') {
|
|
32
|
+
const { values } = parseArgs({ args, options: { project: string } })
|
|
33
|
+
print(await probeDshBackends(values.project ?? process.cwd()))
|
|
34
|
+
} else if (command === 'sessions') {
|
|
35
|
+
const { values } = parseArgs({ args, options: {
|
|
36
|
+
...backendOptions, cwd: string, limit: string, offset: string,
|
|
37
|
+
} })
|
|
38
|
+
print(await listDshSessions({
|
|
39
|
+
project: values.project ?? process.cwd(),
|
|
40
|
+
backend: values.backend, dshHome: values['dsh-home'], sessionRoot: values['session-root'],
|
|
41
|
+
cwd: values.cwd, limit: values.limit === undefined ? undefined : Number(values.limit),
|
|
42
|
+
offset: values.offset === undefined ? undefined : Number(values.offset),
|
|
43
|
+
}))
|
|
44
|
+
} else if (command === 'destination') {
|
|
45
|
+
const { values } = parseArgs({ args, options: destinationOptions })
|
|
46
|
+
const { workspace, piHome, sessionDir, sessionDirSource } = await resolvePiDestination({
|
|
47
|
+
workspace: values.workspace ?? process.cwd(), piHome: values['pi-home'], sessionDir: values['session-dir'],
|
|
48
|
+
})
|
|
49
|
+
print({ workspace, piHome, sessionDir, sessionDirSource })
|
|
50
|
+
} else if (command === 'plan') {
|
|
51
|
+
const { values } = parseArgs({ args, options: {
|
|
52
|
+
...backendOptions, ...destinationOptions, id: string, 'plan-file': string, 'on-conflict': string,
|
|
53
|
+
} })
|
|
54
|
+
if (!values.id || !values.workspace || !values['plan-file'])
|
|
55
|
+
throw new Error('Pass the selected --id, --workspace and a fresh --plan-file')
|
|
56
|
+
const plan = await planReverseMigration({
|
|
57
|
+
project: values.project ?? process.cwd(), backend: values.backend,
|
|
58
|
+
dshHome: values['dsh-home'], sessionRoot: values['session-root'], id: values.id,
|
|
59
|
+
workspace: values.workspace, piHome: values['pi-home'], sessionDir: values['session-dir'],
|
|
60
|
+
onConflict: values['on-conflict'] as ReverseOptions['onConflict'],
|
|
61
|
+
})
|
|
62
|
+
await fs.writeFile(values['plan-file'], JSON.stringify(plan, null, 2) + '\n', { mode: 0o600, flag: 'wx' })
|
|
63
|
+
print(plan)
|
|
64
|
+
} else if (command === 'apply') {
|
|
65
|
+
const { values } = parseArgs({ args, options: { 'plan-file': string, confirm: string } })
|
|
66
|
+
if (!values['plan-file'] || !values.confirm) throw new Error('Pass --plan-file and the approved --confirm code')
|
|
67
|
+
print(await applyReverseMigration(JSON.parse(await fs.readFile(values['plan-file'], 'utf8')), values.confirm))
|
|
68
|
+
} else {
|
|
69
|
+
throw new Error(help)
|
|
70
|
+
}
|
|
71
|
+
}
|