@narumitw/pi-sync 0.60.2 → 0.60.5

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.
Files changed (45) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +10 -0
  3. package/dist/chunks/{chunk-FOMZEZER.ts → chunk-6KIWZ4AY.ts} +360 -60
  4. package/dist/chunks/chunk-6KIWZ4AY.ts.map +7 -0
  5. package/dist/chunks/{chunk-B53FS4RW.ts → chunk-F64YWRXG.ts} +2 -2
  6. package/dist/chunks/{chunk-ENFHHB5O.ts → chunk-H7VOTY5N.ts} +55 -6
  7. package/dist/chunks/chunk-H7VOTY5N.ts.map +7 -0
  8. package/dist/chunks/{chunk-E7UJHMNW.ts → chunk-V2QIMC3U.ts} +2 -2
  9. package/dist/chunks/{chunk-3YXBG7BQ.ts → chunk-YVH5VJR4.ts} +2 -2
  10. package/dist/chunks/{command-handler-RTBEFZUX.ts → command-handler-TNPWFIPG.ts} +10 -8
  11. package/dist/chunks/command-handler-TNPWFIPG.ts.map +7 -0
  12. package/dist/chunks/{conflict-review-YXROU42F.ts → conflict-review-ETCSYJTH.ts} +3 -3
  13. package/dist/chunks/{manager-result-dispatcher-4PEUHK7F.ts → manager-result-dispatcher-2GFNWHDM.ts} +4 -4
  14. package/dist/chunks/{manager-ui-TNAMQNEU.ts → manager-ui-LFONXWQN.ts} +8 -8
  15. package/dist/chunks/{remote-selection-ui-47H7V62F.ts → remote-selection-ui-GFR6TDTX.ts} +3 -3
  16. package/dist/chunks/{sync-inspection-5GQEB62G.ts → sync-inspection-6VGR2UVZ.ts} +3 -3
  17. package/dist/chunks/{sync-operations-65HDA67O.ts → sync-operations-SAKAZL6Z.ts} +3 -3
  18. package/dist/index.ts +64 -41
  19. package/dist/index.ts.map +3 -3
  20. package/docs/agent-mode-verification.md +1 -1
  21. package/docs/agent-quality-verification.md +1 -1
  22. package/docs/continuous-sync-verification.md +1 -1
  23. package/docs/daemon-migration.md +88 -6
  24. package/docs/tui-contract.md +7 -1
  25. package/package.json +3 -3
  26. package/skills/configure-pi-sync/references/configuration.md +1 -0
  27. package/src/commands/command-execution.ts +1 -1
  28. package/src/commands/command-handler.ts +2 -0
  29. package/src/daemon/pi-client.ts +302 -57
  30. package/src/daemon/queue-release-ui.ts +88 -0
  31. package/src/sync-extension.ts +68 -43
  32. package/src/ui/sync-status.ts +67 -4
  33. package/dist/chunks/chunk-ENFHHB5O.ts.map +0 -7
  34. package/dist/chunks/chunk-FOMZEZER.ts.map +0 -7
  35. package/dist/chunks/command-handler-RTBEFZUX.ts.map +0 -7
  36. package/docs/settings.md +0 -90
  37. /package/dist/chunks/{chunk-B53FS4RW.ts.map → chunk-F64YWRXG.ts.map} +0 -0
  38. /package/dist/chunks/{chunk-E7UJHMNW.ts.map → chunk-V2QIMC3U.ts.map} +0 -0
  39. /package/dist/chunks/{chunk-3YXBG7BQ.ts.map → chunk-YVH5VJR4.ts.map} +0 -0
  40. /package/dist/chunks/{conflict-review-YXROU42F.ts.map → conflict-review-ETCSYJTH.ts.map} +0 -0
  41. /package/dist/chunks/{manager-result-dispatcher-4PEUHK7F.ts.map → manager-result-dispatcher-2GFNWHDM.ts.map} +0 -0
  42. /package/dist/chunks/{manager-ui-TNAMQNEU.ts.map → manager-ui-LFONXWQN.ts.map} +0 -0
  43. /package/dist/chunks/{remote-selection-ui-47H7V62F.ts.map → remote-selection-ui-GFR6TDTX.ts.map} +0 -0
  44. /package/dist/chunks/{sync-inspection-5GQEB62G.ts.map → sync-inspection-6VGR2UVZ.ts.map} +0 -0
  45. /package/dist/chunks/{sync-operations-65HDA67O.ts.map → sync-operations-SAKAZL6Z.ts.map} +0 -0
@@ -0,0 +1,88 @@
1
+ import type { ConnectionOptions } from "@narumitw/pi-sync-daemon";
2
+
3
+ export type QueueReleaseEvent = Parameters<NonNullable<ConnectionOptions["queueRelease"]>>[0];
4
+ type ClearStatus = (redraw?: boolean) => void;
5
+
6
+ /** Session-owned presentation only; it neither controls delivery nor infers a job's outcome. */
7
+ export function createQueueReleaseUI(show: () => ClearStatus | undefined, warn: () => void) {
8
+ const retries = new Map<string, { job: string; foreground: boolean }>();
9
+ const handledJobs = new Set<string>();
10
+ const deferredWarnings = new Set<string>();
11
+ let timer: ReturnType<typeof setTimeout> | undefined;
12
+ let clearStatus: ClearStatus | undefined;
13
+
14
+ function remember(job: string) {
15
+ deferredWarnings.delete(job);
16
+ if (handledJobs.has(job)) return false;
17
+ if (handledJobs.size >= 128) {
18
+ const oldest = handledJobs.values().next();
19
+ if (!oldest.done) handledJobs.delete(oldest.value);
20
+ }
21
+ handledJobs.add(job);
22
+ return true;
23
+ }
24
+ function clearPresentation(redraw: boolean) {
25
+ clearTimeout(timer);
26
+ timer = undefined;
27
+ const release = clearStatus;
28
+ clearStatus = undefined;
29
+ release?.(redraw);
30
+ }
31
+
32
+ return {
33
+ get retrying() {
34
+ return retries.size > 0;
35
+ },
36
+ observe({ id, job, state, foreground }: QueueReleaseEvent, commandBusy: boolean, cancelled: boolean) {
37
+ if (state === "retrying") {
38
+ if (foreground && cancelled) {
39
+ remember(job);
40
+ return;
41
+ }
42
+ if (retries.has(id)) return;
43
+ retries.set(id, { job, foreground });
44
+ if (retries.size !== 1) return;
45
+ timer = setTimeout(() => {
46
+ timer = undefined;
47
+ const release = show();
48
+ if (retries.size) clearStatus = release;
49
+ else release?.(false); // Presentation may have synchronously reentered lifecycle cleanup.
50
+ }, 2_000);
51
+ timer.unref?.();
52
+ return;
53
+ }
54
+ const retry = retries.get(id);
55
+ retries.delete(id);
56
+ if (!retries.size) clearPresentation(true);
57
+ if (state !== "unconfirmed") return;
58
+ const background = !foreground && !retry?.foreground;
59
+ if (background && commandBusy) {
60
+ if (!handledJobs.has(job)) deferredWarnings.add(job);
61
+ } else if (remember(job) && background) warn();
62
+ },
63
+ flushWarnings() {
64
+ if (!deferredWarnings.size) return;
65
+ // One warning covers the background releases deferred by this command.
66
+ for (const job of deferredWarnings) remember(job);
67
+ try {
68
+ warn();
69
+ } catch {
70
+ // Presentation must not interrupt publication of the new idle state.
71
+ }
72
+ },
73
+ finishForeground(redraw: boolean) {
74
+ for (const [id, { job, foreground }] of retries) {
75
+ if (!foreground) continue;
76
+ retries.delete(id);
77
+ remember(job); // Late observations of this job should not duplicate its command result.
78
+ }
79
+ if (!retries.size) clearPresentation(redraw);
80
+ },
81
+ clear(redraw: boolean) {
82
+ retries.clear();
83
+ handledJobs.clear();
84
+ deferredWarnings.clear();
85
+ clearPresentation(redraw);
86
+ },
87
+ };
88
+ }
@@ -47,54 +47,75 @@ 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
- await withPiDaemonClient(ctx, async (ownedContext) => {
51
- ctx = ownedContext;
52
- const command = splitArgs(args)[0];
53
- const ready = await initialization;
54
- if (signal.aborted || owner !== client) return;
55
- await client.setBusy("command", true);
56
- try {
57
- await check.stop();
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
- // Recovery cannot guess an authoritative root when roots coexist or are unsafe.
76
- stateDirectoryMigrationNotice();
77
- }
78
- const commands = await loaders.commands();
79
- if (signal.aborted || owner !== client) return;
80
- await commands.handleCommand(args, ctx, signal, loaders, attention);
81
- } catch (error) {
82
- if (!signal.aborted) {
83
- ctx.ui.notify(`pi-sync command unavailable: ${safeTerminalText(errorMessage(error))}`, "error");
84
- if (command === "unlock" || command === "migrate-state") throw error;
85
- }
86
- } finally {
87
- if (!signal.aborted && owner === client) await client.setBusy("command", false);
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) => {
93
- const releaseStatus = status.start(ctx);
94
114
  const previousClient = owner;
95
115
  shutdownAbort?.abort(new DOMException("Session replaced", "AbortError"));
96
116
  shutdownAbort = undefined;
97
117
  sessionAbort.abort(new DOMException("Session replaced", "AbortError"));
118
+ const releaseStatus = status.start(ctx);
98
119
  sessionAbort = new AbortController();
99
120
  const signal = sessionAbort.signal;
100
121
  const client = bindPiDaemonClient(ctx, signal, publishTimings);
@@ -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
- // Register the replacement before removing old session protection.
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
  }
@@ -139,7 +160,10 @@ export default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDepende
139
160
  });
140
161
  try {
141
162
  const ready = await initialization;
142
- if (ready === false) releaseStatus();
163
+ if (ready === false) {
164
+ client.disableQueueReleaseUI();
165
+ releaseStatus();
166
+ }
143
167
  if (
144
168
  ready &&
145
169
  !signal.aborted &&
@@ -151,6 +175,7 @@ export default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDepende
151
175
  check.start(ctx, signal, ready);
152
176
  });
