@leitwerk-dev/pi-session-transfer 0.0.0-bootstrap.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/LICENSE +13 -0
- package/README.md +65 -1
- package/dist/LICENSE +13 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +637 -0
- package/dist/index.js.map +1 -0
- package/package.json +48 -14
- package/src/client.ts +82 -0
- package/src/importer.ts +208 -0
- package/src/index.ts +196 -0
- package/src/local-state.ts +284 -0
- package/src/workspace-commit.ts +38 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,637 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import path4 from "path";
|
|
3
|
+
import {
|
|
4
|
+
formatSize,
|
|
5
|
+
getAgentDir
|
|
6
|
+
} from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import { CancellableLoader } from "@earendil-works/pi-tui";
|
|
8
|
+
import { parseTransferLink } from "@leitwerk-dev/session-transfer";
|
|
9
|
+
|
|
10
|
+
// src/client.ts
|
|
11
|
+
import { Readable } from "stream";
|
|
12
|
+
async function responseError(response) {
|
|
13
|
+
let message = `Transfer request failed with HTTP ${response.status}`;
|
|
14
|
+
try {
|
|
15
|
+
const body = await response.json();
|
|
16
|
+
if (typeof body.error === "string") message = body.error;
|
|
17
|
+
if (typeof body.code === "string") message = `${message} (${body.code})`;
|
|
18
|
+
} catch {
|
|
19
|
+
}
|
|
20
|
+
return new Error(message);
|
|
21
|
+
}
|
|
22
|
+
var SessionTransferClient = class {
|
|
23
|
+
constructor(link) {
|
|
24
|
+
this.link = link;
|
|
25
|
+
}
|
|
26
|
+
link;
|
|
27
|
+
attemptPath(attemptId, suffix = "") {
|
|
28
|
+
return `/attempts/${encodeURIComponent(attemptId)}${suffix}`;
|
|
29
|
+
}
|
|
30
|
+
async request(suffix, init = {}) {
|
|
31
|
+
const response = await fetch(`${this.link.grantUrl}${suffix}`, {
|
|
32
|
+
...init,
|
|
33
|
+
redirect: "manual",
|
|
34
|
+
headers: { ...init.headers, Authorization: `Bearer ${this.link.token}` }
|
|
35
|
+
});
|
|
36
|
+
if (response.status >= 300 && response.status < 400)
|
|
37
|
+
throw new Error("Transfer endpoint returned a redirect");
|
|
38
|
+
return response;
|
|
39
|
+
}
|
|
40
|
+
async requestOk(url, init = {}, acceptedStatus) {
|
|
41
|
+
const response = await this.request(url, init);
|
|
42
|
+
if (!response.ok && response.status !== acceptedStatus) throw await responseError(response);
|
|
43
|
+
return response;
|
|
44
|
+
}
|
|
45
|
+
async requestAttempt(url, init = {}) {
|
|
46
|
+
const response = await this.requestOk(url, init);
|
|
47
|
+
return (await response.json()).attempt;
|
|
48
|
+
}
|
|
49
|
+
async start(signal) {
|
|
50
|
+
return this.requestAttempt("/attempts", { method: "POST", signal });
|
|
51
|
+
}
|
|
52
|
+
async status(attemptId, signal) {
|
|
53
|
+
return this.requestAttempt(this.attemptPath(attemptId), { signal });
|
|
54
|
+
}
|
|
55
|
+
async stream(attemptId, signal) {
|
|
56
|
+
const response = await this.requestOk(this.attemptPath(attemptId, "/stream"), { signal });
|
|
57
|
+
if (!response.body) throw new Error("Transfer endpoint returned no stream");
|
|
58
|
+
return Readable.fromWeb(response.body);
|
|
59
|
+
}
|
|
60
|
+
async cancel(attemptId) {
|
|
61
|
+
await this.requestOk(
|
|
62
|
+
this.attemptPath(attemptId),
|
|
63
|
+
{ method: "DELETE", signal: AbortSignal.timeout(1e4) },
|
|
64
|
+
404
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
async acknowledge(attemptId, signal) {
|
|
68
|
+
await this.requestOk(this.attemptPath(attemptId, "/acknowledge"), {
|
|
69
|
+
method: "POST",
|
|
70
|
+
signal
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
// src/importer.ts
|
|
76
|
+
import { randomUUID } from "crypto";
|
|
77
|
+
import { access, lstat as lstat2, readFile, rename as rename2, rm, writeFile as writeFile2 } from "fs/promises";
|
|
78
|
+
import path2 from "path";
|
|
79
|
+
import { setTimeout as delay } from "timers/promises";
|
|
80
|
+
import { SessionManager } from "@earendil-works/pi-coding-agent";
|
|
81
|
+
import {
|
|
82
|
+
extractTransferArchive,
|
|
83
|
+
isPathInside,
|
|
84
|
+
readProjectEvidence,
|
|
85
|
+
rewritePiSession
|
|
86
|
+
} from "@leitwerk-dev/session-transfer";
|
|
87
|
+
|
|
88
|
+
// src/workspace-commit.ts
|
|
89
|
+
import { chmod, lstat, mkdir, readdir, rename, rmdir, utimes, writeFile } from "fs/promises";
|
|
90
|
+
import path from "path";
|
|
91
|
+
async function reserveWorkspaceDestination(destination, marker) {
|
|
92
|
+
await mkdir(destination, { recursive: false, mode: 448 });
|
|
93
|
+
try {
|
|
94
|
+
await writeFile(path.join(destination, marker.name), `${marker.ownerId}
|
|
95
|
+
`, {
|
|
96
|
+
mode: 384,
|
|
97
|
+
flag: "wx"
|
|
98
|
+
});
|
|
99
|
+
} catch (error) {
|
|
100
|
+
await rmdir(destination).catch(() => void 0);
|
|
101
|
+
throw error;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
async function populateWorkspaceDestination(source, destination) {
|
|
105
|
+
const metadata = await lstat(source);
|
|
106
|
+
await chmod(source, metadata.mode & 4095 | 448);
|
|
107
|
+
for (const name of await readdir(source)) {
|
|
108
|
+
await rename(path.join(source, name), path.join(destination, name));
|
|
109
|
+
}
|
|
110
|
+
return metadata;
|
|
111
|
+
}
|
|
112
|
+
async function restoreWorkspaceMetadata(destination, metadata) {
|
|
113
|
+
await chmod(destination, metadata.mode & 4095);
|
|
114
|
+
await utimes(destination, metadata.atime, metadata.mtime);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// src/importer.ts
|
|
118
|
+
async function assertDestinationAbsent(destination) {
|
|
119
|
+
try {
|
|
120
|
+
await lstat2(destination);
|
|
121
|
+
throw new Error(`Destination already exists: ${destination}`);
|
|
122
|
+
} catch (error) {
|
|
123
|
+
if (error.code !== "ENOENT") throw error;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
function resolveImportedCwd(root, relative) {
|
|
127
|
+
return relative === null || relative === "." ? root : path2.resolve(root, ...relative.split("/"));
|
|
128
|
+
}
|
|
129
|
+
async function validateProjects(workspaceRoot, projects, signal) {
|
|
130
|
+
const actual = await readProjectEvidence(workspaceRoot, projects, signal);
|
|
131
|
+
for (let index = 0; index < projects.length; index += 1) {
|
|
132
|
+
const expected = projects[index];
|
|
133
|
+
const candidate = actual[index];
|
|
134
|
+
if (!expected || !candidate) throw new Error("Project evidence is incomplete");
|
|
135
|
+
if (expected.head && candidate.head !== expected.head) {
|
|
136
|
+
throw new Error(`Project '${expected.key}' HEAD does not match the transfer manifest`);
|
|
137
|
+
}
|
|
138
|
+
if (candidate.branch !== expected.branch) {
|
|
139
|
+
throw new Error(
|
|
140
|
+
`Project '${expected.key}' branch state does not match the transfer manifest`
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
async function importTransfer(input) {
|
|
146
|
+
const destination = path2.resolve(input.destination);
|
|
147
|
+
await assertDestinationAbsent(destination);
|
|
148
|
+
const client = new SessionTransferClient(input.link);
|
|
149
|
+
let attempt = null;
|
|
150
|
+
let temporaryDirectory = null;
|
|
151
|
+
let recoveryRecordCreated = false;
|
|
152
|
+
let destinationReserved = false;
|
|
153
|
+
let heartbeat = null;
|
|
154
|
+
const progress = {
|
|
155
|
+
phase: "queued",
|
|
156
|
+
compressedBytes: 0,
|
|
157
|
+
entriesProcessed: 0,
|
|
158
|
+
logicalBytesProcessed: 0,
|
|
159
|
+
entriesTotal: null,
|
|
160
|
+
logicalBytesTotal: null,
|
|
161
|
+
finishing: false
|
|
162
|
+
};
|
|
163
|
+
const report = (patch) => {
|
|
164
|
+
Object.assign(progress, patch);
|
|
165
|
+
input.onProgress({ ...progress });
|
|
166
|
+
};
|
|
167
|
+
try {
|
|
168
|
+
attempt = await client.start(input.signal);
|
|
169
|
+
heartbeat = setInterval(() => {
|
|
170
|
+
if (attempt) void client.status(attempt.id).catch(() => void 0);
|
|
171
|
+
}, 3e4);
|
|
172
|
+
while (attempt.phase !== "ready_to_stream") {
|
|
173
|
+
if (["cancelled", "failed", "consumed"].includes(attempt.state)) {
|
|
174
|
+
throw new Error(
|
|
175
|
+
attempt.failureCode ? `Transfer ended: ${attempt.failureCode}` : `Transfer ended in state ${attempt.state}`
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
report({
|
|
179
|
+
phase: attempt.phase,
|
|
180
|
+
entriesTotal: attempt.entriesTotal,
|
|
181
|
+
logicalBytesTotal: attempt.logicalBytesTotal
|
|
182
|
+
});
|
|
183
|
+
await delay(1e3, void 0, { signal: input.signal });
|
|
184
|
+
attempt = await client.status(attempt.id, input.signal);
|
|
185
|
+
}
|
|
186
|
+
const ownerId = randomUUID();
|
|
187
|
+
const destinationMarkerName = input.state.markerName(ownerId);
|
|
188
|
+
temporaryDirectory = path2.join(
|
|
189
|
+
path2.dirname(destination),
|
|
190
|
+
`.leitwerk-transfer-${input.link.instanceId}-${randomUUID()}`
|
|
191
|
+
);
|
|
192
|
+
await input.state.begin(input.link, {
|
|
193
|
+
attemptId: attempt.id,
|
|
194
|
+
temporaryDirectory,
|
|
195
|
+
ownerId
|
|
196
|
+
});
|
|
197
|
+
recoveryRecordCreated = true;
|
|
198
|
+
report({
|
|
199
|
+
phase: "streaming",
|
|
200
|
+
entriesTotal: attempt.entriesTotal,
|
|
201
|
+
logicalBytesTotal: attempt.logicalBytesTotal
|
|
202
|
+
});
|
|
203
|
+
const compressed = await client.stream(attempt.id, input.signal);
|
|
204
|
+
const extracted = await extractTransferArchive({
|
|
205
|
+
compressed,
|
|
206
|
+
outputRoot: temporaryDirectory,
|
|
207
|
+
signal: input.signal,
|
|
208
|
+
ownershipMarker: { name: input.state.markerName(), value: ownerId },
|
|
209
|
+
onProgress: (archiveProgress) => report({
|
|
210
|
+
phase: "streaming",
|
|
211
|
+
...archiveProgress
|
|
212
|
+
})
|
|
213
|
+
});
|
|
214
|
+
if (extracted.manifest.instanceId !== input.link.instanceId)
|
|
215
|
+
throw new Error("Transfer manifest process id does not match the link");
|
|
216
|
+
attempt = await client.status(attempt.id, input.signal);
|
|
217
|
+
if (attempt.state !== "awaiting_ack" || attempt.compressedBytes !== extracted.compressedBytes || attempt.streamSha256 !== extracted.streamSha256) {
|
|
218
|
+
throw new Error("Transfer stream digest or byte count does not match the server record");
|
|
219
|
+
}
|
|
220
|
+
report({ phase: "validating_local" });
|
|
221
|
+
const temporaryWorkspace = path2.join(temporaryDirectory, "workspace");
|
|
222
|
+
await validateProjects(temporaryWorkspace, extracted.manifest.projects, input.signal);
|
|
223
|
+
const relativeCwd = extracted.manifest.session.cwdRelativeToWorkspace;
|
|
224
|
+
const localCwd = resolveImportedCwd(destination, relativeCwd);
|
|
225
|
+
if (!isPathInside(destination, localCwd))
|
|
226
|
+
throw new Error("Imported session cwd escapes the destination");
|
|
227
|
+
const temporaryCwd = resolveImportedCwd(temporaryWorkspace, relativeCwd);
|
|
228
|
+
if (!isPathInside(temporaryWorkspace, temporaryCwd))
|
|
229
|
+
throw new Error("Imported session cwd escapes the workspace");
|
|
230
|
+
await access(temporaryCwd);
|
|
231
|
+
const rewritten = rewritePiSession(
|
|
232
|
+
await readFile(path2.join(temporaryDirectory, "session.jsonl"), {
|
|
233
|
+
encoding: "utf8",
|
|
234
|
+
signal: input.signal
|
|
235
|
+
}),
|
|
236
|
+
localCwd,
|
|
237
|
+
extracted.manifest.session.sourceCwd
|
|
238
|
+
);
|
|
239
|
+
input.signal.throwIfAborted();
|
|
240
|
+
report({ finishing: true, phase: "finishing_import" });
|
|
241
|
+
const createdSessionPath = SessionManager.create(localCwd).getSessionFile();
|
|
242
|
+
if (!createdSessionPath) throw new Error("Pi did not create a persistent target session");
|
|
243
|
+
const sessionPath = createdSessionPath;
|
|
244
|
+
await input.state.recordCommitTargets(input.link, { destination, sessionPath });
|
|
245
|
+
await reserveWorkspaceDestination(destination, { name: destinationMarkerName, ownerId });
|
|
246
|
+
destinationReserved = true;
|
|
247
|
+
const workspaceMetadata = await populateWorkspaceDestination(temporaryWorkspace, destination);
|
|
248
|
+
const temporarySession = `${sessionPath}.${randomUUID()}.importing`;
|
|
249
|
+
await writeFile2(temporarySession, rewritten.content, { mode: 384, flag: "wx" });
|
|
250
|
+
await rename2(temporarySession, sessionPath);
|
|
251
|
+
await input.state.complete(input.link, {
|
|
252
|
+
destination,
|
|
253
|
+
sessionPath,
|
|
254
|
+
completedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
255
|
+
});
|
|
256
|
+
await rm(path2.join(destination, destinationMarkerName), { force: true });
|
|
257
|
+
await restoreWorkspaceMetadata(destination, workspaceMetadata);
|
|
258
|
+
await rm(temporaryDirectory, { recursive: true, force: true });
|
|
259
|
+
return { destination, sessionPath, attemptId: attempt.id };
|
|
260
|
+
} catch (error) {
|
|
261
|
+
if (attempt && !progress.finishing) await client.cancel(attempt.id).catch(() => void 0);
|
|
262
|
+
if (recoveryRecordCreated && !destinationReserved) {
|
|
263
|
+
await input.state.discard(input.link).catch(() => void 0);
|
|
264
|
+
}
|
|
265
|
+
throw error;
|
|
266
|
+
} finally {
|
|
267
|
+
if (heartbeat) clearInterval(heartbeat);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// src/local-state.ts
|
|
272
|
+
import { createHash, randomUUID as randomUUID2 } from "crypto";
|
|
273
|
+
import {
|
|
274
|
+
chmod as chmod2,
|
|
275
|
+
link as linkFile,
|
|
276
|
+
lstat as lstat3,
|
|
277
|
+
mkdir as mkdir2,
|
|
278
|
+
readdir as readdir2,
|
|
279
|
+
readFile as readFile2,
|
|
280
|
+
rename as rename3,
|
|
281
|
+
rm as rm2,
|
|
282
|
+
rmdir as rmdir2,
|
|
283
|
+
writeFile as writeFile3
|
|
284
|
+
} from "fs/promises";
|
|
285
|
+
import path3 from "path";
|
|
286
|
+
import { isPathInside as isPathInside2 } from "@leitwerk-dev/session-transfer";
|
|
287
|
+
var OWNER_MARKER = ".leitwerk-transfer-owner";
|
|
288
|
+
var STALE_IMPORT_MS = 2 * 60 * 60 * 1e3;
|
|
289
|
+
async function readJson(file, fallback) {
|
|
290
|
+
try {
|
|
291
|
+
return JSON.parse(await readFile2(file, "utf8"));
|
|
292
|
+
} catch (error) {
|
|
293
|
+
if (error.code === "ENOENT") return fallback;
|
|
294
|
+
throw error;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
async function atomicJson(file, value, exclusive = false) {
|
|
298
|
+
await mkdir2(path3.dirname(file), { recursive: true, mode: 448 });
|
|
299
|
+
const temporary = `${file}.${randomUUID2()}.tmp`;
|
|
300
|
+
try {
|
|
301
|
+
await writeFile3(temporary, `${JSON.stringify(value, null, 2)}
|
|
302
|
+
`, { mode: 384, flag: "wx" });
|
|
303
|
+
if (exclusive) await linkFile(temporary, file);
|
|
304
|
+
else await rename3(temporary, file);
|
|
305
|
+
await chmod2(file, 384);
|
|
306
|
+
} finally {
|
|
307
|
+
await rm2(temporary, { force: true });
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
async function ownsDirectory(directory, ownerId, marker) {
|
|
311
|
+
try {
|
|
312
|
+
return (await lstat3(directory)).isDirectory() && (await readFile2(path3.join(directory, marker), "utf8")).trim() === ownerId;
|
|
313
|
+
} catch (error) {
|
|
314
|
+
if (error.code === "ENOENT") return false;
|
|
315
|
+
throw error;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
async function removeOwnedDirectory(directory, ownerId, marker) {
|
|
319
|
+
if (!await ownsDirectory(directory, ownerId, marker)) return;
|
|
320
|
+
for (const name of await readdir2(directory)) {
|
|
321
|
+
if (name !== marker) await rm2(path3.join(directory, name), { recursive: true, force: true });
|
|
322
|
+
}
|
|
323
|
+
await rm2(path3.join(directory, marker));
|
|
324
|
+
await rmdir2(directory);
|
|
325
|
+
}
|
|
326
|
+
function tokenHash(token) {
|
|
327
|
+
return createHash("sha256").update(token, "utf8").digest("hex");
|
|
328
|
+
}
|
|
329
|
+
function stateKey(link) {
|
|
330
|
+
return createHash("sha256").update(`${link.origin}\0${link.grantId}\0${tokenHash(link.token)}`).digest("hex");
|
|
331
|
+
}
|
|
332
|
+
function completedReceipt(record) {
|
|
333
|
+
if (record.phase !== "completed" || !record.destination || !record.sessionPath || !record.completedAt) {
|
|
334
|
+
return null;
|
|
335
|
+
}
|
|
336
|
+
return {
|
|
337
|
+
version: 1,
|
|
338
|
+
origin: record.origin,
|
|
339
|
+
grantId: record.grantId,
|
|
340
|
+
tokenHash: record.tokenHash,
|
|
341
|
+
attemptId: record.attemptId,
|
|
342
|
+
destination: record.destination,
|
|
343
|
+
sessionPath: record.sessionPath,
|
|
344
|
+
completedAt: record.completedAt
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
var LocalTransferState = class {
|
|
348
|
+
agentRoot;
|
|
349
|
+
recordsRoot;
|
|
350
|
+
stateTail = Promise.resolve();
|
|
351
|
+
constructor(agentDir) {
|
|
352
|
+
this.agentRoot = path3.resolve(agentDir);
|
|
353
|
+
this.recordsRoot = path3.join(this.agentRoot, "leitwerk-session-transfer", "transfers");
|
|
354
|
+
}
|
|
355
|
+
recordFile(link) {
|
|
356
|
+
return path3.join(this.recordsRoot, `${stateKey(link)}.json`);
|
|
357
|
+
}
|
|
358
|
+
async serialized(operation) {
|
|
359
|
+
const previous = this.stateTail;
|
|
360
|
+
let release;
|
|
361
|
+
this.stateTail = new Promise((resolve) => {
|
|
362
|
+
release = resolve;
|
|
363
|
+
});
|
|
364
|
+
await previous;
|
|
365
|
+
try {
|
|
366
|
+
return await operation();
|
|
367
|
+
} finally {
|
|
368
|
+
release();
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
markerName(ownerId) {
|
|
372
|
+
return ownerId ? `${OWNER_MARKER}-${ownerId}` : OWNER_MARKER;
|
|
373
|
+
}
|
|
374
|
+
async receipt(link) {
|
|
375
|
+
const record = await readJson(this.recordFile(link), null);
|
|
376
|
+
return record ? completedReceipt(record) : null;
|
|
377
|
+
}
|
|
378
|
+
async begin(link, input) {
|
|
379
|
+
await this.serialized(async () => {
|
|
380
|
+
try {
|
|
381
|
+
await atomicJson(
|
|
382
|
+
this.recordFile(link),
|
|
383
|
+
{
|
|
384
|
+
version: 1,
|
|
385
|
+
phase: "temporary",
|
|
386
|
+
origin: link.origin,
|
|
387
|
+
grantId: link.grantId,
|
|
388
|
+
tokenHash: tokenHash(link.token),
|
|
389
|
+
attemptId: input.attemptId,
|
|
390
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
391
|
+
temporaryDirectory: input.temporaryDirectory,
|
|
392
|
+
ownerId: input.ownerId
|
|
393
|
+
},
|
|
394
|
+
true
|
|
395
|
+
);
|
|
396
|
+
} catch (error) {
|
|
397
|
+
if (error.code === "EEXIST") {
|
|
398
|
+
throw new Error("A previous import for this link still has recovery state", {
|
|
399
|
+
cause: error
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
throw error;
|
|
403
|
+
}
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
async recordCommitTargets(link, targets) {
|
|
407
|
+
await this.serialized(async () => {
|
|
408
|
+
const file = this.recordFile(link);
|
|
409
|
+
const record = await readJson(file, null);
|
|
410
|
+
if (!record || record.phase === "completed") {
|
|
411
|
+
throw new Error("Transfer recovery state is missing or already complete");
|
|
412
|
+
}
|
|
413
|
+
await atomicJson(file, { ...record, ...targets, phase: "committing" });
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
async complete(link, input) {
|
|
417
|
+
return this.serialized(async () => {
|
|
418
|
+
const file = this.recordFile(link);
|
|
419
|
+
const record = await readJson(file, null);
|
|
420
|
+
if (!record) throw new Error("Transfer recovery state is missing");
|
|
421
|
+
const completed = { ...record, ...input, phase: "completed" };
|
|
422
|
+
await atomicJson(file, completed);
|
|
423
|
+
return completedReceipt(completed);
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
async discard(link) {
|
|
427
|
+
await this.serialized(async () => {
|
|
428
|
+
const file = this.recordFile(link);
|
|
429
|
+
const record = await readJson(file, null);
|
|
430
|
+
if (!record) return;
|
|
431
|
+
if (record.phase === "completed") throw new Error("Completed imports cannot be discarded");
|
|
432
|
+
if (record.destination && await ownsDirectory(record.destination, record.ownerId, this.markerName(record.ownerId))) {
|
|
433
|
+
throw new Error("A reserved import must retain its recovery state");
|
|
434
|
+
}
|
|
435
|
+
await removeOwnedDirectory(record.temporaryDirectory, record.ownerId, OWNER_MARKER);
|
|
436
|
+
await rm2(file, { force: true });
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
async reconcile() {
|
|
440
|
+
await this.serialized(async () => {
|
|
441
|
+
let names;
|
|
442
|
+
try {
|
|
443
|
+
names = await readdir2(this.recordsRoot);
|
|
444
|
+
} catch (error) {
|
|
445
|
+
if (error.code === "ENOENT") return;
|
|
446
|
+
throw error;
|
|
447
|
+
}
|
|
448
|
+
for (const name of names.filter((candidate) => candidate.endsWith(".json"))) {
|
|
449
|
+
const file = path3.join(this.recordsRoot, name);
|
|
450
|
+
try {
|
|
451
|
+
const record = await readJson(file, null);
|
|
452
|
+
if (!record) continue;
|
|
453
|
+
if (record.phase !== "completed" && Date.now() - Date.parse(record.createdAt) <= STALE_IMPORT_MS) {
|
|
454
|
+
continue;
|
|
455
|
+
}
|
|
456
|
+
const destinationMarker = this.markerName(record.ownerId);
|
|
457
|
+
const ownsDestination = record.destination ? await ownsDirectory(record.destination, record.ownerId, destinationMarker) : false;
|
|
458
|
+
if (record.phase === "completed") {
|
|
459
|
+
if (ownsDestination && record.destination) {
|
|
460
|
+
await rm2(path3.join(record.destination, destinationMarker), { force: true });
|
|
461
|
+
}
|
|
462
|
+
await removeOwnedDirectory(record.temporaryDirectory, record.ownerId, OWNER_MARKER);
|
|
463
|
+
continue;
|
|
464
|
+
}
|
|
465
|
+
if (ownsDestination && record.destination) {
|
|
466
|
+
await removeOwnedDirectory(record.destination, record.ownerId, destinationMarker);
|
|
467
|
+
}
|
|
468
|
+
if (record.sessionPath && isPathInside2(this.agentRoot, record.sessionPath)) {
|
|
469
|
+
await rm2(record.sessionPath, { force: true });
|
|
470
|
+
}
|
|
471
|
+
await removeOwnedDirectory(record.temporaryDirectory, record.ownerId, OWNER_MARKER);
|
|
472
|
+
await rm2(file, { force: true });
|
|
473
|
+
} catch {
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
};
|
|
479
|
+
|
|
480
|
+
// src/index.ts
|
|
481
|
+
function phaseLabel(phase) {
|
|
482
|
+
return {
|
|
483
|
+
queued: "Queued",
|
|
484
|
+
waiting_for_execution_chain: "Waiting for accepted work",
|
|
485
|
+
stopping_worker: "Stopping the idle worker",
|
|
486
|
+
starting_exporter: "Starting the read-only exporter",
|
|
487
|
+
scanning: "Checking portable files",
|
|
488
|
+
ready_to_stream: "Ready to stream",
|
|
489
|
+
streaming: "Copying workspace and session",
|
|
490
|
+
validating_local: "Validating local import",
|
|
491
|
+
finishing_import: "Finishing import\u2026"
|
|
492
|
+
}[phase] ?? phase.replaceAll("_", " ");
|
|
493
|
+
}
|
|
494
|
+
function percentage(progress) {
|
|
495
|
+
if (progress.logicalBytesTotal && progress.logicalBytesTotal > 0) {
|
|
496
|
+
return Math.min(
|
|
497
|
+
100,
|
|
498
|
+
Math.floor(progress.logicalBytesProcessed / progress.logicalBytesTotal * 100)
|
|
499
|
+
);
|
|
500
|
+
}
|
|
501
|
+
if (progress.entriesTotal && progress.entriesTotal > 0) {
|
|
502
|
+
return Math.min(100, Math.floor(progress.entriesProcessed / progress.entriesTotal * 100));
|
|
503
|
+
}
|
|
504
|
+
return null;
|
|
505
|
+
}
|
|
506
|
+
function progressMessage(progress) {
|
|
507
|
+
const percent = percentage(progress);
|
|
508
|
+
const files = `${progress.entriesProcessed}${progress.entriesTotal === null ? "" : ` / ${progress.entriesTotal}`} files`;
|
|
509
|
+
const logical = `${formatSize(progress.logicalBytesProcessed)}${progress.logicalBytesTotal === null ? "" : ` / ${formatSize(progress.logicalBytesTotal)}`} expanded`;
|
|
510
|
+
const received = `${formatSize(progress.compressedBytes)} received`;
|
|
511
|
+
return `${phaseLabel(progress.phase)} \xB7 ${percent === null ? "" : `${percent}% \xB7 `}${files} \xB7 ${logical} \xB7 ${received}`;
|
|
512
|
+
}
|
|
513
|
+
async function switchImportedSession(ctx, link, imported) {
|
|
514
|
+
const retryAcknowledgement = (activeCtx) => {
|
|
515
|
+
void new SessionTransferClient(link).acknowledge(imported.attemptId, AbortSignal.timeout(3e4)).catch(() => {
|
|
516
|
+
try {
|
|
517
|
+
activeCtx.ui.notify(
|
|
518
|
+
"The local import is complete. Leitwerk acknowledgement is still pending; use the same link to retry it.",
|
|
519
|
+
"warning"
|
|
520
|
+
);
|
|
521
|
+
} catch {
|
|
522
|
+
}
|
|
523
|
+
});
|
|
524
|
+
};
|
|
525
|
+
const switched = await ctx.switchSession(imported.sessionPath, {
|
|
526
|
+
withSession: async (replacementCtx) => {
|
|
527
|
+
replacementCtx.ui.notify(
|
|
528
|
+
"Leitwerk process imported. Local Pi tools and resources are active.",
|
|
529
|
+
"info"
|
|
530
|
+
);
|
|
531
|
+
retryAcknowledgement(replacementCtx);
|
|
532
|
+
}
|
|
533
|
+
});
|
|
534
|
+
if (switched.cancelled) {
|
|
535
|
+
ctx.ui.notify(
|
|
536
|
+
`Import complete. Session switch was cancelled; open it with /resume: ${imported.sessionPath}`,
|
|
537
|
+
"info"
|
|
538
|
+
);
|
|
539
|
+
retryAcknowledgement(ctx);
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
async function leitwerkSessionTransfer(pi) {
|
|
543
|
+
const state = new LocalTransferState(getAgentDir());
|
|
544
|
+
await state.reconcile();
|
|
545
|
+
pi.registerCommand("leitwerk-transfer", {
|
|
546
|
+
description: "Import a Leitwerk process workspace and Pi session",
|
|
547
|
+
handler: async (args, ctx) => {
|
|
548
|
+
if (ctx.mode !== "tui") {
|
|
549
|
+
ctx.ui.notify("/leitwerk-transfer is available only in interactive TUI mode", "error");
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
const rawLink = args.trim() || await ctx.ui.input(
|
|
553
|
+
"Leitwerk transfer link",
|
|
554
|
+
"https://leitwerk.example/api/session-transfers/\u2026#token=\u2026"
|
|
555
|
+
);
|
|
556
|
+
if (!rawLink) return;
|
|
557
|
+
let link;
|
|
558
|
+
try {
|
|
559
|
+
link = parseTransferLink(rawLink);
|
|
560
|
+
} catch (error) {
|
|
561
|
+
ctx.ui.notify(error instanceof Error ? error.message : "Invalid transfer link", "error");
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
const originWarning = `${link.origin} will receive the bearer credential and stream files into this Pi process. Continue only if you recognize it.`;
|
|
565
|
+
const receipt = await state.receipt(link);
|
|
566
|
+
if (receipt) {
|
|
567
|
+
if (!await ctx.ui.confirm(
|
|
568
|
+
"Import already complete",
|
|
569
|
+
`Use the imported session at ${receipt.sessionPath}? ${originWarning}`
|
|
570
|
+
)) {
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
await switchImportedSession(ctx, link, receipt);
|
|
574
|
+
return;
|
|
575
|
+
}
|
|
576
|
+
const defaultDestination = path4.join(ctx.cwd, link.instanceId);
|
|
577
|
+
const selectedDestination = await ctx.ui.input(
|
|
578
|
+
"New destination directory",
|
|
579
|
+
defaultDestination
|
|
580
|
+
);
|
|
581
|
+
if (!selectedDestination) return;
|
|
582
|
+
const destination = path4.resolve(ctx.cwd, selectedDestination);
|
|
583
|
+
await ctx.waitForIdle();
|
|
584
|
+
if (!await ctx.ui.confirm(
|
|
585
|
+
"Import Leitwerk process?",
|
|
586
|
+
`Create ${destination}, copy the retained workspace, and import its Pi conversation? ${originWarning}`
|
|
587
|
+
))
|
|
588
|
+
return;
|
|
589
|
+
let finishing = false;
|
|
590
|
+
const outcome = await ctx.ui.custom(
|
|
591
|
+
(tui, theme, _keybindings, done) => {
|
|
592
|
+
const loader = new CancellableLoader(
|
|
593
|
+
tui,
|
|
594
|
+
(s) => theme.fg("accent", s),
|
|
595
|
+
(s) => theme.fg("muted", s),
|
|
596
|
+
"Starting transfer\u2026"
|
|
597
|
+
);
|
|
598
|
+
loader.onAbort = () => {
|
|
599
|
+
if (!finishing) loader.setMessage("Cancelling transfer\u2026");
|
|
600
|
+
};
|
|
601
|
+
void importTransfer({
|
|
602
|
+
link,
|
|
603
|
+
destination,
|
|
604
|
+
state,
|
|
605
|
+
signal: loader.signal,
|
|
606
|
+
onProgress(progress) {
|
|
607
|
+
finishing = progress.finishing;
|
|
608
|
+
loader.setMessage(progressMessage(progress));
|
|
609
|
+
}
|
|
610
|
+
}).then(
|
|
611
|
+
(result) => done(result),
|
|
612
|
+
(error) => done(
|
|
613
|
+
loader.aborted && !finishing ? null : error instanceof Error ? error : new Error("Transfer failed")
|
|
614
|
+
)
|
|
615
|
+
);
|
|
616
|
+
return loader;
|
|
617
|
+
}
|
|
618
|
+
);
|
|
619
|
+
if (!outcome) {
|
|
620
|
+
ctx.ui.notify(
|
|
621
|
+
"Transfer cancelled. The link can be retried while it remains valid.",
|
|
622
|
+
"info"
|
|
623
|
+
);
|
|
624
|
+
return;
|
|
625
|
+
}
|
|
626
|
+
if (outcome instanceof Error) {
|
|
627
|
+
ctx.ui.notify(outcome.message, "error");
|
|
628
|
+
return;
|
|
629
|
+
}
|
|
630
|
+
await switchImportedSession(ctx, link, outcome);
|
|
631
|
+
}
|
|
632
|
+
});
|
|
633
|
+
}
|
|
634
|
+
export {
|
|
635
|
+
leitwerkSessionTransfer as default
|
|
636
|
+
};
|
|
637
|
+
//# sourceMappingURL=index.js.map
|