@narumitw/pi-sync 0.61.0 → 0.62.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.
Files changed (250) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +24 -17
  3. package/dist/chunks/{chunk-EMVZL4PH.ts → chunk-3E3TR3JE.ts} +4 -4
  4. package/dist/chunks/{chunk-JVFCVPPD.ts → chunk-6PFZUEUG.ts} +41 -18
  5. package/dist/chunks/chunk-6PFZUEUG.ts.map +7 -0
  6. package/dist/chunks/{chunk-ZIL6PW5L.ts → chunk-6YKOHBSC.ts} +2 -2
  7. package/dist/chunks/{chunk-OA4NZLSL.ts → chunk-APZVJAEW.ts} +4 -3
  8. package/dist/chunks/{chunk-4SR3ZYHA.ts → chunk-GELYN4UC.ts} +2 -2
  9. package/dist/chunks/{chunk-S7F4FOAS.ts → chunk-GSCZ4VXV.ts} +5 -5
  10. package/dist/chunks/{chunk-YQSFJLJ3.ts → chunk-IBXEM35O.ts} +4 -3
  11. package/dist/chunks/{chunk-E3YLRLJM.ts → chunk-INECVQNR.ts} +10 -10
  12. package/dist/chunks/{chunk-2JHAN3ZO.ts → chunk-JREGWM2B.ts} +3 -3
  13. package/dist/chunks/{chunk-277VHM2P.ts → chunk-MNYRU5U5.ts} +5 -2
  14. package/dist/chunks/{chunk-277VHM2P.ts.map → chunk-MNYRU5U5.ts.map} +2 -2
  15. package/dist/chunks/{chunk-2ZGV5KNC.ts → chunk-NHFGAZEC.ts} +11 -8
  16. package/dist/chunks/chunk-NHFGAZEC.ts.map +7 -0
  17. package/dist/chunks/{chunk-EMRFVLZM.ts → chunk-NXWHPVXR.ts} +2 -2
  18. package/dist/chunks/{chunk-SMVKMYLK.ts → chunk-P4GI7LTT.ts} +2 -2
  19. package/dist/chunks/{chunk-PJMM75W5.ts → chunk-PWESMTH6.ts} +6 -6
  20. package/dist/chunks/{chunk-ZVGRZD4C.ts → chunk-R3SAMXB6.ts} +2 -2
  21. package/dist/chunks/{chunk-RNIEVDTR.ts → chunk-T3LABNHF.ts} +2 -2
  22. package/dist/chunks/{chunk-S3R3W3KF.ts → chunk-UMPA5S7X.ts} +2 -2
  23. package/dist/chunks/{chunk-WP2M67XZ.ts → chunk-WBIOSK76.ts} +2 -2
  24. package/dist/chunks/{chunk-4KTJLJSJ.ts → chunk-ZB3GNX3P.ts} +11 -11
  25. package/dist/chunks/{chunk-HEB6YT64.ts → chunk-ZO52JM4H.ts} +2 -2
  26. package/dist/chunks/{command-handler-K4XJOGYC.ts → command-handler-6ATREPG7.ts} +16 -16
  27. package/dist/chunks/command-handler-6ATREPG7.ts.map +7 -0
  28. package/dist/chunks/{conflict-review-IGKY2TOJ.ts → conflict-review-MAOGTIAI.ts} +4 -4
  29. package/dist/chunks/{continuous-record-3XDXDOMV.ts → continuous-record-3SKJ6I3V.ts} +2 -2
  30. package/dist/chunks/{continuous-storage-HLKCHF6Z.ts → continuous-storage-3EU6I7Z3.ts} +2 -2
  31. package/dist/chunks/{file-selection-MGGVOKM7.ts → file-selection-QR2KZVGD.ts} +10 -10
  32. package/dist/chunks/manager-result-dispatcher-MC6EQOQY.ts +19 -0
  33. package/dist/chunks/{manager-ui-KYQ5AZJS.ts → manager-ui-AOFUNXAJ.ts} +547 -135
  34. package/dist/chunks/manager-ui-AOFUNXAJ.ts.map +7 -0
  35. package/dist/chunks/remote-selection-ui-4BTP2OJR.ts +18 -0
  36. package/dist/chunks/{setup-switch-D6K6PBPC.ts → setup-switch-Y6AMFFNK.ts} +7 -7
  37. package/dist/chunks/{setup-wizard-4DYUDHJR.ts → setup-wizard-5G426MOZ.ts} +10 -10
  38. package/dist/chunks/{snapshot-5HY3M2NL.ts → snapshot-ZUJJZCFW.ts} +2 -2
  39. package/dist/chunks/{snapshot-transaction-directory-OU2D7R7A.ts → snapshot-transaction-directory-F46JWRAU.ts} +2 -2
  40. package/dist/chunks/{state-directory-XXHU73Z3.ts → state-directory-CMAIF34J.ts} +2 -2
  41. package/dist/chunks/{sync-inspection-J3CRBORL.ts → sync-inspection-ITZ6Z4DE.ts} +5 -5
  42. package/dist/chunks/{sync-operations-BVWYYKH3.ts → sync-operations-NMVKF7SE.ts} +13 -9
  43. package/dist/chunks/sync-operations-NMVKF7SE.ts.map +7 -0
  44. package/dist/chunks/{sync-state-2LMIXJ2C.ts → sync-state-QIT64TKV.ts} +2 -2
  45. package/dist/daemon/LICENSE +21 -0
  46. package/dist/daemon/dist/build-version.js +8 -0
  47. package/dist/daemon/dist/child-sdk.mjs +17 -0
  48. package/dist/daemon/dist/cli.js +169 -0
  49. package/dist/daemon/dist/client.js +909 -0
  50. package/dist/daemon/dist/consent.js +265 -0
  51. package/dist/daemon/dist/document.js +6 -0
  52. package/dist/daemon/dist/endpoint.js +91 -0
  53. package/dist/daemon/dist/engine/backends/backend-factory.js +16 -0
  54. package/dist/daemon/dist/engine/backends/backend-identity.js +38 -0
  55. package/dist/daemon/dist/engine/backends/backend-types.js +1 -0
  56. package/dist/daemon/dist/engine/backends/git/git-backend.js +715 -0
  57. package/dist/daemon/dist/engine/backends/git/git-config.js +118 -0
  58. package/dist/daemon/dist/engine/backends/git/git-runner.js +232 -0
  59. package/dist/daemon/dist/engine/backends/git/git-storage.js +252 -0
  60. package/dist/daemon/dist/engine/backends/s3/s3-backend.js +444 -0
  61. package/dist/daemon/dist/engine/backends/s3/s3-client.js +352 -0
  62. package/dist/daemon/dist/engine/backends/s3/s3-conditions.js +66 -0
  63. package/dist/daemon/dist/engine/backends/snapshot-pointer.js +22 -0
  64. package/dist/daemon/dist/engine/backends/sync-backend.js +23 -0
  65. package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +542 -0
  66. package/dist/daemon/dist/engine/backends/webdav/webdav-client.js +326 -0
  67. package/dist/daemon/dist/engine/backends/webdav/webdav-config.js +73 -0
  68. package/dist/daemon/dist/engine/commands/command-types.js +1 -0
  69. package/dist/daemon/dist/engine/host.js +16 -0
  70. package/dist/daemon/dist/engine/ignore/effective-ignore-policy.js +33 -0
  71. package/dist/daemon/dist/engine/ignore/ignore-edit.js +102 -0
  72. package/dist/daemon/dist/engine/ignore/ignore-initialization.js +186 -0
  73. package/dist/daemon/dist/engine/ignore/ignore-migration-prompt.js +139 -0
  74. package/dist/daemon/dist/engine/ignore/ignore-settings.js +322 -0
  75. package/dist/daemon/dist/engine/ignore/ignore-source.js +250 -0
  76. package/dist/daemon/dist/engine/paths.js +71 -0
  77. package/dist/daemon/dist/engine/settings/config-errors.js +4 -0
  78. package/dist/daemon/dist/engine/settings/config-file.js +736 -0
  79. package/dist/daemon/dist/engine/settings/config.js +301 -0
  80. package/dist/daemon/dist/engine/settings/settings-management.js +193 -0
  81. package/dist/daemon/dist/engine/settings/settings-store.js +41 -0
  82. package/dist/daemon/dist/engine/settings/settings-types.js +1 -0
  83. package/dist/daemon/dist/engine/settings/settings-validation.js +384 -0
  84. package/dist/daemon/dist/engine/snapshot/session-paths.js +160 -0
  85. package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +348 -0
  86. package/dist/daemon/dist/engine/snapshot/snapshot-bounds.js +20 -0
  87. package/dist/daemon/dist/engine/snapshot/snapshot-case-replacement.js +82 -0
  88. package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +61 -0
  89. package/dist/daemon/dist/engine/snapshot/snapshot-entry-projection.js +78 -0
  90. package/dist/daemon/dist/engine/snapshot/snapshot-exclude-safety.js +262 -0
  91. package/dist/daemon/dist/engine/snapshot/snapshot-mutation-queues.js +133 -0
  92. package/dist/daemon/dist/engine/snapshot/snapshot-paths.js +11 -0
  93. package/dist/daemon/dist/engine/snapshot/snapshot-payload.js +10 -0
  94. package/dist/daemon/dist/engine/snapshot/snapshot-reviewed-preimages.js +60 -0
  95. package/dist/daemon/dist/engine/snapshot/snapshot-root-transition.js +138 -0
  96. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-directory.js +16 -0
  97. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-images.js +387 -0
  98. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-plan.js +68 -0
  99. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-policy.js +276 -0
  100. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-stage.js +303 -0
  101. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-verification.js +78 -0
  102. package/dist/daemon/dist/engine/snapshot/snapshot-transaction.js +813 -0
  103. package/dist/daemon/dist/engine/snapshot/snapshot-types.js +9 -0
  104. package/dist/daemon/dist/engine/snapshot/snapshot.js +678 -0
  105. package/dist/daemon/dist/engine/state/json-file.js +49 -0
  106. package/dist/daemon/dist/engine/state/lock-policy.js +2 -0
  107. package/dist/daemon/dist/engine/state/lock.js +259 -0
  108. package/dist/daemon/dist/engine/state/lockfile-fs.js +13 -0
  109. package/dist/daemon/dist/engine/state/merge-baseline-store.js +198 -0
  110. package/dist/daemon/dist/engine/state/mutation-directory-sync.js +34 -0
  111. package/dist/daemon/dist/engine/state/operation-availability.js +40 -0
  112. package/dist/daemon/dist/engine/state/state-directory.js +227 -0
  113. package/dist/daemon/dist/engine/state/state-types.js +1 -0
  114. package/dist/daemon/dist/engine/state/sync-state-store.js +54 -0
  115. package/dist/daemon/dist/engine/sync/agent-candidate.js +207 -0
  116. package/dist/daemon/dist/engine/sync/agent-plan.js +84 -0
  117. package/dist/daemon/dist/engine/sync/agent-policy.js +10 -0
  118. package/dist/daemon/dist/engine/sync/agent-refusal-retry.js +39 -0
  119. package/dist/daemon/dist/engine/sync/agent-request.js +13 -0
  120. package/dist/daemon/dist/engine/sync/agent-runner.js +183 -0
  121. package/dist/daemon/dist/engine/sync/agent-store.js +177 -0
  122. package/dist/daemon/dist/engine/sync/agent-sync.js +132 -0
  123. package/dist/daemon/dist/engine/sync/apply-review.js +52 -0
  124. package/dist/daemon/dist/engine/sync/conflict-artifact-ownership.js +53 -0
  125. package/dist/daemon/dist/engine/sync/conflict-artifacts.js +158 -0
  126. package/dist/daemon/dist/engine/sync/conflict-groups.js +76 -0
  127. package/dist/daemon/dist/engine/sync/conflict-preview.js +53 -0
  128. package/dist/daemon/dist/engine/sync/conflict-resolution.js +53 -0
  129. package/dist/daemon/dist/engine/sync/conflict-retention.js +61 -0
  130. package/dist/daemon/dist/engine/sync/conflict-review.js +73 -0
  131. package/dist/daemon/dist/engine/sync/content-conflicts.js +70 -0
  132. package/dist/daemon/dist/engine/sync/continuous-errors.js +66 -0
  133. package/dist/daemon/dist/engine/sync/continuous-lease.js +206 -0
  134. package/dist/daemon/dist/engine/sync/continuous-record.js +199 -0
  135. package/dist/daemon/dist/engine/sync/continuous-storage.js +59 -0
  136. package/dist/daemon/dist/engine/sync/continuous-sync.js +521 -0
  137. package/dist/daemon/dist/engine/sync/continuous-watch.js +140 -0
  138. package/dist/daemon/dist/engine/sync/exclude-policy.js +86 -0
  139. package/dist/daemon/dist/engine/sync/field-migration.js +20 -0
  140. package/dist/daemon/dist/engine/sync/file-merge-planner.js +123 -0
  141. package/dist/daemon/dist/engine/sync/initialization.js +80 -0
  142. package/dist/daemon/dist/engine/sync/json-document.js +172 -0
  143. package/dist/daemon/dist/engine/sync/local-field-policy.js +26 -0
  144. package/dist/daemon/dist/engine/sync/local-fields.js +196 -0
  145. package/dist/daemon/dist/engine/sync/merge-apply.js +529 -0
  146. package/dist/daemon/dist/engine/sync/merge-journal.js +295 -0
  147. package/dist/daemon/dist/engine/sync/merge-transfer-error.js +64 -0
  148. package/dist/daemon/dist/engine/sync/merged-sync.js +674 -0
  149. package/dist/daemon/dist/engine/sync/mutation-owner.js +18 -0
  150. package/dist/daemon/dist/engine/sync/package-merge.js +82 -0
  151. package/dist/daemon/dist/engine/sync/partial-progress.js +41 -0
  152. package/dist/daemon/dist/engine/sync/remote-snapshot.js +104 -0
  153. package/dist/daemon/dist/engine/sync/resolver-stream.js +34 -0
  154. package/dist/daemon/dist/engine/sync/session-merge.js +178 -0
  155. package/dist/daemon/dist/engine/sync/session-push.js +33 -0
  156. package/dist/daemon/dist/engine/sync/settings-conflicts.js +56 -0
  157. package/dist/daemon/dist/engine/sync/settings-merge.js +93 -0
  158. package/dist/daemon/dist/engine/sync/signals.js +8 -0
  159. package/dist/daemon/dist/engine/sync/startup-timings.js +44 -0
  160. package/dist/daemon/dist/engine/sync/sync-decision.js +81 -0
  161. package/dist/daemon/dist/engine/sync/sync-error-guidance.js +55 -0
  162. package/dist/daemon/dist/engine/sync/sync-errors.js +18 -0
  163. package/dist/daemon/dist/engine/sync/sync-inspection.js +42 -0
  164. package/dist/daemon/dist/engine/sync/sync-loaders.js +8 -0
  165. package/dist/daemon/dist/engine/sync/sync-local.js +40 -0
  166. package/dist/daemon/dist/engine/sync/sync-mutations.js +733 -0
  167. package/dist/daemon/dist/engine/sync/sync-operations.js +3 -0
  168. package/dist/daemon/dist/engine/sync/sync-policy.js +621 -0
  169. package/dist/daemon/dist/engine/sync/sync-queries.js +212 -0
  170. package/dist/daemon/dist/engine/sync/sync-state.js +129 -0
  171. package/dist/daemon/dist/engine/sync/text-merge.js +124 -0
  172. package/dist/daemon/dist/engine/types.js +2 -0
  173. package/dist/daemon/dist/engine/ui/merge-review.js +7 -0
  174. package/dist/daemon/dist/engine/ui/merged-sync-summary.js +86 -0
  175. package/dist/daemon/dist/engine/ui/sync-format.js +165 -0
  176. package/dist/daemon/dist/engine/ui/sync-status.js +30 -0
  177. package/dist/daemon/dist/engine/ui/terminal-text.js +9 -0
  178. package/dist/daemon/dist/engine/ui/transfer-changes.js +24 -0
  179. package/dist/daemon/dist/engine/ui/transfer-review.js +19 -0
  180. package/dist/daemon/dist/engine-service.js +344 -0
  181. package/dist/daemon/dist/identity.js +241 -0
  182. package/dist/daemon/dist/idle-exit.js +77 -0
  183. package/dist/daemon/dist/index.js +4 -0
  184. package/dist/daemon/dist/lifecycle-log.js +53 -0
  185. package/dist/daemon/dist/lifecycle.js +21 -0
  186. package/dist/daemon/dist/model-signature.js +7 -0
  187. package/dist/daemon/dist/monitor.js +272 -0
  188. package/dist/daemon/dist/participant-admission.js +30 -0
  189. package/dist/daemon/dist/protocol.js +104 -0
  190. package/dist/daemon/dist/resolver-host.js +78 -0
  191. package/dist/daemon/dist/server.js +953 -0
  192. package/dist/daemon/dist/service-host.js +174 -0
  193. package/dist/daemon/dist/upgrade-repair.js +55 -0
  194. package/dist/daemon/package.json +3 -0
  195. package/dist/index.ts +21 -21
  196. package/dist/package.json +6 -0
  197. package/docs/daemon-migration.md +27 -16
  198. package/package.json +9 -3
  199. package/skills/configure-pi-sync/SKILL.md +38 -13
  200. package/skills/configure-pi-sync/references/configuration.md +2 -2
  201. package/src/commands/command-execution.ts +1 -1
  202. package/src/settings/config.ts +1 -0
  203. package/src/sync/sync-operations.ts +18 -10
  204. package/src/ui/excluded-paths-ui.ts +4 -1
  205. package/src/ui/ignore-file-ui.ts +271 -0
  206. package/src/ui/ignore-migration-prompt.ts +65 -0
  207. package/src/ui/manager-state.ts +27 -13
  208. package/src/ui/manager-ui.ts +38 -19
  209. package/src/ui/remote-selection-ui.ts +41 -8
  210. package/src/ui/settings-review.ts +26 -0
  211. package/src/ui/settings-ui.ts +316 -213
  212. package/src/ui/storage-connections-ui.ts +20 -12
  213. package/src/ui/sync-setups-ui.ts +45 -27
  214. package/dist/chunks/chunk-2ZGV5KNC.ts.map +0 -7
  215. package/dist/chunks/chunk-JVFCVPPD.ts.map +0 -7
  216. package/dist/chunks/command-handler-K4XJOGYC.ts.map +0 -7
  217. package/dist/chunks/manager-result-dispatcher-4VJVDEUD.ts +0 -19
  218. package/dist/chunks/manager-ui-KYQ5AZJS.ts.map +0 -7
  219. package/dist/chunks/remote-selection-ui-W3KOZM3W.ts +0 -18
  220. package/dist/chunks/sync-operations-BVWYYKH3.ts.map +0 -7
  221. /package/dist/chunks/{chunk-EMVZL4PH.ts.map → chunk-3E3TR3JE.ts.map} +0 -0
  222. /package/dist/chunks/{chunk-ZIL6PW5L.ts.map → chunk-6YKOHBSC.ts.map} +0 -0
  223. /package/dist/chunks/{chunk-OA4NZLSL.ts.map → chunk-APZVJAEW.ts.map} +0 -0
  224. /package/dist/chunks/{chunk-4SR3ZYHA.ts.map → chunk-GELYN4UC.ts.map} +0 -0
  225. /package/dist/chunks/{chunk-S7F4FOAS.ts.map → chunk-GSCZ4VXV.ts.map} +0 -0
  226. /package/dist/chunks/{chunk-YQSFJLJ3.ts.map → chunk-IBXEM35O.ts.map} +0 -0
  227. /package/dist/chunks/{chunk-E3YLRLJM.ts.map → chunk-INECVQNR.ts.map} +0 -0
  228. /package/dist/chunks/{chunk-2JHAN3ZO.ts.map → chunk-JREGWM2B.ts.map} +0 -0
  229. /package/dist/chunks/{chunk-EMRFVLZM.ts.map → chunk-NXWHPVXR.ts.map} +0 -0
  230. /package/dist/chunks/{chunk-SMVKMYLK.ts.map → chunk-P4GI7LTT.ts.map} +0 -0
  231. /package/dist/chunks/{chunk-PJMM75W5.ts.map → chunk-PWESMTH6.ts.map} +0 -0
  232. /package/dist/chunks/{chunk-ZVGRZD4C.ts.map → chunk-R3SAMXB6.ts.map} +0 -0
  233. /package/dist/chunks/{chunk-RNIEVDTR.ts.map → chunk-T3LABNHF.ts.map} +0 -0
  234. /package/dist/chunks/{chunk-S3R3W3KF.ts.map → chunk-UMPA5S7X.ts.map} +0 -0
  235. /package/dist/chunks/{chunk-WP2M67XZ.ts.map → chunk-WBIOSK76.ts.map} +0 -0
  236. /package/dist/chunks/{chunk-4KTJLJSJ.ts.map → chunk-ZB3GNX3P.ts.map} +0 -0
  237. /package/dist/chunks/{chunk-HEB6YT64.ts.map → chunk-ZO52JM4H.ts.map} +0 -0
  238. /package/dist/chunks/{conflict-review-IGKY2TOJ.ts.map → conflict-review-MAOGTIAI.ts.map} +0 -0
  239. /package/dist/chunks/{continuous-record-3XDXDOMV.ts.map → continuous-record-3SKJ6I3V.ts.map} +0 -0
  240. /package/dist/chunks/{continuous-storage-HLKCHF6Z.ts.map → continuous-storage-3EU6I7Z3.ts.map} +0 -0
  241. /package/dist/chunks/{file-selection-MGGVOKM7.ts.map → file-selection-QR2KZVGD.ts.map} +0 -0
  242. /package/dist/chunks/{manager-result-dispatcher-4VJVDEUD.ts.map → manager-result-dispatcher-MC6EQOQY.ts.map} +0 -0
  243. /package/dist/chunks/{remote-selection-ui-W3KOZM3W.ts.map → remote-selection-ui-4BTP2OJR.ts.map} +0 -0
  244. /package/dist/chunks/{setup-switch-D6K6PBPC.ts.map → setup-switch-Y6AMFFNK.ts.map} +0 -0
  245. /package/dist/chunks/{setup-wizard-4DYUDHJR.ts.map → setup-wizard-5G426MOZ.ts.map} +0 -0
  246. /package/dist/chunks/{snapshot-5HY3M2NL.ts.map → snapshot-ZUJJZCFW.ts.map} +0 -0
  247. /package/dist/chunks/{snapshot-transaction-directory-OU2D7R7A.ts.map → snapshot-transaction-directory-F46JWRAU.ts.map} +0 -0
  248. /package/dist/chunks/{state-directory-XXHU73Z3.ts.map → state-directory-CMAIF34J.ts.map} +0 -0
  249. /package/dist/chunks/{sync-inspection-J3CRBORL.ts.map → sync-inspection-ITZ6Z4DE.ts.map} +0 -0
  250. /package/dist/chunks/{sync-state-2LMIXJ2C.ts.map → sync-state-QIT64TKV.ts.map} +0 -0