153
177
  } catch (error) {
178
+ client.disableQueueReleaseUI();
154
179
  releaseStatus();
155
180
  throw error;
156
181
  }
@@ -51,6 +51,14 @@ export function syncStatusFailureReason(kind: ContinuousErrorKind | undefined):
51
51
 
52
52
  const enabledBySession = new WeakMap<ExtensionContext["sessionManager"], boolean>();
53
53
  const publishersBySession = new WeakMap<ExtensionContext["sessionManager"], StatusBinding>();
54
+ const statusesBySession = new WeakMap<ExtensionContext["sessionManager"], StatusValue>();
55
+ const connectionStatusBySession = new WeakMap<ExtensionContext["sessionManager"], StatusValue>();
56
+ const recoveryStatusBySession = new WeakMap<ExtensionContext["sessionManager"], StatusValue>();
57
+
58
+ interface StatusValue {
59
+ value: string;
60
+ presentation?: SyncStatusPresentation;
61
+ }
54
62
 
55
63
  interface StatusBinding {
56
64
  update(value: string | undefined, presentation?: SyncStatusPresentation): void;
@@ -136,6 +144,9 @@ export function createSyncStatusPublisher(events: ExtensionAPI["events"] | undef
136
144
  revision++;
137
145
  if (owned) {
138
146
  publishersBySession.delete(sessionManager);
147
+ statusesBySession.delete(sessionManager);
148
+ connectionStatusBySession.delete(sessionManager);
149
+ recoveryStatusBySession.delete(sessionManager);
139
150
  current = undefined;
140
151
  }
141
152
  // Retire before optional callbacks; withdrawal observers cannot revive first-use binding.
@@ -212,17 +223,69 @@ export function createSyncStatusPublisher(events: ExtensionAPI["events"] | undef
212
223
  export function configureSyncStatus(ctx: SyncStatusContext, enabled: boolean) {
213
224
  enabledBySession.set(ctx.sessionManager, enabled);
214
225
  if (!enabled) {
215
- if (ctx.hasUI) ctx.ui.setStatus(STATUS_KEY, undefined);
216
- publishersBySession.get(ctx.sessionManager)?.update(undefined);
226
+ statusesBySession.delete(ctx.sessionManager);
227
+ connectionStatusBySession.delete(ctx.sessionManager);
228
+ recoveryStatusBySession.delete(ctx.sessionManager);
229
+ renderSyncStatus(ctx);
217
230
  }
218
231
  }
219
232
 
233
+ function renderSyncStatus(ctx: SyncStatusContext) {
234
+ if (!ctx.hasUI) return;
235
+ const { sessionManager } = ctx;
236
+ const status = statusesBySession.get(sessionManager);
237
+ const connection = connectionStatusBySession.get(sessionManager);
238
+ const recovery = recoveryStatusBySession.get(sessionManager);
239
+ const activity = status?.presentation?.activity;
240
+ const normal = status && activity !== "idle" ? status : (connection ?? status);
241
+ // Recovery explains a transfer's wait, but must not obscure confirmed failures or review.
242
+ const current = activity === "blocked" || activity === "review" ? status : (recovery ?? normal);
243
+ ctx.ui.setStatus(STATUS_KEY, current?.value);
244
+ publishersBySession.get(sessionManager)?.update(current?.value, current?.presentation);
245
+ }
246
+
220
247
  export function setSyncStatus(
221
248
  ctx: SyncStatusContext,
222
249
  value: string | undefined,
223
250
  presentation?: SyncStatusPresentation,
224
251
  ) {
225
252
  if (!ctx.hasUI || (value !== undefined && enabledBySession.get(ctx.sessionManager) === false)) return;
226
- ctx.ui.setStatus(STATUS_KEY, value);
227
- publishersBySession.get(ctx.sessionManager)?.update(value, presentation);
253
+ const { sessionManager } = ctx;
254
+ if (value === undefined) statusesBySession.delete(sessionManager);
255
+ else {
256
+ const status: StatusValue = { value };
257
+ statusesBySession.set(sessionManager, status);
258
+ status.presentation = statusPresentation(presentation);
259
+ // An annotation getter can reenter publication or replace the session.
260
+ if (statusesBySession.get(sessionManager) !== status) return;
261
+ }
262
+ renderSyncStatus(ctx);
263
+ }
264
+
265
+ function showOwnedStatus(
266
+ statuses: WeakMap<ExtensionContext["sessionManager"], StatusValue>,
267
+ ctx: SyncStatusContext,
268
+ value: string,
269
+ presentation: SyncStatusPresentation,
270
+ ) {
271
+ if (!ctx.hasUI || enabledBySession.get(ctx.sessionManager) === false) return (_redraw?: boolean) => {};
272
+ const { sessionManager } = ctx;
273
+ const status: StatusValue = { value };
274
+ statuses.set(sessionManager, status);
275
+ status.presentation = statusPresentation(presentation);
276
+ if (statuses.get(sessionManager) === status) renderSyncStatus(ctx);
277
+ return (redraw = true) => {
278
+ if (statuses.get(sessionManager) !== status) return;
279
+ statuses.delete(sessionManager);
280
+ if (redraw) renderSyncStatus(ctx);
281
+ };
282
+ }
283
+
284
+ /** Connection repair never clears or replaces a transfer or review status. */
285
+ export function showSyncConnectionStatus(ctx: SyncStatusContext, value: string, presentation: SyncStatusPresentation) {
286
+ return showOwnedStatus(connectionStatusBySession, ctx, value, presentation);
287
+ }
288
+
289
+ export function showSyncQueueReleaseRecovery(ctx: SyncStatusContext) {
290
+ return showOwnedStatus(recoveryStatusBySession, ctx, "sync recovering", { activity: "retry", reason: "temp" });
228
291
  }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/ui/sync-status.ts"],
4
- "sourcesContent": ["import type { ExtensionAPI, ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport type { ContinuousErrorKind } from \"../sync/continuous-errors.js\";\n\nconst STATUS_KEY = \"sync\";\n\ntype SyncStatusContext = Pick<ExtensionContext, \"hasUI\" | \"sessionManager\" | \"ui\">;\n\nexport type SyncStatusPresentation =\n | {\n activity:\n | \"idle\"\n | \"checking\"\n | \"working\"\n | \"pushing\"\n | \"pulling\"\n | \"resolving\"\n | \"local-change\"\n | \"remote-change\"\n | \"review\";\n reason?: never;\n }\n | { activity: \"retry\" | \"blocked\"; reason: SyncStatusReason };\n\ntype SyncStatusReason =\n | \"temp\"\n | \"busy\"\n | \"stale\"\n | \"auth\"\n | \"storage\"\n | \"review\"\n | \"model\"\n | \"limit\"\n | \"unknown\"\n | \"repair\";\n\nconst failureReasons: Record<ContinuousErrorKind, SyncStatusReason> = {\n transient: \"temp\",\n contention: \"busy\",\n stale: \"stale\",\n authentication: \"auth\",\n storage: \"storage\",\n unsafe: \"review\",\n model: \"model\",\n budget: \"limit\",\n unknown: \"unknown\",\n};\n\nexport function syncStatusFailureReason(kind: ContinuousErrorKind | undefined): SyncStatusReason {\n return typeof kind === \"string\" && Object.hasOwn(failureReasons, kind) ? failureReasons[kind] : \"unknown\";\n}\n\nconst enabledBySession = new WeakMap<ExtensionContext[\"sessionManager\"], boolean>();\nconst publishersBySession = new WeakMap<ExtensionContext[\"sessionManager\"], StatusBinding>();\n\ninterface StatusBinding {\n update(value: string | undefined, presentation?: SyncStatusPresentation): void;\n release(): void;\n}\n\nfunction statusPresentation(presentation: SyncStatusPresentation | undefined): SyncStatusPresentation | undefined {\n if (!presentation) return;\n try {\n const { activity, reason } = presentation;\n if (activity === \"retry\" || activity === \"blocked\") {\n if (typeof reason === \"string\" && /^[a-z][a-z0-9-]{0,31}$/u.exec(reason)?.[0] === reason)\n return { activity, reason };\n } else if (\n [\n \"idle\",\n \"checking\",\n \"working\",\n \"pushing\",\n \"pulling\",\n \"resolving\",\n \"local-change\",\n \"remote-change\",\n \"review\",\n ].includes(activity) &&\n reason === undefined\n ) {\n return { activity };\n }\n } catch {\n // Invalid optional annotations withdraw metadata, not the readable status.\n }\n return undefined;\n}\n\n/** Optional extension-status v1 publisher; it owns no domain work or captured context. */\nexport function createSyncStatusPublisher(events: ExtensionAPI[\"events\"] | undefined) {\n let active: { sessionManager: ExtensionContext[\"sessionManager\"]; binding: StatusBinding } | undefined;\n let used = false;\n let activation = 0;\n const emit = (payload: object) => {\n try {\n events?.emit(\"extension-status:v1:update\", payload);\n } catch {\n // Optional delivery must not interrupt sync, including on minimal test buses.\n }\n };\n const bind = (ctx: SyncStatusContext): (() => void) => {\n if (!ctx.hasUI || (!active && used) || (active && active.sessionManager !== ctx.sessionManager)) return () => {};\n const { sessionManager } = ctx;\n if (active) {\n return publishersBySession.get(sessionManager) === active.binding ? active.binding.release : () => {};\n }\n const owner = activation;\n // Reserve first use before foreign cleanup can reenter this factory.\n used = true;\n publishersBySession.get(sessionManager)?.release();\n if (activation !== owner || publishersBySession.has(sessionManager)) return () => {};\n let current: ({ value: string } & SyncStatusPresentation) | undefined;\n let revision = 0;\n let unsubscribe: (() => void) | undefined;\n const isCurrent = () => publishersBySession.get(sessionManager) === binding;\n const publish = (requestId?: object) => {\n emit({\n version: 1,\n sessionManager,\n key: STATUS_KEY,\n ...(current ?? { value: undefined }),\n ...(requestId === undefined ? {} : { requestId }),\n });\n };\n const binding: StatusBinding = {\n update(value, presentation) {\n if (!isCurrent()) return;\n const owner = ++revision;\n const safePresentation = statusPresentation(presentation);\n if (!isCurrent() || revision !== owner) return;\n current = value && safePresentation ? { value, ...safePresentation } : undefined;\n publish();\n },\n release() {\n const owned = isCurrent();\n revision++;\n if (owned) {\n publishersBySession.delete(sessionManager);\n current = undefined;\n }\n // Retire before optional callbacks; withdrawal observers cannot revive first-use binding.\n if (active?.binding === binding) active = undefined;\n const stop = unsubscribe;\n unsubscribe = undefined;\n try {\n stop?.();\n } catch {\n // A failing optional unsubscribe cannot stop lifecycle cleanup.\n }\n if (owned && !publishersBySession.has(sessionManager)) publish();\n },\n };\n active = { sessionManager, binding };\n used = true;\n publishersBySession.set(sessionManager, binding);\n try {\n unsubscribe = events?.on(\"extension-status:v1:request\", (payload) => {\n try {\n if (!isCurrent() || !payload || typeof payload !== \"object\" || Array.isArray(payload)) return;\n const {\n version,\n sessionManager: manager,\n requestId,\n } = payload as {\n version?: unknown;\n sessionManager?: unknown;\n requestId?: unknown;\n };\n if (\n !isCurrent() ||\n version !== 1 ||\n manager !== sessionManager ||\n !requestId ||\n typeof requestId !== \"object\"\n )\n return;\n publish(requestId);\n } catch {\n // Malformed requests and optional delivery cannot affect sync.\n }\n });\n } catch {\n // Raw status remains available when optional subscription fails.\n }\n return binding.release;\n };\n return {\n bind,\n start(ctx: SyncStatusContext) {\n const owner = ++activation;\n const { sessionManager } = ctx;\n const previous = publishersBySession.get(sessionManager);\n active?.binding.release();\n if (\n activation !== owner ||\n (publishersBySession.has(sessionManager) && publishersBySession.get(sessionManager) !== previous)\n )\n return () => {};\n // Only an explicit lifecycle start can reactivate a released publisher.\n used = false;\n const release = bind(ctx);\n used = true;\n // A superseded start must not receive the newer activation's cleanup capability.\n return activation === owner ? release : () => {};\n },\n cleanupFor(ctx: SyncStatusContext) {\n return active?.sessionManager === ctx.sessionManager ? active.binding.release : () => {};\n },\n };\n}\n\nexport function configureSyncStatus(ctx: SyncStatusContext, enabled: boolean) {\n enabledBySession.set(ctx.sessionManager, enabled);\n if (!enabled) {\n if (ctx.hasUI) ctx.ui.setStatus(STATUS_KEY, undefined);\n publishersBySession.get(ctx.sessionManager)?.update(undefined);\n }\n}\n\nexport function setSyncStatus(\n ctx: SyncStatusContext,\n value: string | undefined,\n presentation?: SyncStatusPresentation,\n) {\n if (!ctx.hasUI || (value !== undefined && enabledBySession.get(ctx.sessionManager) === false)) return;\n ctx.ui.setStatus(STATUS_KEY, value);\n publishersBySession.get(ctx.sessionManager)?.update(value, presentation);\n}\n"],
5
- "mappings": ";;;;AAGA,IAAM,aAAa;AAgDnB,IAAM,mBAAmB,oBAAI,QAAqD;AAClF,IAAM,sBAAsB,oBAAI,QAA2D;AAO3F,SAAS,mBAAmB,cAAsF;AAChH,MAAI,CAAC,aAAc;AACnB,MAAI;AACF,UAAM,EAAE,UAAU,OAAO,IAAI;AAC7B,QAAI,aAAa,WAAW,aAAa,WAAW;AAClD,UAAI,OAAO,WAAW,YAAY,0BAA0B,KAAK,MAAM,IAAI,CAAC,MAAM;AAChF,eAAO,EAAE,UAAU,OAAO;AAAA,IAC9B,WACE;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,EAAE,SAAS,QAAQ,KACnB,WAAW,QACX;AACA,aAAO,EAAE,SAAS;AAAA,IACpB;AAAA,EACF,QAAQ;AAAA,EAER;AACA,SAAO;AACT;AAGO,SAAS,0BAA0B,QAA4C;AACpF,MAAI;AACJ,MAAI,OAAO;AACX,MAAI,aAAa;AACjB,QAAM,OAAO,CAAC,YAAoB;AAChC,QAAI;AACF,cAAQ,KAAK,8BAA8B,OAAO;AAAA,IACpD,QAAQ;AAAA,IAER;AAAA,EACF;AACA,QAAM,OAAO,CAAC,QAAyC;AACrD,QAAI,CAAC,IAAI,SAAU,CAAC,UAAU,QAAU,UAAU,OAAO,mBAAmB,IAAI,eAAiB,QAAO,MAAM;AAAA,IAAC;AAC/G,UAAM,EAAE,eAAe,IAAI;AAC3B,QAAI,QAAQ;AACV,aAAO,oBAAoB,IAAI,cAAc,MAAM,OAAO,UAAU,OAAO,QAAQ,UAAU,MAAM;AAAA,MAAC;AAAA,IACtG;AACA,UAAM,QAAQ;AAEd,WA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YAAY;AACzE;",
6
- "names": ["owner"]
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/daemon/pi-client.ts", "../../src/daemon/apply-gate.ts", "../../src/daemon/recovery.ts"],
4
- "sourcesContent": ["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { randomUUID } from \"node:crypto\";\nimport { realpathSync } from \"node:fs\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { type ExtensionContext, getAgentDir } from \"@earendil-works/pi-coding-agent\";\nimport {\n type Callback,\n type ClientFacts,\n type ClientHandoff,\n DaemonConnection,\n DaemonError,\n type DocumentView,\n documentFingerprint,\n ensureDaemon,\n findDaemon,\n MAX_SETTINGS_BYTES,\n modelSignature,\n waitForDaemonExit,\n} from \"@narumitw/pi-sync-daemon\";\nimport { type ConfigAuthority, configureEngineHost } from \"@narumitw/pi-sync-daemon/engine/host\";\nimport {\n type LocalConfigDocument,\n peekLocalConfigDocument,\n} from \"@narumitw/pi-sync-daemon/engine/settings/config-file\";\nimport { validateSettingsDocument } from \"@narumitw/pi-sync-daemon/engine/settings/settings-validation\";\nimport { sessionDirFromContext } from \"@narumitw/pi-sync-daemon/engine/snapshot/session-paths\";\nimport type { CommandOptions } from \"../commands/command-types.js\";\nimport type { StartupTimingPublisher } from \"../sync/startup-timings.js\";\nimport { SyncDecisionRequiredError } from \"../sync/sync-errors.js\";\nimport { RemoteSelectionMismatchError } from \"../sync/sync-policy.js\";\nimport { type SyncStatusPresentation, setSyncStatus } from \"../ui/sync-status.js\";\nimport { safeTerminalText } from \"../ui/terminal-text.js\";\nimport { PiApplyGate } from \"./apply-gate.js\";\nimport { quarantineClient, recoverDetachedClients } from \"./recovery.js\";\n\nconst scope = new AsyncLocalStorage<PiDaemonClient>();\nconst clients = new WeakMap<ExtensionContext[\"sessionManager\"], PiDaemonClient>();\nexport function currentPiDaemonClient() {\n return current();\n}\nfunction current() {\n const client = scope.getStore();\n if (!client) throw new Error(\"Pi synchronization requires a current session-bound daemon client.\");\n client.validate();\n return client;\n}\nfunction canonicalPath(value: string | undefined): string | undefined {\n if (value === undefined) return undefined;\n if (!path.isAbsolute(value)) throw new Error(\"Pi session paths must be absolute.\");\n const parts: string[] = [];\n let cursor = path.resolve(value);\n for (;;) {\n try {\n return path.join(realpathSync(cursor), ...parts.toReversed());\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\" || path.dirname(cursor) === cursor) throw error;\n parts.push(path.basename(cursor));\n cursor = path.dirname(cursor);\n }\n }\n}\nfunction decode(value: unknown): LocalConfigDocument | undefined {\n if (value === null) return undefined;\n const document = value as DocumentView;\n if (\n !document ||\n typeof document.path !== \"string\" ||\n typeof document.bytes !== \"string\" ||\n !document.identity ||\n !document.parsed\n )\n throw new Error(\"Invalid settings response.\");\n return { ...document, bytes: Buffer.from(document.bytes, \"base64\") };\n}\nfunction fingerprint(document: LocalConfigDocument | undefined) {\n return documentFingerprint(\n document ? { bytes: document.bytes.toString(\"base64\"), identity: document.identity } : undefined,\n );\n}\nlet settingsQueue = Promise.resolve();\nconst authority: ConfigAuthority = {\n read: (repair) => {\n const client = current();\n return settingsQueue.then(() => {\n client.validate();\n return client.readSettings(repair);\n });\n },\n update: <T extends Record<string, unknown>>(\n fallback: T,\n update: (value: T) => T,\n validate: (value: Record<string, unknown>) => void,\n signal?: AbortSignal,\n ): Promise<T> => {\n const client = current();\n // Capture ownership and invocation order before prerequisite awaits.\n const operation = settingsQueue.then(async () => {\n client.validate();\n signal?.throwIfAborted();\n const document = await client.readSettings(true);\n client.validate();\n signal?.throwIfAborted();\n const next = update(structuredClone(document?.parsed ?? fallback) as T);\n validate(next);\n await client.run(\"settings.cas\", { expected: fingerprint(document), next }, signal);\n client.validate();\n return next;\n });\n settingsQueue = operation.then(\n () => undefined,\n () => undefined,\n );\n return operation;\n },\n create: async (next, signal) => {\n await current().run(\"settings.cas\", { expected: null, next }, signal);\n },\n replace: async (document, next) => {\n await current().run(\"settings.cas\", { expected: fingerprint(document), next });\n },\n};\n/** Factory registration installs only adapters; it starts no process and performs no I/O. */\nexport function installPiDaemonHost() {\n configureEngineHost({\n root: () => scope.getStore()?.root ?? path.resolve(getAgentDir()),\n config: authority,\n mutate: async () => {\n throw new Error(\"File mutation belongs to pi-sync-daemon; no in-process fallback is permitted.\");\n },\n review: async () => {\n throw new Error(\"Engine reviews must arrive through the daemon API.\");\n },\n });\n}\nexport function bindPiDaemonClient(ctx: ExtensionContext, signal: AbortSignal, publish?: StartupTimingPublisher) {\n const client = new PiDaemonClient(ctx, signal, publish);\n clients.set(ctx.sessionManager, client);\n return client;\n}\nexport function piDaemonClient(ctx: ExtensionContext) {\n const client = clients.get(ctx.sessionManager);\n if (!client) throw new Error(\"The Pi synchronization client is not attached to this session.\");\n client.validate();\n return client;\n}\nexport function withPiDaemonClient<Context extends ExtensionContext, T>(\n ctx: Context,\n action: (owned: Context) => Promise<T>,\n) {\n const client = piDaemonClient(ctx);\n // TUI input arrives from Pi's event loop, outside the command's async call tree.\n // Bind public component methods so later menu actions retain this exact owner,\n // never a replacement session selected through a global fallback.\n const ui = new Proxy(ctx.ui, {\n get(target, property) {\n if (property !== \"custom\") return Reflect.get(target, property, target);\n return (...args: Parameters<ExtensionContext[\"ui\"][\"custom\"]>) => {\n const [factory, options] = args;\n const wrap = (component: Awaited<ReturnType<typeof factory>>) => {\n const methods = new Map<PropertyKey, { source: unknown; bound: unknown }>();\n return new Proxy(component, {\n get(original, key) {\n const value: unknown = Reflect.get(original, key, original);\n if (typeof value !== \"function\") return value;\n const saved = methods.get(key);\n if (saved?.source === value) return saved.bound;\n const bound = (...values: unknown[]) => scope.run(client, () => Reflect.apply(value, original, values));\n methods.set(key, { source: value, bound });\n return bound;\n },\n });\n };\n const invoke = (...provided: Parameters<typeof factory>) => {\n const component = scope.run(client, () => factory(...provided));\n return component instanceof Promise ? component.then(wrap) : wrap(component);\n };\n // Do not turn synchronous editors/reviews into asynchronous factories.\n return target.custom(\n factory.constructor.name === \"AsyncFunction\" ? async (...provided) => invoke(...provided) : invoke,\n options,\n );\n };\n },\n });\n const owned = new Proxy(ctx, {\n get(target, key) {\n return key === \"ui\" ? ui : Reflect.get(target, key, target);\n },\n });\n return scope.run(client, () => action(owned));\n}\nexport async function remoteOperation(ctx: ExtensionContext, operation: string, options: CommandOptions) {\n const client = piDaemonClient(ctx);\n const { signal, onCommit, args, setup } = options;\n const payload = {\n args,\n ...(setup === undefined ? {} : { setup }),\n yes: options.yes,\n force: options.force,\n stale: options.stale,\n silent: options.silent,\n reload: options.reload,\n ...(options.agentRetryRefusal ? { agentRetryRefusal: true } : {}),\n };\n return client.run(operation, payload, signal, ctx, onCommit);\n}\nexport class PiDaemonClient {\n private connection?: DaemonConnection;\n private partialConnection?: DaemonConnection;\n private work = Promise.resolve();\n private closing = false;\n private paused = false;\n private pausing?: Promise<void>;\n private connecting?: Promise<DaemonConnection>;\n private disposed = false;\n private disposing?: Promise<void>;\n private uiContext: ExtensionContext;\n private reloadRequested = false;\n private readonly busy = new Set<string>();\n private initialized = false;\n private startupDebug = false;\n private participantIdentity = { id: randomUUID(), generation: randomUUID() };\n get id() {\n return this.participantIdentity.id;\n }\n get generation() {\n return this.participantIdentity.generation;\n }\n readonly root: string;\n private readonly rawRoot: string;\n private readonly gate: PiApplyGate;\n private readonly manager: ExtensionContext[\"sessionManager\"];\n constructor(\n private readonly ctx: ExtensionContext,\n private readonly signal: AbortSignal,\n private readonly publish?: StartupTimingPublisher,\n ) {\n this.uiContext = ctx;\n this.manager = ctx.sessionManager;\n this.rawRoot = getAgentDir();\n const root = canonicalPath(path.resolve(this.rawRoot));\n if (!root) throw new Error(\"Agent directory is unavailable.\");\n this.root = root;\n this.gate = new PiApplyGate(() => this.validate());\n }\n validate() {\n this.signal.throwIfAborted();\n if (this.disposed || this.closing || clients.get(this.manager) !== this)\n throw new Error(\"Synchronization session was replaced.\");\n // Public context access verifies the SDK runner is still active after awaits.\n this.ctx.isIdle();\n if (getAgentDir() !== this.rawRoot || canonicalPath(path.resolve(this.rawRoot)) !== this.root)\n throw new Error(\"Agent directory changed; reload before synchronization.\");\n }\n private modelBinding(): ClientFacts[\"model\"] {\n const model = this.ctx.model;\n if (!model) return undefined;\n const registry = this.ctx.modelRegistry;\n if (registry.getRegisteredProviderIds().includes(model.provider)) return undefined;\n const source = registry.getProviderAuthStatus(model.provider).source;\n if (\n source !== \"stored\" &&\n source !== \"environment\" &&\n source !== \"models_json_key\" &&\n source !== \"models_json_command\"\n )\n return undefined;\n return { provider: model.provider, id: model.id, signature: modelSignature(model), authSource: source };\n }\n private facts(): ClientFacts {\n const manager = this.ctx.sessionManager;\n return {\n id: this.id,\n generation: this.generation,\n pid: process.pid,\n cwd: this.ctx.cwd,\n mode: this.ctx.mode,\n hasUI: this.ctx.hasUI,\n idle: !this.paused && !this.busy.size && this.ctx.isIdle(),\n ready: this.initialized,\n startupDebug: this.startupDebug,\n sessionFile: canonicalPath(manager.getSessionFile?.()),\n sessionId: manager.getSessionId?.(),\n sessionDir: canonicalPath(sessionDirFromContext(this.ctx)),\n model: this.modelBinding(),\n };\n }\n async configured() {\n this.validate();\n await settingsQueue;\n this.validate();\n const document = await peekLocalConfigDocument();\n this.validate();\n return Boolean(document && validateSettingsDocument(document.parsed).activeSyncSetup);\n }\n async pauseForSessionChange() {\n this.validate();\n this.paused = true;\n this.gate.cancelPending();\n this.pausing ??= (async () => {\n const connection = this.connection ?? this.partialConnection ?? (await this.connecting?.catch(() => undefined));\n if (connection) {\n await connection.pause();\n await this.gate.releaseAfterDrain();\n }\n })();\n return this.pausing;\n }\n async attachExisting() {\n this.validate();\n const address = await findDaemon(this.root);\n this.validate();\n if (address) {\n try {\n await this.connect(address);\n } catch (error) {\n this.validate();\n if (error instanceof DaemonError && error.remote.name === \"DaemonStoppingError\") return false;\n throw error;\n }\n }\n this.validate();\n return Boolean(address);\n }\n async finishReattachment() {\n this.validate();\n if (this.connection) {\n await recoverDetachedClients({ paths: this.connection.paths, identity: this.connection.identity });\n this.validate();\n await this.connection.attach(this.signal);\n this.validate();\n }\n }\n async connect(existing?: Awaited<ReturnType<typeof ensureDaemon>>, requestSignal?: AbortSignal) {\n const startupSignal = requestSignal ? AbortSignal.any([this.signal, requestSignal]) : this.signal;\n const validateStartup = () => {\n this.validate();\n startupSignal.throwIfAborted();\n };\n validateStartup();\n if (this.connection) return this.connection;\n this.connecting ??= (async () => {\n if (this.partialConnection) {\n // A failed unpublished attempt may already be retired or own queue grants.\n // Confirm drain before replacing its identity; failed cleanup must block retry.\n await this.partialConnection.dispose();\n // Finish acknowledged cleanup even if this new startup was cancelled meanwhile.\n await this.gate.releaseAfterDrain();\n validateStartup();\n this.partialConnection = undefined;\n this.participantIdentity = { id: randomUUID(), generation: randomUUID() };\n }\n // Only explicit setup/command paths or a configured interactive session call connect.\n if (!existing) await fs.mkdir(this.root, { recursive: true, mode: 0o700 });\n validateStartup();\n let retried = false;\n for (;;) {\n validateStartup();\n const daemon = existing ?? (await ensureDaemon(this.root, startupSignal));\n validateStartup();\n if (daemon.paths.root !== this.root) throw new Error(\"Daemon root changed before attach.\");\n const connection = new DaemonConnection(daemon.paths, daemon.identity, this.facts(), {\n callback: (callback, signal) => this.callback(callback, signal),\n event: (event) => {\n if (event.kind === \"commit\") return;\n if (this.signal.aborted || this.disposed || this.closing || clients.get(this.manager) !== this) return;\n const payload = event.payload as {\n message?: string;\n level?: \"info\" | \"warning\" | \"error\";\n value?: string;\n presentation?: SyncStatusPresentation;\n };\n if (event.kind === \"notify\" && typeof payload?.message === \"string\")\n this.uiContext.ui.notify(safeTerminalText(payload.message), payload.level ?? \"info\");\n if (event.kind === \"timings\" && typeof (event.payload as { report?: unknown })?.report === \"string\") {\n this.publish?.(this.ctx, safeTerminalText((event.payload as { report: string }).report));\n }\n if (event.kind === \"status\")\n setSyncStatus(\n this.uiContext,\n typeof payload?.value === \"string\" ? safeTerminalText(payload.value) : undefined,\n payload.presentation,\n );\n },\n error: () => {\n if (!this.signal.aborted && !this.disposed && !this.closing && clients.get(this.manager) === this)\n setSyncStatus(this.ctx, \"sync service unavailable\", { activity: \"blocked\", reason: \"repair\" });\n },\n });\n this.partialConnection = connection;\n try {\n await connection.attach(startupSignal);\n } catch (error) {\n if (!(error instanceof DaemonError) || error.remote.name !== \"DaemonStoppingError\") throw error;\n // The final idle fence rejected publication, so this connection owns no queue grants.\n await connection.dispose().catch(() => {});\n this.partialConnection = undefined;\n validateStartup();\n if (existing || retried) throw error;\n retried = true;\n await waitForDaemonExit(daemon.identity, startupSignal);\n validateStartup();\n continue;\n }\n this.validate();\n await recoverDetachedClients(daemon);\n if (this.signal.aborted || this.disposed || this.closing) {\n await connection.dispose();\n this.validate();\n }\n this.validate();\n this.connection = connection;\n this.partialConnection = undefined;\n return connection;\n }\n })().catch((error) => {\n this.connecting = undefined;\n throw error;\n });\n return this.connecting;\n }\n async readSettings(repair = false) {\n this.validate();\n if (!this.connection || this.paused) {\n const document = await peekLocalConfigDocument();\n this.validate();\n if (document && document.bytes.length > MAX_SETTINGS_BYTES)\n throw new Error(\"Settings exceed the local API byte limit; the source document is unchanged.\");\n if (document && !repair) validateSettingsDocument(document.parsed);\n return document;\n }\n return decode(await this.run(repair ? \"settings.repair-read\" : \"settings.read\", {}));\n }\n run(operation: string, payload: unknown, signal?: AbortSignal, ctx = this.ctx, onCommit?: () => void) {\n const result = this.work.then(() => this.runCurrent(operation, payload, signal, ctx, onCommit));\n this.work = result.then(\n () => {},\n () => {},\n );\n return result;\n }\n private async runCurrent(\n operation: string,\n payload: unknown,\n signal?: AbortSignal,\n ctx = this.ctx,\n onCommit?: () => void,\n ) {\n this.validate();\n signal?.throwIfAborted();\n if (this.paused && operation !== \"shutdown\")\n throw new Error(\"Synchronization is paused for a session change; if it was cancelled, use /reload to reattach.\");\n const connection = await this.connect(undefined, signal);\n if (this.paused && operation === \"shutdown\") {\n Object.assign(connection.facts, { ...this.facts(), idle: false, ready: false });\n await connection.attach(signal ? AbortSignal.any([signal, this.signal]) : this.signal);\n this.validate();\n }\n this.validate();\n signal?.throwIfAborted();\n await connection.update(this.facts());\n this.validate();\n signal?.throwIfAborted();\n this.uiContext = ctx;\n try {\n return await connection.run(\n operation,\n payload,\n signal ? AbortSignal.any([signal, this.signal]) : this.signal,\n onCommit,\n );\n } catch (error) {\n if (error instanceof DaemonError) {\n const prototype =\n error.name === \"RemoteSelectionMismatchError\"\n ? RemoteSelectionMismatchError.prototype\n : error.name === \"SyncDecisionRequiredError\"\n ? SyncDecisionRequiredError.prototype\n : undefined;\n if (prototype) {\n const restored = Object.create(prototype) as Error;\n Object.assign(restored, error.remote.properties, { name: error.name, message: error.message });\n throw restored;\n }\n Object.assign(error, error.remote.properties);\n }\n throw error;\n } finally {\n this.uiContext = this.ctx;\n if (\n this.reloadRequested &&\n !this.signal.aborted &&\n !this.disposed &&\n !this.closing &&\n clients.get(this.manager) === this\n ) {\n this.reloadRequested = false;\n if (\"reload\" in ctx && typeof ctx.reload === \"function\") await ctx.reload();\n }\n }\n }\n async markReady(debug: boolean) {\n this.validate();\n this.startupDebug = debug;\n this.initialized = true;\n await this.update();\n this.validate();\n }\n async setBusy(reason: string, busy: boolean) {\n this.validate();\n if (busy) this.busy.add(reason);\n else this.busy.delete(reason);\n await this.update();\n this.validate();\n }\n async update() {\n if (this.connection && !this.paused && !this.disposed && !this.signal.aborted)\n await this.connection.update(this.facts());\n }\n private async callback(callback: Callback, signal: AbortSignal) {\n const payload = callback.payload as {\n reservation?: string;\n targets?: string[];\n generation?: string;\n title?: string;\n message?: string;\n content?: string;\n confirmationLabel?: string;\n summaryLines?: string[];\n items?: string[];\n helpText?: string;\n background?: boolean;\n };\n if (callback.kind === \"queue-release\") {\n if (typeof payload?.reservation !== \"string\") throw new Error(\"Invalid queue release.\");\n await this.gate.releaseRequest(payload.reservation);\n return true;\n }\n this.validate();\n signal.throwIfAborted();\n if (this.paused) throw new Error(\"Pi session is changing; no new work is authorized.\");\n if (callback.kind === \"queue-acquire\") {\n if (payload.background && !this.facts().idle) throw new Error(\"Pi is busy; background apply was not granted.\");\n if (\n payload.generation !== this.generation ||\n typeof payload.reservation !== \"string\" ||\n !Array.isArray(payload.targets)\n )\n throw new Error(\"Stale file-queue request.\");\n return this.gate.acquire(payload.reservation, payload.targets, AbortSignal.any([signal, this.signal]));\n }\n const ctx = this.uiContext;\n const combined = AbortSignal.any([signal, this.signal]);\n if (callback.kind === \"model-binding\") {\n const facts = this.facts();\n const connection = this.connection ?? this.partialConnection;\n if (connection && JSON.stringify(connection.facts.model) !== JSON.stringify(facts.model)) {\n await connection.update(facts);\n this.validate();\n }\n return payload.background && !facts.idle ? null : (facts.model ?? null);\n }\n if (callback.kind === \"reload\") {\n this.reloadRequested = true;\n return true;\n }\n if (!ctx.hasUI || ![\"tui\", \"rpc\"].includes(ctx.mode)) throw new Error(\"This client cannot present safety reviews.\");\n let result: unknown;\n if (callback.kind === \"merge-review\" && typeof payload.title === \"string\" && typeof payload.content === \"string\") {\n const { confirmMergeReview } = await import(\"../ui/merge-review.js\");\n this.validate();\n combined.throwIfAborted();\n result = await confirmMergeReview(\n ctx,\n payload.title,\n payload.content,\n combined,\n () => !combined.aborted && !this.disposed,\n payload.confirmationLabel,\n payload.summaryLines,\n );\n } else if (\n callback.kind === \"confirm\" &&\n typeof payload.title === \"string\" &&\n typeof payload.message === \"string\"\n ) {\n result = await ctx.ui.confirm(safeTerminalText(payload.title), safeTerminalText(payload.message), {\n signal: combined,\n });\n } else if (\n callback.kind === \"select\" &&\n typeof payload.title === \"string\" &&\n Array.isArray(payload.items) &&\n payload.items.every((item) => typeof item === \"string\")\n ) {\n const labels = payload.items.map(safeTerminalText);\n if (new Set(labels).size !== labels.length) throw new Error(\"Daemon choices have ambiguous terminal labels.\");\n const selected = await ctx.ui.select(safeTerminalText(payload.title), labels, { signal: combined });\n const index = selected === undefined ? -1 : labels.indexOf(selected);\n result = index < 0 ? undefined : payload.items[index];\n } else throw new Error(\"Unsupported daemon UI callback.\");\n this.validate();\n combined.throwIfAborted();\n return result;\n }\n disposeForShutdown(reason: string | undefined, targetFile?: string) {\n const facts = this.connection?.facts ?? this.partialConnection?.facts;\n return this.dispose({\n kind: [\"new\", \"resume\", \"fork\", \"reload\"].includes(reason ?? \"\") ? \"replace\" : \"exit\",\n ...(targetFile !== undefined\n ? { file: canonicalPath(targetFile) }\n : reason === \"reload\"\n ? { file: facts?.sessionFile, sessionId: facts?.sessionId }\n : {}),\n cwd: facts?.cwd,\n });\n }\n async dispose(handoff?: ClientHandoff) {\n if (this.disposing) return this.disposing;\n this.closing = true;\n this.disposing = (async () => {\n const connection = this.connection ?? this.partialConnection ?? (await this.connecting?.catch(() => undefined));\n let confirmed = false;\n try {\n await connection?.dispose(handoff);\n confirmed = Boolean(connection);\n } finally {\n this.disposed = true;\n if (clients.get(this.manager) === this) clients.delete(this.manager);\n const gate = this.gate;\n gate.detach();\n if (connection) {\n if (confirmed) await gate.releaseAfterDrain();\n else quarantineClient(gate, connection.paths.root, connection.identity, connection.facts);\n }\n await this.work;\n }\n })();\n return this.disposing;\n }\n}\n", "import { randomUUID } from \"node:crypto\";\nimport path from \"node:path\";\nimport { withFileMutationQueue } from \"@earendil-works/pi-coding-agent\";\nimport { withTargetQueues } from \"@narumitw/pi-sync-daemon/engine/snapshot/snapshot-mutation-queues\";\n\ninterface Gate {\n token: string;\n paths: readonly string[];\n entered: Promise<string>;\n task: Promise<void>;\n granted: boolean;\n cancelled: boolean;\n reject(error: unknown): void;\n release(): void;\n}\n/**\n * Holds the running Pi's actual public file queues; it does not authorize filesystem writes.\n * The engine owns reviewed destinations, which can differ from every participant's current roots.\n */\nexport class PiApplyGate {\n private gates = new Map<string, Gate>();\n constructor(private validate: () => void) {}\n async acquire(requestId: string, targets: readonly string[], signal?: AbortSignal) {\n this.validate();\n signal?.throwIfAborted();\n if (\n !targets.length ||\n targets.length > 16_384 ||\n targets.some((target) => typeof target !== \"string\" || target.includes(\"\\0\") || !path.isAbsolute(target))\n )\n throw new Error(\"Invalid daemon mutation targets.\");\n const normalized = [...new Set(targets.map((target) => path.resolve(target)))].sort();\n const existing = this.gates.get(requestId);\n if (existing) {\n if (JSON.stringify(existing.paths) !== JSON.stringify(normalized)) throw new Error(\"File-queue request changed.\");\n return existing.entered;\n }\n const token = randomUUID();\n let entered!: (token: string) => void;\n let rejected!: (error: unknown) => void;\n const ready = new Promise<string>((resolve, reject) => {\n entered = resolve;\n rejected = reject;\n });\n let release!: () => void;\n const held = new Promise<void>((resolve) => {\n release = resolve;\n });\n const gate: Gate = {\n token,\n paths: normalized,\n entered: ready,\n task: Promise.resolve(),\n release,\n reject: rejected,\n granted: false,\n cancelled: false,\n };\n this.gates.set(requestId, gate);\n const validate = () => {\n if (gate.cancelled) throw new DOMException(\"File-queue reservation was cancelled\", \"AbortError\");\n this.validate();\n };\n gate.task = withTargetQueues(\n normalized,\n { signal, validateMutation: validate },\n async () => {\n validate();\n signal?.throwIfAborted();\n gate.granted = true;\n entered(token);\n // Prompt cancellation cannot revoke a grant while a remote writer may still run.\n await held;\n },\n { mutate: withFileMutationQueue },\n )\n .catch((error) => {\n rejected(error);\n })\n .finally(() => {\n if (this.gates.get(requestId) === gate) this.gates.delete(requestId);\n });\n const abort = () => {\n if (!gate.granted) {\n gate.cancelled = true;\n rejected(signal?.reason);\n release();\n }\n };\n signal?.addEventListener(\"abort\", abort, { once: true });\n void gate.task.finally(() => signal?.removeEventListener(\"abort\", abort));\n return ready;\n }\n async release(token: string) {\n const gate = [...this.gates.values()].find((value) => value.token === token);\n if (!gate) throw new Error(\"Unknown file-queue grant.\");\n await this.releaseGate(gate);\n }\n private async releaseGate(gate: Gate) {\n if (!gate.granted) {\n gate.cancelled = true;\n gate.reject(new DOMException(\"File-queue reservation was released\", \"AbortError\"));\n }\n gate.release();\n // A queued, ungranted placeholder cannot write after cancellation and need not\n // wait for another Pi tool to finish before acknowledgement.\n if (gate.granted) await gate.task;\n }\n async releaseRequest(requestId: string) {\n const gate = this.gates.get(requestId);\n if (!gate) return;\n await this.releaseGate(gate);\n }\n detach() {\n const failure = new DOMException(\"Pi session detached\", \"AbortError\");\n this.validate = () => {\n throw failure;\n };\n this.cancelPending(failure);\n }\n cancelPending(failure: unknown = new DOMException(\"Pi session changing\", \"AbortError\")) {\n for (const gate of this.gates.values())\n if (!gate.granted) {\n gate.cancelled = true;\n gate.reject(failure);\n gate.release();\n }\n }\n get size() {\n return [...this.gates.values()].filter((gate) => gate.granted || !gate.cancelled).length;\n }\n /** Release only after establishing that the associated service cannot still write. */\n async releaseAfterOwnerExit(pid: number) {\n try {\n process.kill(pid, 0);\n throw new Error(\"Daemon owner is still alive; grants remain held.\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ESRCH\") throw error;\n }\n await this.releaseAfterDrain();\n }\n /** Caller must first receive an authenticated same-owner detach/drain acknowledgement. */\n async releaseAfterDrain() {\n await Promise.all([...this.gates.values()].map((gate) => this.releaseGate(gate)));\n }\n}\n", "import { type ClientFacts, DaemonConnection, findDaemon, type Identity } from \"@narumitw/pi-sync-daemon\";\nimport type { PiApplyGate } from \"./apply-gate.js\";\n\ntype Address = { paths: DaemonConnection[\"paths\"]; identity: Identity };\ninterface Recovery {\n gate: PiApplyGate;\n root: string;\n identity: Identity;\n facts: ClientFacts;\n timer?: ReturnType<typeof setInterval>;\n attempt?: Promise<boolean>;\n}\nconst recoveries = new Set<Recovery>();\nfunction alive(pid: number) {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code !== \"ESRCH\";\n }\n}\nfunction finish(record: Recovery) {\n if (record.timer) clearInterval(record.timer);\n recoveries.delete(record);\n}\nfunction attempt(record: Recovery, known?: Address): Promise<boolean> {\n record.attempt ??= (async () => {\n const exited = !alive(record.identity.pid);\n if (exited) await record.gate.releaseAfterOwnerExit(record.identity.pid);\n const address = known ?? (await findDaemon(record.root));\n if (!address || (!exited && address.identity.instance !== record.identity.instance)) return false;\n // Only plain closed-session facts and detached grants cross this recovery boundary.\n // Reclaim the obsolete participant on a compatible owner, reject all new work,\n // and service release callbacks until an authenticated detach confirms drain.\n const connection = new DaemonConnection(\n address.paths,\n address.identity,\n {\n ...record.facts,\n hasUI: false,\n idle: false,\n ready: false,\n },\n {\n callback: async (callback) => {\n const data = callback.payload;\n if (\n callback.kind === \"queue-release\" &&\n data !== null &&\n typeof data === \"object\" &&\n \"reservation\" in data &&\n typeof data.reservation === \"string\"\n ) {\n await record.gate.releaseRequest(data.reservation);\n return true;\n }\n throw new Error(\"Closed Pi participant cannot authorize new work.\");\n },\n },\n );\n try {\n // Cleanup polling does not attach or recreate a retired participant.\n await connection.dispose();\n await record.gate.releaseAfterDrain();\n finish(record);\n return true;\n } finally {\n await connection.dispose();\n }\n })()\n .catch(() => false)\n .finally(() => {\n record.attempt = undefined;\n });\n return record.attempt;\n}\n\n/** Intentionally shared cleanup may outlive a session, but never retains its ctx or UI. */\nexport function quarantineClient(gate: PiApplyGate, root: string, identity: Identity, facts: ClientFacts) {\n gate.detach();\n const record: Recovery = { gate, root, identity: structuredClone(identity), facts: structuredClone(facts) };\n recoveries.add(record);\n record.timer = setInterval(() => {\n void attempt(record);\n }, 1000);\n record.timer.unref();\n void attempt(record);\n}\n\n/** A newly attached client stays unready until obsolete local participants are retired. */\nexport async function recoverDetachedClients(address: Address) {\n const pending = [...recoveries].filter((record) => record.root === address.paths.root);\n const results = await Promise.all(\n pending.map(async (record) => {\n const done = await attempt(record, address);\n return done || !recoveries.has(record) || (await attempt(record, address));\n }),\n );\n if (results.some((done) => !done))\n throw new Error(\n \"Previous Pi cleanup is still uncertain; stop or repair the existing daemon before retrying /reload.\",\n );\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;AAAA,SAAS,yBAAyB;AAClC,SAAS,cAAAA,mBAAkB;AAC3B,SAAS,oBAAoB;AAC7B,OAAO,QAAQ;AACf,OAAOC,WAAU;AACjB,SAAgC,mBAAmB;AACnD;AAAA,EAIE,oBAAAC;AAAA,EACA;AAAA,EA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,QAAQ,EAAE,SAAS,UAAU,EAAE,IAAI,YAAY;AAAA,MAC/E,GAAI,eAAe,SACf,EAAE,MAAM,cAAc,UAAU,EAAE,IAClC,WAAW,WACT,EAAE,MAAM,OAAO,aAAa,WAAW,OAAO,UAAU,IACxD,CAAC;AAAA,MACP,KAAK,OAAO;AAAA,IACd,CAAC;AAAA,EACH;AAAA,EACA,MAAM,QAAQ,SAAyB;AACrC,QAAI,KAAK,UAAW,QAAO,KAAK;AAChC,SAAK,UAAU;AACf,SAAK,aAAa,YAAY;AAC5B,YAAM,aAAa,KAAK,cAAc,KAAK,qBAAsB,MAAM,KAAK,YAAY,MAAM,MAAM,MAAS;AAC7G,UAAI,YAAY;AAChB,UAAI;AACF,cAAM,YAAY,QAAQ,OAAO;AACjC,oBAAY,QAAQ,UAAU;AAAA,MAChC,UAAE;AACA,aAAK,WAAW;AAChB,YAAI,QAAQ,IAAI,KAAK,OAAO,MAAM,KAAM,SAAQ,OAAO,KAAK,OAAO;AACnE,cAAM,OAAO,KAAK;AAClB,aAAK,OAAO;AACZ,YAAI,YAAY;AACd,cAAI,UAAW,OAAM,KAAK,kBAAkB;AAAA,cACvC,kBAAiB,MAAM,WAAW,MAAM,MAAM,WAAW,UAAU,WAAW,KAAK;AAAA,QAC1F;AACA,cAAM,KAAK;AAAA,MACb;AAAA,IACF,GAAG;AACH,WAAO,KAAK;AAAA,EACd;AACF;",
6
- "names": ["randomUUID", "path", "DaemonConnection", "findDaemon", "path", "randomUUID", "findDaemon", "DaemonConnection"]
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/ui/operation-dialogs.ts", "../../src/commands/command-execution.ts", "../../src/commands/command-handler.ts"],
4
- "sourcesContent": ["import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\n\n/** Track History's Pi-owned selector/confirmation lifetime without inspecting renderer internals. */\nexport function trackOperationDialogs<Context extends ExtensionContext>(\n ctx: Context,\n onDialog?: (active: boolean) => void,\n): Context {\n if (!onDialog) return ctx;\n const runDialog = async <Value>(task: () => Promise<Value>): Promise<Value> => {\n onDialog(true);\n try {\n return await task();\n } finally {\n onDialog(false);\n }\n };\n const ui: ExtensionContext[\"ui\"] = {\n ...ctx.ui,\n select: (...args) => runDialog(() => ctx.ui.select(...args)),\n confirm: (...args) => runDialog(() => ctx.ui.confirm(...args)),\n };\n // Forward live context properties: copying the context would hide session\n // replacement from mutation-owner revalidation after a dialog settles.\n return new Proxy(ctx, {\n get(target, key, receiver) {\n return key === \"ui\" ? ui : Reflect.get(target, key, receiver);\n },\n });\n}\n", "import type { ExtensionCommandContext, ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { piDaemonClient, remoteOperation } from \"../daemon/pi-client.js\";\nimport { loadConfig, sessionTokenWarnings, syncSessionsWarnings } from \"../settings/config.js\";\nimport { activeLocalConfigPath, createLocalConfigDocument, localConfigPath } from \"../settings/config-file.js\";\nimport { localConfigTemplate, readLocalConfigObject } from \"../settings/settings-store.js\";\nimport type { AnySyncConfig } from \"../settings/settings-types.js\";\nimport { throwIfAborted } from \"../sync/signals.js\";\nimport { syncErrorGuidance } from \"../sync/sync-error-guidance.js\";\nimport { isSyncDecisionRequiredError, SetupPullRequiresUiError } from \"../sync/sync-errors.js\";\nimport type { SyncLoaders } from \"../sync/sync-loaders.js\";\nimport { RemoteSelectionMismatchError, syncSessionsSelected } from \"../sync/sync-policy.js\";\nimport { automaticSyncSummary } from \"../ui/automatic-sync-summary.js\";\nimport type { RunRouteResult } from \"../ui/cancellable-operation.js\";\nimport { trackOperationDialogs } from \"../ui/operation-dialogs.js\";\nimport { startupTransferSummary } from \"../ui/sync-behavior.js\";\nimport { setSyncStatus } from \"../ui/sync-status.js\";\nimport { safeTerminalText } from \"../ui/terminal-text.js\";\nimport { parseOptions, resolveSyncCommand, splitArgs, usage, validateCommandOptions } from \"./command.js\";\nimport type { CommandOptions } from \"./command-types.js\";\n\nexport async function executeRecoveryCommand(\n rawArgs: string,\n ctx: ExtensionContext,\n signal: AbortSignal | undefined,\n loaders: SyncLoaders,\n onCommit?: () => void,\n setup?: string,\n): Promise<RunRouteResult> {\n try {\n const [subcommand, ...rest] = splitArgs(rawArgs);\n if (subcommand !== \"sync\" && subcommand !== \"pull\" && subcommand !== \"push\") {\n throw new Error(`Unsupported sync recovery route: ${subcommand ?? \"missing\"}`);\n }\n const options = parseOptions(rest);\n if (setup !== undefined) options.setup = setup;\n if (signal) options.signal = signal;\n if (onCommit) options.onCommit = onCommit;\n options.reload = false;\n options.auto = false;\n validateCommandOptions(subcommand, options);\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n if (subcommand === \"push\") {\n const outcome = await operations.push(ctx, options);\n return { kind: \"completed\", ...(outcome ? { outcome } : {}) };\n }\n if (subcommand === \"pull\") {\n const outcome = await operations.pull(ctx, options);\n return { kind: \"completed\", ...(outcome ? { outcome } : {}) };\n }\n await operations.syncBoth(ctx, options);\n return { kind: \"completed\" };\n } catch (error) {\n if (signal?.aborted) return { kind: \"failed\" };\n setSyncStatus(ctx, undefined);\n if (error instanceof RemoteSelectionMismatchError) {\n return { kind: \"remote-selection-required\", decision: error.decision };\n }\n if (isSyncDecisionRequiredError(error)) {\n return { kind: \"decision-required\", decision: error.decision };\n }\n ctx.ui.notify(syncErrorGuidance(error), \"error\");\n return { kind: \"failed\" };\n }\n}\n\nexport async function executeCommand(\n rawArgs: string,\n ctx: ExtensionCommandContext,\n signal: AbortSignal | undefined,\n loaders: SyncLoaders,\n onCommit?: () => void,\n setup?: string,\n onDialog?: (active: boolean) => void,\n retryRefusal = false,\n): Promise<RunRouteResult> {\n ctx = trackOperationDialogs(ctx, onDialog);\n try {\n const command = await resolveSyncCommand(rawArgs, ctx);\n if (signal?.aborted || !command) return { kind: \"completed\" };\n const { subcommand, rest } = command;\n const options = parseOptions(rest);\n if (setup !== undefined) options.setup = setup;\n if (signal) options.signal = signal;\n if (onCommit) options.onCommit = onCommit;\n validateCommandOptions(subcommand, options);\n if (retryRefusal) {\n if (subcommand !== \"sync\") throw new Error(\"A refused-model retry is available only for merged sync.\");\n options.agentRetryRefusal = true;\n }\n\n switch (subcommand) {\n case \"daemon\": {\n const client = piDaemonClient(ctx);\n const action = options.args[0] ?? \"status\";\n if (action === \"handover\") {\n await client.run(\"daemon.handover\", {}, options.signal);\n } else if (action === \"allow-after-exit\" || action === \"revoke-after-exit\") {\n await client.run(\"daemon.handover\", {}, options.signal);\n const policy = (await client.run(\"daemon.policy\", {}, options.signal)) as { fingerprint: string };\n await client.run(\n \"daemon.authorize\",\n { fingerprint: policy.fingerprint, afterExit: action === \"allow-after-exit\" },\n options.signal,\n );\n } else if (action === \"status\") {\n const connection = await client.connect();\n ctx.ui.notify(\n `pi-sync-daemon: connected\\nPID: ${connection.identity.pid}\\nInstance: ${connection.identity.instance}\\nUse pi-sync-daemon status/stop/restart --root <agent-directory> for explicit lifecycle control.`,\n \"info\",\n );\n } else throw new Error(\"Use /sync daemon status|handover|allow-after-exit|revoke-after-exit.\");\n return { kind: \"completed\" };\n }\n case \"help\":\n ctx.ui.notify(usage(), \"info\");\n return { kind: \"completed\" };\n case \"use\": {\n const { useSyncSetup } = await loaders.setupSwitch();\n throwIfAborted(options.signal);\n await useSyncSetup(\n ctx,\n options.args[0] ?? \"\",\n async (selectedSetup) => {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n return operations.pull(ctx, { ...options, setup: selectedSetup });\n },\n undefined,\n options.signal,\n );\n return { kind: \"completed\" };\n }\n case \"init\":\n await initConfig(ctx, signal);\n return { kind: \"completed\" };\n case \"config\":\n await showConfig(ctx, options);\n return { kind: \"completed\" };\n case \"files\": {\n const { showFileSelection } = await import(\"../ui/file-selection.js\");\n throwIfAborted(options.signal);\n await showFileSelection(ctx, options.setup, options.signal);\n return { kind: \"completed\" };\n }\n case \"status\": {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n await operations.status(ctx, options);\n return { kind: \"completed\" };\n }\n case \"diff\": {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n await operations.diff(ctx, options);\n return { kind: \"completed\" };\n }\n case \"conflicts\": {\n const { showConflicts } = await import(\"../sync/conflict-review.js\");\n throwIfAborted(options.signal);\n await showConflicts(ctx, options);\n return { kind: \"completed\" };\n }\n case \"doctor\": {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n await operations.doctor(ctx, options);\n return { kind: \"completed\" };\n }\n case \"push\": {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n const outcome = await operations.push(ctx, options);\n return { kind: \"completed\", ...(outcome ? { outcome } : {}) };\n }\n case \"pull\": {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n const outcome = await operations.pull(ctx, options);\n return { kind: \"completed\", ...(outcome ? { outcome } : {}) };\n }\n case \"sync\": {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n const outcome = await operations.syncBoth(ctx, options);\n return { kind: \"completed\", ...(retryRefusal && outcome ? { outcome } : {}) };\n }\n case \"history\": {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n await operations.history(ctx, options);\n return { kind: \"completed\" };\n }\n case \"rollback\": {\n const operations = await loaders.operations();\n throwIfAborted(options.signal);\n await operations.rollback(ctx, options);\n return { kind: \"completed\" };\n }\n case \"migrate-state\":\n await migrateStateDirectory(ctx, options);\n return { kind: \"completed\" };\n case \"unlock\":\n await remoteOperation(ctx, \"unlock\", options);\n return { kind: \"completed\" };\n default:\n ctx.ui.notify(`Unknown /sync command: ${subcommand}\\n\\n${usage()}`, \"warning\");\n return { kind: \"failed\" };\n }\n } catch (error) {\n if (signal?.aborted) return { kind: \"failed\" };\n setSyncStatus(ctx, undefined);\n if (error instanceof SetupPullRequiresUiError) throw error;\n if (error instanceof RemoteSelectionMismatchError) {\n return { kind: \"remote-selection-required\", decision: error.decision };\n }\n if (isSyncDecisionRequiredError(error)) {\n return { kind: \"decision-required\", decision: error.decision };\n }\n ctx.ui.notify(syncErrorGuidance(error), \"error\");\n return { kind: \"failed\" };\n }\n}\n\nasync function migrateStateDirectory(ctx: ExtensionCommandContext, options: CommandOptions) {\n const result = (await remoteOperation(ctx, \"migrate-state\", options)) as\n | { status: string; message?: string }\n | undefined;\n throwIfAborted(options.signal);\n ctx.ui.notify(\n result?.message ?? \"pi-sync already uses the canonical pi-sync/ state directory.\",\n result?.status === \"deferred\" ? \"warning\" : \"info\",\n );\n}\n\nasync function initConfig(ctx: ExtensionCommandContext, signal?: AbortSignal) {\n const configPath = localConfigPath();\n const existing = await readLocalConfigObject();\n throwIfAborted(signal);\n if (existing) {\n const activePath = await activeLocalConfigPath();\n throwIfAborted(signal);\n ctx.ui.notify(`Config already exists: ${activePath}`, \"info\");\n return;\n }\n\n if (ctx.mode === \"tui\") {\n const { showSetupWizard } = await import(\"../ui/setup/setup-wizard.js\");\n throwIfAborted(signal);\n await showSetupWizard(ctx, signal);\n return;\n }\n await createLocalConfigDocument(localConfigTemplate(), signal);\n throwIfAborted(signal);\n ctx.ui.notify(`Created ${configPath}. Add a storage connection and sync setup before syncing.`, \"info\");\n}\n\nasync function showConfig(ctx: ExtensionCommandContext, options: CommandOptions) {\n const config = await loadConfig(options.setup);\n const warnings = [\n ...(config.backend.type === \"s3\" ? sessionTokenWarnings(config.backend.profile) : []),\n ...syncSessionsWarnings(config),\n ];\n const storageLines = configStorageLines(config);\n ctx.ui.notify(\n [\n \"pi-sync config:\",\n `sync setup: ${config.setupName}`,\n `storage connection: ${config.connectionName}`,\n ...storageLines,\n `storage path: ${config.storagePath}`,\n `automatic sync: ${automaticSyncSummary(config.automatic)}`,\n `settings field merge: ${config.mergeSettings ? \"On\" : \"Off\"}`,\n `machine-local settings.json fields: ${(config.localFields ?? []).map(safeTerminalText).join(\", \") || \"none\"}`,\n `startup transfer: ${startupTransferSummary(config)}`,\n `autonomous sync: ${config.agentMode ? \"On\" : \"Off\"}`,\n `continuous sync: ${config.continuous ? (config.agentMode ? \"On\" : \"paused; Autonomous sync is Off\") : \"Off\"}`,\n `included content: ${config.include.join(\", \") || \"none\"}`,\n `sessions: ${syncSessionsSelected(config) ? \"included\" : \"not included\"}`,\n `settings file: ${localConfigPath()}`,\n ...warnings,\n ].join(\"\\n\"),\n warnings.length > 0 ? \"warning\" : \"info\",\n );\n}\n\nfunction configStorageLines(config: AnySyncConfig) {\n switch (config.backend.type) {\n case \"git\":\n return [\n \"kind: git\",\n `remote: ${displayGitRemote(config.backend.profile.remote)}`,\n \"authentication: existing Git/SSH credentials (not stored)\",\n `branch: ${config.backend.destination.branch}`,\n ];\n case \"webdav\":\n return [\n \"kind: webdav\",\n `url: ${displayWebDavUrl(config.backend.profile.url, config.backend.profile.username)}`,\n \"username: configured (value hidden)\",\n \"password: configured\",\n ];\n case \"s3\":\n return [\n \"kind: s3\",\n `endpoint: ${config.backend.profile.endpoint}`,\n `bucket: ${config.backend.destination.bucket}`,\n `region: ${config.backend.profile.region}`,\n \"access key id: configured\",\n \"secret access key: configured\",\n `session token: ${config.backend.profile.sessionToken ? \"configured\" : \"not configured\"}`,\n ];\n }\n}\n\nfunction displayGitRemote(value: string | undefined) {\n if (!value) return \"missing\";\n try {\n const url = new URL(value);\n url.username = \"\";\n url.password = \"\";\n url.search = \"\";\n url.hash = \"\";\n return url.toString();\n } catch {\n return value.replace(/^(?:[^@\\s]+@)?(?<host>[^:]+):.+$/u, \"$<host>:\u2026\");\n }\n}\n\nfunction displayWebDavUrl(value: string | undefined, username: string | undefined) {\n if (!value) return \"missing\";\n try {\n const url = new URL(value);\n url.username = \"\";\n url.password = \"\";\n url.search = \"\";\n url.hash = \"\";\n return username ? `${url.origin}/\u2026` : `${url.origin}${url.pathname}`;\n } catch {\n return \"invalid (value hidden)\";\n }\n}\n", "import type { ExtensionCommandContext, ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { loadConfig } from \"../settings/config.js\";\nimport { readStateForConfig, syncStateFingerprint } from \"../state/sync-state-store.js\";\nimport { combineSignals } from \"../sync/signals.js\";\nimport { errorMessage } from \"../sync/sync-errors.js\";\nimport type { SyncLoaders } from \"../sync/sync-loaders.js\";\nimport { formatRemoteSelectionMismatch } from \"../sync/sync-policy.js\";\nimport type { RunRouteResult } from \"../ui/cancellable-operation.js\";\nimport {\n observationMatchesConfig,\n type SyncAttentionController,\n type SyncAttentionOrigin,\n syncAttentionMatchesConfig,\n} from \"../ui/sync-attention.js\";\nimport { setSyncStatus } from \"../ui/sync-status.js\";\nimport { parseOptions, splitArgs, validateCommandOptions } from \"./command.js\";\nimport { executeCommand, executeRecoveryCommand } from \"./command-execution.js\";\n\nexport async function handleCommand(\n rawArgs: string,\n ctx: ExtensionCommandContext,\n sessionSignal: AbortSignal,\n loaders: SyncLoaders,\n attention: SyncAttentionController,\n onExplicitSync?: (setup?: string) => void,\n) {\n await reconcileObservation(attention, sessionSignal);\n if (sessionSignal.aborted) return;\n const run = (\n route: string,\n signal?: AbortSignal,\n onCommit?: () => void,\n target?: string,\n onDialog?: (active: boolean) => void,\n retryRefusal = false,\n ) => {\n const [command, ...args] = splitArgs(route);\n if (command === \"sync\" && !retryRefusal) {\n try {\n const options = parseOptions(args);\n validateCommandOptions(\"sync\", options);\n onExplicitSync?.(target ?? options.setup);\n } catch {\n /* Invalid routes do not request an automatic retry. */\n }\n }\n return executeCommand(\n route,\n ctx,\n combineSignals(sessionSignal, signal),\n loaders,\n observationCommitCallback(attention, sessionSignal, onCommit),\n target,\n onDialog,\n retryRefusal,\n );\n };\n if (!rawArgs.trim()) {\n attention.expand();\n try {\n const { showSyncManager } = await import(\"../ui/manager-ui.js\");\n if (sessionSignal.aborted) return;\n await showSyncManager(ctx, run, sessionSignal, {\n getAttention: () => attention.current(),\n getObservation: () => attention.observation(),\n onObservationInvalidated: () => attention.clearObservation(),\n onSelectionResolved: (expected) => {\n if (attention.current() === expected) attention.clear(ctx);\n },\n });\n } catch (error) {\n if (sessionSignal.aborted) return;\n setSyncStatus(ctx, undefined);\n ctx.ui.notify(errorMessage(error), \"error\");\n }\n await reconcileObservation(attention, sessionSignal);\n if (!sessionSignal.aborted) await attention.publish(ctx, sessionSignal);\n return;\n }\n const result = await run(rawArgs);\n if (result.kind === \"decision-required\") {\n ctx.ui.notify(result.decision.directMessage, \"error\");\n } else if (result.kind === \"remote-selection-required\") {\n const origin = directSelectionOrigin(rawArgs);\n if (origin) attention.set(result.decision, origin);\n const deterministic = splitArgs(rawArgs).some((arg) => arg === \"--yes\" || arg === \"-y\");\n if (origin && ctx.mode === \"tui\" && !deterministic) {\n await resolveSelectionAttention(ctx, attention, sessionSignal, loaders);\n } else {\n ctx.ui.notify(\n formatRemoteSelectionMismatch(\n result.decision.setupName,\n result.decision.localInclude,\n result.decision.remoteInclude,\n ),\n \"error\",\n );\n }\n }\n await clearAttentionAfterCompletedOperation(rawArgs, result, ctx, attention, sessionSignal);\n await reconcileSelectionAttention(ctx, attention, sessionSignal);\n await reconcileObservation(attention, sessionSignal);\n if (!sessionSignal.aborted) await attention.publish(ctx, sessionSignal);\n}\n\nfunction observationCommitCallback(\n attention: SyncAttentionController,\n sessionSignal: AbortSignal,\n onCommit?: () => void,\n) {\n const observed = attention.observation();\n return () => {\n // Opening or cancelling a review changes nothing. A commit may change data\n // even if later publication/baseline cleanup fails; never restore old hints.\n if (!sessionSignal.aborted && attention.observation() === observed) attention.clearObservation();\n onCommit?.();\n };\n}\n\nasync function reconcileObservation(attention: SyncAttentionController, signal: AbortSignal) {\n const observed = attention.observation();\n if (!observed || signal.aborted) return;\n try {\n const config = await loadConfig();\n if (signal.aborted || attention.observation() !== observed) return;\n if (!observationMatchesConfig(observed, config)) {\n attention.clearObservation();\n return;\n }\n const state = await readStateForConfig(config);\n if (signal.aborted || attention.observation() !== observed) return;\n if (syncStateFingerprint(state) !== observed.inspection.stateIdentity) attention.clearObservation();\n } catch {\n if (!signal.aborted && attention.observation() === observed) attention.clearObservation();\n }\n}\n\nasync function clearAttentionAfterCompletedOperation(\n rawArgs: string,\n result: RunRouteResult,\n ctx: ExtensionContext,\n attention: SyncAttentionController,\n signal: AbortSignal,\n) {\n if (result.kind !== \"completed\" || result.outcome === \"cancelled\" || signal.aborted) return;\n const [command, ...rest] = splitArgs(rawArgs);\n if (command !== \"sync\" && command !== \"pull\" && command !== \"push\") return;\n const current = attention.current();\n if (!current) return;\n try {\n const options = parseOptions(rest);\n const setupName = options.setup ?? (await loadConfig()).setupName;\n if (signal.aborted || attention.current() !== current) return;\n if (current.decision.setupName === setupName) attention.clear(ctx);\n } catch {\n // Attention reconciliation below owns malformed or concurrently changed settings.\n }\n}\n\nasync function reconcileSelectionAttention(\n ctx: ExtensionContext,\n attention: SyncAttentionController,\n signal: AbortSignal,\n) {\n const current = attention.current();\n if (!current || signal.aborted) return;\n try {\n const config = await loadConfig(current.decision.setupName);\n if (signal.aborted || attention.current() !== current) return;\n if (!syncAttentionMatchesConfig(current, config)) attention.clear(ctx);\n } catch {\n if (!signal.aborted && attention.current() === current) attention.clear(ctx);\n }\n}\n\nfunction directSelectionOrigin(rawArgs: string): SyncAttentionOrigin | undefined {\n const command = splitArgs(rawArgs)[0];\n return command === \"sync\" || command === \"pull\" || command === \"push\" ? command : undefined;\n}\n\nexport async function resolveSelectionAttention(\n ctx: ExtensionContext,\n attention: SyncAttentionController,\n signal: AbortSignal,\n loaders: SyncLoaders,\n options: {\n cancelLabel?: string;\n withStateAccess?: <T>(task: () => Promise<T>) => Promise<T>;\n } = {},\n) {\n const current = attention.current();\n if (!current || signal.aborted) return;\n const { dispatchManagerResult } = await import(\"../ui/manager-result-dispatcher.js\");\n if (signal.aborted || attention.current() !== current) return;\n await dispatchManagerResult(\n ctx,\n { kind: \"remote-selection-required\", decision: current.decision },\n current.origin,\n (route, actionSignal, onCommit, target) => {\n const execute = () =>\n executeRecoveryCommand(\n route,\n ctx,\n combineSignals(signal, actionSignal),\n loaders,\n observationCommitCallback(attention, signal, onCommit),\n target,\n );\n return options.withStateAccess ? options.withStateAccess(execute) : execute();\n },\n signal,\n {\n cancelLabel: options.cancelLabel,\n withStateAccess: options.withStateAccess,\n onSelectionResol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