@leitwerk-dev/pi-session-transfer 0.2.0 → 0.2.1

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/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { ExtensionAPI } from '@earendil-works/pi-coding-agent';
2
2
 
3
+ /** @internal */
3
4
  declare function leitwerkSessionTransfer(pi: ExtensionAPI): Promise<void>;
4
5
 
5
6
  export { leitwerkSessionTransfer as default };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/client.ts","../src/importer.ts","../src/workspace-commit.ts","../src/local-state.ts"],"sourcesContent":["import path from \"node:path\";\nimport {\n\ttype ExtensionAPI,\n\ttype ExtensionCommandContext,\n\tformatSize,\n\tgetAgentDir,\n} from \"@earendil-works/pi-coding-agent\";\nimport { CancellableLoader } from \"@earendil-works/pi-tui\";\nimport { type ParsedTransferLink, parseTransferLink } from \"@leitwerk-dev/session-transfer\";\nimport { SessionTransferClient } from \"./client.js\";\nimport { type ImportProgress, type ImportResult, importTransfer } from \"./importer.js\";\nimport { LocalTransferState } from \"./local-state.js\";\n\nfunction phaseLabel(phase: string): string {\n\treturn (\n\t\t{\n\t\t\tqueued: \"Queued\",\n\t\t\twaiting_for_execution_chain: \"Waiting for accepted work\",\n\t\t\tstopping_worker: \"Stopping the idle worker\",\n\t\t\tstarting_exporter: \"Starting the read-only exporter\",\n\t\t\tscanning: \"Checking portable files\",\n\t\t\tready_to_stream: \"Ready to stream\",\n\t\t\tstreaming: \"Copying workspace and session\",\n\t\t\tvalidating_local: \"Validating local import\",\n\t\t\tfinishing_import: \"Finishing import…\",\n\t\t}[phase] ?? phase.replaceAll(\"_\", \" \")\n\t);\n}\n\nfunction percentage(progress: ImportProgress): number | null {\n\tif (progress.logicalBytesTotal && progress.logicalBytesTotal > 0) {\n\t\treturn Math.min(\n\t\t\t100,\n\t\t\tMath.floor((progress.logicalBytesProcessed / progress.logicalBytesTotal) * 100),\n\t\t);\n\t}\n\tif (progress.entriesTotal && progress.entriesTotal > 0) {\n\t\treturn Math.min(100, Math.floor((progress.entriesProcessed / progress.entriesTotal) * 100));\n\t}\n\treturn null;\n}\n\nfunction progressMessage(progress: ImportProgress): string {\n\tconst percent = percentage(progress);\n\tconst files = `${progress.entriesProcessed}${progress.entriesTotal === null ? \"\" : ` / ${progress.entriesTotal}`} files`;\n\tconst logical = `${formatSize(progress.logicalBytesProcessed)}${progress.logicalBytesTotal === null ? \"\" : ` / ${formatSize(progress.logicalBytesTotal)}`} expanded`;\n\tconst received = `${formatSize(progress.compressedBytes)} received`;\n\treturn `${phaseLabel(progress.phase)} · ${percent === null ? \"\" : `${percent}% · `}${files} · ${logical} · ${received}`;\n}\n\nasync function switchImportedSession(\n\tctx: ExtensionCommandContext,\n\tlink: ParsedTransferLink,\n\timported: Pick<ImportResult, \"sessionPath\" | \"attemptId\">,\n): Promise<void> {\n\tconst retryAcknowledgement = (activeCtx: ExtensionCommandContext): void => {\n\t\tvoid new SessionTransferClient(link)\n\t\t\t.acknowledge(imported.attemptId, AbortSignal.timeout(30_000))\n\t\t\t.catch(() => {\n\t\t\t\ttry {\n\t\t\t\t\tactiveCtx.ui.notify(\n\t\t\t\t\t\t\"The local import is complete. Leitwerk acknowledgement is still pending; use the same link to retry it.\",\n\t\t\t\t\t\t\"warning\",\n\t\t\t\t\t);\n\t\t\t\t} catch {\n\t\t\t\t\t// Pi may have replaced this context while acknowledgement was pending.\n\t\t\t\t}\n\t\t\t});\n\t};\n\tconst switched = await ctx.switchSession(imported.sessionPath, {\n\t\twithSession: async (replacementCtx) => {\n\t\t\treplacementCtx.ui.notify(\n\t\t\t\t\"Leitwerk process imported. Local Pi tools and resources are active.\",\n\t\t\t\t\"info\",\n\t\t\t);\n\t\t\tretryAcknowledgement(replacementCtx);\n\t\t},\n\t});\n\tif (switched.cancelled) {\n\t\tctx.ui.notify(\n\t\t\t`Import complete. Session switch was cancelled; open it with /resume: ${imported.sessionPath}`,\n\t\t\t\"info\",\n\t\t);\n\t\tretryAcknowledgement(ctx);\n\t}\n}\n\nexport default async function leitwerkSessionTransfer(pi: ExtensionAPI) {\n\tconst state = new LocalTransferState(getAgentDir());\n\tawait state.reconcile();\n\n\tpi.registerCommand(\"leitwerk-transfer\", {\n\t\tdescription: \"Import a Leitwerk process workspace and Pi session\",\n\t\thandler: async (args, ctx) => {\n\t\t\tif (ctx.mode !== \"tui\") {\n\t\t\t\tctx.ui.notify(\"/leitwerk-transfer is available only in interactive TUI mode\", \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst rawLink =\n\t\t\t\targs.trim() ||\n\t\t\t\t(await ctx.ui.input(\n\t\t\t\t\t\"Leitwerk transfer link\",\n\t\t\t\t\t\"https://leitwerk.example/api/session-transfers/…#token=…\",\n\t\t\t\t));\n\t\t\tif (!rawLink) return;\n\t\t\tlet link: ParsedTransferLink;\n\t\t\ttry {\n\t\t\t\tlink = parseTransferLink(rawLink);\n\t\t\t} catch (error) {\n\t\t\t\tctx.ui.notify(error instanceof Error ? error.message : \"Invalid transfer link\", \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst originWarning = `${link.origin} will receive the bearer credential and stream files into this Pi process. Continue only if you recognize it.`;\n\t\t\tconst receipt = await state.receipt(link);\n\t\t\tif (receipt) {\n\t\t\t\tif (\n\t\t\t\t\t!(await ctx.ui.confirm(\n\t\t\t\t\t\t\"Import already complete\",\n\t\t\t\t\t\t`Use the imported session at ${receipt.sessionPath}? ${originWarning}`,\n\t\t\t\t\t))\n\t\t\t\t) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tawait switchImportedSession(ctx, link, receipt);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst defaultDestination = path.join(ctx.cwd, link.instanceId);\n\t\t\tconst selectedDestination = await ctx.ui.input(\n\t\t\t\t\"New destination directory\",\n\t\t\t\tdefaultDestination,\n\t\t\t);\n\t\t\tif (!selectedDestination) return;\n\t\t\tconst destination = path.resolve(ctx.cwd, selectedDestination);\n\t\t\tawait ctx.waitForIdle();\n\t\t\tif (\n\t\t\t\t!(await ctx.ui.confirm(\n\t\t\t\t\t\"Import Leitwerk process?\",\n\t\t\t\t\t`Create ${destination}, copy the retained workspace, and import its Pi conversation? ${originWarning}`,\n\t\t\t\t))\n\t\t\t)\n\t\t\t\treturn;\n\n\t\t\tlet finishing = false;\n\t\t\tconst outcome = await ctx.ui.custom<ImportResult | Error | null>(\n\t\t\t\t(tui, theme, _keybindings, done) => {\n\t\t\t\t\tconst loader = new CancellableLoader(\n\t\t\t\t\t\ttui,\n\t\t\t\t\t\t(s) => theme.fg(\"accent\", s),\n\t\t\t\t\t\t(s) => theme.fg(\"muted\", s),\n\t\t\t\t\t\t\"Starting transfer…\",\n\t\t\t\t\t);\n\t\t\t\t\tloader.onAbort = () => {\n\t\t\t\t\t\tif (!finishing) loader.setMessage(\"Cancelling transfer…\");\n\t\t\t\t\t};\n\t\t\t\t\tvoid importTransfer({\n\t\t\t\t\t\tlink,\n\t\t\t\t\t\tdestination,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\tsignal: loader.signal,\n\t\t\t\t\t\tonProgress(progress) {\n\t\t\t\t\t\t\tfinishing = progress.finishing;\n\t\t\t\t\t\t\tloader.setMessage(progressMessage(progress));\n\t\t\t\t\t\t},\n\t\t\t\t\t}).then(\n\t\t\t\t\t\t(result) => done(result),\n\t\t\t\t\t\t(error: unknown) =>\n\t\t\t\t\t\t\tdone(\n\t\t\t\t\t\t\t\tloader.aborted && !finishing\n\t\t\t\t\t\t\t\t\t? null\n\t\t\t\t\t\t\t\t\t: error instanceof Error\n\t\t\t\t\t\t\t\t\t\t? error\n\t\t\t\t\t\t\t\t\t\t: new Error(\"Transfer failed\"),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn loader;\n\t\t\t\t},\n\t\t\t);\n\n\t\t\tif (!outcome) {\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\"Transfer cancelled. The link can be retried while it remains valid.\",\n\t\t\t\t\t\"info\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (outcome instanceof Error) {\n\t\t\t\tctx.ui.notify(outcome.message, \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait switchImportedSession(ctx, link, outcome);\n\t\t},\n\t});\n}\n","import { Readable } from \"node:stream\";\nimport type {\n\tParsedTransferLink,\n\tSessionTransferAttemptWire,\n} from \"@leitwerk-dev/session-transfer\";\n\nexport type RemoteTransferAttempt = SessionTransferAttemptWire;\n\nasync function responseError(response: Response): Promise<Error> {\n\tlet message = `Transfer request failed with HTTP ${response.status}`;\n\ttry {\n\t\tconst body = (await response.json()) as { error?: unknown; code?: unknown };\n\t\tif (typeof body.error === \"string\") message = body.error;\n\t\tif (typeof body.code === \"string\") message = `${message} (${body.code})`;\n\t} catch {\n\t\t// Keep the generic status without exposing response bodies that may contain credentials.\n\t}\n\treturn new Error(message);\n}\n\nexport class SessionTransferClient {\n\tconstructor(private readonly link: ParsedTransferLink) {}\n\n\tprivate attemptPath(attemptId: string, suffix = \"\"): string {\n\t\treturn `/attempts/${encodeURIComponent(attemptId)}${suffix}`;\n\t}\n\n\tprivate async request(suffix: string, init: RequestInit = {}): Promise<Response> {\n\t\tconst response = await fetch(`${this.link.grantUrl}${suffix}`, {\n\t\t\t...init,\n\t\t\tredirect: \"manual\",\n\t\t\theaders: { ...init.headers, Authorization: `Bearer ${this.link.token}` },\n\t\t});\n\t\tif (response.status >= 300 && response.status < 400)\n\t\t\tthrow new Error(\"Transfer endpoint returned a redirect\");\n\t\treturn response;\n\t}\n\n\tprivate async requestOk(\n\t\turl: string,\n\t\tinit: RequestInit = {},\n\t\tacceptedStatus?: number,\n\t): Promise<Response> {\n\t\tconst response = await this.request(url, init);\n\t\tif (!response.ok && response.status !== acceptedStatus) throw await responseError(response);\n\t\treturn response;\n\t}\n\n\tprivate async requestAttempt(url: string, init: RequestInit = {}) {\n\t\tconst response = await this.requestOk(url, init);\n\t\treturn ((await response.json()) as { attempt: RemoteTransferAttempt }).attempt;\n\t}\n\n\tasync start(signal?: AbortSignal): Promise<RemoteTransferAttempt> {\n\t\treturn this.requestAttempt(\"/attempts\", { method: \"POST\", signal });\n\t}\n\n\tasync status(attemptId: string, signal?: AbortSignal): Promise<RemoteTransferAttempt> {\n\t\treturn this.requestAttempt(this.attemptPath(attemptId), { signal });\n\t}\n\n\tasync stream(attemptId: string, signal?: AbortSignal): Promise<Readable> {\n\t\tconst response = await this.requestOk(this.attemptPath(attemptId, \"/stream\"), { signal });\n\t\tif (!response.body) throw new Error(\"Transfer endpoint returned no stream\");\n\t\treturn Readable.fromWeb(response.body as import(\"node:stream/web\").ReadableStream);\n\t}\n\n\tasync cancel(attemptId: string): Promise<void> {\n\t\tawait this.requestOk(\n\t\t\tthis.attemptPath(attemptId),\n\t\t\t{ method: \"DELETE\", signal: AbortSignal.timeout(10_000) },\n\t\t\t404,\n\t\t);\n\t}\n\n\tasync acknowledge(attemptId: string, signal?: AbortSignal): Promise<void> {\n\t\tawait this.requestOk(this.attemptPath(attemptId, \"/acknowledge\"), {\n\t\t\tmethod: \"POST\",\n\t\t\tsignal,\n\t\t});\n\t}\n}\n","import { randomUUID } from \"node:crypto\";\nimport { access, lstat, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport { SessionManager } from \"@earendil-works/pi-coding-agent\";\nimport {\n\textractTransferArchive,\n\tisPathInside,\n\ttype ParsedTransferLink,\n\treadProjectEvidence,\n\trewritePiSession,\n\ttype TransferArchiveProgress,\n} from \"@leitwerk-dev/session-transfer\";\nimport { type RemoteTransferAttempt, SessionTransferClient } from \"./client.js\";\nimport type { LocalTransferState } from \"./local-state.js\";\nimport {\n\tpopulateWorkspaceDestination,\n\treserveWorkspaceDestination,\n\trestoreWorkspaceMetadata,\n} from \"./workspace-commit.js\";\n\nexport interface ImportProgress extends TransferArchiveProgress {\n\tphase: string;\n\tcompressedBytes: number;\n\tentriesTotal: number | null;\n\tlogicalBytesTotal: number | null;\n\tfinishing: boolean;\n}\n\nexport interface ImportResult {\n\tdestination: string;\n\tsessionPath: string;\n\tattemptId: string;\n}\n\nasync function assertDestinationAbsent(destination: string): Promise<void> {\n\ttry {\n\t\tawait lstat(destination);\n\t\tthrow new Error(`Destination already exists: ${destination}`);\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n\t}\n}\n\nfunction resolveImportedCwd(root: string, relative: string | null): string {\n\treturn relative === null || relative === \".\" ? root : path.resolve(root, ...relative.split(\"/\"));\n}\n\nasync function validateProjects(\n\tworkspaceRoot: string,\n\tprojects: Parameters<typeof readProjectEvidence>[1],\n\tsignal: AbortSignal,\n): Promise<void> {\n\tconst actual = await readProjectEvidence(workspaceRoot, projects, signal);\n\tfor (let index = 0; index < projects.length; index += 1) {\n\t\tconst expected = projects[index];\n\t\tconst candidate = actual[index];\n\t\tif (!expected || !candidate) throw new Error(\"Project evidence is incomplete\");\n\t\tif (expected.head && candidate.head !== expected.head) {\n\t\t\tthrow new Error(`Project '${expected.key}' HEAD does not match the transfer manifest`);\n\t\t}\n\t\tif (candidate.branch !== expected.branch) {\n\t\t\tthrow new Error(\n\t\t\t\t`Project '${expected.key}' branch state does not match the transfer manifest`,\n\t\t\t);\n\t\t}\n\t}\n}\n\nexport async function importTransfer(input: {\n\tlink: ParsedTransferLink;\n\tdestination: string;\n\tstate: LocalTransferState;\n\tsignal: AbortSignal;\n\tonProgress(progress: ImportProgress): void;\n}): Promise<ImportResult> {\n\tconst destination = path.resolve(input.destination);\n\tawait assertDestinationAbsent(destination);\n\tconst client = new SessionTransferClient(input.link);\n\tlet attempt: RemoteTransferAttempt | null = null;\n\tlet temporaryDirectory: string | null = null;\n\tlet recoveryRecordCreated = false;\n\tlet destinationReserved = false;\n\tlet heartbeat: NodeJS.Timeout | null = null;\n\tconst progress: ImportProgress = {\n\t\tphase: \"queued\",\n\t\tcompressedBytes: 0,\n\t\tentriesProcessed: 0,\n\t\tlogicalBytesProcessed: 0,\n\t\tentriesTotal: null,\n\t\tlogicalBytesTotal: null,\n\t\tfinishing: false,\n\t};\n\tconst report = (patch: Partial<ImportProgress>): void => {\n\t\tObject.assign(progress, patch);\n\t\tinput.onProgress({ ...progress });\n\t};\n\ttry {\n\t\tattempt = await client.start(input.signal);\n\t\theartbeat = setInterval(() => {\n\t\t\tif (attempt) void client.status(attempt.id).catch(() => undefined);\n\t\t}, 30_000);\n\t\twhile (attempt.phase !== \"ready_to_stream\") {\n\t\t\tif ([\"cancelled\", \"failed\", \"consumed\"].includes(attempt.state)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\tattempt.failureCode\n\t\t\t\t\t\t? `Transfer ended: ${attempt.failureCode}`\n\t\t\t\t\t\t: `Transfer ended in state ${attempt.state}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treport({\n\t\t\t\tphase: attempt.phase,\n\t\t\t\tentriesTotal: attempt.entriesTotal,\n\t\t\t\tlogicalBytesTotal: attempt.logicalBytesTotal,\n\t\t\t});\n\t\t\tawait delay(1_000, undefined, { signal: input.signal });\n\t\t\tattempt = await client.status(attempt.id, input.signal);\n\t\t}\n\t\tconst ownerId = randomUUID();\n\t\tconst destinationMarkerName = input.state.markerName(ownerId);\n\t\ttemporaryDirectory = path.join(\n\t\t\tpath.dirname(destination),\n\t\t\t`.leitwerk-transfer-${input.link.instanceId}-${randomUUID()}`,\n\t\t);\n\t\tawait input.state.begin(input.link, {\n\t\t\tattemptId: attempt.id,\n\t\t\ttemporaryDirectory,\n\t\t\townerId,\n\t\t});\n\t\trecoveryRecordCreated = true;\n\t\treport({\n\t\t\tphase: \"streaming\",\n\t\t\tentriesTotal: attempt.entriesTotal,\n\t\t\tlogicalBytesTotal: attempt.logicalBytesTotal,\n\t\t});\n\t\tconst compressed = await client.stream(attempt.id, input.signal);\n\t\tconst extracted = await extractTransferArchive({\n\t\t\tcompressed,\n\t\t\toutputRoot: temporaryDirectory,\n\t\t\tsignal: input.signal,\n\t\t\townershipMarker: { name: input.state.markerName(), value: ownerId },\n\t\t\tonProgress: (archiveProgress) =>\n\t\t\t\treport({\n\t\t\t\t\tphase: \"streaming\",\n\t\t\t\t\t...archiveProgress,\n\t\t\t\t}),\n\t\t});\n\t\tif (extracted.manifest.instanceId !== input.link.instanceId)\n\t\t\tthrow new Error(\"Transfer manifest process id does not match the link\");\n\t\tattempt = await client.status(attempt.id, input.signal);\n\t\tif (\n\t\t\tattempt.state !== \"awaiting_ack\" ||\n\t\t\tattempt.compressedBytes !== extracted.compressedBytes ||\n\t\t\tattempt.streamSha256 !== extracted.streamSha256\n\t\t) {\n\t\t\tthrow new Error(\"Transfer stream digest or byte count does not match the server record\");\n\t\t}\n\t\treport({ phase: \"validating_local\" });\n\t\tconst temporaryWorkspace = path.join(temporaryDirectory, \"workspace\");\n\t\tawait validateProjects(temporaryWorkspace, extracted.manifest.projects, input.signal);\n\t\tconst relativeCwd = extracted.manifest.session.cwdRelativeToWorkspace;\n\t\tconst localCwd = resolveImportedCwd(destination, relativeCwd);\n\t\tif (!isPathInside(destination, localCwd))\n\t\t\tthrow new Error(\"Imported session cwd escapes the destination\");\n\t\tconst temporaryCwd = resolveImportedCwd(temporaryWorkspace, relativeCwd);\n\t\tif (!isPathInside(temporaryWorkspace, temporaryCwd))\n\t\t\tthrow new Error(\"Imported session cwd escapes the workspace\");\n\t\tawait access(temporaryCwd);\n\t\tconst rewritten = rewritePiSession(\n\t\t\tawait readFile(path.join(temporaryDirectory, \"session.jsonl\"), {\n\t\t\t\tencoding: \"utf8\",\n\t\t\t\tsignal: input.signal,\n\t\t\t}),\n\t\t\tlocalCwd,\n\t\t\textracted.manifest.session.sourceCwd,\n\t\t);\n\n\t\tinput.signal.throwIfAborted();\n\t\treport({ finishing: true, phase: \"finishing_import\" });\n\t\tconst createdSessionPath = SessionManager.create(localCwd).getSessionFile();\n\t\tif (!createdSessionPath) throw new Error(\"Pi did not create a persistent target session\");\n\t\tconst sessionPath = createdSessionPath;\n\t\tawait input.state.recordCommitTargets(input.link, { destination, sessionPath });\n\t\tawait reserveWorkspaceDestination(destination, { name: destinationMarkerName, ownerId });\n\t\tdestinationReserved = true;\n\t\tconst workspaceMetadata = await populateWorkspaceDestination(temporaryWorkspace, destination);\n\t\tconst temporarySession = `${sessionPath}.${randomUUID()}.importing`;\n\t\tawait writeFile(temporarySession, rewritten.content, { mode: 0o600, flag: \"wx\" });\n\t\tawait rename(temporarySession, sessionPath);\n\t\tawait input.state.complete(input.link, {\n\t\t\tdestination,\n\t\t\tsessionPath,\n\t\t\tcompletedAt: new Date().toISOString(),\n\t\t});\n\t\tawait rm(path.join(destination, destinationMarkerName), { force: true });\n\t\tawait restoreWorkspaceMetadata(destination, workspaceMetadata);\n\t\tawait rm(temporaryDirectory, { recursive: true, force: true });\n\t\treturn { destination, sessionPath, attemptId: attempt.id };\n\t} catch (error) {\n\t\tif (attempt && !progress.finishing) await client.cancel(attempt.id).catch(() => undefined);\n\t\tif (recoveryRecordCreated && !destinationReserved) {\n\t\t\tawait input.state.discard(input.link).catch(() => undefined);\n\t\t}\n\t\tthrow error;\n\t} finally {\n\t\tif (heartbeat) clearInterval(heartbeat);\n\t}\n}\n","import { chmod, lstat, mkdir, readdir, rename, rmdir, utimes, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nexport async function reserveWorkspaceDestination(\n\tdestination: string,\n\tmarker: { name: string; ownerId: string },\n): Promise<void> {\n\t// mkdir is the exclusive claim: never replace even an empty existing directory.\n\tawait mkdir(destination, { recursive: false, mode: 0o700 });\n\ttry {\n\t\tawait writeFile(path.join(destination, marker.name), `${marker.ownerId}\\n`, {\n\t\t\tmode: 0o600,\n\t\t\tflag: \"wx\",\n\t\t});\n\t} catch (error) {\n\t\t// An unsuccessful marker write must not recursively remove any intervening data.\n\t\tawait rmdir(destination).catch(() => undefined);\n\t\tthrow error;\n\t}\n}\n\nexport async function populateWorkspaceDestination(source: string, destination: string) {\n\tconst metadata = await lstat(source);\n\t// Staging stays writable for moves and recovery; restore the imported mode last.\n\tawait chmod(source, (metadata.mode & 0o7777) | 0o700);\n\tfor (const name of await readdir(source)) {\n\t\tawait rename(path.join(source, name), path.join(destination, name));\n\t}\n\treturn metadata;\n}\n\nexport async function restoreWorkspaceMetadata(\n\tdestination: string,\n\tmetadata: { mode: number; atime: Date; mtime: Date },\n): Promise<void> {\n\tawait chmod(destination, metadata.mode & 0o7777);\n\tawait utimes(destination, metadata.atime, metadata.mtime);\n}\n","import { createHash, randomUUID } from \"node:crypto\";\nimport {\n\tchmod,\n\tlink as linkFile,\n\tlstat,\n\tmkdir,\n\treaddir,\n\treadFile,\n\trename,\n\trm,\n\trmdir,\n\twriteFile,\n} from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { isPathInside, type ParsedTransferLink } from \"@leitwerk-dev/session-transfer\";\n\nconst OWNER_MARKER = \".leitwerk-transfer-owner\";\nconst STALE_IMPORT_MS = 2 * 60 * 60 * 1000;\n\nexport interface TransferReceipt {\n\tversion: 1;\n\torigin: string;\n\tgrantId: string;\n\ttokenHash: string;\n\tattemptId: string;\n\tdestination: string;\n\tsessionPath: string;\n\tcompletedAt: string;\n}\n\ninterface TransferStateRecord {\n\tversion: 1;\n\tphase: \"temporary\" | \"committing\" | \"completed\";\n\torigin: string;\n\tgrantId: string;\n\ttokenHash: string;\n\tattemptId: string;\n\tcreatedAt: string;\n\ttemporaryDirectory: string;\n\townerId: string;\n\tdestination?: string;\n\tsessionPath?: string;\n\tcompletedAt?: string;\n}\n\nasync function readJson<T>(file: string, fallback: T): Promise<T> {\n\ttry {\n\t\treturn JSON.parse(await readFile(file, \"utf8\")) as T;\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return fallback;\n\t\tthrow error;\n\t}\n}\n\nasync function atomicJson(file: string, value: unknown, exclusive = false): Promise<void> {\n\tawait mkdir(path.dirname(file), { recursive: true, mode: 0o700 });\n\tconst temporary = `${file}.${randomUUID()}.tmp`;\n\ttry {\n\t\tawait writeFile(temporary, `${JSON.stringify(value, null, 2)}\\n`, { mode: 0o600, flag: \"wx\" });\n\t\tif (exclusive) await linkFile(temporary, file);\n\t\telse await rename(temporary, file);\n\t\tawait chmod(file, 0o600);\n\t} finally {\n\t\tawait rm(temporary, { force: true });\n\t}\n}\n\nasync function ownsDirectory(directory: string, ownerId: string, marker: string): Promise<boolean> {\n\ttry {\n\t\treturn (\n\t\t\t(await lstat(directory)).isDirectory() &&\n\t\t\t(await readFile(path.join(directory, marker), \"utf8\")).trim() === ownerId\n\t\t);\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return false;\n\t\tthrow error;\n\t}\n}\n\nasync function removeOwnedDirectory(\n\tdirectory: string,\n\townerId: string,\n\tmarker: string,\n): Promise<void> {\n\tif (!(await ownsDirectory(directory, ownerId, marker))) return;\n\t// Keep the ownership proof until all imported children have been removed.\n\tfor (const name of await readdir(directory)) {\n\t\tif (name !== marker) await rm(path.join(directory, name), { recursive: true, force: true });\n\t}\n\tawait rm(path.join(directory, marker));\n\tawait rmdir(directory);\n}\n\nfunction tokenHash(token: string): string {\n\treturn createHash(\"sha256\").update(token, \"utf8\").digest(\"hex\");\n}\n\nfunction stateKey(link: ParsedTransferLink): string {\n\treturn createHash(\"sha256\")\n\t\t.update(`${link.origin}\\0${link.grantId}\\0${tokenHash(link.token)}`)\n\t\t.digest(\"hex\");\n}\n\nfunction completedReceipt(record: TransferStateRecord): TransferReceipt | null {\n\tif (\n\t\trecord.phase !== \"completed\" ||\n\t\t!record.destination ||\n\t\t!record.sessionPath ||\n\t\t!record.completedAt\n\t) {\n\t\treturn null;\n\t}\n\treturn {\n\t\tversion: 1,\n\t\torigin: record.origin,\n\t\tgrantId: record.grantId,\n\t\ttokenHash: record.tokenHash,\n\t\tattemptId: record.attemptId,\n\t\tdestination: record.destination,\n\t\tsessionPath: record.sessionPath,\n\t\tcompletedAt: record.completedAt,\n\t};\n}\n\nexport class LocalTransferState {\n\tprivate readonly agentRoot: string;\n\tprivate readonly recordsRoot: string;\n\tprivate stateTail: Promise<void> = Promise.resolve();\n\n\tconstructor(agentDir: string) {\n\t\tthis.agentRoot = path.resolve(agentDir);\n\t\tthis.recordsRoot = path.join(this.agentRoot, \"leitwerk-session-transfer\", \"transfers\");\n\t}\n\n\tprivate recordFile(link: ParsedTransferLink): string {\n\t\treturn path.join(this.recordsRoot, `${stateKey(link)}.json`);\n\t}\n\n\tprivate async serialized<T>(operation: () => Promise<T>): Promise<T> {\n\t\tconst previous = this.stateTail;\n\t\tlet release!: () => void;\n\t\tthis.stateTail = new Promise<void>((resolve) => {\n\t\t\trelease = resolve;\n\t\t});\n\t\tawait previous;\n\t\ttry {\n\t\t\treturn await operation();\n\t\t} finally {\n\t\t\trelease();\n\t\t}\n\t}\n\n\tmarkerName(ownerId?: string): string {\n\t\treturn ownerId ? `${OWNER_MARKER}-${ownerId}` : OWNER_MARKER;\n\t}\n\n\tasync receipt(link: ParsedTransferLink): Promise<TransferReceipt | null> {\n\t\tconst record = await readJson<TransferStateRecord | null>(this.recordFile(link), null);\n\t\treturn record ? completedReceipt(record) : null;\n\t}\n\n\tasync begin(\n\t\tlink: ParsedTransferLink,\n\t\tinput: { attemptId: string; temporaryDirectory: string; ownerId: string },\n\t): Promise<void> {\n\t\tawait this.serialized(async () => {\n\t\t\ttry {\n\t\t\t\tawait atomicJson(\n\t\t\t\t\tthis.recordFile(link),\n\t\t\t\t\t{\n\t\t\t\t\t\tversion: 1,\n\t\t\t\t\t\tphase: \"temporary\",\n\t\t\t\t\t\torigin: link.origin,\n\t\t\t\t\t\tgrantId: link.grantId,\n\t\t\t\t\t\ttokenHash: tokenHash(link.token),\n\t\t\t\t\t\tattemptId: input.attemptId,\n\t\t\t\t\t\tcreatedAt: new Date().toISOString(),\n\t\t\t\t\t\ttemporaryDirectory: input.temporaryDirectory,\n\t\t\t\t\t\townerId: input.ownerId,\n\t\t\t\t\t} satisfies TransferStateRecord,\n\t\t\t\t\ttrue,\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tif ((error as NodeJS.ErrnoException).code === \"EEXIST\") {\n\t\t\t\t\tthrow new Error(\"A previous import for this link still has recovery state\", {\n\t\t\t\t\t\tcause: error,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t});\n\t}\n\n\tasync recordCommitTargets(\n\t\tlink: ParsedTransferLink,\n\t\ttargets: Required<Pick<TransferStateRecord, \"destination\" | \"sessionPath\">>,\n\t): Promise<void> {\n\t\tawait this.serialized(async () => {\n\t\t\tconst file = this.recordFile(link);\n\t\t\tconst record = await readJson<TransferStateRecord | null>(file, null);\n\t\t\tif (!record || record.phase === \"completed\") {\n\t\t\t\tthrow new Error(\"Transfer recovery state is missing or already complete\");\n\t\t\t}\n\t\t\tawait atomicJson(file, { ...record, ...targets, phase: \"committing\" });\n\t\t});\n\t}\n\n\tasync complete(\n\t\tlink: ParsedTransferLink,\n\t\tinput: { destination: string; sessionPath: string; completedAt: string },\n\t): Promise<TransferReceipt> {\n\t\treturn this.serialized(async () => {\n\t\t\tconst file = this.recordFile(link);\n\t\t\tconst record = await readJson<TransferStateRecord | null>(file, null);\n\t\t\tif (!record) throw new Error(\"Transfer recovery state is missing\");\n\t\t\tconst completed: TransferStateRecord = { ...record, ...input, phase: \"completed\" };\n\t\t\tawait atomicJson(file, completed);\n\t\t\treturn completedReceipt(completed) as TransferReceipt;\n\t\t});\n\t}\n\n\tasync discard(link: ParsedTransferLink): Promise<void> {\n\t\tawait this.serialized(async () => {\n\t\t\tconst file = this.recordFile(link);\n\t\t\tconst record = await readJson<TransferStateRecord | null>(file, null);\n\t\t\tif (!record) return;\n\t\t\tif (record.phase === \"completed\") throw new Error(\"Completed imports cannot be discarded\");\n\t\t\tif (\n\t\t\t\trecord.destination &&\n\t\t\t\t(await ownsDirectory(record.destination, record.ownerId, this.markerName(record.ownerId)))\n\t\t\t) {\n\t\t\t\tthrow new Error(\"A reserved import must retain its recovery state\");\n\t\t\t}\n\t\t\tawait removeOwnedDirectory(record.temporaryDirectory, record.ownerId, OWNER_MARKER);\n\t\t\tawait rm(file, { force: true });\n\t\t});\n\t}\n\n\tasync reconcile(): Promise<void> {\n\t\tawait this.serialized(async () => {\n\t\t\tlet names: string[];\n\t\t\ttry {\n\t\t\t\tnames = await readdir(this.recordsRoot);\n\t\t\t} catch (error) {\n\t\t\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tfor (const name of names.filter((candidate) => candidate.endsWith(\".json\"))) {\n\t\t\t\tconst file = path.join(this.recordsRoot, name);\n\t\t\t\ttry {\n\t\t\t\t\tconst record = await readJson<TransferStateRecord | null>(file, null);\n\t\t\t\t\tif (!record) continue;\n\t\t\t\t\tif (\n\t\t\t\t\t\trecord.phase !== \"completed\" &&\n\t\t\t\t\t\tDate.now() - Date.parse(record.createdAt) <= STALE_IMPORT_MS\n\t\t\t\t\t) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst destinationMarker = this.markerName(record.ownerId);\n\t\t\t\t\tconst ownsDestination = record.destination\n\t\t\t\t\t\t? await ownsDirectory(record.destination, record.ownerId, destinationMarker)\n\t\t\t\t\t\t: false;\n\t\t\t\t\tif (record.phase === \"completed\") {\n\t\t\t\t\t\tif (ownsDestination && record.destination) {\n\t\t\t\t\t\t\tawait rm(path.join(record.destination, destinationMarker), { force: true });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tawait removeOwnedDirectory(record.temporaryDirectory, record.ownerId, OWNER_MARKER);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (ownsDestination && record.destination) {\n\t\t\t\t\t\tawait removeOwnedDirectory(record.destination, record.ownerId, destinationMarker);\n\t\t\t\t\t}\n\t\t\t\t\tif (record.sessionPath && isPathInside(this.agentRoot, record.sessionPath)) {\n\t\t\t\t\t\tawait rm(record.sessionPath, { force: true });\n\t\t\t\t\t}\n\t\t\t\t\tawait removeOwnedDirectory(record.temporaryDirectory, record.ownerId, OWNER_MARKER);\n\t\t\t\t\tawait rm(file, { force: true });\n\t\t\t\t} catch {\n\t\t\t\t\t// Keep the record for a later reconciliation attempt.\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n}\n"],"mappings":";AAAA,OAAOA,WAAU;AACjB;AAAA,EAGC;AAAA,EACA;AAAA,OACM;AACP,SAAS,yBAAyB;AAClC,SAAkC,yBAAyB;;;ACR3D,SAAS,gBAAgB;AAQzB,eAAe,cAAc,UAAoC;AAChE,MAAI,UAAU,qCAAqC,SAAS,MAAM;AAClE,MAAI;AACH,UAAM,OAAQ,MAAM,SAAS,KAAK;AAClC,QAAI,OAAO,KAAK,UAAU,SAAU,WAAU,KAAK;AACnD,QAAI,OAAO,KAAK,SAAS,SAAU,WAAU,GAAG,OAAO,KAAK,KAAK,IAAI;AAAA,EACtE,QAAQ;AAAA,EAER;AACA,SAAO,IAAI,MAAM,OAAO;AACzB;AAEO,IAAM,wBAAN,MAA4B;AAAA,EAClC,YAA6B,MAA0B;AAA1B;AAAA,EAA2B;AAAA,EAA3B;AAAA,EAErB,YAAY,WAAmB,SAAS,IAAY;AAC3D,WAAO,aAAa,mBAAmB,SAAS,CAAC,GAAG,MAAM;AAAA,EAC3D;AAAA,EAEA,MAAc,QAAQ,QAAgB,OAAoB,CAAC,GAAsB;AAChF,UAAM,WAAW,MAAM,MAAM,GAAG,KAAK,KAAK,QAAQ,GAAG,MAAM,IAAI;AAAA,MAC9D,GAAG;AAAA,MACH,UAAU;AAAA,MACV,SAAS,EAAE,GAAG,KAAK,SAAS,eAAe,UAAU,KAAK,KAAK,KAAK,GAAG;AAAA,IACxE,CAAC;AACD,QAAI,SAAS,UAAU,OAAO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C,gBAAM,SAAS,IAAI;AAAA,YAClB;AAAA,YACA,CAAC,MAAM,MAAM,GAAG,UAAU,CAAC;AAAA,YAC3B,CAAC,MAAM,MAAM,GAAG,SAAS,CAAC;AAAA,YAC1B;AAAA,UACD;AACA,iBAAO,UAAU,MAAM;AACtB,gBAAI,CAAC,UAAW,QAAO,WAAW,2BAAsB;AAAA,UACzD;AACA,eAAK,eAAe;AAAA,YACnB;AAAA,YACA;AAAA,YACA;AAAA,YACA,QAAQ,OAAO;AAAA,YACf,WAAW,UAAU;AACpB,0BAAY,SAAS;AACrB,qBAAO,WAAW,gBAAgB,QAAQ,CAAC;AAAA,YAC5C;AAAA,UACD,CAAC,EAAE;AAAA,YACF,CAAC,WAAW,KAAK,MAAM;AAAA,YACvB,CAAC,UACA;AAAA,cACC,OAAO,WAAW,CAAC,YAChB,OACA,iBAAiB,QAChB,QACA,IAAI,MAAM,iBAAiB;AAAA,YAChC;AAAA,UACF;AACA,iBAAO;AAAA,QACR;AAAA,MACD;AAEA,UAAI,CAAC,SAAS;AACb,YAAI,GAAG;AAAA,UACN;AAAA,UACA;AAAA,QACD;AACA;AAAA,MACD;AACA,UAAI,mBAAmB,OAAO;AAC7B,YAAI,GAAG,OAAO,QAAQ,SAAS,OAAO;AACtC;AAAA,MACD;AACA,YAAM,sBAAsB,KAAK,MAAM,OAAO;AAAA,IAC/C;AAAA,EACD,CAAC;AACF;","names":["path","lstat","rename","writeFile","path","lstat","path","writeFile","rename","randomUUID","chmod","lstat","mkdir","readdir","readFile","rename","rm","rmdir","writeFile","path","isPathInside","path"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/client.ts","../src/importer.ts","../src/workspace-commit.ts","../src/local-state.ts"],"sourcesContent":["import path from \"node:path\";\nimport {\n\ttype ExtensionAPI,\n\ttype ExtensionCommandContext,\n\tformatSize,\n\tgetAgentDir,\n} from \"@earendil-works/pi-coding-agent\";\nimport { CancellableLoader } from \"@earendil-works/pi-tui\";\nimport { type ParsedTransferLink, parseTransferLink } from \"@leitwerk-dev/session-transfer\";\nimport { SessionTransferClient } from \"./client.js\";\nimport { type ImportProgress, type ImportResult, importTransfer } from \"./importer.js\";\nimport { LocalTransferState } from \"./local-state.js\";\n\nfunction phaseLabel(phase: string): string {\n\treturn (\n\t\t{\n\t\t\tqueued: \"Queued\",\n\t\t\twaiting_for_execution_chain: \"Waiting for accepted work\",\n\t\t\tstopping_worker: \"Stopping the idle worker\",\n\t\t\tstarting_exporter: \"Starting the read-only exporter\",\n\t\t\tscanning: \"Checking portable files\",\n\t\t\tready_to_stream: \"Ready to stream\",\n\t\t\tstreaming: \"Copying workspace and session\",\n\t\t\tvalidating_local: \"Validating local import\",\n\t\t\tfinishing_import: \"Finishing import…\",\n\t\t}[phase] ?? phase.replaceAll(\"_\", \" \")\n\t);\n}\n\nfunction percentage(progress: ImportProgress): number | null {\n\tif (progress.logicalBytesTotal && progress.logicalBytesTotal > 0) {\n\t\treturn Math.min(\n\t\t\t100,\n\t\t\tMath.floor((progress.logicalBytesProcessed / progress.logicalBytesTotal) * 100),\n\t\t);\n\t}\n\tif (progress.entriesTotal && progress.entriesTotal > 0) {\n\t\treturn Math.min(100, Math.floor((progress.entriesProcessed / progress.entriesTotal) * 100));\n\t}\n\treturn null;\n}\n\nfunction progressMessage(progress: ImportProgress): string {\n\tconst percent = percentage(progress);\n\tconst files = `${progress.entriesProcessed}${progress.entriesTotal === null ? \"\" : ` / ${progress.entriesTotal}`} files`;\n\tconst logical = `${formatSize(progress.logicalBytesProcessed)}${progress.logicalBytesTotal === null ? \"\" : ` / ${formatSize(progress.logicalBytesTotal)}`} expanded`;\n\tconst received = `${formatSize(progress.compressedBytes)} received`;\n\treturn `${phaseLabel(progress.phase)} · ${percent === null ? \"\" : `${percent}% · `}${files} · ${logical} · ${received}`;\n}\n\nasync function switchImportedSession(\n\tctx: ExtensionCommandContext,\n\tlink: ParsedTransferLink,\n\timported: Pick<ImportResult, \"sessionPath\" | \"attemptId\">,\n): Promise<void> {\n\tconst retryAcknowledgement = (activeCtx: ExtensionCommandContext): void => {\n\t\tvoid new SessionTransferClient(link)\n\t\t\t.acknowledge(imported.attemptId, AbortSignal.timeout(30_000))\n\t\t\t.catch(() => {\n\t\t\t\ttry {\n\t\t\t\t\tactiveCtx.ui.notify(\n\t\t\t\t\t\t\"The local import is complete. Leitwerk acknowledgement is still pending; use the same link to retry it.\",\n\t\t\t\t\t\t\"warning\",\n\t\t\t\t\t);\n\t\t\t\t} catch {\n\t\t\t\t\t// Pi may have replaced this context while acknowledgement was pending.\n\t\t\t\t}\n\t\t\t});\n\t};\n\tconst switched = await ctx.switchSession(imported.sessionPath, {\n\t\twithSession: async (replacementCtx) => {\n\t\t\treplacementCtx.ui.notify(\n\t\t\t\t\"Leitwerk process imported. Local Pi tools and resources are active.\",\n\t\t\t\t\"info\",\n\t\t\t);\n\t\t\tretryAcknowledgement(replacementCtx);\n\t\t},\n\t});\n\tif (switched.cancelled) {\n\t\tctx.ui.notify(\n\t\t\t`Import complete. Session switch was cancelled; open it with /resume: ${imported.sessionPath}`,\n\t\t\t\"info\",\n\t\t);\n\t\tretryAcknowledgement(ctx);\n\t}\n}\n\n/** @internal */\nexport default async function leitwerkSessionTransfer(pi: ExtensionAPI) {\n\tconst state = new LocalTransferState(getAgentDir());\n\tawait state.reconcile();\n\n\tpi.registerCommand(\"leitwerk-transfer\", {\n\t\tdescription: \"Import a Leitwerk process workspace and Pi session\",\n\t\thandler: async (args, ctx) => {\n\t\t\tif (ctx.mode !== \"tui\") {\n\t\t\t\tctx.ui.notify(\"/leitwerk-transfer is available only in interactive TUI mode\", \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst rawLink =\n\t\t\t\targs.trim() ||\n\t\t\t\t(await ctx.ui.input(\n\t\t\t\t\t\"Leitwerk transfer link\",\n\t\t\t\t\t\"https://leitwerk.example/api/session-transfers/…#token=…\",\n\t\t\t\t));\n\t\t\tif (!rawLink) return;\n\t\t\tlet link: ParsedTransferLink;\n\t\t\ttry {\n\t\t\t\tlink = parseTransferLink(rawLink);\n\t\t\t} catch (error) {\n\t\t\t\tctx.ui.notify(error instanceof Error ? error.message : \"Invalid transfer link\", \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst originWarning = `${link.origin} will receive the bearer credential and stream files into this Pi process. Continue only if you recognize it.`;\n\t\t\tconst receipt = await state.receipt(link);\n\t\t\tif (receipt) {\n\t\t\t\tif (\n\t\t\t\t\t!(await ctx.ui.confirm(\n\t\t\t\t\t\t\"Import already complete\",\n\t\t\t\t\t\t`Use the imported session at ${receipt.sessionPath}? ${originWarning}`,\n\t\t\t\t\t))\n\t\t\t\t) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tawait switchImportedSession(ctx, link, receipt);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst defaultDestination = path.join(ctx.cwd, link.instanceId);\n\t\t\tconst selectedDestination = await ctx.ui.input(\n\t\t\t\t\"New destination directory\",\n\t\t\t\tdefaultDestination,\n\t\t\t);\n\t\t\tif (!selectedDestination) return;\n\t\t\tconst destination = path.resolve(ctx.cwd, selectedDestination);\n\t\t\tawait ctx.waitForIdle();\n\t\t\tif (\n\t\t\t\t!(await ctx.ui.confirm(\n\t\t\t\t\t\"Import Leitwerk process?\",\n\t\t\t\t\t`Create ${destination}, copy the retained workspace, and import its Pi conversation? ${originWarning}`,\n\t\t\t\t))\n\t\t\t)\n\t\t\t\treturn;\n\n\t\t\tlet finishing = false;\n\t\t\tconst outcome = await ctx.ui.custom<ImportResult | Error | null>(\n\t\t\t\t(tui, theme, _keybindings, done) => {\n\t\t\t\t\tconst loader = new CancellableLoader(\n\t\t\t\t\t\ttui,\n\t\t\t\t\t\t(s) => theme.fg(\"accent\", s),\n\t\t\t\t\t\t(s) => theme.fg(\"muted\", s),\n\t\t\t\t\t\t\"Starting transfer…\",\n\t\t\t\t\t);\n\t\t\t\t\tloader.onAbort = () => {\n\t\t\t\t\t\tif (!finishing) loader.setMessage(\"Cancelling transfer…\");\n\t\t\t\t\t};\n\t\t\t\t\tvoid importTransfer({\n\t\t\t\t\t\tlink,\n\t\t\t\t\t\tdestination,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\tsignal: loader.signal,\n\t\t\t\t\t\tonProgress(progress) {\n\t\t\t\t\t\t\tfinishing = progress.finishing;\n\t\t\t\t\t\t\tloader.setMessage(progressMessage(progress));\n\t\t\t\t\t\t},\n\t\t\t\t\t}).then(\n\t\t\t\t\t\t(result) => done(result),\n\t\t\t\t\t\t(error: unknown) =>\n\t\t\t\t\t\t\tdone(\n\t\t\t\t\t\t\t\tloader.aborted && !finishing\n\t\t\t\t\t\t\t\t\t? null\n\t\t\t\t\t\t\t\t\t: error instanceof Error\n\t\t\t\t\t\t\t\t\t\t? error\n\t\t\t\t\t\t\t\t\t\t: new Error(\"Transfer failed\"),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn loader;\n\t\t\t\t},\n\t\t\t);\n\n\t\t\tif (!outcome) {\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\"Transfer cancelled. The link can be retried while it remains valid.\",\n\t\t\t\t\t\"info\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (outcome instanceof Error) {\n\t\t\t\tctx.ui.notify(outcome.message, \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait switchImportedSession(ctx, link, outcome);\n\t\t},\n\t});\n}\n","import { Readable } from \"node:stream\";\nimport type {\n\tParsedTransferLink,\n\tSessionTransferAttemptWire,\n} from \"@leitwerk-dev/session-transfer\";\n\nexport type RemoteTransferAttempt = SessionTransferAttemptWire;\n\nasync function responseError(response: Response): Promise<Error> {\n\tlet message = `Transfer request failed with HTTP ${response.status}`;\n\ttry {\n\t\tconst body = (await response.json()) as { error?: unknown; code?: unknown };\n\t\tif (typeof body.error === \"string\") message = body.error;\n\t\tif (typeof body.code === \"string\") message = `${message} (${body.code})`;\n\t} catch {\n\t\t// Keep the generic status without exposing response bodies that may contain credentials.\n\t}\n\treturn new Error(message);\n}\n\nexport class SessionTransferClient {\n\tconstructor(private readonly link: ParsedTransferLink) {}\n\n\tprivate attemptPath(attemptId: string, suffix = \"\"): string {\n\t\treturn `/attempts/${encodeURIComponent(attemptId)}${suffix}`;\n\t}\n\n\tprivate async request(suffix: string, init: RequestInit = {}): Promise<Response> {\n\t\tconst response = await fetch(`${this.link.grantUrl}${suffix}`, {\n\t\t\t...init,\n\t\t\tredirect: \"manual\",\n\t\t\theaders: { ...init.headers, Authorization: `Bearer ${this.link.token}` },\n\t\t});\n\t\tif (response.status >= 300 && response.status < 400)\n\t\t\tthrow new Error(\"Transfer endpoint returned a redirect\");\n\t\treturn response;\n\t}\n\n\tprivate async requestOk(\n\t\turl: string,\n\t\tinit: RequestInit = {},\n\t\tacceptedStatus?: number,\n\t): Promise<Response> {\n\t\tconst response = await this.request(url, init);\n\t\tif (!response.ok && response.status !== acceptedStatus) throw await responseError(response);\n\t\treturn response;\n\t}\n\n\tprivate async requestAttempt(url: string, init: RequestInit = {}) {\n\t\tconst response = await this.requestOk(url, init);\n\t\treturn ((await response.json()) as { attempt: RemoteTransferAttempt }).attempt;\n\t}\n\n\tasync start(signal?: AbortSignal): Promise<RemoteTransferAttempt> {\n\t\treturn this.requestAttempt(\"/attempts\", { method: \"POST\", signal });\n\t}\n\n\tasync status(attemptId: string, signal?: AbortSignal): Promise<RemoteTransferAttempt> {\n\t\treturn this.requestAttempt(this.attemptPath(attemptId), { signal });\n\t}\n\n\tasync stream(attemptId: string, signal?: AbortSignal): Promise<Readable> {\n\t\tconst response = await this.requestOk(this.attemptPath(attemptId, \"/stream\"), { signal });\n\t\tif (!response.body) throw new Error(\"Transfer endpoint returned no stream\");\n\t\treturn Readable.fromWeb(response.body as import(\"node:stream/web\").ReadableStream);\n\t}\n\n\tasync cancel(attemptId: string): Promise<void> {\n\t\tawait this.requestOk(\n\t\t\tthis.attemptPath(attemptId),\n\t\t\t{ method: \"DELETE\", signal: AbortSignal.timeout(10_000) },\n\t\t\t404,\n\t\t);\n\t}\n\n\tasync acknowledge(attemptId: string, signal?: AbortSignal): Promise<void> {\n\t\tawait this.requestOk(this.attemptPath(attemptId, \"/acknowledge\"), {\n\t\t\tmethod: \"POST\",\n\t\t\tsignal,\n\t\t});\n\t}\n}\n","import { randomUUID } from \"node:crypto\";\nimport { access, lstat, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport { SessionManager } from \"@earendil-works/pi-coding-agent\";\nimport {\n\textractTransferArchive,\n\tisPathInside,\n\ttype ParsedTransferLink,\n\treadProjectEvidence,\n\trewritePiSession,\n\ttype TransferArchiveProgress,\n} from \"@leitwerk-dev/session-transfer\";\nimport { type RemoteTransferAttempt, SessionTransferClient } from \"./client.js\";\nimport type { LocalTransferState } from \"./local-state.js\";\nimport {\n\tpopulateWorkspaceDestination,\n\treserveWorkspaceDestination,\n\trestoreWorkspaceMetadata,\n} from \"./workspace-commit.js\";\n\nexport interface ImportProgress extends TransferArchiveProgress {\n\tphase: string;\n\tcompressedBytes: number;\n\tentriesTotal: number | null;\n\tlogicalBytesTotal: number | null;\n\tfinishing: boolean;\n}\n\nexport interface ImportResult {\n\tdestination: string;\n\tsessionPath: string;\n\tattemptId: string;\n}\n\nasync function assertDestinationAbsent(destination: string): Promise<void> {\n\ttry {\n\t\tawait lstat(destination);\n\t\tthrow new Error(`Destination already exists: ${destination}`);\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n\t}\n}\n\nfunction resolveImportedCwd(root: string, relative: string | null): string {\n\treturn relative === null || relative === \".\" ? root : path.resolve(root, ...relative.split(\"/\"));\n}\n\nasync function validateProjects(\n\tworkspaceRoot: string,\n\tprojects: Parameters<typeof readProjectEvidence>[1],\n\tsignal: AbortSignal,\n): Promise<void> {\n\tconst actual = await readProjectEvidence(workspaceRoot, projects, signal);\n\tfor (let index = 0; index < projects.length; index += 1) {\n\t\tconst expected = projects[index];\n\t\tconst candidate = actual[index];\n\t\tif (!expected || !candidate) throw new Error(\"Project evidence is incomplete\");\n\t\tif (expected.head && candidate.head !== expected.head) {\n\t\t\tthrow new Error(`Project '${expected.key}' HEAD does not match the transfer manifest`);\n\t\t}\n\t\tif (candidate.branch !== expected.branch) {\n\t\t\tthrow new Error(\n\t\t\t\t`Project '${expected.key}' branch state does not match the transfer manifest`,\n\t\t\t);\n\t\t}\n\t}\n}\n\nexport async function importTransfer(input: {\n\tlink: ParsedTransferLink;\n\tdestination: string;\n\tstate: LocalTransferState;\n\tsignal: AbortSignal;\n\tonProgress(progress: ImportProgress): void;\n}): Promise<ImportResult> {\n\tconst destination = path.resolve(input.destination);\n\tawait assertDestinationAbsent(destination);\n\tconst client = new SessionTransferClient(input.link);\n\tlet attempt: RemoteTransferAttempt | null = null;\n\tlet temporaryDirectory: string | null = null;\n\tlet recoveryRecordCreated = false;\n\tlet destinationReserved = false;\n\tlet heartbeat: NodeJS.Timeout | null = null;\n\tconst progress: ImportProgress = {\n\t\tphase: \"queued\",\n\t\tcompressedBytes: 0,\n\t\tentriesProcessed: 0,\n\t\tlogicalBytesProcessed: 0,\n\t\tentriesTotal: null,\n\t\tlogicalBytesTotal: null,\n\t\tfinishing: false,\n\t};\n\tconst report = (patch: Partial<ImportProgress>): void => {\n\t\tObject.assign(progress, patch);\n\t\tinput.onProgress({ ...progress });\n\t};\n\ttry {\n\t\tattempt = await client.start(input.signal);\n\t\theartbeat = setInterval(() => {\n\t\t\tif (attempt) void client.status(attempt.id).catch(() => undefined);\n\t\t}, 30_000);\n\t\twhile (attempt.phase !== \"ready_to_stream\") {\n\t\t\tif ([\"cancelled\", \"failed\", \"consumed\"].includes(attempt.state)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\tattempt.failureCode\n\t\t\t\t\t\t? `Transfer ended: ${attempt.failureCode}`\n\t\t\t\t\t\t: `Transfer ended in state ${attempt.state}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treport({\n\t\t\t\tphase: attempt.phase,\n\t\t\t\tentriesTotal: attempt.entriesTotal,\n\t\t\t\tlogicalBytesTotal: attempt.logicalBytesTotal,\n\t\t\t});\n\t\t\tawait delay(1_000, undefined, { signal: input.signal });\n\t\t\tattempt = await client.status(attempt.id, input.signal);\n\t\t}\n\t\tconst ownerId = randomUUID();\n\t\tconst destinationMarkerName = input.state.markerName(ownerId);\n\t\ttemporaryDirectory = path.join(\n\t\t\tpath.dirname(destination),\n\t\t\t`.leitwerk-transfer-${input.link.instanceId}-${randomUUID()}`,\n\t\t);\n\t\tawait input.state.begin(input.link, {\n\t\t\tattemptId: attempt.id,\n\t\t\ttemporaryDirectory,\n\t\t\townerId,\n\t\t});\n\t\trecoveryRecordCreated = true;\n\t\treport({\n\t\t\tphase: \"streaming\",\n\t\t\tentriesTotal: attempt.entriesTotal,\n\t\t\tlogicalBytesTotal: attempt.logicalBytesTotal,\n\t\t});\n\t\tconst compressed = await client.stream(attempt.id, input.signal);\n\t\tconst extracted = await extractTransferArchive({\n\t\t\tcompressed,\n\t\t\toutputRoot: temporaryDirectory,\n\t\t\tsignal: input.signal,\n\t\t\townershipMarker: { name: input.state.markerName(), value: ownerId },\n\t\t\tonProgress: (archiveProgress) =>\n\t\t\t\treport({\n\t\t\t\t\tphase: \"streaming\",\n\t\t\t\t\t...archiveProgress,\n\t\t\t\t}),\n\t\t});\n\t\tif (extracted.manifest.instanceId !== input.link.instanceId)\n\t\t\tthrow new Error(\"Transfer manifest process id does not match the link\");\n\t\tattempt = await client.status(attempt.id, input.signal);\n\t\tif (\n\t\t\tattempt.state !== \"awaiting_ack\" ||\n\t\t\tattempt.compressedBytes !== extracted.compressedBytes ||\n\t\t\tattempt.streamSha256 !== extracted.streamSha256\n\t\t) {\n\t\t\tthrow new Error(\"Transfer stream digest or byte count does not match the server record\");\n\t\t}\n\t\treport({ phase: \"validating_local\" });\n\t\tconst temporaryWorkspace = path.join(temporaryDirectory, \"workspace\");\n\t\tawait validateProjects(temporaryWorkspace, extracted.manifest.projects, input.signal);\n\t\tconst relativeCwd = extracted.manifest.session.cwdRelativeToWorkspace;\n\t\tconst localCwd = resolveImportedCwd(destination, relativeCwd);\n\t\tif (!isPathInside(destination, localCwd))\n\t\t\tthrow new Error(\"Imported session cwd escapes the destination\");\n\t\tconst temporaryCwd = resolveImportedCwd(temporaryWorkspace, relativeCwd);\n\t\tif (!isPathInside(temporaryWorkspace, temporaryCwd))\n\t\t\tthrow new Error(\"Imported session cwd escapes the workspace\");\n\t\tawait access(temporaryCwd);\n\t\tconst rewritten = rewritePiSession(\n\t\t\tawait readFile(path.join(temporaryDirectory, \"session.jsonl\"), {\n\t\t\t\tencoding: \"utf8\",\n\t\t\t\tsignal: input.signal,\n\t\t\t}),\n\t\t\tlocalCwd,\n\t\t\textracted.manifest.session.sourceCwd,\n\t\t);\n\n\t\tinput.signal.throwIfAborted();\n\t\treport({ finishing: true, phase: \"finishing_import\" });\n\t\tconst createdSessionPath = SessionManager.create(localCwd).getSessionFile();\n\t\tif (!createdSessionPath) throw new Error(\"Pi did not create a persistent target session\");\n\t\tconst sessionPath = createdSessionPath;\n\t\tawait input.state.recordCommitTargets(input.link, { destination, sessionPath });\n\t\tawait reserveWorkspaceDestination(destination, { name: destinationMarkerName, ownerId });\n\t\tdestinationReserved = true;\n\t\tconst workspaceMetadata = await populateWorkspaceDestination(temporaryWorkspace, destination);\n\t\tconst temporarySession = `${sessionPath}.${randomUUID()}.importing`;\n\t\tawait writeFile(temporarySession, rewritten.content, { mode: 0o600, flag: \"wx\" });\n\t\tawait rename(temporarySession, sessionPath);\n\t\tawait input.state.complete(input.link, {\n\t\t\tdestination,\n\t\t\tsessionPath,\n\t\t\tcompletedAt: new Date().toISOString(),\n\t\t});\n\t\tawait rm(path.join(destination, destinationMarkerName), { force: true });\n\t\tawait restoreWorkspaceMetadata(destination, workspaceMetadata);\n\t\tawait rm(temporaryDirectory, { recursive: true, force: true });\n\t\treturn { destination, sessionPath, attemptId: attempt.id };\n\t} catch (error) {\n\t\tif (attempt && !progress.finishing) await client.cancel(attempt.id).catch(() => undefined);\n\t\tif (recoveryRecordCreated && !destinationReserved) {\n\t\t\tawait input.state.discard(input.link).catch(() => undefined);\n\t\t}\n\t\tthrow error;\n\t} finally {\n\t\tif (heartbeat) clearInterval(heartbeat);\n\t}\n}\n","import { chmod, lstat, mkdir, readdir, rename, rmdir, utimes, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nexport async function reserveWorkspaceDestination(\n\tdestination: string,\n\tmarker: { name: string; ownerId: string },\n): Promise<void> {\n\t// mkdir is the exclusive claim: never replace even an empty existing directory.\n\tawait mkdir(destination, { recursive: false, mode: 0o700 });\n\ttry {\n\t\tawait writeFile(path.join(destination, marker.name), `${marker.ownerId}\\n`, {\n\t\t\tmode: 0o600,\n\t\t\tflag: \"wx\",\n\t\t});\n\t} catch (error) {\n\t\t// An unsuccessful marker write must not recursively remove any intervening data.\n\t\tawait rmdir(destination).catch(() => undefined);\n\t\tthrow error;\n\t}\n}\n\nexport async function populateWorkspaceDestination(source: string, destination: string) {\n\tconst metadata = await lstat(source);\n\t// Staging stays writable for moves and recovery; restore the imported mode last.\n\tawait chmod(source, (metadata.mode & 0o7777) | 0o700);\n\tfor (const name of await readdir(source)) {\n\t\tawait rename(path.join(source, name), path.join(destination, name));\n\t}\n\treturn metadata;\n}\n\nexport async function restoreWorkspaceMetadata(\n\tdestination: string,\n\tmetadata: { mode: number; atime: Date; mtime: Date },\n): Promise<void> {\n\tawait chmod(destination, metadata.mode & 0o7777);\n\tawait utimes(destination, metadata.atime, metadata.mtime);\n}\n","import { createHash, randomUUID } from \"node:crypto\";\nimport {\n\tchmod,\n\tlink as linkFile,\n\tlstat,\n\tmkdir,\n\treaddir,\n\treadFile,\n\trename,\n\trm,\n\trmdir,\n\twriteFile,\n} from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { isPathInside, type ParsedTransferLink } from \"@leitwerk-dev/session-transfer\";\n\nconst OWNER_MARKER = \".leitwerk-transfer-owner\";\nconst STALE_IMPORT_MS = 2 * 60 * 60 * 1000;\n\nexport interface TransferReceipt {\n\tversion: 1;\n\torigin: string;\n\tgrantId: string;\n\ttokenHash: string;\n\tattemptId: string;\n\tdestination: string;\n\tsessionPath: string;\n\tcompletedAt: string;\n}\n\ninterface TransferStateRecord {\n\tversion: 1;\n\tphase: \"temporary\" | \"committing\" | \"completed\";\n\torigin: string;\n\tgrantId: string;\n\ttokenHash: string;\n\tattemptId: string;\n\tcreatedAt: string;\n\ttemporaryDirectory: string;\n\townerId: string;\n\tdestination?: string;\n\tsessionPath?: string;\n\tcompletedAt?: string;\n}\n\nasync function readJson<T>(file: string, fallback: T): Promise<T> {\n\ttry {\n\t\treturn JSON.parse(await readFile(file, \"utf8\")) as T;\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return fallback;\n\t\tthrow error;\n\t}\n}\n\nasync function atomicJson(file: string, value: unknown, exclusive = false): Promise<void> {\n\tawait mkdir(path.dirname(file), { recursive: true, mode: 0o700 });\n\tconst temporary = `${file}.${randomUUID()}.tmp`;\n\ttry {\n\t\tawait writeFile(temporary, `${JSON.stringify(value, null, 2)}\\n`, { mode: 0o600, flag: \"wx\" });\n\t\tif (exclusive) await linkFile(temporary, file);\n\t\telse await rename(temporary, file);\n\t\tawait chmod(file, 0o600);\n\t} finally {\n\t\tawait rm(temporary, { force: true });\n\t}\n}\n\nasync function ownsDirectory(directory: string, ownerId: string, marker: string): Promise<boolean> {\n\ttry {\n\t\treturn (\n\t\t\t(await lstat(directory)).isDirectory() &&\n\t\t\t(await readFile(path.join(directory, marker), \"utf8\")).trim() === ownerId\n\t\t);\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return false;\n\t\tthrow error;\n\t}\n}\n\nasync function removeOwnedDirectory(\n\tdirectory: string,\n\townerId: string,\n\tmarker: string,\n): Promise<void> {\n\tif (!(await ownsDirectory(directory, ownerId, marker))) return;\n\t// Keep the ownership proof until all imported children have been removed.\n\tfor (const name of await readdir(directory)) {\n\t\tif (name !== marker) await rm(path.join(directory, name), { recursive: true, force: true });\n\t}\n\tawait rm(path.join(directory, marker));\n\tawait rmdir(directory);\n}\n\nfunction tokenHash(token: string): string {\n\treturn createHash(\"sha256\").update(token, \"utf8\").digest(\"hex\");\n}\n\nfunction stateKey(link: ParsedTransferLink): string {\n\treturn createHash(\"sha256\")\n\t\t.update(`${link.origin}\\0${link.grantId}\\0${tokenHash(link.token)}`)\n\t\t.digest(\"hex\");\n}\n\nfunction completedReceipt(record: TransferStateRecord): TransferReceipt | null {\n\tif (\n\t\trecord.phase !== \"completed\" ||\n\t\t!record.destination ||\n\t\t!record.sessionPath ||\n\t\t!record.completedAt\n\t) {\n\t\treturn null;\n\t}\n\treturn {\n\t\tversion: 1,\n\t\torigin: record.origin,\n\t\tgrantId: record.grantId,\n\t\ttokenHash: record.tokenHash,\n\t\tattemptId: record.attemptId,\n\t\tdestination: record.destination,\n\t\tsessionPath: record.sessionPath,\n\t\tcompletedAt: record.completedAt,\n\t};\n}\n\nexport class LocalTransferState {\n\tprivate readonly agentRoot: string;\n\tprivate readonly recordsRoot: string;\n\tprivate stateTail: Promise<void> = Promise.resolve();\n\n\tconstructor(agentDir: string) {\n\t\tthis.agentRoot = path.resolve(agentDir);\n\t\tthis.recordsRoot = path.join(this.agentRoot, \"leitwerk-session-transfer\", \"transfers\");\n\t}\n\n\tprivate recordFile(link: ParsedTransferLink): string {\n\t\treturn path.join(this.recordsRoot, `${stateKey(link)}.json`);\n\t}\n\n\tprivate async serialized<T>(operation: () => Promise<T>): Promise<T> {\n\t\tconst previous = this.stateTail;\n\t\tlet release!: () => void;\n\t\tthis.stateTail = new Promise<void>((resolve) => {\n\t\t\trelease = resolve;\n\t\t});\n\t\tawait previous;\n\t\ttry {\n\t\t\treturn await operation();\n\t\t} finally {\n\t\t\trelease();\n\t\t}\n\t}\n\n\tmarkerName(ownerId?: string): string {\n\t\treturn ownerId ? `${OWNER_MARKER}-${ownerId}` : OWNER_MARKER;\n\t}\n\n\tasync receipt(link: ParsedTransferLink): Promise<TransferReceipt | null> {\n\t\tconst record = await readJson<TransferStateRecord | null>(this.recordFile(link), null);\n\t\treturn record ? completedReceipt(record) : null;\n\t}\n\n\tasync begin(\n\t\tlink: ParsedTransferLink,\n\t\tinput: { attemptId: string; temporaryDirectory: string; ownerId: string },\n\t): Promise<void> {\n\t\tawait this.serialized(async () => {\n\t\t\ttry {\n\t\t\t\tawait atomicJson(\n\t\t\t\t\tthis.recordFile(link),\n\t\t\t\t\t{\n\t\t\t\t\t\tversion: 1,\n\t\t\t\t\t\tphase: \"temporary\",\n\t\t\t\t\t\torigin: link.origin,\n\t\t\t\t\t\tgrantId: link.grantId,\n\t\t\t\t\t\ttokenHash: tokenHash(link.token),\n\t\t\t\t\t\tattemptId: input.attemptId,\n\t\t\t\t\t\tcreatedAt: new Date().toISOString(),\n\t\t\t\t\t\ttemporaryDirectory: input.temporaryDirectory,\n\t\t\t\t\t\townerId: input.ownerId,\n\t\t\t\t\t} satisfies TransferStateRecord,\n\t\t\t\t\ttrue,\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tif ((error as NodeJS.ErrnoException).code === \"EEXIST\") {\n\t\t\t\t\tthrow new Error(\"A previous import for this link still has recovery state\", {\n\t\t\t\t\t\tcause: error,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t});\n\t}\n\n\tasync recordCommitTargets(\n\t\tlink: ParsedTransferLink,\n\t\ttargets: Required<Pick<TransferStateRecord, \"destination\" | \"sessionPath\">>,\n\t): Promise<void> {\n\t\tawait this.serialized(async () => {\n\t\t\tconst file = this.recordFile(link);\n\t\t\tconst record = await readJson<TransferStateRecord | null>(file, null);\n\t\t\tif (!record || record.phase === \"completed\") {\n\t\t\t\tthrow new Error(\"Transfer recovery state is missing or already complete\");\n\t\t\t}\n\t\t\tawait atomicJson(file, { ...record, ...targets, phase: \"committing\" });\n\t\t});\n\t}\n\n\tasync complete(\n\t\tlink: ParsedTransferLink,\n\t\tinput: { destination: string; sessionPath: string; completedAt: string },\n\t): Promise<TransferReceipt> {\n\t\treturn this.serialized(async () => {\n\t\t\tconst file = this.recordFile(link);\n\t\t\tconst record = await readJson<TransferStateRecord | null>(file, null);\n\t\t\tif (!record) throw new Error(\"Transfer recovery state is missing\");\n\t\t\tconst completed: TransferStateRecord = { ...record, ...input, phase: \"completed\" };\n\t\t\tawait atomicJson(file, completed);\n\t\t\treturn completedReceipt(completed) as TransferReceipt;\n\t\t});\n\t}\n\n\tasync discard(link: ParsedTransferLink): Promise<void> {\n\t\tawait this.serialized(async () => {\n\t\t\tconst file = this.recordFile(link);\n\t\t\tconst record = await readJson<TransferStateRecord | null>(file, null);\n\t\t\tif (!record) return;\n\t\t\tif (record.phase === \"completed\") throw new Error(\"Completed imports cannot be discarded\");\n\t\t\tif (\n\t\t\t\trecord.destination &&\n\t\t\t\t(await ownsDirectory(record.destination, record.ownerId, this.markerName(record.ownerId)))\n\t\t\t) {\n\t\t\t\tthrow new Error(\"A reserved import must retain its recovery state\");\n\t\t\t}\n\t\t\tawait removeOwnedDirectory(record.temporaryDirectory, record.ownerId, OWNER_MARKER);\n\t\t\tawait rm(file, { force: true });\n\t\t});\n\t}\n\n\tasync reconcile(): Promise<void> {\n\t\tawait this.serialized(async () => {\n\t\t\tlet names: string[];\n\t\t\ttry {\n\t\t\t\tnames = await readdir(this.recordsRoot);\n\t\t\t} catch (error) {\n\t\t\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tfor (const name of names.filter((candidate) => candidate.endsWith(\".json\"))) {\n\t\t\t\tconst file = path.join(this.recordsRoot, name);\n\t\t\t\ttry {\n\t\t\t\t\tconst record = await readJson<TransferStateRecord | null>(file, null);\n\t\t\t\t\tif (!record) continue;\n\t\t\t\t\tif (\n\t\t\t\t\t\trecord.phase !== \"completed\" &&\n\t\t\t\t\t\tDate.now() - Date.parse(record.createdAt) <= STALE_IMPORT_MS\n\t\t\t\t\t) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst destinationMarker = this.markerName(record.ownerId);\n\t\t\t\t\tconst ownsDestination = record.destination\n\t\t\t\t\t\t? await ownsDirectory(record.destination, record.ownerId, destinationMarker)\n\t\t\t\t\t\t: false;\n\t\t\t\t\tif (record.phase === \"completed\") {\n\t\t\t\t\t\tif (ownsDestination && record.destination) {\n\t\t\t\t\t\t\tawait rm(path.join(record.destination, destinationMarker), { force: true });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tawait removeOwnedDirectory(record.temporaryDirectory, record.ownerId, OWNER_MARKER);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (ownsDestination && record.destination) {\n\t\t\t\t\t\tawait removeOwnedDirectory(record.destination, record.ownerId, destinationMarker);\n\t\t\t\t\t}\n\t\t\t\t\tif (record.sessionPath && isPathInside(this.agentRoot, record.sessionPath)) {\n\t\t\t\t\t\tawait rm(record.sessionPath, { force: true });\n\t\t\t\t\t}\n\t\t\t\t\tawait removeOwnedDirectory(record.temporaryDirectory, record.ownerId, OWNER_MARKER);\n\t\t\t\t\tawait rm(file, { force: true });\n\t\t\t\t} catch {\n\t\t\t\t\t// Keep the record for a later reconciliation attempt.\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n}\n"],"mappings":";AAAA,OAAOA,WAAU;AACjB;AAAA,EAGC;AAAA,EACA;AAAA,OACM;AACP,SAAS,yBAAyB;AAClC,SAAkC,yBAAyB;;;ACR3D,SAAS,gBAAgB;AAQzB,eAAe,cAAc,UAAoC;AAChE,MAAI,UAAU,qCAAqC,SAAS,MAAM;AAClE,MAAI;AACH,UAAM,OAAQ,MAAM,SAAS,KAAK;AAClC,QAAI,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UACF;AACA,iBAAO;AAAA,QACR;AAAA,MACD;AAEA,UAAI,CAAC,SAAS;AACb,YAAI,GAAG;AAAA,UACN;AAAA,UACA;AAAA,QACD;AACA;AAAA,MACD;AACA,UAAI,mBAAmB,OAAO;AAC7B,YAAI,GAAG,OAAO,QAAQ,SAAS,OAAO;AACtC;AAAA,MACD;AACA,YAAM,sBAAsB,KAAK,MAAM,OAAO;AAAA,IAC/C;AAAA,EACD,CAAC;AACF;","names":["path","lstat","rename","writeFile","path","lstat","path","writeFile","rename","randomUUID","chmod","lstat","mkdir","readdir","readFile","rename","rm","rmdir","writeFile","path","isPathInside","path"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leitwerk-dev/pi-session-transfer",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Import a Leitwerk process workspace and Pi conversation into local Pi",
5
5
  "repository": {
6
6
  "type": "git",
@@ -18,18 +18,11 @@
18
18
  "./dist/index.js"
19
19
  ]
20
20
  },
21
- "exports": {
22
- ".": {
23
- "source": "./src/index.ts",
24
- "import": "./dist/index.js",
25
- "types": "./dist/index.d.ts"
26
- }
27
- },
28
21
  "scripts": {
29
22
  "build": "tsup --silent"
30
23
  },
31
24
  "dependencies": {
32
- "@leitwerk-dev/session-transfer": "0.2.0"
25
+ "@leitwerk-dev/session-transfer": "0.2.1"
33
26
  },
34
27
  "peerDependencies": {
35
28
  "@earendil-works/pi-coding-agent": "*",
package/src/index.ts CHANGED
@@ -85,6 +85,7 @@ async function switchImportedSession(
85
85
  }
86
86
  }
87
87
 
88
+ /** @internal */
88
89
  export default async function leitwerkSessionTransfer(pi: ExtensionAPI) {
89
90
  const state = new LocalTransferState(getAgentDir());
90
91
  await state.reconcile();