@narumitw/pi-sync 0.59.0 → 0.60.0
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 +15 -0
- package/README.md +19 -10
- package/dist/chunks/{chunk-AMJRUXFT.ts → chunk-2JNFEZ3V.ts} +2 -6
- package/dist/chunks/{chunk-AMJRUXFT.ts.map → chunk-2JNFEZ3V.ts.map} +1 -1
- package/dist/chunks/{chunk-NGW4JMBF.ts → chunk-4RNCZZY7.ts} +33 -27
- package/dist/chunks/{chunk-NGW4JMBF.ts.map → chunk-4RNCZZY7.ts.map} +3 -3
- package/dist/chunks/{config-J5VZUY4J.ts → chunk-7AC2RX4M.ts} +6 -13
- package/dist/chunks/chunk-7AC2RX4M.ts.map +7 -0
- package/dist/chunks/{chunk-76HID27T.ts → chunk-BGGKHHO4.ts} +18 -14
- package/dist/chunks/{chunk-76HID27T.ts.map → chunk-BGGKHHO4.ts.map} +1 -1
- package/dist/chunks/chunk-BWWTOQOW.ts +737 -0
- package/dist/chunks/chunk-BWWTOQOW.ts.map +7 -0
- package/dist/chunks/chunk-CEMFCWIU.ts +20 -0
- package/dist/chunks/chunk-CEMFCWIU.ts.map +7 -0
- package/dist/chunks/chunk-CZNBKIM5.ts +20 -0
- package/dist/chunks/chunk-CZNBKIM5.ts.map +7 -0
- package/dist/chunks/{chunk-YIPK23JW.ts → chunk-ENFHHB5O.ts} +1 -16
- package/dist/chunks/{chunk-YIPK23JW.ts.map → chunk-ENFHHB5O.ts.map} +1 -1
- package/dist/chunks/{chunk-KHBPED6W.ts → chunk-GSQGBVKG.ts} +2 -2
- package/dist/chunks/chunk-HNKLBM3U.ts +18 -0
- package/dist/chunks/chunk-HNKLBM3U.ts.map +7 -0
- package/dist/chunks/{chunk-QPC5HT3A.ts → chunk-J5COV5TY.ts} +21 -2
- package/dist/chunks/chunk-J5COV5TY.ts.map +7 -0
- package/dist/chunks/chunk-JKBUYCPC.ts +52 -0
- package/dist/chunks/chunk-JKBUYCPC.ts.map +7 -0
- package/dist/chunks/chunk-JZKCOM62.ts +26 -0
- package/dist/chunks/chunk-JZKCOM62.ts.map +7 -0
- package/dist/chunks/chunk-M7RHV3H6.ts +33 -0
- package/dist/chunks/chunk-M7RHV3H6.ts.map +7 -0
- package/dist/chunks/{chunk-2ZZJXITS.ts → chunk-MIXZVHFR.ts} +24 -10
- package/dist/chunks/chunk-MIXZVHFR.ts.map +7 -0
- package/dist/chunks/chunk-NPT2G4FU.ts +15 -0
- package/dist/chunks/chunk-NPT2G4FU.ts.map +7 -0
- package/dist/chunks/chunk-PDBTD2K6.ts +11 -0
- package/dist/chunks/chunk-PDBTD2K6.ts.map +7 -0
- package/dist/chunks/chunk-UBE6XWOM.ts +29 -0
- package/dist/chunks/chunk-UBE6XWOM.ts.map +7 -0
- package/dist/chunks/{chunk-PQ75RPUP.ts → chunk-UZUUUY7C.ts} +8 -8
- package/dist/chunks/chunk-VZCWYXRS.ts +23 -0
- package/dist/chunks/chunk-VZCWYXRS.ts.map +7 -0
- package/dist/chunks/{chunk-DTPELCPW.ts → chunk-YWEYRRQI.ts} +45 -37
- package/dist/chunks/chunk-YWEYRRQI.ts.map +7 -0
- package/dist/chunks/{chunk-ECYCNZOE.ts → chunk-ZMNVNECV.ts} +5 -1
- package/dist/chunks/chunk-ZMNVNECV.ts.map +7 -0
- package/dist/chunks/{command-handler-SDGKIQH2.ts → command-handler-3O76V7Q5.ts} +80 -86
- package/dist/chunks/command-handler-3O76V7Q5.ts.map +7 -0
- package/dist/chunks/conflict-review-XBSME2ER.ts +18 -0
- package/dist/chunks/conflict-review-XBSME2ER.ts.map +7 -0
- package/dist/chunks/{continuous-record-OM64J27R.ts → continuous-record-ZHUXVO4E.ts} +5 -13
- package/dist/chunks/continuous-record-ZHUXVO4E.ts.map +7 -0
- package/dist/chunks/{file-selection-7HEVPO4T.ts → file-selection-S6CNNNQI.ts} +11 -14
- package/dist/chunks/{file-selection-7HEVPO4T.ts.map → file-selection-S6CNNNQI.ts.map} +1 -1
- package/dist/chunks/manager-result-dispatcher-I2AMCCE7.ts +18 -0
- package/dist/chunks/{manager-ui-65ZETN6F.ts → manager-ui-SJOBTJLY.ts} +80 -123
- package/dist/chunks/manager-ui-SJOBTJLY.ts.map +7 -0
- package/dist/chunks/merge-review-SGDLMVS4.ts +10 -0
- package/dist/chunks/remote-selection-ui-GZHPDQ4L.ts +17 -0
- package/dist/chunks/{setup-switch-AB27ADDI.ts → setup-switch-M3BAFGJM.ts} +9 -13
- package/dist/chunks/{setup-wizard-5FILKFLQ.ts → setup-wizard-NFAWP4KF.ts} +18 -21
- package/dist/chunks/{setup-wizard-5FILKFLQ.ts.map → setup-wizard-NFAWP4KF.ts.map} +1 -1
- package/dist/chunks/{snapshot-G3W2GOGB.ts → snapshot-D4SFDP5J.ts} +8 -13
- package/dist/chunks/snapshot-D4SFDP5J.ts.map +7 -0
- package/dist/chunks/snapshot-transaction-directory-TNKBQ3UQ.ts +13 -0
- package/dist/chunks/snapshot-transaction-directory-TNKBQ3UQ.ts.map +7 -0
- package/dist/chunks/state-directory-JZSZVVPX.ts +17 -0
- package/dist/chunks/sync-inspection-BJ4KPPNO.ts +23 -0
- package/dist/chunks/sync-inspection-BJ4KPPNO.ts.map +7 -0
- package/dist/chunks/sync-operations-TLWER2TT.ts +45 -0
- package/dist/chunks/sync-operations-TLWER2TT.ts.map +7 -0
- package/dist/chunks/{sync-state-H4TFZZ7S.ts → sync-state-FVCJJ7MY.ts} +5 -11
- package/dist/chunks/sync-state-FVCJJ7MY.ts.map +7 -0
- package/dist/index.ts +269 -313
- package/dist/index.ts.map +4 -4
- package/docs/daemon-migration.md +93 -0
- package/package.json +3 -6
- package/skills/configure-pi-sync/SKILL.md +1 -1
- package/skills/configure-pi-sync/references/configuration.md +19 -6
- package/src/backends/backend-factory.ts +2 -23
- package/src/backends/backend-identity.ts +5 -40
- package/src/backends/backend-types.ts +1 -81
- package/src/backends/git/git-backend.ts +6 -784
- package/src/backends/git/git-config.ts +8 -130
- package/src/backends/git/git-runner.ts +7 -255
- package/src/backends/git/git-storage.ts +14 -293
- package/src/backends/s3/s3-backend.ts +11 -523
- package/src/backends/s3/s3-client.ts +2 -399
- package/src/backends/s3/s3-conditions.ts +2 -67
- package/src/backends/snapshot-pointer.ts +2 -27
- package/src/backends/sync-backend.ts +6 -101
- package/src/backends/webdav/webdav-backend.ts +10 -622
- package/src/backends/webdav/webdav-client.ts +6 -370
- package/src/backends/webdav/webdav-config.ts +8 -82
- package/src/commands/command-execution.ts +40 -36
- package/src/commands/command.ts +23 -1
- package/src/daemon/apply-gate.ts +146 -0
- package/src/daemon/pi-client.ts +591 -0
- package/src/daemon/recovery.ts +103 -0
- package/src/paths.ts +12 -83
- package/src/settings/config-errors.ts +2 -6
- package/src/settings/config-file.ts +19 -693
- package/src/settings/config.ts +16 -263
- package/src/settings/settings-management.ts +11 -254
- package/src/settings/settings-store.ts +10 -48
- package/src/settings/settings-types.ts +1 -157
- package/src/settings/settings-validation.ts +17 -435
- package/src/snapshot/session-paths.ts +11 -111
- package/src/snapshot/snapshot-apply.ts +9 -322
- package/src/snapshot/snapshot-case-replacement.ts +6 -80
- package/src/snapshot/snapshot-codec.ts +2 -59
- package/src/snapshot/snapshot-exclude-safety.ts +2 -44
- package/src/snapshot/snapshot-mutation-queues.ts +6 -142
- package/src/snapshot/snapshot-paths.ts +2 -11
- package/src/snapshot/snapshot-root-transition.ts +6 -154
- package/src/snapshot/snapshot-transaction-directory.ts +5 -16
- package/src/snapshot/snapshot-transaction-plan.ts +2 -72
- package/src/snapshot/snapshot-transaction.ts +6 -946
- package/src/snapshot/snapshot-types.ts +1 -43
- package/src/snapshot/snapshot.ts +19 -447
- package/src/state/json-file.ts +2 -47
- package/src/state/lock-policy.ts +2 -2
- package/src/state/lock.ts +10 -292
- package/src/state/lockfile-fs.ts +2 -25
- package/src/state/merge-baseline-store.ts +8 -208
- package/src/state/mutation-directory-sync.ts +2 -34
- package/src/state/operation-availability.ts +7 -59
- package/src/state/state-directory.ts +8 -243
- package/src/state/state-types.ts +1 -25
- package/src/state/sync-state-store.ts +11 -75
- package/src/sync/agent-candidate.ts +7 -256
- package/src/sync/agent-plan.ts +2 -107
- package/src/sync/agent-policy.ts +10 -13
- package/src/sync/agent-refusal-retry.ts +2 -54
- package/src/sync/agent-request.ts +2 -19
- package/src/sync/agent-runner.ts +2 -191
- package/src/sync/agent-store.ts +7 -182
- package/src/sync/agent-sync.ts +2 -141
- package/src/sync/apply-review.ts +2 -63
- package/src/sync/automatic-sync.ts +55 -111
- package/src/sync/conflict-artifact-ownership.ts +2 -63
- package/src/sync/conflict-artifacts.ts +8 -195
- package/src/sync/conflict-groups.ts +2 -68
- package/src/sync/conflict-preview.ts +2 -56
- package/src/sync/conflict-resolution.ts +2 -93
- package/src/sync/conflict-retention.ts +2 -72
- package/src/sync/conflict-review.ts +3 -92
- package/src/sync/content-conflicts.ts +2 -73
- package/src/sync/continuous-errors.ts +7 -85
- package/src/sync/continuous-lease.ts +2 -216
- package/src/sync/continuous-record.ts +10 -261
- package/src/sync/continuous-storage.ts +12 -64
- package/src/sync/continuous-sync.ts +2 -563
- package/src/sync/continuous-watch.ts +2 -61
- package/src/sync/exclude-policy.ts +6 -84
- package/src/sync/field-migration.ts +2 -39
- package/src/sync/file-merge-planner.ts +2 -143
- package/src/sync/json-document.ts +7 -184
- package/src/sync/local-field-policy.ts +2 -29
- package/src/sync/local-fields.ts +9 -119
- package/src/sync/merge-apply.ts +2 -439
- package/src/sync/merge-journal.ts +10 -228
- package/src/sync/merge-transfer-error.ts +2 -72
- package/src/sync/merged-sync.ts +2 -919
- package/src/sync/mutation-owner.ts +2 -22
- package/src/sync/package-merge.ts +2 -87
- package/src/sync/partial-progress.ts +2 -55
- package/src/sync/remote-snapshot.ts +7 -79
- package/src/sync/session-merge.ts +2 -194
- package/src/sync/settings-conflicts.ts +2 -64
- package/src/sync/settings-merge.ts +6 -121
- package/src/sync/signals.ts +2 -8
- package/src/sync/startup-check.ts +15 -31
- package/src/sync/startup-timings.ts +2 -94
- package/src/sync/sync-decision.ts +3 -111
- package/src/sync/sync-error-guidance.ts +2 -46
- package/src/sync/sync-errors.ts +7 -23
- package/src/sync/sync-inspection.ts +10 -59
- package/src/sync/sync-local.ts +2 -44
- package/src/sync/sync-mutations.ts +10 -788
- package/src/sync/sync-operations.ts +32 -11
- package/src/sync/sync-policy.ts +34 -474
- package/src/sync/sync-queries.ts +2 -247
- package/src/sync/sync-state.ts +18 -157
- package/src/sync/text-merge.ts +10 -133
- package/src/sync-extension.ts +192 -142
- package/dist/chunks/agent-candidate-ZHN7FTZT.ts +0 -30
- package/dist/chunks/agent-plan-ILFEUJ2E.ts +0 -124
- package/dist/chunks/agent-plan-ILFEUJ2E.ts.map +0 -7
- package/dist/chunks/agent-refusal-retry-HRMHCX2A.ts +0 -73
- package/dist/chunks/agent-refusal-retry-HRMHCX2A.ts.map +0 -7
- package/dist/chunks/agent-runner-FCRV2Z75.ts +0 -185
- package/dist/chunks/agent-runner-FCRV2Z75.ts.map +0 -7
- package/dist/chunks/agent-store-CCKN4DPR.ts +0 -175
- package/dist/chunks/agent-store-CCKN4DPR.ts.map +0 -7
- package/dist/chunks/agent-sync-EGA2I5W7.ts +0 -22
- package/dist/chunks/chunk-25QCU3LY.ts +0 -220
- package/dist/chunks/chunk-25QCU3LY.ts.map +0 -7
- package/dist/chunks/chunk-2JZFHNLM.ts +0 -113
- package/dist/chunks/chunk-2JZFHNLM.ts.map +0 -7
- package/dist/chunks/chunk-2UKUKIBI.ts +0 -25
- package/dist/chunks/chunk-2UKUKIBI.ts.map +0 -7
- package/dist/chunks/chunk-2ZZJXITS.ts.map +0 -7
- package/dist/chunks/chunk-3JTZF7Z5.ts +0 -77
- package/dist/chunks/chunk-3JTZF7Z5.ts.map +0 -7
- package/dist/chunks/chunk-3ST7RSYN.ts +0 -21
- package/dist/chunks/chunk-3ST7RSYN.ts.map +0 -7
- package/dist/chunks/chunk-4NVHHDN2.ts +0 -61
- package/dist/chunks/chunk-4NVHHDN2.ts.map +0 -7
- package/dist/chunks/chunk-5SFMBY5P.ts +0 -26
- package/dist/chunks/chunk-5SFMBY5P.ts.map +0 -7
- package/dist/chunks/chunk-6OFMB6KK.ts +0 -215
- package/dist/chunks/chunk-6OFMB6KK.ts.map +0 -7
- package/dist/chunks/chunk-6XU5HZAN.ts +0 -205
- package/dist/chunks/chunk-6XU5HZAN.ts.map +0 -7
- package/dist/chunks/chunk-6YGRZSCN.ts +0 -128
- package/dist/chunks/chunk-6YGRZSCN.ts.map +0 -7
- package/dist/chunks/chunk-7D5SF7P3.ts +0 -29
- package/dist/chunks/chunk-7D5SF7P3.ts.map +0 -7
- package/dist/chunks/chunk-7WYF2KUO.ts +0 -1161
- package/dist/chunks/chunk-7WYF2KUO.ts.map +0 -7
- package/dist/chunks/chunk-APDNHB2T.ts +0 -2037
- package/dist/chunks/chunk-APDNHB2T.ts.map +0 -7
- package/dist/chunks/chunk-AR2DGDUI.ts +0 -55
- package/dist/chunks/chunk-AR2DGDUI.ts.map +0 -7
- package/dist/chunks/chunk-DT7M4VQS.ts +0 -69
- package/dist/chunks/chunk-DT7M4VQS.ts.map +0 -7
- package/dist/chunks/chunk-DTPELCPW.ts.map +0 -7
- package/dist/chunks/chunk-ECYCNZOE.ts.map +0 -7
- package/dist/chunks/chunk-FHE2DCA2.ts +0 -61
- package/dist/chunks/chunk-FHE2DCA2.ts.map +0 -7
- package/dist/chunks/chunk-G4RUXRWZ.ts +0 -48
- package/dist/chunks/chunk-G4RUXRWZ.ts.map +0 -7
- package/dist/chunks/chunk-ILXMZ2HU.ts +0 -58
- package/dist/chunks/chunk-ILXMZ2HU.ts.map +0 -7
- package/dist/chunks/chunk-LA3HQMFG.ts +0 -115
- package/dist/chunks/chunk-LA3HQMFG.ts.map +0 -7
- package/dist/chunks/chunk-M6VQJIOU.ts +0 -54
- package/dist/chunks/chunk-M6VQJIOU.ts.map +0 -7
- package/dist/chunks/chunk-MKC3PXCN.ts +0 -369
- package/dist/chunks/chunk-MKC3PXCN.ts.map +0 -7
- package/dist/chunks/chunk-OQBE2OMB.ts +0 -88
- package/dist/chunks/chunk-OQBE2OMB.ts.map +0 -7
- package/dist/chunks/chunk-P3YD4ONV.ts +0 -123
- package/dist/chunks/chunk-P3YD4ONV.ts.map +0 -7
- package/dist/chunks/chunk-PRUEIIK7.ts +0 -24
- package/dist/chunks/chunk-PRUEIIK7.ts.map +0 -7
- package/dist/chunks/chunk-PWMWOJP4.ts +0 -17
- package/dist/chunks/chunk-PWMWOJP4.ts.map +0 -7
- package/dist/chunks/chunk-QPC5HT3A.ts.map +0 -7
- package/dist/chunks/chunk-QQVK2XFC.ts +0 -64
- package/dist/chunks/chunk-QQVK2XFC.ts.map +0 -7
- package/dist/chunks/chunk-RDOX3VH5.ts +0 -140
- package/dist/chunks/chunk-RDOX3VH5.ts.map +0 -7
- package/dist/chunks/chunk-S7D6XWHI.ts +0 -258
- package/dist/chunks/chunk-S7D6XWHI.ts.map +0 -7
- package/dist/chunks/chunk-SHPNS7FM.ts +0 -64
- package/dist/chunks/chunk-SHPNS7FM.ts.map +0 -7
- package/dist/chunks/chunk-SWRVXVFD.ts +0 -248
- package/dist/chunks/chunk-SWRVXVFD.ts.map +0 -7
- package/dist/chunks/chunk-T2SJD3N7.ts +0 -99
- package/dist/chunks/chunk-T2SJD3N7.ts.map +0 -7
- package/dist/chunks/chunk-T2TYBLXK.ts +0 -27
- package/dist/chunks/chunk-T2TYBLXK.ts.map +0 -7
- package/dist/chunks/chunk-UZSDS4HF.ts +0 -403
- package/dist/chunks/chunk-UZSDS4HF.ts.map +0 -7
- package/dist/chunks/chunk-VPODHKOX.ts +0 -229
- package/dist/chunks/chunk-VPODHKOX.ts.map +0 -7
- package/dist/chunks/chunk-WEKGW7HV.ts +0 -162
- package/dist/chunks/chunk-WEKGW7HV.ts.map +0 -7
- package/dist/chunks/chunk-WUHRVSWI.ts +0 -369
- package/dist/chunks/chunk-WUHRVSWI.ts.map +0 -7
- package/dist/chunks/chunk-X7R6DCVF.ts +0 -28
- package/dist/chunks/chunk-X7R6DCVF.ts.map +0 -7
- package/dist/chunks/chunk-XJHQPB3E.ts +0 -107
- package/dist/chunks/chunk-XJHQPB3E.ts.map +0 -7
- package/dist/chunks/chunk-XZ3ZTHKR.ts +0 -1184
- package/dist/chunks/chunk-XZ3ZTHKR.ts.map +0 -7
- package/dist/chunks/chunk-YDVQYUHE.ts +0 -34
- package/dist/chunks/chunk-YDVQYUHE.ts.map +0 -7
- package/dist/chunks/chunk-YEULK7MK.ts +0 -415
- package/dist/chunks/chunk-YEULK7MK.ts.map +0 -7
- package/dist/chunks/chunk-YHT4YTYG.ts +0 -31
- package/dist/chunks/chunk-YHT4YTYG.ts.map +0 -7
- package/dist/chunks/chunk-ZW5ZLGBI.ts +0 -154
- package/dist/chunks/chunk-ZW5ZLGBI.ts.map +0 -7
- package/dist/chunks/command-handler-SDGKIQH2.ts.map +0 -7
- package/dist/chunks/conflict-artifacts-MYSH3L2J.ts +0 -33
- package/dist/chunks/conflict-review-J6ZSPNWL.ts +0 -190
- package/dist/chunks/conflict-review-J6ZSPNWL.ts.map +0 -7
- package/dist/chunks/continuous-sync-BH5SWIRV.ts +0 -590
- package/dist/chunks/continuous-sync-BH5SWIRV.ts.map +0 -7
- package/dist/chunks/git-backend-6CKI6CUG.ts +0 -1074
- package/dist/chunks/git-backend-6CKI6CUG.ts.map +0 -7
- package/dist/chunks/local-fields-SR7PH66U.ts +0 -27
- package/dist/chunks/local-fields-SR7PH66U.ts.map +0 -7
- package/dist/chunks/manager-result-dispatcher-CXUP5WDP.ts +0 -33
- package/dist/chunks/manager-result-dispatcher-CXUP5WDP.ts.map +0 -7
- package/dist/chunks/manager-ui-65ZETN6F.ts.map +0 -7
- package/dist/chunks/merge-baseline-store-4Y2X7P2D.ts +0 -26
- package/dist/chunks/merge-baseline-store-4Y2X7P2D.ts.map +0 -7
- package/dist/chunks/remote-selection-ui-W55BQDJQ.ts +0 -32
- package/dist/chunks/remote-selection-ui-W55BQDJQ.ts.map +0 -7
- package/dist/chunks/s3-backend-FDK7JSDQ.ts +0 -845
- package/dist/chunks/s3-backend-FDK7JSDQ.ts.map +0 -7
- package/dist/chunks/setup-switch-AB27ADDI.ts.map +0 -7
- package/dist/chunks/snapshot-G3W2GOGB.ts.map +0 -7
- package/dist/chunks/snapshot-transaction-SGRUWT73.ts +0 -25
- package/dist/chunks/snapshot-transaction-SGRUWT73.ts.map +0 -7
- package/dist/chunks/sync-inspection-MDYHZHT7.ts +0 -26
- package/dist/chunks/sync-inspection-MDYHZHT7.ts.map +0 -7
- package/dist/chunks/sync-operations-ZAUP65FH.ts +0 -1032
- package/dist/chunks/sync-operations-ZAUP65FH.ts.map +0 -7
- package/dist/chunks/sync-state-H4TFZZ7S.ts.map +0 -7
- package/dist/chunks/webdav-backend-UNMIAXM5.ts +0 -852
- package/dist/chunks/webdav-backend-UNMIAXM5.ts.map +0 -7
- /package/dist/chunks/{chunk-KHBPED6W.ts.map → chunk-GSQGBVKG.ts.map} +0 -0
- /package/dist/chunks/{chunk-PQ75RPUP.ts.map → chunk-UZUUUY7C.ts.map} +0 -0
- /package/dist/chunks/{agent-candidate-ZHN7FTZT.ts.map → manager-result-dispatcher-I2AMCCE7.ts.map} +0 -0
- /package/dist/chunks/{agent-sync-EGA2I5W7.ts.map → merge-review-SGDLMVS4.ts.map} +0 -0
- /package/dist/chunks/{config-J5VZUY4J.ts.map → remote-selection-ui-GZHPDQ4L.ts.map} +0 -0
- /package/dist/chunks/{conflict-artifacts-MYSH3L2J.ts.map → setup-switch-M3BAFGJM.ts.map} +0 -0
- /package/dist/chunks/{continuous-record-OM64J27R.ts.map → state-directory-JZSZVVPX.ts.map} +0 -0
|
@@ -0,0 +1,591 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { realpathSync } from "node:fs";
|
|
4
|
+
import fs from "node:fs/promises";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { type ExtensionContext, getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import {
|
|
8
|
+
type Callback,
|
|
9
|
+
type ClientFacts,
|
|
10
|
+
type ClientHandoff,
|
|
11
|
+
DaemonConnection,
|
|
12
|
+
DaemonError,
|
|
13
|
+
type DocumentView,
|
|
14
|
+
documentFingerprint,
|
|
15
|
+
ensureDaemon,
|
|
16
|
+
findDaemon,
|
|
17
|
+
MAX_SETTINGS_BYTES,
|
|
18
|
+
modelSignature,
|
|
19
|
+
} from "@narumitw/sync-daemon";
|
|
20
|
+
import { type ConfigAuthority, configureEngineHost } from "@narumitw/sync-daemon/engine/host";
|
|
21
|
+
import { type LocalConfigDocument, peekLocalConfigDocument } from "@narumitw/sync-daemon/engine/settings/config-file";
|
|
22
|
+
import { validateSettingsDocument } from "@narumitw/sync-daemon/engine/settings/settings-validation";
|
|
23
|
+
import { sessionDirFromContext } from "@narumitw/sync-daemon/engine/snapshot/session-paths";
|
|
24
|
+
import type { CommandOptions } from "../commands/command-types.js";
|
|
25
|
+
import type { StartupTimingPublisher } from "../sync/startup-timings.js";
|
|
26
|
+
import { SyncDecisionRequiredError } from "../sync/sync-errors.js";
|
|
27
|
+
import { RemoteSelectionMismatchError } from "../sync/sync-policy.js";
|
|
28
|
+
import { type SyncStatusPresentation, setSyncStatus } from "../ui/sync-status.js";
|
|
29
|
+
import { safeTerminalText } from "../ui/terminal-text.js";
|
|
30
|
+
import { PiApplyGate } from "./apply-gate.js";
|
|
31
|
+
import { quarantineClient, recoverDetachedClients } from "./recovery.js";
|
|
32
|
+
|
|
33
|
+
const scope = new AsyncLocalStorage<PiDaemonClient>();
|
|
34
|
+
const clients = new WeakMap<ExtensionContext["sessionManager"], PiDaemonClient>();
|
|
35
|
+
export function currentPiDaemonClient() {
|
|
36
|
+
return current();
|
|
37
|
+
}
|
|
38
|
+
function current() {
|
|
39
|
+
const client = scope.getStore();
|
|
40
|
+
if (!client) throw new Error("Pi synchronization requires a current session-bound daemon client.");
|
|
41
|
+
client.validate();
|
|
42
|
+
return client;
|
|
43
|
+
}
|
|
44
|
+
function canonicalPath(value: string | undefined): string | undefined {
|
|
45
|
+
if (value === undefined) return undefined;
|
|
46
|
+
if (!path.isAbsolute(value)) throw new Error("Pi session paths must be absolute.");
|
|
47
|
+
const parts: string[] = [];
|
|
48
|
+
let cursor = path.resolve(value);
|
|
49
|
+
for (;;) {
|
|
50
|
+
try {
|
|
51
|
+
return path.join(realpathSync(cursor), ...parts.toReversed());
|
|
52
|
+
} catch (error) {
|
|
53
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT" || path.dirname(cursor) === cursor) throw error;
|
|
54
|
+
parts.push(path.basename(cursor));
|
|
55
|
+
cursor = path.dirname(cursor);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
function decode(value: unknown): LocalConfigDocument | undefined {
|
|
60
|
+
if (value === null) return undefined;
|
|
61
|
+
const document = value as DocumentView;
|
|
62
|
+
if (
|
|
63
|
+
!document ||
|
|
64
|
+
typeof document.path !== "string" ||
|
|
65
|
+
typeof document.bytes !== "string" ||
|
|
66
|
+
!document.identity ||
|
|
67
|
+
!document.parsed
|
|
68
|
+
)
|
|
69
|
+
throw new Error("Invalid settings response.");
|
|
70
|
+
return { ...document, bytes: Buffer.from(document.bytes, "base64") };
|
|
71
|
+
}
|
|
72
|
+
function fingerprint(document: LocalConfigDocument | undefined) {
|
|
73
|
+
return documentFingerprint(
|
|
74
|
+
document ? { bytes: document.bytes.toString("base64"), identity: document.identity } : undefined,
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
let settingsQueue = Promise.resolve();
|
|
78
|
+
const authority: ConfigAuthority = {
|
|
79
|
+
read: (repair) => {
|
|
80
|
+
const client = current();
|
|
81
|
+
return settingsQueue.then(() => {
|
|
82
|
+
client.validate();
|
|
83
|
+
return client.readSettings(repair);
|
|
84
|
+
});
|
|
85
|
+
},
|
|
86
|
+
update: <T extends Record<string, unknown>>(
|
|
87
|
+
fallback: T,
|
|
88
|
+
update: (value: T) => T,
|
|
89
|
+
validate: (value: Record<string, unknown>) => void,
|
|
90
|
+
signal?: AbortSignal,
|
|
91
|
+
): Promise<T> => {
|
|
92
|
+
const client = current();
|
|
93
|
+
// Capture ownership and invocation order before prerequisite awaits.
|
|
94
|
+
const operation = settingsQueue.then(async () => {
|
|
95
|
+
client.validate();
|
|
96
|
+
signal?.throwIfAborted();
|
|
97
|
+
const document = await client.readSettings(true);
|
|
98
|
+
client.validate();
|
|
99
|
+
signal?.throwIfAborted();
|
|
100
|
+
const next = update(structuredClone(document?.parsed ?? fallback) as T);
|
|
101
|
+
validate(next);
|
|
102
|
+
await client.run("settings.cas", { expected: fingerprint(document), next }, signal);
|
|
103
|
+
client.validate();
|
|
104
|
+
return next;
|
|
105
|
+
});
|
|
106
|
+
settingsQueue = operation.then(
|
|
107
|
+
() => undefined,
|
|
108
|
+
() => undefined,
|
|
109
|
+
);
|
|
110
|
+
return operation;
|
|
111
|
+
},
|
|
112
|
+
create: async (next, signal) => {
|
|
113
|
+
await current().run("settings.cas", { expected: null, next }, signal);
|
|
114
|
+
},
|
|
115
|
+
replace: async (document, next) => {
|
|
116
|
+
await current().run("settings.cas", { expected: fingerprint(document), next });
|
|
117
|
+
},
|
|
118
|
+
};
|
|
119
|
+
/** Factory registration installs only adapters; it starts no process and performs no I/O. */
|
|
120
|
+
export function installPiDaemonHost() {
|
|
121
|
+
configureEngineHost({
|
|
122
|
+
root: () => scope.getStore()?.root ?? path.resolve(getAgentDir()),
|
|
123
|
+
config: authority,
|
|
124
|
+
mutate: async () => {
|
|
125
|
+
throw new Error("File mutation belongs to sync-daemon; no in-process fallback is permitted.");
|
|
126
|
+
},
|
|
127
|
+
review: async () => {
|
|
128
|
+
throw new Error("Engine reviews must arrive through the daemon API.");
|
|
129
|
+
},
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
export function bindPiDaemonClient(ctx: ExtensionContext, signal: AbortSignal, publish?: StartupTimingPublisher) {
|
|
133
|
+
const client = new PiDaemonClient(ctx, signal, publish);
|
|
134
|
+
clients.set(ctx.sessionManager, client);
|
|
135
|
+
return client;
|
|
136
|
+
}
|
|
137
|
+
export function piDaemonClient(ctx: ExtensionContext) {
|
|
138
|
+
const client = clients.get(ctx.sessionManager);
|
|
139
|
+
if (!client) throw new Error("The Pi synchronization client is not attached to this session.");
|
|
140
|
+
client.validate();
|
|
141
|
+
return client;
|
|
142
|
+
}
|
|
143
|
+
export function withPiDaemonClient<Context extends ExtensionContext, T>(
|
|
144
|
+
ctx: Context,
|
|
145
|
+
action: (owned: Context) => Promise<T>,
|
|
146
|
+
) {
|
|
147
|
+
const client = piDaemonClient(ctx);
|
|
148
|
+
// TUI input arrives from Pi's event loop, outside the command's async call tree.
|
|
149
|
+
// Bind public component methods so later menu actions retain this exact owner,
|
|
150
|
+
// never a replacement session selected through a global fallback.
|
|
151
|
+
const ui = new Proxy(ctx.ui, {
|
|
152
|
+
get(target, property) {
|
|
153
|
+
if (property !== "custom") return Reflect.get(target, property, target);
|
|
154
|
+
return (...args: Parameters<ExtensionContext["ui"]["custom"]>) => {
|
|
155
|
+
const [factory, options] = args;
|
|
156
|
+
const wrap = (component: Awaited<ReturnType<typeof factory>>) => {
|
|
157
|
+
const methods = new Map<PropertyKey, { source: unknown; bound: unknown }>();
|
|
158
|
+
return new Proxy(component, {
|
|
159
|
+
get(original, key) {
|
|
160
|
+
const value: unknown = Reflect.get(original, key, original);
|
|
161
|
+
if (typeof value !== "function") return value;
|
|
162
|
+
const saved = methods.get(key);
|
|
163
|
+
if (saved?.source === value) return saved.bound;
|
|
164
|
+
const bound = (...values: unknown[]) => scope.run(client, () => Reflect.apply(value, original, values));
|
|
165
|
+
methods.set(key, { source: value, bound });
|
|
166
|
+
return bound;
|
|
167
|
+
},
|
|
168
|
+
});
|
|
169
|
+
};
|
|
170
|
+
const invoke = (...provided: Parameters<typeof factory>) => {
|
|
171
|
+
const component = scope.run(client, () => factory(...provided));
|
|
172
|
+
return component instanceof Promise ? component.then(wrap) : wrap(component);
|
|
173
|
+
};
|
|
174
|
+
// Do not turn synchronous editors/reviews into asynchronous factories.
|
|
175
|
+
return target.custom(
|
|
176
|
+
factory.constructor.name === "AsyncFunction" ? async (...provided) => invoke(...provided) : invoke,
|
|
177
|
+
options,
|
|
178
|
+
);
|
|
179
|
+
};
|
|
180
|
+
},
|
|
181
|
+
});
|
|
182
|
+
const owned = new Proxy(ctx, {
|
|
183
|
+
get(target, key) {
|
|
184
|
+
return key === "ui" ? ui : Reflect.get(target, key, target);
|
|
185
|
+
},
|
|
186
|
+
});
|
|
187
|
+
return scope.run(client, () => action(owned));
|
|
188
|
+
}
|
|
189
|
+
export async function remoteOperation(ctx: ExtensionContext, operation: string, options: CommandOptions) {
|
|
190
|
+
const client = piDaemonClient(ctx);
|
|
191
|
+
const { signal, onCommit, args, setup } = options;
|
|
192
|
+
const payload = {
|
|
193
|
+
args,
|
|
194
|
+
...(setup === undefined ? {} : { setup }),
|
|
195
|
+
yes: options.yes,
|
|
196
|
+
force: options.force,
|
|
197
|
+
stale: options.stale,
|
|
198
|
+
silent: options.silent,
|
|
199
|
+
reload: options.reload,
|
|
200
|
+
...(options.agentRetryRefusal ? { agentRetryRefusal: true } : {}),
|
|
201
|
+
};
|
|
202
|
+
return client.run(operation, payload, signal, ctx, onCommit);
|
|
203
|
+
}
|
|
204
|
+
export class PiDaemonClient {
|
|
205
|
+
private connection?: DaemonConnection;
|
|
206
|
+
private partialConnection?: DaemonConnection;
|
|
207
|
+
private work = Promise.resolve();
|
|
208
|
+
private closing = false;
|
|
209
|
+
private paused = false;
|
|
210
|
+
private pausing?: Promise<void>;
|
|
211
|
+
private connecting?: Promise<DaemonConnection>;
|
|
212
|
+
private disposed = false;
|
|
213
|
+
private disposing?: Promise<void>;
|
|
214
|
+
private uiContext: ExtensionContext;
|
|
215
|
+
private reloadRequested = false;
|
|
216
|
+
private readonly busy = new Set<string>();
|
|
217
|
+
private initialized = false;
|
|
218
|
+
private startupDebug = false;
|
|
219
|
+
readonly id = randomUUID();
|
|
220
|
+
readonly generation = randomUUID();
|
|
221
|
+
readonly root: string;
|
|
222
|
+
private readonly rawRoot: string;
|
|
223
|
+
private readonly gate: PiApplyGate;
|
|
224
|
+
private readonly manager: ExtensionContext["sessionManager"];
|
|
225
|
+
constructor(
|
|
226
|
+
private readonly ctx: ExtensionContext,
|
|
227
|
+
private readonly signal: AbortSignal,
|
|
228
|
+
private readonly publish?: StartupTimingPublisher,
|
|
229
|
+
) {
|
|
230
|
+
this.uiContext = ctx;
|
|
231
|
+
this.manager = ctx.sessionManager;
|
|
232
|
+
this.rawRoot = getAgentDir();
|
|
233
|
+
const root = canonicalPath(path.resolve(this.rawRoot));
|
|
234
|
+
if (!root) throw new Error("Agent directory is unavailable.");
|
|
235
|
+
this.root = root;
|
|
236
|
+
this.gate = new PiApplyGate(() => this.validate());
|
|
237
|
+
}
|
|
238
|
+
validate() {
|
|
239
|
+
this.signal.throwIfAborted();
|
|
240
|
+
if (this.disposed || this.closing || clients.get(this.manager) !== this)
|
|
241
|
+
throw new Error("Synchronization session was replaced.");
|
|
242
|
+
// Public context access verifies the SDK runner is still active after awaits.
|
|
243
|
+
this.ctx.isIdle();
|
|
244
|
+
if (getAgentDir() !== this.rawRoot || canonicalPath(path.resolve(this.rawRoot)) !== this.root)
|
|
245
|
+
throw new Error("Agent directory changed; reload before synchronization.");
|
|
246
|
+
}
|
|
247
|
+
private modelBinding(): ClientFacts["model"] {
|
|
248
|
+
const model = this.ctx.model;
|
|
249
|
+
if (!model) return undefined;
|
|
250
|
+
const registry = this.ctx.modelRegistry;
|
|
251
|
+
if (registry.getRegisteredProviderIds().includes(model.provider)) return undefined;
|
|
252
|
+
const source = registry.getProviderAuthStatus(model.provider).source;
|
|
253
|
+
if (
|
|
254
|
+
source !== "stored" &&
|
|
255
|
+
source !== "environment" &&
|
|
256
|
+
source !== "models_json_key" &&
|
|
257
|
+
source !== "models_json_command"
|
|
258
|
+
)
|
|
259
|
+
return undefined;
|
|
260
|
+
return { provider: model.provider, id: model.id, signature: modelSignature(model), authSource: source };
|
|
261
|
+
}
|
|
262
|
+
private facts(): ClientFacts {
|
|
263
|
+
const manager = this.ctx.sessionManager;
|
|
264
|
+
return {
|
|
265
|
+
id: this.id,
|
|
266
|
+
generation: this.generation,
|
|
267
|
+
pid: process.pid,
|
|
268
|
+
cwd: this.ctx.cwd,
|
|
269
|
+
mode: this.ctx.mode,
|
|
270
|
+
hasUI: this.ctx.hasUI,
|
|
271
|
+
idle: !this.paused && !this.busy.size && this.ctx.isIdle(),
|
|
272
|
+
ready: this.initialized,
|
|
273
|
+
startupDebug: this.startupDebug,
|
|
274
|
+
sessionFile: canonicalPath(manager.getSessionFile?.()),
|
|
275
|
+
sessionId: manager.getSessionId?.(),
|
|
276
|
+
sessionDir: canonicalPath(sessionDirFromContext(this.ctx)),
|
|
277
|
+
model: this.modelBinding(),
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
async configured() {
|
|
281
|
+
this.validate();
|
|
282
|
+
await settingsQueue;
|
|
283
|
+
this.validate();
|
|
284
|
+
const document = await peekLocalConfigDocument();
|
|
285
|
+
this.validate();
|
|
286
|
+
return Boolean(document && validateSettingsDocument(document.parsed).activeSyncSetup);
|
|
287
|
+
}
|
|
288
|
+
async pauseForSessionChange() {
|
|
289
|
+
this.validate();
|
|
290
|
+
this.paused = true;
|
|
291
|
+
this.gate.cancelPending();
|
|
292
|
+
this.pausing ??= (async () => {
|
|
293
|
+
const connection = this.connection ?? this.partialConnection ?? (await this.connecting?.catch(() => undefined));
|
|
294
|
+
if (connection) {
|
|
295
|
+
await connection.pause();
|
|
296
|
+
await this.gate.releaseAfterDrain();
|
|
297
|
+
}
|
|
298
|
+
})();
|
|
299
|
+
return this.pausing;
|
|
300
|
+
}
|
|
301
|
+
async attachExisting() {
|
|
302
|
+
this.validate();
|
|
303
|
+
const address = await findDaemon(this.root);
|
|
304
|
+
this.validate();
|
|
305
|
+
if (address) await this.connect(address);
|
|
306
|
+
this.validate();
|
|
307
|
+
return Boolean(address);
|
|
308
|
+
}
|
|
309
|
+
async finishReattachment() {
|
|
310
|
+
this.validate();
|
|
311
|
+
if (this.connection) {
|
|
312
|
+
await recoverDetachedClients({ paths: this.connection.paths, identity: this.connection.identity });
|
|
313
|
+
this.validate();
|
|
314
|
+
await this.connection.attach();
|
|
315
|
+
this.validate();
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
async connect(existing?: Awaited<ReturnType<typeof ensureDaemon>>) {
|
|
319
|
+
this.validate();
|
|
320
|
+
if (this.connection) return this.connection;
|
|
321
|
+
this.connecting ??= (async () => {
|
|
322
|
+
// Only explicit setup/command paths or a configured interactive session call connect.
|
|
323
|
+
if (!existing) await fs.mkdir(this.root, { recursive: true, mode: 0o700 });
|
|
324
|
+
this.validate();
|
|
325
|
+
const daemon = existing ?? (await ensureDaemon(this.root, this.signal));
|
|
326
|
+
this.validate();
|
|
327
|
+
if (daemon.paths.root !== this.root) throw new Error("Daemon root changed before attach.");
|
|
328
|
+
const connection = new DaemonConnection(daemon.paths, daemon.identity, this.facts(), {
|
|
329
|
+
callback: (callback, signal) => this.callback(callback, signal),
|
|
330
|
+
event: (event) => {
|
|
331
|
+
if (event.kind === "commit") return;
|
|
332
|
+
if (this.signal.aborted || this.disposed || this.closing || clients.get(this.manager) !== this) return;
|
|
333
|
+
const payload = event.payload as {
|
|
334
|
+
message?: string;
|
|
335
|
+
level?: "info" | "warning" | "error";
|
|
336
|
+
value?: string;
|
|
337
|
+
presentation?: SyncStatusPresentation;
|
|
338
|
+
};
|
|
339
|
+
if (event.kind === "notify" && typeof payload?.message === "string")
|
|
340
|
+
this.uiContext.ui.notify(safeTerminalText(payload.message), payload.level ?? "info");
|
|
341
|
+
if (event.kind === "timings" && typeof (event.payload as { report?: unknown })?.report === "string") {
|
|
342
|
+
this.publish?.(this.ctx, safeTerminalText((event.payload as { report: string }).report));
|
|
343
|
+
}
|
|
344
|
+
if (event.kind === "status")
|
|
345
|
+
setSyncStatus(
|
|
346
|
+
this.uiContext,
|
|
347
|
+
typeof payload?.value === "string" ? safeTerminalText(payload.value) : undefined,
|
|
348
|
+
payload.presentation,
|
|
349
|
+
);
|
|
350
|
+
},
|
|
351
|
+
error: () => {
|
|
352
|
+
if (!this.signal.aborted && !this.disposed && !this.closing && clients.get(this.manager) === this)
|
|
353
|
+
setSyncStatus(this.ctx, "sync service unavailable", { activity: "blocked", reason: "repair" });
|
|
354
|
+
},
|
|
355
|
+
});
|
|
356
|
+
this.partialConnection = connection;
|
|
357
|
+
await connection.attach();
|
|
358
|
+
this.validate();
|
|
359
|
+
await recoverDetachedClients(daemon);
|
|
360
|
+
if (this.signal.aborted || this.disposed || this.closing) {
|
|
361
|
+
await connection.dispose();
|
|
362
|
+
this.validate();
|
|
363
|
+
}
|
|
364
|
+
this.connection = connection;
|
|
365
|
+
return connection;
|
|
366
|
+
})().catch((error) => {
|
|
367
|
+
this.connecting = undefined;
|
|
368
|
+
throw error;
|
|
369
|
+
});
|
|
370
|
+
return this.connecting;
|
|
371
|
+
}
|
|
372
|
+
async readSettings(repair = false) {
|
|
373
|
+
this.validate();
|
|
374
|
+
if (!this.connection || this.paused) {
|
|
375
|
+
const document = await peekLocalConfigDocument();
|
|
376
|
+
this.validate();
|
|
377
|
+
if (document && document.bytes.length > MAX_SETTINGS_BYTES)
|
|
378
|
+
throw new Error("Settings exceed the local API byte limit; the source document is unchanged.");
|
|
379
|
+
if (document && !repair) validateSettingsDocument(document.parsed);
|
|
380
|
+
return document;
|
|
381
|
+
}
|
|
382
|
+
return decode(await this.run(repair ? "settings.repair-read" : "settings.read", {}));
|
|
383
|
+
}
|
|
384
|
+
run(operation: string, payload: unknown, signal?: AbortSignal, ctx = this.ctx, onCommit?: () => void) {
|
|
385
|
+
const result = this.work.then(() => this.runCurrent(operation, payload, signal, ctx, onCommit));
|
|
386
|
+
this.work = result.then(
|
|
387
|
+
() => {},
|
|
388
|
+
() => {},
|
|
389
|
+
);
|
|
390
|
+
return result;
|
|
391
|
+
}
|
|
392
|
+
private async runCurrent(
|
|
393
|
+
operation: string,
|
|
394
|
+
payload: unknown,
|
|
395
|
+
signal?: AbortSignal,
|
|
396
|
+
ctx = this.ctx,
|
|
397
|
+
onCommit?: () => void,
|
|
398
|
+
) {
|
|
399
|
+
this.validate();
|
|
400
|
+
signal?.throwIfAborted();
|
|
401
|
+
if (this.paused && operation !== "shutdown")
|
|
402
|
+
throw new Error("Synchronization is paused for a session change; if it was cancelled, use /reload to reattach.");
|
|
403
|
+
const connection = await this.connect();
|
|
404
|
+
if (this.paused && operation === "shutdown") {
|
|
405
|
+
Object.assign(connection.facts, { ...this.facts(), idle: false, ready: false });
|
|
406
|
+
await connection.attach();
|
|
407
|
+
this.validate();
|
|
408
|
+
}
|
|
409
|
+
this.validate();
|
|
410
|
+
signal?.throwIfAborted();
|
|
411
|
+
await connection.update(this.facts());
|
|
412
|
+
this.validate();
|
|
413
|
+
signal?.throwIfAborted();
|
|
414
|
+
this.uiContext = ctx;
|
|
415
|
+
try {
|
|
416
|
+
return await connection.run(
|
|
417
|
+
operation,
|
|
418
|
+
payload,
|
|
419
|
+
signal ? AbortSignal.any([signal, this.signal]) : this.signal,
|
|
420
|
+
onCommit,
|
|
421
|
+
);
|
|
422
|
+
} catch (error) {
|
|
423
|
+
if (error instanceof DaemonError) {
|
|
424
|
+
const prototype =
|
|
425
|
+
error.name === "RemoteSelectionMismatchError"
|
|
426
|
+
? RemoteSelectionMismatchError.prototype
|
|
427
|
+
: error.name === "SyncDecisionRequiredError"
|
|
428
|
+
? SyncDecisionRequiredError.prototype
|
|
429
|
+
: undefined;
|
|
430
|
+
if (prototype) {
|
|
431
|
+
const restored = Object.create(prototype) as Error;
|
|
432
|
+
Object.assign(restored, error.remote.properties, { name: error.name, message: error.message });
|
|
433
|
+
throw restored;
|
|
434
|
+
}
|
|
435
|
+
Object.assign(error, error.remote.properties);
|
|
436
|
+
}
|
|
437
|
+
throw error;
|
|
438
|
+
} finally {
|
|
439
|
+
this.uiContext = this.ctx;
|
|
440
|
+
if (
|
|
441
|
+
this.reloadRequested &&
|
|
442
|
+
!this.signal.aborted &&
|
|
443
|
+
!this.disposed &&
|
|
444
|
+
!this.closing &&
|
|
445
|
+
clients.get(this.manager) === this
|
|
446
|
+
) {
|
|
447
|
+
this.reloadRequested = false;
|
|
448
|
+
if ("reload" in ctx && typeof ctx.reload === "function") await ctx.reload();
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
async markReady(debug: boolean) {
|
|
453
|
+
this.validate();
|
|
454
|
+
this.startupDebug = debug;
|
|
455
|
+
this.initialized = true;
|
|
456
|
+
await this.update();
|
|
457
|
+
this.validate();
|
|
458
|
+
}
|
|
459
|
+
async setBusy(reason: string, busy: boolean) {
|
|
460
|
+
this.validate();
|
|
461
|
+
if (busy) this.busy.add(reason);
|
|
462
|
+
else this.busy.delete(reason);
|
|
463
|
+
await this.update();
|
|
464
|
+
this.validate();
|
|
465
|
+
}
|
|
466
|
+
async update() {
|
|
467
|
+
if (this.connection && !this.paused && !this.disposed && !this.signal.aborted)
|
|
468
|
+
await this.connection.update(this.facts());
|
|
469
|
+
}
|
|
470
|
+
private async callback(callback: Callback, signal: AbortSignal) {
|
|
471
|
+
const payload = callback.payload as {
|
|
472
|
+
reservation?: string;
|
|
473
|
+
targets?: string[];
|
|
474
|
+
generation?: string;
|
|
475
|
+
title?: string;
|
|
476
|
+
message?: string;
|
|
477
|
+
content?: string;
|
|
478
|
+
confirmationLabel?: string;
|
|
479
|
+
summaryLines?: string[];
|
|
480
|
+
items?: string[];
|
|
481
|
+
helpText?: string;
|
|
482
|
+
background?: boolean;
|
|
483
|
+
};
|
|
484
|
+
if (callback.kind === "queue-release") {
|
|
485
|
+
if (typeof payload?.reservation !== "string") throw new Error("Invalid queue release.");
|
|
486
|
+
await this.gate.releaseRequest(payload.reservation);
|
|
487
|
+
return true;
|
|
488
|
+
}
|
|
489
|
+
this.validate();
|
|
490
|
+
signal.throwIfAborted();
|
|
491
|
+
if (this.paused) throw new Error("Pi session is changing; no new work is authorized.");
|
|
492
|
+
if (callback.kind === "queue-acquire") {
|
|
493
|
+
if (payload.background && !this.facts().idle) throw new Error("Pi is busy; background apply was not granted.");
|
|
494
|
+
if (
|
|
495
|
+
payload.generation !== this.generation ||
|
|
496
|
+
typeof payload.reservation !== "string" ||
|
|
497
|
+
!Array.isArray(payload.targets)
|
|
498
|
+
)
|
|
499
|
+
throw new Error("Stale file-queue request.");
|
|
500
|
+
return this.gate.acquire(payload.reservation, payload.targets, AbortSignal.any([signal, this.signal]));
|
|
501
|
+
}
|
|
502
|
+
const ctx = this.uiContext;
|
|
503
|
+
const combined = AbortSignal.any([signal, this.signal]);
|
|
504
|
+
if (callback.kind === "model-binding") {
|
|
505
|
+
const facts = this.facts();
|
|
506
|
+
const connection = this.connection ?? this.partialConnection;
|
|
507
|
+
if (connection && JSON.stringify(connection.facts.model) !== JSON.stringify(facts.model)) {
|
|
508
|
+
await connection.update(facts);
|
|
509
|
+
this.validate();
|
|
510
|
+
}
|
|
511
|
+
return payload.background && !facts.idle ? null : (facts.model ?? null);
|
|
512
|
+
}
|
|
513
|
+
if (callback.kind === "reload") {
|
|
514
|
+
this.reloadRequested = true;
|
|
515
|
+
return true;
|
|
516
|
+
}
|
|
517
|
+
if (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode)) throw new Error("This client cannot present safety reviews.");
|
|
518
|
+
let result: unknown;
|
|
519
|
+
if (callback.kind === "merge-review" && typeof payload.title === "string" && typeof payload.content === "string") {
|
|
520
|
+
const { confirmMergeReview } = await import("../ui/merge-review.js");
|
|
521
|
+
this.validate();
|
|
522
|
+
combined.throwIfAborted();
|
|
523
|
+
result = await confirmMergeReview(
|
|
524
|
+
ctx,
|
|
525
|
+
payload.title,
|
|
526
|
+
payload.content,
|
|
527
|
+
combined,
|
|
528
|
+
() => !combined.aborted && !this.disposed,
|
|
529
|
+
payload.confirmationLabel,
|
|
530
|
+
payload.summaryLines,
|
|
531
|
+
);
|
|
532
|
+
} else if (
|
|
533
|
+
callback.kind === "confirm" &&
|
|
534
|
+
typeof payload.title === "string" &&
|
|
535
|
+
typeof payload.message === "string"
|
|
536
|
+
) {
|
|
537
|
+
result = await ctx.ui.confirm(safeTerminalText(payload.title), safeTerminalText(payload.message), {
|
|
538
|
+
signal: combined,
|
|
539
|
+
});
|
|
540
|
+
} else if (
|
|
541
|
+
callback.kind === "select" &&
|
|
542
|
+
typeof payload.title === "string" &&
|
|
543
|
+
Array.isArray(payload.items) &&
|
|
544
|
+
payload.items.every((item) => typeof item === "string")
|
|
545
|
+
) {
|
|
546
|
+
const labels = payload.items.map(safeTerminalText);
|
|
547
|
+
if (new Set(labels).size !== labels.length) throw new Error("Daemon choices have ambiguous terminal labels.");
|
|
548
|
+
const selected = await ctx.ui.select(safeTerminalText(payload.title), labels, { signal: combined });
|
|
549
|
+
const index = selected === undefined ? -1 : labels.indexOf(selected);
|
|
550
|
+
result = index < 0 ? undefined : payload.items[index];
|
|
551
|
+
} else throw new Error("Unsupported daemon UI callback.");
|
|
552
|
+
this.validate();
|
|
553
|
+
combined.throwIfAborted();
|
|
554
|
+
return result;
|
|
555
|
+
}
|
|
556
|
+
disposeForShutdown(reason: string | undefined, targetFile?: string) {
|
|
557
|
+
const facts = this.connection?.facts ?? this.partialConnection?.facts;
|
|
558
|
+
return this.dispose({
|
|
559
|
+
kind: ["new", "resume", "fork", "reload"].includes(reason ?? "") ? "replace" : "exit",
|
|
560
|
+
...(targetFile !== undefined
|
|
561
|
+
? { file: canonicalPath(targetFile) }
|
|
562
|
+
: reason === "reload"
|
|
563
|
+
? { file: facts?.sessionFile, sessionId: facts?.sessionId }
|
|
564
|
+
: {}),
|
|
565
|
+
cwd: facts?.cwd,
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
async dispose(handoff?: ClientHandoff) {
|
|
569
|
+
if (this.disposing) return this.disposing;
|
|
570
|
+
this.closing = true;
|
|
571
|
+
this.disposing = (async () => {
|
|
572
|
+
const connection = this.connection ?? this.partialConnection ?? (await this.connecting?.catch(() => undefined));
|
|
573
|
+
let confirmed = false;
|
|
574
|
+
try {
|
|
575
|
+
await connection?.dispose(handoff);
|
|
576
|
+
confirmed = Boolean(connection);
|
|
577
|
+
} finally {
|
|
578
|
+
this.disposed = true;
|
|
579
|
+
if (clients.get(this.manager) === this) clients.delete(this.manager);
|
|
580
|
+
const gate = this.gate;
|
|
581
|
+
gate.detach();
|
|
582
|
+
if (connection) {
|
|
583
|
+
if (confirmed) await gate.releaseAfterDrain();
|
|
584
|
+
else quarantineClient(gate, connection.paths.root, connection.identity, connection.facts);
|
|
585
|
+
}
|
|
586
|
+
await this.work;
|
|
587
|
+
}
|
|
588
|
+
})();
|
|
589
|
+
return this.disposing;
|
|
590
|
+
}
|
|
591
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { type ClientFacts, DaemonConnection, findDaemon, type Identity } from "@narumitw/sync-daemon";
|
|
2
|
+
import type { PiApplyGate } from "./apply-gate.js";
|
|
3
|
+
|
|
4
|
+
type Address = { paths: DaemonConnection["paths"]; identity: Identity };
|
|
5
|
+
interface Recovery {
|
|
6
|
+
gate: PiApplyGate;
|
|
7
|
+
root: string;
|
|
8
|
+
identity: Identity;
|
|
9
|
+
facts: ClientFacts;
|
|
10
|
+
timer?: ReturnType<typeof setInterval>;
|
|
11
|
+
attempt?: Promise<boolean>;
|
|
12
|
+
}
|
|
13
|
+
const recoveries = new Set<Recovery>();
|
|
14
|
+
function alive(pid: number) {
|
|
15
|
+
try {
|
|
16
|
+
process.kill(pid, 0);
|
|
17
|
+
return true;
|
|
18
|
+
} catch (error) {
|
|
19
|
+
return (error as NodeJS.ErrnoException).code !== "ESRCH";
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function finish(record: Recovery) {
|
|
23
|
+
if (record.timer) clearInterval(record.timer);
|
|
24
|
+
recoveries.delete(record);
|
|
25
|
+
}
|
|
26
|
+
function attempt(record: Recovery, known?: Address): Promise<boolean> {
|
|
27
|
+
record.attempt ??= (async () => {
|
|
28
|
+
const exited = !alive(record.identity.pid);
|
|
29
|
+
if (exited) await record.gate.releaseAfterOwnerExit(record.identity.pid);
|
|
30
|
+
const address = known ?? (await findDaemon(record.root));
|
|
31
|
+
if (!address || (!exited && address.identity.instance !== record.identity.instance)) return false;
|
|
32
|
+
// Only plain closed-session facts and detached grants cross this recovery boundary.
|
|
33
|
+
// Reclaim the obsolete participant on a compatible owner, reject all new work,
|
|
34
|
+
// and service release callbacks until an authenticated detach confirms drain.
|
|
35
|
+
const connection = new DaemonConnection(
|
|
36
|
+
address.paths,
|
|
37
|
+
address.identity,
|
|
38
|
+
{
|
|
39
|
+
...record.facts,
|
|
40
|
+
hasUI: false,
|
|
41
|
+
idle: false,
|
|
42
|
+
ready: false,
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
callback: async (callback) => {
|
|
46
|
+
const data = callback.payload;
|
|
47
|
+
if (
|
|
48
|
+
callback.kind === "queue-release" &&
|
|
49
|
+
data !== null &&
|
|
50
|
+
typeof data === "object" &&
|
|
51
|
+
"reservation" in data &&
|
|
52
|
+
typeof data.reservation === "string"
|
|
53
|
+
) {
|
|
54
|
+
await record.gate.releaseRequest(data.reservation);
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
throw new Error("Closed Pi participant cannot authorize new work.");
|
|
58
|
+
},
|
|
59
|
+
},
|
|
60
|
+
);
|
|
61
|
+
try {
|
|
62
|
+
// Cleanup polling does not attach or recreate a retired participant.
|
|
63
|
+
await connection.dispose();
|
|
64
|
+
await record.gate.releaseAfterDrain();
|
|
65
|
+
finish(record);
|
|
66
|
+
return true;
|
|
67
|
+
} finally {
|
|
68
|
+
await connection.dispose();
|
|
69
|
+
}
|
|
70
|
+
})()
|
|
71
|
+
.catch(() => false)
|
|
72
|
+
.finally(() => {
|
|
73
|
+
record.attempt = undefined;
|
|
74
|
+
});
|
|
75
|
+
return record.attempt;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Intentionally shared cleanup may outlive a session, but never retains its ctx or UI. */
|
|
79
|
+
export function quarantineClient(gate: PiApplyGate, root: string, identity: Identity, facts: ClientFacts) {
|
|
80
|
+
gate.detach();
|
|
81
|
+
const record: Recovery = { gate, root, identity: structuredClone(identity), facts: structuredClone(facts) };
|
|
82
|
+
recoveries.add(record);
|
|
83
|
+
record.timer = setInterval(() => {
|
|
84
|
+
void attempt(record);
|
|
85
|
+
}, 1000);
|
|
86
|
+
record.timer.unref();
|
|
87
|
+
void attempt(record);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** A newly attached client stays unready until obsolete local participants are retired. */
|
|
91
|
+
export async function recoverDetachedClients(address: Address) {
|
|
92
|
+
const pending = [...recoveries].filter((record) => record.root === address.paths.root);
|
|
93
|
+
const results = await Promise.all(
|
|
94
|
+
pending.map(async (record) => {
|
|
95
|
+
const done = await attempt(record, address);
|
|
96
|
+
return done || !recoveries.has(record) || (await attempt(record, address));
|
|
97
|
+
}),
|
|
98
|
+
);
|
|
99
|
+
if (results.some((done) => !done))
|
|
100
|
+
throw new Error(
|
|
101
|
+
"Previous Pi cleanup is still uncertain; stop or repair the existing daemon before retrying /reload.",
|
|
102
|
+
);
|
|
103
|
+
}
|