@@ -0,0 +1,909 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { request as httpRequest } from "node:http";
4
+ import { setTimeout as delay } from "node:timers/promises";
5
+ import { fileURLToPath } from "node:url";
6
+ import lockfile from "proper-lockfile";
7
+ import { lt, valid } from "semver";
8
+ import { DAEMON_BUILD_VERSION } from "./build-version.js";
9
+ import { canonicalRootGuard, clearUpgradeOwner, daemonPaths, privateDirectory, processExists, processExited, readIdentity, readJsonBody, readProcessBirth, readUpgradeOwner, recordUpgradeOwner, runtimePaths, upgradeRepairStarted, } from "./identity.js";
10
+ import { withCleanup } from "./lifecycle.js";
11
+ import { MAX_MESSAGE_BYTES, MAX_REVIEW_BYTES, operationPrefix, REVIEW_PAGE_CHARS, record, } from "./protocol.js";
12
+ export class DaemonError extends Error {
13
+ remote;
14
+ constructor(remote) {
15
+ super(remote.message);
16
+ this.name = remote.name;
17
+ this.remote = remote;
18
+ }
19
+ }
20
+ export async function requestDaemon(paths, identity, method, params, signal) {
21
+ signal?.throwIfAborted();
22
+ const body = JSON.stringify({
23
+ version: 1,
24
+ root: paths.root,
25
+ instance: identity.instance,
26
+ token: identity.token,
27
+ method,
28
+ params,
29
+ });
30
+ if (Buffer.byteLength(body) > MAX_MESSAGE_BYTES)
31
+ throw new Error("Daemon request exceeds its byte limit.");
32
+ return new Promise((resolve, reject) => {
33
+ const request = httpRequest({
34
+ socketPath: daemonPaths(paths, identity.instance).endpoint,
35
+ path: "/v1",
36
+ method: "POST",
37
+ signal,
38
+ headers: { "content-type": "application/json", "content-length": Buffer.byteLength(body) },
39
+ }, (response) => {
40
+ void readJsonBody(response)
41
+ .then((value) => {
42
+ if (!record(value))
43
+ throw new Error("Invalid daemon response.");
44
+ if (record(value.error) && typeof value.error.message === "string")
45
+ throw new DaemonError(value.error);
46
+ if (response.statusCode !== 200 || !Object.hasOwn(value, "result"))
47
+ throw new Error("Invalid daemon response.");
48
+ resolve(value.result);
49
+ })
50
+ .catch(reject);
51
+ });
52
+ // Admission can wait behind a complete apply. The request owner's signal
53
+ // cancels that wait; an idle timeout must not let admission escape the fence.
54
+ request.setTimeout(method === "attach" || method === "resume-contact" ? 0 : 30_000, () => request.destroy(new Error("Daemon request timed out.")));
55
+ request.once("error", reject);
56
+ request.end(body);
57
+ });
58
+ }
59
+ async function hello(paths, identity, signal) {
60
+ const value = await requestDaemon(paths, identity, "hello", {}, signal);
61
+ if (!record(value) ||
62
+ value.version !== 1 ||
63
+ value.root !== paths.root ||
64
+ value.instance !== identity.instance ||
65
+ value.pid !== identity.pid)
66
+ throw new Error("Daemon handshake mismatch.");
67
+ const version = value.buildVersion;
68
+ if (Object.hasOwn(value, "buildVersion") && (typeof version !== "string" || valid(version) !== version))
69
+ throw new Error("Invalid daemon build version.");
70
+ // The old @narumitw/sync-daemon used the same wire protocol without a build version.
71
+ return { needsUpgrade: typeof version !== "string" || lt(version, DAEMON_BUILD_VERSION) };
72
+ }
73
+ async function checkUpgradeConsent(paths, assertRoot, signal) {
74
+ const { readConsent } = await import("./consent.js");
75
+ const { withStateDirectoryGuardForRoot } = await import("./engine/state/state-directory.js");
76
+ signal?.throwIfAborted();
77
+ await withStateDirectoryGuardForRoot(paths.root, () => {
78
+ signal?.throwIfAborted();
79
+ assertRoot();
80
+ // An older owner cannot report an in-memory revocation failure.
81
+ const consent = readConsent(paths.root);
82
+ if (consent && Object.values(consent.setups).some((setup) => setup.afterExit))
83
+ throw new Error("Review or revoke unattended Pi Sync permission before restarting the older daemon.");
84
+ });
85
+ signal?.throwIfAborted();
86
+ assertRoot();
87
+ }
88
+ async function finishUpgrade(paths, owner, assertRoot, signal) {
89
+ await waitForProcessExit(owner, signal);
90
+ if ((await readIdentity(paths))?.instance === owner.instance)
91
+ throw new Error("The daemon exited without releasing its identity.");
92
+ await checkUpgradeConsent(paths, assertRoot, signal);
93
+ await clearUpgradeOwner(paths);
94
+ signal?.throwIfAborted();
95
+ assertRoot();
96
+ }
97
+ async function drainForUpgrade(paths, owner, { recorded, birth }, assertRoot, signal) {
98
+ await checkUpgradeConsent(paths, assertRoot, signal);
99
+ const barrier = recorded ?? { ...owner, birth };
100
+ try {
101
+ // Publish this before stop can remove the identity. A retry keeps the original evidence.
102
+ if (!recorded)
103
+ await recordUpgradeOwner(paths, barrier);
104
+ assertRoot();
105
+ const reply = await requestDaemon(paths, owner, "stop", {}, signal);
106
+ if (!record(reply) || reply.stopping !== true)
107
+ throw new Error("Daemon did not acknowledge stop.");
108
+ }
109
+ catch (error) {
110
+ signal?.throwIfAborted();
111
+ throw new Error("Pi Sync could not upgrade the older daemon safely. Check `pi-sync-daemon status --root <agent-directory>`. Do not force a second owner or remove recovery files.", { cause: error });
112
+ }
113
+ await finishUpgrade(paths, barrier, assertRoot, signal);
114
+ }
115
+ export async function acquireStartupLock(paths, signal) {
116
+ // Include the handshake, stop, exit wait, boot, and final handshake budgets.
117
+ const deadline = performance.now() + 150_000;
118
+ for (;;) {
119
+ signal?.throwIfAborted();
120
+ try {
121
+ return await lockfile.lock(paths.directory, {
122
+ realpath: false,
123
+ lockfilePath: paths.startup,
124
+ stale: 30_000,
125
+ update: 5_000,
126
+ });
127
+ }
128
+ catch (error) {
129
+ signal?.throwIfAborted();
130
+ if (error.code !== "ELOCKED")
131
+ throw error;
132
+ if (performance.now() >= deadline)
133
+ throw new Error("Timed out waiting to start the Pi Sync daemon.", { cause: error });
134
+ await delay(50, undefined, { signal });
135
+ }
136
+ }
137
+ }
138
+ /** Explicit startup only: callers decide whether configuration or a user action authorizes it. */
139
+ export async function ensureDaemon(root, signal) {
140
+ const paths = await runtimePaths(root);
141
+ const assertRoot = canonicalRootGuard(paths.root);
142
+ signal?.throwIfAborted();
143
+ await privateDirectory(paths.directory);
144
+ signal?.throwIfAborted();
145
+ const release = await acquireStartupLock(paths, signal);
146
+ try {
147
+ signal?.throwIfAborted();
148
+ let waited = false;
149
+ let upgraded = false;
150
+ for (;;) {
151
+ signal?.throwIfAborted();
152
+ const upgrade = await readUpgradeOwner(paths);
153
+ if (upgrade && (await upgradeRepairStarted(paths, upgrade)))
154
+ throw new Error("A daemon upgrade repair is incomplete. Run `pi-sync-daemon repair-upgrade` for this root.");
155
+ const existing = await readIdentity(paths);
156
+ if (upgrade && existing?.instance === upgrade.instance && existing.pid !== upgrade.pid)
157
+ throw new Error("The recorded upgrade owner changed; private state was retained.");
158
+ if (upgrade && (existing?.instance !== upgrade.instance || (await processExited(upgrade)))) {
159
+ await finishUpgrade(paths, upgrade, assertRoot, signal);
160
+ upgraded = true;
161
+ continue;
162
+ }
163
+ if (!existing)
164
+ break;
165
+ // A sample taken only after hello could describe an unrelated process reusing the PID.
166
+ const beforeHello = upgrade ? undefined : await readProcessBirth(existing.pid);
167
+ let status;
168
+ try {
169
+ status = await hello(paths, existing, signal);
170
+ }
171
+ catch (error) {
172
+ if (signal?.aborted)
173
+ throw signal.reason;
174
+ if (upgrade) {
175
+ // The stop may have been accepted even if the old endpoint no longer replies.
176
+ await finishUpgrade(paths, upgrade, assertRoot, signal);
177
+ upgraded = true;
178
+ continue;
179
+ }
180
+ if (error instanceof DaemonError && error.remote.name === "DaemonStoppingError" && !waited) {
181
+ waited = true;
182
+ await waitForDaemonExit(existing, signal);
183
+ continue;
184
+ }
185
+ if (processExists(existing.pid))
186
+ throw new Error("A daemon owner is alive but unavailable; use diagnostics instead of starting a second owner.", { cause: error });
187
+ break;
188
+ }
189
+ signal?.throwIfAborted();
190
+ assertRoot();
191
+ if (!status.needsUpgrade) {
192
+ if (upgrade)
193
+ throw new Error("The recorded upgrade owner changed; private state was retained.");
194
+ return { paths: daemonPaths(paths, existing.instance), identity: existing, ...status };
195
+ }
196
+ if (upgraded)
197
+ throw new Error("An older Pi Sync daemon started again. Close or upgrade other Pi sessions, then use /reload.");
198
+ const birth = beforeHello === undefined ? undefined : await readProcessBirth(existing.pid);
199
+ if (birth !== undefined && birth !== beforeHello)
200
+ throw new Error("The daemon process changed during authentication; private state was retained.");
201
+ await drainForUpgrade(paths, existing, { recorded: upgrade, birth }, assertRoot, signal);
202
+ upgraded = true;
203
+ }
204
+ signal?.throwIfAborted();
205
+ assertRoot();
206
+ const executable = process.versions.bun ? "node" : process.execPath;
207
+ const child = spawn(executable, [fileURLToPath(new URL("./cli.js", import.meta.url)), "serve", "--root", paths.root], {
208
+ detached: true,
209
+ stdio: ["ignore", "ignore", "ignore", "ipc"],
210
+ windowsHide: true,
211
+ });
212
+ const ready = await new Promise((resolve, reject) => {
213
+ let timer;
214
+ const abort = () => {
215
+ cleanup();
216
+ reject(signal?.reason);
217
+ };
218
+ const cleanup = () => {
219
+ if (timer)
220
+ clearTimeout(timer);
221
+ signal?.removeEventListener("abort", abort);
222
+ child.off("message", message);
223
+ child.off("error", failed);
224
+ child.off("exit", exited);
225
+ };
226
+ const failed = (error) => {
227
+ cleanup();
228
+ reject(error);
229
+ };
230
+ const exited = (code) => failed(new Error(`Daemon startup exited (${code}); private state was retained.`));
231
+ const message = (value) => {
232
+ if (!record(value))
233
+ return;
234
+ if (value.type === "booting") {
235
+ timer = setTimeout(() => failed(new Error("Daemon readiness timed out.")), 15_000);
236
+ timer.unref?.();
237
+ }
238
+ if (value.type === "error")
239
+ failed(new Error(typeof value.message === "string" ? value.message : "Daemon startup failed."));
240
+ if (value.type === "ready" && record(value.identity)) {
241
+ cleanup();
242
+ resolve(value.identity);
243
+ }
244
+ };
245
+ signal?.addEventListener("abort", abort, { once: true });
246
+ child.on("message", message);
247
+ child.once("error", failed);
248
+ child.once("exit", exited);
249
+ if (signal?.aborted)
250
+ abort();
251
+ }).finally(() => {
252
+ if (child.connected)
253
+ child.disconnect();
254
+ child.unref();
255
+ });
256
+ // Never kill a published shared daemon on caller cancellation.
257
+ const status = await hello(paths, ready, signal);
258
+ signal?.throwIfAborted();
259
+ assertRoot();
260
+ if (status.needsUpgrade)
261
+ throw new Error("The daemon installation changed during startup. Use /reload to retry.");
262
+ return { paths: daemonPaths(paths, ready.instance), identity: ready, ...status };
263
+ }
264
+ finally {
265
+ await release();
266
+ }
267
+ }
268
+ /** Wait only for a previously authenticated owner; never kill it or infer exit from lost contact. */
269
+ export async function waitForDaemonExit({ pid }, signal) {
270
+ await waitForProcessExit({ pid }, signal);
271
+ }
272
+ async function waitForProcessExit(owner, signal) {
273
+ const deadline = Date.now() + 30_000;
274
+ signal?.throwIfAborted();
275
+ while (!(await processExited(owner))) {
276
+ signal?.throwIfAborted();
277
+ if (Date.now() >= deadline)
278
+ throw new Error("Closing daemon is still alive; replacement was not attempted.");
279
+ await delay(25, undefined, { signal });
280
+ }
281
+ signal?.throwIfAborted();
282
+ }
283
+ /** Inspect an existing protocol-compatible owner without starting or replacing it. */
284
+ export async function findDaemon(root) {
285
+ let paths;
286
+ try {
287
+ paths = await runtimePaths(root);
288
+ }
289
+ catch (error) {
290
+ if (error.code === "ENOENT")
291
+ return undefined;
292
+ throw error;
293
+ }
294
+ const identity = await readIdentity(paths);
295
+ if (!identity || !processExists(identity.pid))
296
+ return undefined;
297
+ try {
298
+ const status = await hello(paths, identity);
299
+ return { paths: daemonPaths(paths, identity.instance), identity, ...status };
300
+ }
301
+ catch (error) {
302
+ if (error instanceof DaemonError && error.remote.name === "DaemonStoppingError")
303
+ return undefined;
304
+ throw error;
305
+ }
306
+ }
307
+ /** Gracefully stop an existing compatible owner without creating a new service. */
308
+ export async function stopDaemon(root) {
309
+ const paths = await runtimePaths(root);
310
+ const identity = await readIdentity(paths);
311
+ if (!identity)
312
+ return false;
313
+ // The authenticated stop response is itself instance/root/version bound, even
314
+ // when a changed agent root makes ordinary health checks fail closed.
315
+ await requestDaemon(paths, identity, "stop", {});
316
+ const deadline = Date.now() + 30_000;
317
+ for (;;) {
318
+ const current = await readIdentity(paths);
319
+ if (!current || current.instance !== identity.instance)
320
+ return true;
321
+ if (Date.now() >= deadline)
322
+ throw new Error("Daemon did not drain; no replacement was attempted.");
323
+ await new Promise((resolve) => setTimeout(resolve, 25));
324
+ }
325
+ }
326
+ const MAX_COMPLETED_CALLBACKS = 4096;
327
+ const RELEASE_ATTEMPT_MS = 2_000;
328
+ const RELEASE_BUDGET_MS = 25_000;
329
+ const RELEASE_MAX_ATTEMPTS = 20;
330
+ const TRANSIENT_RELEASE_ERRORS = new Set(["ECONNRESET", "ECONNREFUSED", "EPIPE", "ENOENT", "ETIMEDOUT", "EAGAIN"]);
331
+ export class DaemonConnection {
332
+ paths;
333
+ identity;
334
+ facts;
335
+ options;
336
+ cursor = 0;
337
+ controller = new AbortController();
338
+ callbacks = new Map();
339
+ callbackIO = new AbortController();
340
+ callbackTasks = new Set();
341
+ updates = Promise.resolve();
342
+ attached = false;
343
+ admitting = false;
344
+ observedContact;
345
+ contactRevision = 0;
346
+ lifecycleRevision = 0;
347
+ resuming;
348
+ resumeUncertain = false;
349
+ pendingJobs = new Set();
350
+ uncertain = false;
351
+ reportedError = false;
352
+ commits = new Map();
353
+ completedCallbacks = new Set();
354
+ // Keep drain answers deduplicated even after the lifetime callback ledger fills.
355
+ // The daemon limits each peer to 64 pending callbacks. A newer snapshot retires
356
+ // releases it no longer lists, and older snapshots cannot add them back.
357
+ completedReleases = new Set();
358
+ pausing;
359
+ disposing;
360
+ polling;
361
+ closed = false;
362
+ constructor(paths, identity, facts, options) {
363
+ this.paths = paths;
364
+ this.identity = identity;
365
+ this.facts = facts;
366
+ this.options = options;
367
+ }
368
+ /** Latest owner observation, or undefined if contact is unsupported or not observed. */
369
+ get contactState() {
370
+ return this.observedContact;
371
+ }
372
+ /** An uncertain attempt must not be retried or turned into a new attach. */
373
+ get contactResumeState() {
374
+ return this.resumeUncertain ? "uncertain" : this.resuming ? "running" : "idle";
375
+ }
376
+ /** Original submitted jobs must finish (or be reconciled) before repairing contact. */
377
+ get hasPendingWork() {
378
+ return this.pendingJobs.size > 0 || this.uncertain;
379
+ }
380
+ async attach(signal) {
381
+ if (this.closed ||
382
+ this.hasPendingWork ||
383
+ this.contactResumeState !== "idle" ||
384
+ this.admitting ||
385
+ this.pausing ||
386
+ this.disposing)
387
+ throw new Error("Daemon client is unavailable; reconnect after draining work.");
388
+ this.admitting = true;
389
+ this.lifecycleRevision++;
390
+ this.contactRevision++;
391
+ const request = requestDaemon(this.paths, this.identity, "attach", this.facts, signal ? AbortSignal.any([signal, this.controller.signal]) : this.controller.signal);
392
+ // Poll during attach: stopping a previous controller may need release answers
393
+ // from this reattached participant before the attach response can complete.
394
+ this.polling ??= this.poll();
395
+ let admitted = false;
396
+ try {
397
+ const result = await request;
398
+ admitted = true;
399
+ this.publishContact(this.consume(result));
400
+ this.attached = true;
401
+ return this;
402
+ }
403
+ catch (error) {
404
+ return withCleanup(async () => {
405
+ throw error;
406
+ }, async () => {
407
+ try {
408
+ await this.dispose();
409
+ }
410
+ catch (cleanupError) {
411
+ if (!admitted &&
412
+ !this.attached &&
413
+ this.closed &&
414
+ !this.callbacks.size &&
415
+ !this.callbackTasks.size &&
416
+ !this.completedCallbacks.size &&
417
+ error instanceof DaemonError &&
418
+ error.remote.name === "DaemonStoppingError") {
419
+ // The fenced first attach owned no grants, and local tasks have drained.
420
+ // Keep its retry marker even if the owner closes the cleanup transport.
421
+ error.cause = cleanupError;
422
+ return;
423
+ }
424
+ throw cleanupError;
425
+ }
426
+ });
427
+ }
428
+ finally {
429
+ this.admitting = false;
430
+ }
431
+ }
432
+ async update(facts) {
433
+ const lifecycle = this.lifecycleRevision;
434
+ if (this.admitting || this.pausing || this.disposing)
435
+ throw new Error("Daemon client is changing; wait before updating facts.");
436
+ const update = this.updates.then(async () => {
437
+ if (this.closed || this.uncertain || this.resumeUncertain || lifecycle !== this.lifecycleRevision)
438
+ throw new Error("Daemon client is unavailable; reconnect after draining work.");
439
+ const revision = this.contactRevision;
440
+ let result;
441
+ try {
442
+ result = await requestDaemon(this.paths, this.identity, "update", { facts }, this.controller.signal);
443
+ }
444
+ catch (error) {
445
+ if (this.attached &&
446
+ revision === this.contactRevision &&
447
+ this.sameClient(facts) &&
448
+ error instanceof DaemonError &&
449
+ error.remote.name === "ClientContactExpiredError")
450
+ this.publishContact("expired");
451
+ throw error;
452
+ }
453
+ if (this.closed)
454
+ throw new Error("Daemon client closed during update.");
455
+ if (revision !== this.contactRevision)
456
+ throw new Error("Daemon client changed during update.");
457
+ const contact = this.consume(result);
458
+ if (revision !== this.contactRevision)
459
+ throw new Error("Daemon client changed during update.");
460
+ Object.assign(this.facts, facts);
461
+ this.publishContact(contact);
462
+ });
463
+ this.updates = update.catch(() => { });
464
+ return update;
465
+ }
466
+ /** Resume this participant without replacing its callbacks, jobs, or polling. */
467
+ async resumeContact(facts, signal) {
468
+ signal?.throwIfAborted();
469
+ if (this.contactResumeState !== "idle")
470
+ throw new Error("Daemon contact resume is running or uncertain.");
471
+ const check = () => {
472
+ if (!this.attached || this.admitting || this.pausing || this.disposing || this.closed || this.hasPendingWork)
473
+ throw new Error("Daemon client is unavailable; reconnect after draining work.");
474
+ if (!this.sameClient(facts) || this.contactState !== "expired")
475
+ throw new Error("No confirmed contact expiry for this daemon client.");
476
+ };
477
+ facts = structuredClone(facts);
478
+ check();
479
+ const resume = new AbortController();
480
+ this.resuming = resume;
481
+ const ownedSignal = signal ? AbortSignal.any([signal, resume.signal]) : resume.signal;
482
+ let sent = false;
483
+ const attempt = this.updates.then(async () => {
484
+ ownedSignal.throwIfAborted();
485
+ check();
486
+ sent = true;
487
+ const reply = await requestDaemon(this.paths, this.identity, "resume-contact", facts, ownedSignal);
488
+ ownedSignal.throwIfAborted();
489
+ const contact = this.consume(reply);
490
+ ownedSignal.throwIfAborted();
491
+ if (contact !== "active")
492
+ throw new Error("Daemon did not confirm resumed contact.");
493
+ Object.assign(this.facts, facts);
494
+ this.publishContact(contact);
495
+ });
496
+ this.updates = attempt.catch(() => { });
497
+ // Reject a queued repair on cancellation even if the earlier update has not finished.
498
+ const cancellation = Promise.withResolvers();
499
+ const abort = () => cancellation.reject(ownedSignal.reason);
500
+ ownedSignal.addEventListener("abort", abort, { once: true });
501
+ try {
502
+ await Promise.race([attempt, cancellation.promise]);
503
+ }
504
+ catch (error) {
505
+ if (sent) {
506
+ // The protocol does not distinguish definite pre-publication refusal from a lost acknowledgement.
507
+ this.resumeUncertain = true;
508
+ for (const { controller, kind } of this.callbacks.values())
509
+ if (kind !== "queue-release")
510
+ controller.abort();
511
+ }
512
+ throw error;
513
+ }
514
+ finally {
515
+ this.resuming = undefined;
516
+ ownedSignal.removeEventListener("abort", abort);
517
+ }
518
+ }
519
+ sameClient(facts) {
520
+ return facts.id === this.facts.id && facts.pid === this.facts.pid && facts.generation === this.facts.generation;
521
+ }
522
+ async run(operation, payload, signal, onCommit) {
523
+ if (this.closed ||
524
+ this.uncertain ||
525
+ this.contactResumeState !== "idle" ||
526
+ this.pausing ||
527
+ this.disposing ||
528
+ this.contactState === "expired" ||
529
+ this.contactState === "inactive")
530
+ throw new Error("Daemon client is unavailable; confirm contact and drain work before submitting.");
531
+ signal?.throwIfAborted();
532
+ const id = `${operationPrefix(this.identity)}${randomUUID()}`;
533
+ this.pendingJobs.add(id);
534
+ const abort = () => {
535
+ void requestDaemon(this.paths, this.identity, "cancel", { id, client: this.facts.id }, this.controller.signal).catch(() => { });
536
+ };
537
+ let terminal = false;
538
+ if (onCommit)
539
+ this.commits.set(id, { notify: onCommit, signal });
540
+ signal?.addEventListener("abort", abort, { once: true });
541
+ if (signal?.aborted)
542
+ abort();
543
+ return withCleanup(async () => {
544
+ await requestDaemon(this.paths, this.identity, "submit", { id, client: this.facts.id, operation, payload }, this.controller.signal);
545
+ while (!this.closed) {
546
+ const reply = await requestDaemon(this.paths, this.identity, "poll", { client: this.facts.id, cursor: this.cursor, job: id }, this.controller.signal);
547
+ this.consume(reply);
548
+ const job = record(reply) ? reply.job : undefined;
549
+ if (job?.id === id && job.phase === "failed") {
550
+ terminal = true;
551
+ throw new DaemonError(job.error ?? { name: "Error", message: "Daemon operation failed." });
552
+ }
553
+ if (job?.id === id && job.phase === "done") {
554
+ terminal = true;
555
+ signal?.throwIfAborted();
556
+ return job.result;
557
+ }
558
+ await this.wait(25, true);
559
+ }
560
+ throw new Error("Daemon client closed before operation completed.");
561
+ }, async () => {
562
+ signal?.removeEventListener("abort", abort);
563
+ this.commits.delete(id);
564
+ if (!terminal && !this.closed) {
565
+ for (const callback of this.callbacks.values())
566
+ if (callback.job === id && !callback.kind.startsWith("queue-"))
567
+ callback.controller.abort();
568
+ try {
569
+ await requestDaemon(this.paths, this.identity, "cancel", { id, client: this.facts.id });
570
+ }
571
+ catch (error) {
572
+ this.uncertain = true;
573
+ for (const callback of this.callbacks.values())
574
+ if (callback.kind !== "queue-release")
575
+ callback.controller.abort();
576
+ throw new Error("Operation outcome is uncertain; reload to reconnect and reconcile, never replay the write.", { cause: error });
577
+ }
578
+ }
579
+ }).finally(() => this.pendingJobs.delete(id));
580
+ }
581
+ publishContact(contact) {
582
+ this.contactRevision++;
583
+ this.observedContact = contact;
584
+ }
585
+ consume(reply) {
586
+ if (!record(reply) ||
587
+ typeof reply.cursor !== "number" ||
588
+ !Number.isSafeInteger(reply.cursor) ||
589
+ reply.cursor < 0 ||
590
+ !Array.isArray(reply.callbacks) ||
591
+ !Array.isArray(reply.events))
592
+ throw new Error("Invalid daemon poll response.");
593
+ const { contact } = reply;
594
+ if (contact !== undefined && contact !== "active" && contact !== "expired" && contact !== "inactive")
595
+ throw new Error("Invalid daemon contact state.");
596
+ if (reply.cursor < this.cursor)
597
+ return contact;
598
+ for (const event of reply.events)
599
+ if (event.id > this.cursor) {
600
+ if (event.kind === "commit" && record(event.payload) && typeof event.payload.job === "string") {
601
+ const current = this.commits.get(event.payload.job);
602
+ this.commits.delete(event.payload.job);
603
+ if (current && !current.signal?.aborted)
604
+ current.notify();
605
+ }
606
+ this.options.event?.(event);
607
+ }
608
+ const latest = reply.cursor >= this.cursor;
609
+ const present = new Set(reply.callbacks.map((callback) => callback.id));
610
+ if (reply.cursor > this.cursor) {
611
+ for (const id of this.completedReleases)
612
+ if (!present.has(id))
613
+ this.completedReleases.delete(id);
614
+ this.cursor = reply.cursor;
615
+ }
616
+ for (const [id, pending] of this.callbacks) {
617
+ if (pending.releaseCursor !== undefined) {
618
+ // A job poll and the background poll can arrive out of order.
619
+ if (!latest || reply.cursor <= pending.releaseCursor)
620
+ continue;
621
+ if (present.has(id)) {
622
+ pending.releaseCursor = reply.cursor;
623
+ continue;
624
+ }
625
+ }
626
+ else if (present.has(id))
627
+ continue;
628
+ pending.controller.abort(new DOMException("Callback is no longer current", "AbortError"));
629
+ }
630
+ for (const callback of reply.callbacks) {
631
+ if (this.callbacks.has(callback.id) || this.completedCallbacks.has(callback.id))
632
+ continue;
633
+ const release = callback.kind === "queue-release";
634
+ if (release && (!latest || this.completedReleases.has(callback.id)))
635
+ continue;
636
+ if (this.completedCallbacks.size + this.callbacks.size >= MAX_COMPLETED_CALLBACKS)
637
+ this.uncertain = true;
638
+ const controller = new AbortController();
639
+ const foreground = this.pendingJobs.has(callback.job);
640
+ this.callbacks.set(callback.id, {
641
+ controller,
642
+ kind: callback.kind,
643
+ job: callback.job,
644
+ ...(release && { releaseCursor: reply.cursor }),
645
+ });
646
+ const task = (async () => {
647
+ let value;
648
+ let failed = false;
649
+ try {
650
+ if ((this.uncertain || this.resumeUncertain) && callback.kind !== "queue-release")
651
+ throw new Error("Client is draining uncertain work.");
652
+ value = await this.performCallback(callback, controller.signal);
653
+ }
654
+ catch {
655
+ failed = true;
656
+ }
657
+ if (release) {
658
+ if (!failed && value === true) {
659
+ await this.deliverRelease(callback, foreground, controller.signal);
660
+ return;
661
+ }
662
+ failed = true;
663
+ }
664
+ try {
665
+ await requestDaemon(this.paths, this.identity, "answer", {
666
+ client: this.facts.id,
667
+ id: callback.id,
668
+ ...(failed ? { error: "Client callback cancelled or failed." } : { value }),
669
+ }, this.callbackIO.signal);
670
+ }
671
+ finally {
672
+ if (release)
673
+ this.reportRelease(callback, foreground, "unconfirmed");
674
+ }
675
+ })()
676
+ .catch((error) => {
677
+ if (!this.closed && !controller.signal.aborted)
678
+ this.reportError(error);
679
+ })
680
+ .finally(() => {
681
+ if (this.completedCallbacks.size < MAX_COMPLETED_CALLBACKS)
682
+ this.completedCallbacks.add(callback.id);
683
+ else if (release && !controller.signal.aborted)
684
+ this.completedReleases.add(callback.id);
685
+ this.callbacks.delete(callback.id);
686
+ this.callbackTasks.delete(task);
687
+ });
688
+ this.callbackTasks.add(task);
689
+ }
690
+ return contact;
691
+ }
692
+ reportRelease(callback, foreground, state) {
693
+ if (this.callbackIO.signal.aborted)
694
+ return;
695
+ try {
696
+ this.options.queueRelease?.({ id: callback.id, job: callback.job, foreground, state });
697
+ }
698
+ catch {
699
+ // Presentation must not own a queue or a callback task.
700
+ }
701
+ }
702
+ async deliverRelease(callback, foreground, pending) {
703
+ const signal = AbortSignal.any([pending, this.callbackIO.signal]);
704
+ const deadline = performance.now() + RELEASE_BUDGET_MS;
705
+ let retrying = false;
706
+ let state = "unconfirmed";
707
+ try {
708
+ for (let attempt = 0; attempt < RELEASE_MAX_ATTEMPTS; attempt++) {
709
+ const remaining = Math.floor(deadline - performance.now());
710
+ if (remaining <= 0 || signal.aborted)
711
+ break;
712
+ const controller = new AbortController();
713
+ const timer = setTimeout(() => controller.abort(), Math.min(remaining, RELEASE_ATTEMPT_MS));
714
+ timer.unref?.();
715
+ try {
716
+ await requestDaemon(this.paths, this.identity, "answer", { client: this.facts.id, id: callback.id, value: true }, AbortSignal.any([signal, controller.signal]));
717
+ state = "finished";
718
+ return;
719
+ }
720
+ catch (error) {
721
+ if (signal.aborted)
722
+ break;
723
+ if (error instanceof DaemonError) {
724
+ // The v1 server uses this reply for absent as well as foreign callbacks.
725
+ // Do not infer whether the original release succeeded.
726
+ if (error.message === "Stale or foreign callback response.")
727
+ state = "finished";
728
+ return;
729
+ }
730
+ if (!controller.signal.aborted &&
731
+ (!(error instanceof Error) || !TRANSIENT_RELEASE_ERRORS.has(error.code ?? "")))
732
+ return;
733
+ }
734
+ finally {
735
+ clearTimeout(timer);
736
+ }
737
+ if (!retrying) {
738
+ retrying = true;
739
+ this.reportRelease(callback, foreground, "retrying");
740
+ }
741
+ const wait = Math.min(100 * 2 ** attempt, 2_000, deadline - performance.now());
742
+ if (wait <= 0 || attempt + 1 >= RELEASE_MAX_ATTEMPTS)
743
+ break;
744
+ await delay(wait, undefined, { signal, ref: false }).catch(() => { });
745
+ }
746
+ }
747
+ finally {
748
+ if (pending.aborted && !this.callbackIO.signal.aborted)
749
+ state = "finished";
750
+ if (retrying || state === "unconfirmed")
751
+ this.reportRelease(callback, foreground, state);
752
+ }
753
+ }
754
+ async performCallback(callback, signal) {
755
+ const reference = callback.review;
756
+ if (!reference)
757
+ return this.options.callback(callback, signal);
758
+ if (callback.kind !== "merge-review" ||
759
+ !record(callback.payload) ||
760
+ !Number.isSafeInteger(reference.pages) ||
761
+ reference.pages < 1 ||
762
+ reference.pages > Math.ceil(MAX_REVIEW_BYTES / REVIEW_PAGE_CHARS) ||
763
+ !Number.isSafeInteger(reference.bytes) ||
764
+ reference.bytes > MAX_REVIEW_BYTES ||
765
+ reference.bytes < 1 ||
766
+ !/^[a-f0-9]{64}$/u.test(reference.sha256))
767
+ throw new Error("Invalid exact-review reference.");
768
+ const ownedSignal = AbortSignal.any([signal, this.callbackIO.signal]);
769
+ const pages = [];
770
+ for (let index = 0; index < reference.pages; index++) {
771
+ ownedSignal.throwIfAborted();
772
+ const page = await requestDaemon(this.paths, this.identity, "review-page", { client: this.facts.id, id: callback.id, index }, ownedSignal);
773
+ ownedSignal.throwIfAborted();
774
+ if (!record(page) ||
775
+ page.id !== callback.id ||
776
+ page.index !== index ||
777
+ typeof page.content !== "string" ||
778
+ page.content.length > REVIEW_PAGE_CHARS)
779
+ throw new Error("Invalid exact-review page.");
780
+ pages.push(page.content);
781
+ }
782
+ const content = pages.join("");
783
+ if (Buffer.byteLength(content) !== reference.bytes ||
784
+ createHash("sha256").update(content).digest("hex") !== reference.sha256)
785
+ throw new Error("Exact-review contents changed; approval was refused.");
786
+ ownedSignal.throwIfAborted();
787
+ return this.options.callback({ ...callback, review: undefined, payload: { ...callback.payload, content } }, signal);
788
+ }
789
+ async wait(ms, keepAlive = false) {
790
+ const signal = this.controller.signal;
791
+ signal.throwIfAborted();
792
+ await new Promise((resolve, reject) => {
793
+ const timer = setTimeout(done, ms);
794
+ if (!keepAlive)
795
+ timer.unref?.();
796
+ const abort = () => {
797
+ clearTimeout(timer);
798
+ signal.removeEventListener("abort", abort);
799
+ reject(signal.reason);
800
+ };
801
+ function done() {
802
+ signal.removeEventListener("abort", abort);
803
+ resolve();
804
+ }
805
+ signal.addEventListener("abort", abort, { once: true });
806
+ });
807
+ }
808
+ reportError(error) {
809
+ if (this.reportedError)
810
+ return;
811
+ this.reportedError = true;
812
+ try {
813
+ this.options.error?.(error);
814
+ }
815
+ catch {
816
+ /* Error presentation must not own a task. */
817
+ }
818
+ }
819
+ async poll() {
820
+ while (!this.closed) {
821
+ try {
822
+ const revision = this.contactRevision;
823
+ const reply = await requestDaemon(this.paths, this.identity, "poll", { client: this.facts.id, cursor: this.cursor }, this.controller.signal);
824
+ // An older poll must not undo typed update expiry or a successful resume.
825
+ if (revision === this.contactRevision) {
826
+ const contact = this.consume(reply);
827
+ this.reportedError = false;
828
+ if (revision === this.contactRevision &&
829
+ this.attached &&
830
+ !this.admitting &&
831
+ !this.pausing &&
832
+ !this.disposing &&
833
+ !this.closed) {
834
+ // A new observation fences older facts replies; identical polls do not.
835
+ if (contact !== this.observedContact)
836
+ this.publishContact(contact);
837
+ if (contact !== undefined)
838
+ this.options.contact?.(contact);
839
+ }
840
+ }
841
+ await this.wait(100);
842
+ }
843
+ catch (error) {
844
+ if (this.closed)
845
+ return;
846
+ if (this.attached)
847
+ this.reportError(error);
848
+ try {
849
+ await this.wait(100);
850
+ }
851
+ catch {
852
+ return;
853
+ }
854
+ }
855
+ }
856
+ }
857
+ async pause() {
858
+ if (this.closed || this.disposing)
859
+ throw new Error("Daemon client is closed.");
860
+ if (this.pausing)
861
+ return this.pausing;
862
+ this.resuming?.abort(new DOMException("Client paused", "AbortError"));
863
+ this.lifecycleRevision++;
864
+ this.contactRevision++;
865
+ this.pausing = (async () => {
866
+ const reply = await requestDaemon(this.paths, this.identity, "pause", { client: this.facts.id });
867
+ const contact = this.consume(reply);
868
+ if (!this.disposing)
869
+ this.publishContact(contact);
870
+ })().finally(() => {
871
+ this.pausing = undefined;
872
+ });
873
+ return this.pausing;
874
+ }
875
+ async dispose(handoff) {
876
+ if (this.disposing)
877
+ return this.disposing;
878
+ if (this.closed)
879
+ return;
880
+ this.resuming?.abort(new DOMException("Client disposed", "AbortError"));
881
+ this.lifecycleRevision++;
882
+ this.contactRevision++;
883
+ this.disposing = (async () => {
884
+ this.polling ??= this.poll();
885
+ // Cancel UI before drain, but keep polling for acknowledged queue-release callbacks.
886
+ for (const { controller, kind } of this.callbacks.values())
887
+ if (!kind.startsWith("queue-"))
888
+ controller.abort();
889
+ try {
890
+ const reply = await requestDaemon(this.paths, this.identity, handoff ? "handoff" : "detach", {
891
+ client: this.facts.id,
892
+ generation: this.facts.generation,
893
+ pid: this.facts.pid,
894
+ handoff,
895
+ });
896
+ this.consume(reply);
897
+ }
898
+ finally {
899
+ this.closed = true;
900
+ this.controller.abort(new DOMException("Client disposed", "AbortError"));
901
+ this.callbackIO.abort(new DOMException("Client callback transport disposed", "AbortError"));
902
+ for (const { controller } of this.callbacks.values())
903
+ controller.abort();
904
+ await Promise.allSettled([this.polling, this.updates, ...this.callbackTasks]);
905
+ }
906
+ })();
907
+ return this.disposing;
908
+ }
909
+ }