@narumitw/pi-sync 0.60.2 → 0.60.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/README.md +4 -0
- package/dist/chunks/{chunk-B53FS4RW.ts → chunk-IGDI5CIH.ts} +2 -2
- package/dist/chunks/{chunk-ENFHHB5O.ts → chunk-OVCP2SOB.ts} +42 -6
- package/dist/chunks/chunk-OVCP2SOB.ts.map +7 -0
- package/dist/chunks/{chunk-E7UJHMNW.ts → chunk-RJZIKZI3.ts} +2 -2
- package/dist/chunks/{chunk-3YXBG7BQ.ts → chunk-SE7HHBKH.ts} +2 -2
- package/dist/chunks/{chunk-FOMZEZER.ts → chunk-VQRDL3SY.ts} +227 -54
- package/dist/chunks/chunk-VQRDL3SY.ts.map +7 -0
- package/dist/chunks/{command-handler-RTBEFZUX.ts → command-handler-TMH4US44.ts} +10 -8
- package/dist/chunks/command-handler-TMH4US44.ts.map +7 -0
- package/dist/chunks/{conflict-review-YXROU42F.ts → conflict-review-QGUCODDH.ts} +3 -3
- package/dist/chunks/{manager-result-dispatcher-4PEUHK7F.ts → manager-result-dispatcher-YVVD44QD.ts} +4 -4
- package/dist/chunks/{manager-ui-TNAMQNEU.ts → manager-ui-Q54OHOPR.ts} +8 -8
- package/dist/chunks/{remote-selection-ui-47H7V62F.ts → remote-selection-ui-ODSUHX5N.ts} +3 -3
- package/dist/chunks/{sync-inspection-5GQEB62G.ts → sync-inspection-ECUTWISE.ts} +3 -3
- package/dist/chunks/{sync-operations-65HDA67O.ts → sync-operations-REXODWZB.ts} +3 -3
- package/dist/index.ts +58 -39
- package/dist/index.ts.map +3 -3
- package/docs/agent-mode-verification.md +1 -1
- package/docs/agent-quality-verification.md +1 -1
- package/docs/continuous-sync-verification.md +1 -1
- package/docs/daemon-migration.md +82 -6
- package/docs/tui-contract.md +7 -1
- package/package.json +3 -3
- package/skills/configure-pi-sync/references/configuration.md +1 -0
- package/src/commands/command-execution.ts +1 -1
- package/src/commands/command-handler.ts +2 -0
- package/src/daemon/pi-client.ts +240 -51
- package/src/sync-extension.ts +62 -41
- package/src/ui/sync-status.ts +47 -4
- package/dist/chunks/chunk-ENFHHB5O.ts.map +0 -7
- package/dist/chunks/chunk-FOMZEZER.ts.map +0 -7
- package/dist/chunks/command-handler-RTBEFZUX.ts.map +0 -7
- package/docs/settings.md +0 -90
- /package/dist/chunks/{chunk-B53FS4RW.ts.map → chunk-IGDI5CIH.ts.map} +0 -0
- /package/dist/chunks/{chunk-E7UJHMNW.ts.map → chunk-RJZIKZI3.ts.map} +0 -0
- /package/dist/chunks/{chunk-3YXBG7BQ.ts.map → chunk-SE7HHBKH.ts.map} +0 -0
- /package/dist/chunks/{conflict-review-YXROU42F.ts.map → conflict-review-QGUCODDH.ts.map} +0 -0
- /package/dist/chunks/{manager-result-dispatcher-4PEUHK7F.ts.map → manager-result-dispatcher-YVVD44QD.ts.map} +0 -0
- /package/dist/chunks/{manager-ui-TNAMQNEU.ts.map → manager-ui-Q54OHOPR.ts.map} +0 -0
- /package/dist/chunks/{remote-selection-ui-47H7V62F.ts.map → remote-selection-ui-ODSUHX5N.ts.map} +0 -0
- /package/dist/chunks/{sync-inspection-5GQEB62G.ts.map → sync-inspection-ECUTWISE.ts.map} +0 -0
- /package/dist/chunks/{sync-operations-65HDA67O.ts.map → sync-operations-REXODWZB.ts.map} +0 -0
package/src/daemon/pi-client.ts
CHANGED
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
type Callback,
|
|
9
9
|
type ClientFacts,
|
|
10
10
|
type ClientHandoff,
|
|
11
|
+
type ContactState,
|
|
11
12
|
DaemonConnection,
|
|
12
13
|
DaemonError,
|
|
13
14
|
type DocumentView,
|
|
@@ -27,26 +28,28 @@ import { validateSettingsDocument } from "@narumitw/pi-sync-daemon/engine/settin
|
|
|
27
28
|
import { sessionDirFromContext } from "@narumitw/pi-sync-daemon/engine/snapshot/session-paths";
|
|
28
29
|
import type { CommandOptions } from "../commands/command-types.js";
|
|
29
30
|
import type { StartupTimingPublisher } from "../sync/startup-timings.js";
|
|
30
|
-
import { SyncDecisionRequiredError } from "../sync/sync-errors.js";
|
|
31
|
+
import { errorMessage, SyncDecisionRequiredError } from "../sync/sync-errors.js";
|
|
31
32
|
import { RemoteSelectionMismatchError } from "../sync/sync-policy.js";
|
|
32
|
-
import { type SyncStatusPresentation, setSyncStatus } from "../ui/sync-status.js";
|
|
33
|
+
import { type SyncStatusPresentation, setSyncStatus, showSyncConnectionStatus } from "../ui/sync-status.js";
|
|
33
34
|
import { safeTerminalText } from "../ui/terminal-text.js";
|
|
34
35
|
import { PiApplyGate } from "./apply-gate.js";
|
|
35
36
|
import { quarantineClient, recoverDetachedClients } from "./recovery.js";
|
|
36
37
|
|
|
37
|
-
const scope = new AsyncLocalStorage<PiDaemonClient>();
|
|
38
|
+
const scope = new AsyncLocalStorage<{ client: PiDaemonClient; reload?: AbortController }>();
|
|
38
39
|
const clients = new WeakMap<ExtensionContext["sessionManager"], PiDaemonClient>();
|
|
39
40
|
export function currentPiDaemonClient() {
|
|
40
41
|
return current();
|
|
41
42
|
}
|
|
42
43
|
function current() {
|
|
43
|
-
const client = scope.getStore();
|
|
44
|
+
const client = scope.getStore()?.client;
|
|
44
45
|
if (!client) throw new Error("Pi synchronization requires a current session-bound daemon client.");
|
|
45
46
|
client.validate();
|
|
46
47
|
return client;
|
|
47
48
|
}
|
|
48
49
|
function canonicalPath(value: string | undefined): string | undefined {
|
|
49
|
-
|
|
50
|
+
// An in-memory session (`pi --no-session`) reports an empty session dir instead of
|
|
51
|
+
// omitting it, so an empty path means "no path to publish", not a broken caller.
|
|
52
|
+
if (value === undefined || value === "") return undefined;
|
|
50
53
|
if (!path.isAbsolute(value)) throw new Error("Pi session paths must be absolute.");
|
|
51
54
|
const parts: string[] = [];
|
|
52
55
|
let cursor = path.resolve(value);
|
|
@@ -123,7 +126,7 @@ const authority: ConfigAuthority = {
|
|
|
123
126
|
/** Factory registration installs only adapters; it starts no process and performs no I/O. */
|
|
124
127
|
export function installPiDaemonHost() {
|
|
125
128
|
configureEngineHost({
|
|
126
|
-
root: () => scope.getStore()?.root ?? path.resolve(getAgentDir()),
|
|
129
|
+
root: () => scope.getStore()?.client.root ?? path.resolve(getAgentDir()),
|
|
127
130
|
config: authority,
|
|
128
131
|
mutate: async () => {
|
|
129
132
|
throw new Error("File mutation belongs to pi-sync-daemon; no in-process fallback is permitted.");
|
|
@@ -147,8 +150,9 @@ export function piDaemonClient(ctx: ExtensionContext) {
|
|
|
147
150
|
export function withPiDaemonClient<Context extends ExtensionContext, T>(
|
|
148
151
|
ctx: Context,
|
|
149
152
|
action: (owned: Context) => Promise<T>,
|
|
153
|
+
reload?: AbortController,
|
|
150
154
|
) {
|
|
151
|
-
const
|
|
155
|
+
const owner = { client: piDaemonClient(ctx), reload };
|
|
152
156
|
// TUI input arrives from Pi's event loop, outside the command's async call tree.
|
|
153
157
|
// Bind public component methods so later menu actions retain this exact owner,
|
|
154
158
|
// never a replacement session selected through a global fallback.
|
|
@@ -165,14 +169,14 @@ export function withPiDaemonClient<Context extends ExtensionContext, T>(
|
|
|
165
169
|
if (typeof value !== "function") return value;
|
|
166
170
|
const saved = methods.get(key);
|
|
167
171
|
if (saved?.source === value) return saved.bound;
|
|
168
|
-
const bound = (...values: unknown[]) => scope.run(
|
|
172
|
+
const bound = (...values: unknown[]) => scope.run(owner, () => Reflect.apply(value, original, values));
|
|
169
173
|
methods.set(key, { source: value, bound });
|
|
170
174
|
return bound;
|
|
171
175
|
},
|
|
172
176
|
});
|
|
173
177
|
};
|
|
174
178
|
const invoke = (...provided: Parameters<typeof factory>) => {
|
|
175
|
-
const component = scope.run(
|
|
179
|
+
const component = scope.run(owner, () => factory(...provided));
|
|
176
180
|
return component instanceof Promise ? component.then(wrap) : wrap(component);
|
|
177
181
|
};
|
|
178
182
|
// Do not turn synchronous editors/reviews into asynchronous factories.
|
|
@@ -188,11 +192,14 @@ export function withPiDaemonClient<Context extends ExtensionContext, T>(
|
|
|
188
192
|
return key === "ui" ? ui : Reflect.get(target, key, target);
|
|
189
193
|
},
|
|
190
194
|
});
|
|
191
|
-
return scope.run(
|
|
195
|
+
return scope.run(owner, () => action(owned));
|
|
192
196
|
}
|
|
193
197
|
export async function remoteOperation(ctx: ExtensionContext, operation: string, options: CommandOptions) {
|
|
194
198
|
const client = piDaemonClient(ctx);
|
|
195
199
|
const { signal, onCommit, args, setup } = options;
|
|
200
|
+
const owner = scope.getStore();
|
|
201
|
+
const reload = options.reload && owner?.client === client ? owner.reload : undefined;
|
|
202
|
+
reload?.signal.throwIfAborted();
|
|
196
203
|
const payload = {
|
|
197
204
|
args,
|
|
198
205
|
...(setup === undefined ? {} : { setup }),
|
|
@@ -200,23 +207,33 @@ export async function remoteOperation(ctx: ExtensionContext, operation: string,
|
|
|
200
207
|
force: options.force,
|
|
201
208
|
stale: options.stale,
|
|
202
209
|
silent: options.silent,
|
|
203
|
-
reload:
|
|
210
|
+
reload: reload !== undefined,
|
|
204
211
|
...(options.agentRetryRefusal ? { agentRetryRefusal: true } : {}),
|
|
205
212
|
};
|
|
206
|
-
return client.run(operation, payload, signal, ctx, onCommit);
|
|
213
|
+
return client.run(operation, payload, signal, ctx, onCommit, reload);
|
|
214
|
+
}
|
|
215
|
+
function remoteErrorNamed(error: unknown, name: string) {
|
|
216
|
+
return error instanceof DaemonError && error.remote.name === name;
|
|
207
217
|
}
|
|
218
|
+
|
|
208
219
|
export class PiDaemonClient {
|
|
209
220
|
private connection?: DaemonConnection;
|
|
221
|
+
private protectionOnly = false;
|
|
210
222
|
private partialConnection?: DaemonConnection;
|
|
211
223
|
private work = Promise.resolve();
|
|
212
224
|
private closing = false;
|
|
213
225
|
private paused = false;
|
|
214
226
|
private pausing?: Promise<void>;
|
|
215
227
|
private connecting?: Promise<DaemonConnection>;
|
|
228
|
+
private contactRepair?: { controller: AbortController; done: Promise<void> };
|
|
229
|
+
private contactAttempt?: { error?: unknown };
|
|
230
|
+
private contactFactsUnpublished = false;
|
|
231
|
+
private clearContactStatus?: (redraw?: boolean) => void;
|
|
216
232
|
private disposed = false;
|
|
217
233
|
private disposing?: Promise<void>;
|
|
218
234
|
private uiContext: ExtensionContext;
|
|
219
|
-
private
|
|
235
|
+
private reloadRequest?: { received: boolean };
|
|
236
|
+
private pendingReload?: AbortController;
|
|
220
237
|
private readonly busy = new Set<string>();
|
|
221
238
|
private initialized = false;
|
|
222
239
|
private startupDebug = false;
|
|
@@ -268,7 +285,7 @@ export class PiDaemonClient {
|
|
|
268
285
|
return undefined;
|
|
269
286
|
return { provider: model.provider, id: model.id, signature: modelSignature(model), authSource: source };
|
|
270
287
|
}
|
|
271
|
-
private facts(): ClientFacts {
|
|
288
|
+
private facts(protectionOnly = this.protectionOnly): ClientFacts {
|
|
272
289
|
const manager = this.ctx.sessionManager;
|
|
273
290
|
return {
|
|
274
291
|
id: this.id,
|
|
@@ -276,14 +293,14 @@ export class PiDaemonClient {
|
|
|
276
293
|
pid: process.pid,
|
|
277
294
|
cwd: this.ctx.cwd,
|
|
278
295
|
mode: this.ctx.mode,
|
|
279
|
-
hasUI: this.ctx.hasUI,
|
|
280
|
-
idle: !this.paused && !this.busy.size && this.ctx.isIdle(),
|
|
281
|
-
ready: this.initialized,
|
|
296
|
+
hasUI: !protectionOnly && this.ctx.hasUI,
|
|
297
|
+
idle: !protectionOnly && !this.paused && !this.busy.size && this.ctx.isIdle(),
|
|
298
|
+
ready: !protectionOnly && this.initialized,
|
|
282
299
|
startupDebug: this.startupDebug,
|
|
283
300
|
sessionFile: canonicalPath(manager.getSessionFile?.()),
|
|
284
301
|
sessionId: manager.getSessionId?.(),
|
|
285
302
|
sessionDir: canonicalPath(sessionDirFromContext(this.ctx)),
|
|
286
|
-
model: this.modelBinding(),
|
|
303
|
+
model: protectionOnly ? undefined : this.modelBinding(),
|
|
287
304
|
};
|
|
288
305
|
}
|
|
289
306
|
async configured() {
|
|
@@ -297,6 +314,7 @@ export class PiDaemonClient {
|
|
|
297
314
|
async pauseForSessionChange() {
|
|
298
315
|
this.validate();
|
|
299
316
|
this.paused = true;
|
|
317
|
+
this.stopContactRepair(true);
|
|
300
318
|
this.gate.cancelPending();
|
|
301
319
|
this.pausing ??= (async () => {
|
|
302
320
|
const connection = this.connection ?? this.partialConnection ?? (await this.connecting?.catch(() => undefined));
|
|
@@ -307,21 +325,40 @@ export class PiDaemonClient {
|
|
|
307
325
|
})();
|
|
308
326
|
return this.pausing;
|
|
309
327
|
}
|
|
310
|
-
async attachExisting() {
|
|
328
|
+
async attachExisting({ allowUpgrade = false } = {}) {
|
|
311
329
|
this.validate();
|
|
312
330
|
const address = await findDaemon(this.root);
|
|
313
331
|
this.validate();
|
|
314
|
-
if (address)
|
|
332
|
+
if (!address) return false;
|
|
333
|
+
const upgrade = allowUpgrade && address.needsUpgrade && this.ctx.hasUI && ["tui", "rpc"].includes(this.ctx.mode);
|
|
334
|
+
let upgradeFailure: string | undefined;
|
|
335
|
+
if (upgrade) {
|
|
315
336
|
try {
|
|
316
|
-
await this.connect(
|
|
337
|
+
await this.connect();
|
|
338
|
+
this.validate();
|
|
339
|
+
return true;
|
|
317
340
|
} catch (error) {
|
|
318
341
|
this.validate();
|
|
319
|
-
if (
|
|
320
|
-
|
|
342
|
+
if (this.paused) throw error;
|
|
343
|
+
upgradeFailure = safeTerminalText(errorMessage(error));
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
try {
|
|
347
|
+
// If upgrade failed, try only the original owner, with its protection-only facts.
|
|
348
|
+
await this.connect(address);
|
|
349
|
+
} catch (error) {
|
|
350
|
+
this.validate();
|
|
351
|
+
if (remoteErrorNamed(error, "DaemonStoppingError")) return false;
|
|
352
|
+
throw error;
|
|
353
|
+
} finally {
|
|
354
|
+
if (upgradeFailure !== undefined) {
|
|
355
|
+
this.validate();
|
|
356
|
+
this.ctx.ui.notify(`pi-sync daemon upgrade failed: ${upgradeFailure}`, "error");
|
|
321
357
|
}
|
|
322
358
|
}
|
|
323
359
|
this.validate();
|
|
324
|
-
|
|
360
|
+
// Headless, shutdown, and failed-upgrade paths must not schedule transfers on an older build.
|
|
361
|
+
return !this.protectionOnly;
|
|
325
362
|
}
|
|
326
363
|
async finishReattachment() {
|
|
327
364
|
this.validate();
|
|
@@ -339,7 +376,13 @@ export class PiDaemonClient {
|
|
|
339
376
|
startupSignal.throwIfAborted();
|
|
340
377
|
};
|
|
341
378
|
validateStartup();
|
|
342
|
-
if (this.connection)
|
|
379
|
+
if (this.connection) {
|
|
380
|
+
if (!existing && this.protectionOnly)
|
|
381
|
+
throw new Error(
|
|
382
|
+
"This session is only protecting its files on an older Pi Sync daemon. Use /reload to upgrade.",
|
|
383
|
+
);
|
|
384
|
+
return this.connection;
|
|
385
|
+
}
|
|
343
386
|
this.connecting ??= (async () => {
|
|
344
387
|
if (this.partialConnection) {
|
|
345
388
|
// A failed unpublished attempt may already be retired or own queue grants.
|
|
@@ -360,21 +403,23 @@ export class PiDaemonClient {
|
|
|
360
403
|
const daemon = existing ?? (await ensureDaemon(this.root, startupSignal));
|
|
361
404
|
validateStartup();
|
|
362
405
|
if (daemon.paths.root !== this.root) throw new Error("Daemon root changed before attach.");
|
|
363
|
-
const
|
|
364
|
-
|
|
406
|
+
const protectionOnly = daemon.needsUpgrade === true;
|
|
407
|
+
const connection = new DaemonConnection(daemon.paths, daemon.identity, this.facts(protectionOnly), {
|
|
408
|
+
callback: (callback, signal) => this.callback(callback, signal, protectionOnly),
|
|
365
409
|
event: (event) => {
|
|
366
410
|
if (event.kind === "commit") return;
|
|
367
411
|
if (this.signal.aborted || this.disposed || this.closing || clients.get(this.manager) !== this) return;
|
|
368
412
|
const payload = event.payload as {
|
|
369
413
|
message?: string;
|
|
370
414
|
level?: "info" | "warning" | "error";
|
|
415
|
+
report?: string;
|
|
371
416
|
value?: string;
|
|
372
417
|
presentation?: SyncStatusPresentation;
|
|
373
418
|
};
|
|
374
419
|
if (event.kind === "notify" && typeof payload?.message === "string")
|
|
375
420
|
this.uiContext.ui.notify(safeTerminalText(payload.message), payload.level ?? "info");
|
|
376
|
-
if (event.kind === "timings" && typeof
|
|
377
|
-
this.publish?.(this.ctx,
|
|
421
|
+
if (event.kind === "timings" && typeof payload?.report === "string") {
|
|
422
|
+
this.publish?.(this.ctx, payload.report.split("\n").map(safeTerminalText).join("\n"));
|
|
378
423
|
}
|
|
379
424
|
if (event.kind === "status")
|
|
380
425
|
setSyncStatus(
|
|
@@ -383,9 +428,9 @@ export class PiDaemonClient {
|
|
|
383
428
|
payload.presentation,
|
|
384
429
|
);
|
|
385
430
|
},
|
|
431
|
+
contact: (state) => this.observeContact(connection, state),
|
|
386
432
|
error: () => {
|
|
387
|
-
if (
|
|
388
|
-
setSyncStatus(this.ctx, "sync service unavailable", { activity: "blocked", reason: "repair" });
|
|
433
|
+
if (this.ownsContactUI()) this.showContactStatus("sync service unavailable", "blocked");
|
|
389
434
|
},
|
|
390
435
|
});
|
|
391
436
|
this.partialConnection = connection;
|
|
@@ -411,6 +456,7 @@ export class PiDaemonClient {
|
|
|
411
456
|
}
|
|
412
457
|
this.validate();
|
|
413
458
|
this.connection = connection;
|
|
459
|
+
this.protectionOnly = protectionOnly;
|
|
414
460
|
this.partialConnection = undefined;
|
|
415
461
|
return connection;
|
|
416
462
|
}
|
|
@@ -418,7 +464,125 @@ export class PiDaemonClient {
|
|
|
418
464
|
this.connecting = undefined;
|
|
419
465
|
throw error;
|
|
420
466
|
});
|
|
421
|
-
|
|
467
|
+
const connection = await this.connecting;
|
|
468
|
+
validateStartup();
|
|
469
|
+
if (!existing && this.protectionOnly)
|
|
470
|
+
throw new Error("This session is only protecting its files on an older Pi Sync daemon. Use /reload to upgrade.");
|
|
471
|
+
return connection;
|
|
472
|
+
}
|
|
473
|
+
private ownsContactUI() {
|
|
474
|
+
return (
|
|
475
|
+
!this.signal.aborted && !this.disposed && !this.closing && !this.paused && clients.get(this.manager) === this
|
|
476
|
+
);
|
|
477
|
+
}
|
|
478
|
+
private showContactStatus(text: string, activity: "retry" | "blocked") {
|
|
479
|
+
const previous = this.clearContactStatus;
|
|
480
|
+
this.clearContactStatus = showSyncConnectionStatus(this.ctx, text, {
|
|
481
|
+
activity,
|
|
482
|
+
reason: activity === "retry" ? "temp" : "repair",
|
|
483
|
+
});
|
|
484
|
+
previous?.();
|
|
485
|
+
}
|
|
486
|
+
private stopContactRepair(redraw: boolean) {
|
|
487
|
+
this.contactRepair?.controller.abort(new DOMException("Pi session is changing", "AbortError"));
|
|
488
|
+
this.clearContactStatus?.(redraw);
|
|
489
|
+
this.clearContactStatus = undefined;
|
|
490
|
+
}
|
|
491
|
+
private observeContact(connection: DaemonConnection, state: ContactState) {
|
|
492
|
+
if (connection !== this.connection || !this.ownsContactUI()) return;
|
|
493
|
+
if (state === "active") {
|
|
494
|
+
if (this.contactRepair || this.contactFactsUnpublished || connection.contactResumeState === "uncertain") return;
|
|
495
|
+
this.clearRestoredContact();
|
|
496
|
+
} else if (state === "expired" && connection.facts.hasUI && !this.contactAttempt && !this.contactRepair) {
|
|
497
|
+
if (this.gate.size || connection.hasPendingWork) return;
|
|
498
|
+
void this.resumeContact(connection).catch(() => {
|
|
499
|
+
// The owning repair updates the status; a later command reports the error.
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
private clearRestoredContact() {
|
|
504
|
+
this.contactAttempt = undefined;
|
|
505
|
+
this.contactFactsUnpublished = false;
|
|
506
|
+
this.clearContactStatus?.();
|
|
507
|
+
this.clearContactStatus = undefined;
|
|
508
|
+
}
|
|
509
|
+
private async resumeContact(connection: DaemonConnection) {
|
|
510
|
+
this.validate();
|
|
511
|
+
if (this.paused || this.connection !== connection) throw new Error("Pi Sync is paused for a session change.");
|
|
512
|
+
if (this.contactRepair) return this.contactRepair.done;
|
|
513
|
+
if (connection.contactState === "active" && connection.contactResumeState !== "uncertain") return;
|
|
514
|
+
if (this.gate.size || connection.hasPendingWork || connection.contactResumeState === "uncertain") {
|
|
515
|
+
throw new Error(
|
|
516
|
+
"Pi Sync cannot reconnect while previous work is still running or uncertain. Check sync recovery before retrying.",
|
|
517
|
+
);
|
|
518
|
+
}
|
|
519
|
+
const earlier = this.contactAttempt;
|
|
520
|
+
if (connection.contactState !== "expired" || earlier) {
|
|
521
|
+
throw new Error("Pi Sync could not restore contact. Review pending work before using /reload.", {
|
|
522
|
+
cause: earlier?.error,
|
|
523
|
+
});
|
|
524
|
+
}
|
|
525
|
+
const controller = new AbortController();
|
|
526
|
+
const signal = AbortSignal.any([this.signal, controller.signal]);
|
|
527
|
+
const attempt: { error?: unknown } = {};
|
|
528
|
+
this.contactAttempt = attempt;
|
|
529
|
+
const done = Promise.resolve().then(async () => {
|
|
530
|
+
try {
|
|
531
|
+
this.validate();
|
|
532
|
+
signal.throwIfAborted();
|
|
533
|
+
this.showContactStatus("sync reconnecting", "retry");
|
|
534
|
+
// Admission can wait behind an apply. Do not advertise readiness using
|
|
535
|
+
// facts sampled before that wait; publish current facts after the ack.
|
|
536
|
+
await connection.resumeContact({ ...this.facts(), idle: false, ready: false }, signal);
|
|
537
|
+
this.validate();
|
|
538
|
+
signal.throwIfAborted();
|
|
539
|
+
this.contactFactsUnpublished = true;
|
|
540
|
+
this.contactAttempt = undefined;
|
|
541
|
+
await connection.update(this.facts());
|
|
542
|
+
this.validate();
|
|
543
|
+
signal.throwIfAborted();
|
|
544
|
+
this.confirmContact(connection);
|
|
545
|
+
} catch (error) {
|
|
546
|
+
attempt.error = error;
|
|
547
|
+
if (this.ownsContactUI() && !signal.aborted)
|
|
548
|
+
this.showContactStatus("sync reconnect blocked; check /sync daemon status", "blocked");
|
|
549
|
+
throw error;
|
|
550
|
+
} finally {
|
|
551
|
+
if (this.contactRepair?.controller === controller) this.contactRepair = undefined;
|
|
552
|
+
}
|
|
553
|
+
});
|
|
554
|
+
this.contactRepair = { controller, done };
|
|
555
|
+
return done;
|
|
556
|
+
}
|
|
557
|
+
private async publishFacts(connection: DaemonConnection) {
|
|
558
|
+
if (this.contactRepair) await this.contactRepair.done;
|
|
559
|
+
this.validate();
|
|
560
|
+
if (this.paused) throw new Error("Pi Sync is paused for a session change.");
|
|
561
|
+
if (connection.contactResumeState === "uncertain")
|
|
562
|
+
throw new Error("Pi Sync cannot verify the previous reconnect. Review pending work before using /reload.");
|
|
563
|
+
try {
|
|
564
|
+
await connection.update(this.facts());
|
|
565
|
+
} catch (error) {
|
|
566
|
+
if (!connection.facts.hasUI || !remoteErrorNamed(error, "ClientContactExpiredError")) throw error;
|
|
567
|
+
await this.resumeContact(connection);
|
|
568
|
+
this.validate();
|
|
569
|
+
// A shared repair might have started before these facts changed.
|
|
570
|
+
await connection.update(this.facts());
|
|
571
|
+
}
|
|
572
|
+
this.validate();
|
|
573
|
+
this.confirmContact(connection);
|
|
574
|
+
}
|
|
575
|
+
private confirmContact(connection: DaemonConnection) {
|
|
576
|
+
if (connection.contactState === "expired" || connection.contactState === "inactive")
|
|
577
|
+
throw new Error("Pi Sync did not confirm active participation in the daemon.");
|
|
578
|
+
this.clearRestoredContact();
|
|
579
|
+
}
|
|
580
|
+
async verifyConnection(signal?: AbortSignal) {
|
|
581
|
+
const connection = await this.connect(undefined, signal);
|
|
582
|
+
signal?.throwIfAborted();
|
|
583
|
+
await this.publishFacts(connection);
|
|
584
|
+
signal?.throwIfAborted();
|
|
585
|
+
return connection;
|
|
422
586
|
}
|
|
423
587
|
async readSettings(repair = false) {
|
|
424
588
|
this.validate();
|
|
@@ -432,8 +596,15 @@ export class PiDaemonClient {
|
|
|
432
596
|
}
|
|
433
597
|
return decode(await this.run(repair ? "settings.repair-read" : "settings.read", {}));
|
|
434
598
|
}
|
|
435
|
-
run(
|
|
436
|
-
|
|
599
|
+
run(
|
|
600
|
+
operation: string,
|
|
601
|
+
payload: unknown,
|
|
602
|
+
signal?: AbortSignal,
|
|
603
|
+
ctx = this.ctx,
|
|
604
|
+
onCommit?: () => void,
|
|
605
|
+
reload?: AbortController,
|
|
606
|
+
) {
|
|
607
|
+
const result = this.work.then(() => this.runCurrent(operation, payload, signal, ctx, onCommit, reload));
|
|
437
608
|
this.work = result.then(
|
|
438
609
|
() => {},
|
|
439
610
|
() => {},
|
|
@@ -446,9 +617,12 @@ export class PiDaemonClient {
|
|
|
446
617
|
signal?: AbortSignal,
|
|
447
618
|
ctx = this.ctx,
|
|
448
619
|
onCommit?: () => void,
|
|
620
|
+
reload?: AbortController,
|
|
449
621
|
) {
|
|
450
622
|
this.validate();
|
|
451
623
|
signal?.throwIfAborted();
|
|
624
|
+
reload?.signal.throwIfAborted();
|
|
625
|
+
if (this.pendingReload) throw new Error("Pi resources are about to reload.");
|
|
452
626
|
if (this.paused && operation !== "shutdown")
|
|
453
627
|
throw new Error("Synchronization is paused for a session change; if it was cancelled, use /reload to reattach.");
|
|
454
628
|
const connection = await this.connect(undefined, signal);
|
|
@@ -459,17 +633,29 @@ export class PiDaemonClient {
|
|
|
459
633
|
}
|
|
460
634
|
this.validate();
|
|
461
635
|
signal?.throwIfAborted();
|
|
462
|
-
|
|
636
|
+
if (this.paused)
|
|
637
|
+
await connection.update(this.facts()); // Existing, explicitly attached shutdown path.
|
|
638
|
+
else await this.publishFacts(connection);
|
|
463
639
|
this.validate();
|
|
464
640
|
signal?.throwIfAborted();
|
|
465
641
|
this.uiContext = ctx;
|
|
642
|
+
// The daemon directs reload only to the submitting client, and run() serializes its jobs.
|
|
643
|
+
const request = reload ? { received: false } : undefined;
|
|
644
|
+
this.reloadRequest = request;
|
|
466
645
|
try {
|
|
467
|
-
|
|
646
|
+
const result = await connection.run(
|
|
468
647
|
operation,
|
|
469
648
|
payload,
|
|
470
649
|
signal ? AbortSignal.any([signal, this.signal]) : this.signal,
|
|
471
650
|
onCommit,
|
|
472
651
|
);
|
|
652
|
+
if (request?.received && reload && !this.paused && !reload.signal.aborted && !signal?.aborted) {
|
|
653
|
+
this.validate();
|
|
654
|
+
this.pendingReload = reload;
|
|
655
|
+
// Close the command's UI, not the session. Pi reload must run after this job and its UI drain.
|
|
656
|
+
reload.abort(new DOMException("Pi resource reload requested", "AbortError"));
|
|
657
|
+
}
|
|
658
|
+
return result;
|
|
473
659
|
} catch (error) {
|
|
474
660
|
if (error instanceof DaemonError) {
|
|
475
661
|
const prototype =
|
|
@@ -488,18 +674,17 @@ export class PiDaemonClient {
|
|
|
488
674
|
throw error;
|
|
489
675
|
} finally {
|
|
490
676
|
this.uiContext = this.ctx;
|
|
491
|
-
|
|
492
|
-
this.reloadRequested &&
|
|
493
|
-
!this.signal.aborted &&
|
|
494
|
-
!this.disposed &&
|
|
495
|
-
!this.closing &&
|
|
496
|
-
clients.get(this.manager) === this
|
|
497
|
-
) {
|
|
498
|
-
this.reloadRequested = false;
|
|
499
|
-
if ("reload" in ctx && typeof ctx.reload === "function") await ctx.reload();
|
|
500
|
-
}
|
|
677
|
+
this.reloadRequest = undefined;
|
|
501
678
|
}
|
|
502
679
|
}
|
|
680
|
+
canReload(owner: AbortController) {
|
|
681
|
+
if (this.pendingReload !== owner || this.paused) return false;
|
|
682
|
+
this.validate();
|
|
683
|
+
return true;
|
|
684
|
+
}
|
|
685
|
+
releaseReload(owner: AbortController) {
|
|
686
|
+
if (this.pendingReload === owner) this.pendingReload = undefined;
|
|
687
|
+
}
|
|
503
688
|
async markReady(debug: boolean) {
|
|
504
689
|
this.validate();
|
|
505
690
|
this.startupDebug = debug;
|
|
@@ -507,18 +692,18 @@ export class PiDaemonClient {
|
|
|
507
692
|
await this.update();
|
|
508
693
|
this.validate();
|
|
509
694
|
}
|
|
510
|
-
async setBusy(reason: string, busy: boolean) {
|
|
695
|
+
async setBusy(reason: string, busy: boolean, publish = true) {
|
|
511
696
|
this.validate();
|
|
512
697
|
if (busy) this.busy.add(reason);
|
|
513
698
|
else this.busy.delete(reason);
|
|
514
|
-
await this.update();
|
|
699
|
+
if (publish) await this.update();
|
|
515
700
|
this.validate();
|
|
516
701
|
}
|
|
517
702
|
async update() {
|
|
518
703
|
if (this.connection && !this.paused && !this.disposed && !this.signal.aborted)
|
|
519
|
-
await this.
|
|
704
|
+
await this.publishFacts(this.connection);
|
|
520
705
|
}
|
|
521
|
-
private async callback(callback: Callback, signal: AbortSignal) {
|
|
706
|
+
private async callback(callback: Callback, signal: AbortSignal, protectionOnly: boolean) {
|
|
522
707
|
const payload = callback.payload as {
|
|
523
708
|
reservation?: string;
|
|
524
709
|
targets?: string[];
|
|
@@ -541,6 +726,7 @@ export class PiDaemonClient {
|
|
|
541
726
|
signal.throwIfAborted();
|
|
542
727
|
if (this.paused) throw new Error("Pi session is changing; no new work is authorized.");
|
|
543
728
|
if (callback.kind === "queue-acquire") {
|
|
729
|
+
if (this.pendingReload) throw new Error("Pi resources are about to reload.");
|
|
544
730
|
if (payload.background && !this.facts().idle) throw new Error("Pi is busy; background apply was not granted.");
|
|
545
731
|
if (
|
|
546
732
|
payload.generation !== this.generation ||
|
|
@@ -553,6 +739,7 @@ export class PiDaemonClient {
|
|
|
553
739
|
const ctx = this.uiContext;
|
|
554
740
|
const combined = AbortSignal.any([signal, this.signal]);
|
|
555
741
|
if (callback.kind === "model-binding") {
|
|
742
|
+
if (protectionOnly) return null;
|
|
556
743
|
const facts = this.facts();
|
|
557
744
|
const connection = this.connection ?? this.partialConnection;
|
|
558
745
|
if (connection && JSON.stringify(connection.facts.model) !== JSON.stringify(facts.model)) {
|
|
@@ -562,7 +749,8 @@ export class PiDaemonClient {
|
|
|
562
749
|
return payload.background && !facts.idle ? null : (facts.model ?? null);
|
|
563
750
|
}
|
|
564
751
|
if (callback.kind === "reload") {
|
|
565
|
-
this.
|
|
752
|
+
if (!this.reloadRequest) throw new Error("No active Pi command can reload resources.");
|
|
753
|
+
this.reloadRequest.received = true;
|
|
566
754
|
return true;
|
|
567
755
|
}
|
|
568
756
|
if (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode)) throw new Error("This client cannot present safety reviews.");
|
|
@@ -619,6 +807,7 @@ export class PiDaemonClient {
|
|
|
619
807
|
async dispose(handoff?: ClientHandoff) {
|
|
620
808
|
if (this.disposing) return this.disposing;
|
|
621
809
|
this.closing = true;
|
|
810
|
+
this.stopContactRepair(false);
|
|
622
811
|
this.disposing = (async () => {
|
|
623
812
|
const connection = this.connection ?? this.partialConnection ?? (await this.connecting?.catch(() => undefined));
|
|
624
813
|
let confirmed = false;
|
package/src/sync-extension.ts
CHANGED
|
@@ -47,46 +47,67 @@ export default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDepende
|
|
|
47
47
|
await commands.handleCommand(args, ctx, signal, loaders, attention);
|
|
48
48
|
return;
|
|
49
49
|
}
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
if (signal.aborted || owner !== client) return;
|
|
59
|
-
if (
|
|
60
|
-
ready === false &&
|
|
61
|
-
command !== "help" &&
|
|
62
|
-
command !== "unlock" &&
|
|
63
|
-
command !== "migrate-state" &&
|
|
64
|
-
command !== "daemon"
|
|
65
|
-
) {
|
|
66
|
-
ctx.ui.notify(
|
|
67
|
-
"pi-sync recovery required. Repair the startup error, then /reload before syncing. Use /sync help for recovery guidance.",
|
|
68
|
-
"error",
|
|
69
|
-
);
|
|
70
|
-
return;
|
|
71
|
-
}
|
|
72
|
-
if (command === "unlock" || command === "migrate-state") {
|
|
73
|
-
const { stateDirectoryMigrationNotice } = await import("./state/state-directory.js");
|
|
50
|
+
const reload = new AbortController();
|
|
51
|
+
const commandSignal = combineSignals(signal, reload.signal);
|
|
52
|
+
try {
|
|
53
|
+
await withPiDaemonClient(
|
|
54
|
+
ctx,
|
|
55
|
+
async (ctx) => {
|
|
56
|
+
const command = splitArgs(args)[0];
|
|
57
|
+
const ready = await initialization;
|
|
74
58
|
if (signal.aborted || owner !== client) return;
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
59
|
+
const requiresContact = !["help", "unlock", "migrate-state"].includes(command ?? "");
|
|
60
|
+
let busyPublished = false;
|
|
61
|
+
try {
|
|
62
|
+
await client.setBusy("command", true, requiresContact);
|
|
63
|
+
busyPublished = requiresContact;
|
|
64
|
+
if (signal.aborted || owner !== client) return;
|
|
65
|
+
await check.stop();
|
|
66
|
+
if (signal.aborted || owner !== client) return;
|
|
67
|
+
if (
|
|
68
|
+
ready === false &&
|
|
69
|
+
command !== "help" &&
|
|
70
|
+
command !== "unlock" &&
|
|
71
|
+
command !== "migrate-state" &&
|
|
72
|
+
command !== "daemon"
|
|
73
|
+
) {
|
|
74
|
+
ctx.ui.notify(
|
|
75
|
+
"pi-sync recovery required. Repair the startup error, then /reload before syncing. Use /sync help for recovery guidance.",
|
|
76
|
+
"error",
|
|
77
|
+
);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
if (command === "unlock" || command === "migrate-state") {
|
|
81
|
+
const { stateDirectoryMigrationNotice } = await import("./state/state-directory.js");
|
|
82
|
+
if (signal.aborted || owner !== client) return;
|
|
83
|
+
// Recovery cannot guess an authoritative root when roots coexist or are unsafe.
|
|
84
|
+
stateDirectoryMigrationNotice();
|
|
85
|
+
}
|
|
86
|
+
const commands = await loaders.commands();
|
|
87
|
+
if (signal.aborted || owner !== client) return;
|
|
88
|
+
await commands.handleCommand(args, ctx, commandSignal, loaders, attention);
|
|
89
|
+
} catch (error) {
|
|
90
|
+
if (!commandSignal.aborted && owner === client) {
|
|
91
|
+
ctx.ui.notify(`pi-sync command unavailable: ${safeTerminalText(errorMessage(error))}`, "error");
|
|
92
|
+
if (command === "unlock" || command === "migrate-state") throw error;
|
|
93
|
+
}
|
|
94
|
+
} finally {
|
|
95
|
+
if (!signal.aborted && owner === client) {
|
|
96
|
+
// Recovery can publish busy facts after bypassing the initial contact check.
|
|
97
|
+
const publish = busyPublished || command === "unlock" || command === "migrate-state";
|
|
98
|
+
// Release local busy state even if contact failed; do not mask the command result.
|
|
99
|
+
await client.setBusy("command", false, publish).catch(() => {});
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
},
|
|
103
|
+
reload,
|
|
104
|
+
);
|
|
105
|
+
// Pi reload awaits our shutdown hook. Neither daemon work nor old UI may await reload.
|
|
106
|
+
if (!signal.aborted && owner === client && client.canReload(reload)) await ctx.reload();
|
|
107
|
+
} finally {
|
|
108
|
+
client.releaseReload(reload);
|
|
109
|
+
reload.abort();
|
|
110
|
+
}
|
|
90
111
|
},
|
|
91
112
|
});
|
|
92
113
|
pi.on("session_start", async (_event, ctx) => {
|
|
@@ -109,9 +130,9 @@ export default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDepende
|
|
|
109
130
|
try {
|
|
110
131
|
await check.stop();
|
|
111
132
|
if (previousClient) {
|
|
112
|
-
//
|
|
133
|
+
// Protect the replacement session before removing old session protection.
|
|
113
134
|
try {
|
|
114
|
-
await client.attachExisting();
|
|
135
|
+
await client.attachExisting({ allowUpgrade: true });
|
|
115
136
|
} catch {
|
|
116
137
|
/* Initialization below reports an unavailable owner. */
|
|
117
138
|
}
|