@narumitw/pi-sync-daemon 0.0.0-stage → 0.3.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 (267) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/LICENSE +21 -0
  3. package/README.md +91 -2
  4. package/dist/cli.d.ts +2 -0
  5. package/dist/cli.js +127 -0
  6. package/dist/client.d.ts +57 -0
  7. package/dist/client.js +534 -0
  8. package/dist/consent.d.ts +24 -0
  9. package/dist/consent.js +205 -0
  10. package/dist/document.d.ts +10 -0
  11. package/dist/document.js +6 -0
  12. package/dist/endpoint.d.ts +8 -0
  13. package/dist/endpoint.js +91 -0
  14. package/dist/engine/backends/backend-factory.d.ts +6 -0
  15. package/dist/engine/backends/backend-factory.js +16 -0
  16. package/dist/engine/backends/backend-identity.d.ts +3 -0
  17. package/dist/engine/backends/backend-identity.js +38 -0
  18. package/dist/engine/backends/backend-types.d.ts +70 -0
  19. package/dist/engine/backends/backend-types.js +1 -0
  20. package/dist/engine/backends/git/git-backend.d.ts +55 -0
  21. package/dist/engine/backends/git/git-backend.js +700 -0
  22. package/dist/engine/backends/git/git-config.d.ts +5 -0
  23. package/dist/engine/backends/git/git-config.js +118 -0
  24. package/dist/engine/backends/git/git-runner.d.ts +25 -0
  25. package/dist/engine/backends/git/git-runner.js +232 -0
  26. package/dist/engine/backends/git/git-storage.d.ts +39 -0
  27. package/dist/engine/backends/git/git-storage.js +226 -0
  28. package/dist/engine/backends/s3/s3-backend.d.ts +32 -0
  29. package/dist/engine/backends/s3/s3-backend.js +436 -0
  30. package/dist/engine/backends/s3/s3-client.d.ts +36 -0
  31. package/dist/engine/backends/s3/s3-client.js +352 -0
  32. package/dist/engine/backends/s3/s3-conditions.d.ts +4 -0
  33. package/dist/engine/backends/s3/s3-conditions.js +66 -0
  34. package/dist/engine/backends/snapshot-pointer.d.ts +6 -0
  35. package/dist/engine/backends/snapshot-pointer.js +22 -0
  36. package/dist/engine/backends/sync-backend.d.ts +71 -0
  37. package/dist/engine/backends/sync-backend.js +23 -0
  38. package/dist/engine/backends/webdav/webdav-backend.d.ts +34 -0
  39. package/dist/engine/backends/webdav/webdav-backend.js +534 -0
  40. package/dist/engine/backends/webdav/webdav-client.d.ts +36 -0
  41. package/dist/engine/backends/webdav/webdav-client.js +326 -0
  42. package/dist/engine/backends/webdav/webdav-config.d.ts +5 -0
  43. package/dist/engine/backends/webdav/webdav-config.js +73 -0
  44. package/dist/engine/commands/command-types.d.ts +31 -0
  45. package/dist/engine/commands/command-types.js +1 -0
  46. package/dist/engine/host.d.ts +70 -0
  47. package/dist/engine/host.js +16 -0
  48. package/dist/engine/paths.d.ts +9 -0
  49. package/dist/engine/paths.js +71 -0
  50. package/dist/engine/settings/config-errors.d.ts +1 -0
  51. package/dist/engine/settings/config-errors.js +4 -0
  52. package/dist/engine/settings/config-file.d.ts +33 -0
  53. package/dist/engine/settings/config-file.js +630 -0
  54. package/dist/engine/settings/config.d.ts +24 -0
  55. package/dist/engine/settings/config.js +200 -0
  56. package/dist/engine/settings/settings-management.d.ts +24 -0
  57. package/dist/engine/settings/settings-management.js +191 -0
  58. package/dist/engine/settings/settings-store.d.ts +8 -0
  59. package/dist/engine/settings/settings-store.js +41 -0
  60. package/dist/engine/settings/settings-types.d.ts +134 -0
  61. package/dist/engine/settings/settings-types.js +1 -0
  62. package/dist/engine/settings/settings-validation.d.ts +15 -0
  63. package/dist/engine/settings/settings-validation.js +356 -0
  64. package/dist/engine/snapshot/session-paths.d.ts +12 -0
  65. package/dist/engine/snapshot/session-paths.js +91 -0
  66. package/dist/engine/snapshot/snapshot-apply.d.ts +22 -0
  67. package/dist/engine/snapshot/snapshot-apply.js +262 -0
  68. package/dist/engine/snapshot/snapshot-case-replacement.d.ts +15 -0
  69. package/dist/engine/snapshot/snapshot-case-replacement.js +82 -0
  70. package/dist/engine/snapshot/snapshot-codec.d.ts +6 -0
  71. package/dist/engine/snapshot/snapshot-codec.js +53 -0
  72. package/dist/engine/snapshot/snapshot-exclude-safety.d.ts +7 -0
  73. package/dist/engine/snapshot/snapshot-exclude-safety.js +47 -0
  74. package/dist/engine/snapshot/snapshot-mutation-queues.d.ts +9 -0
  75. package/dist/engine/snapshot/snapshot-mutation-queues.js +133 -0
  76. package/dist/engine/snapshot/snapshot-paths.d.ts +1 -0
  77. package/dist/engine/snapshot/snapshot-paths.js +11 -0
  78. package/dist/engine/snapshot/snapshot-root-transition.d.ts +25 -0
  79. package/dist/engine/snapshot/snapshot-root-transition.js +122 -0
  80. package/dist/engine/snapshot/snapshot-transaction-directory.d.ts +2 -0
  81. package/dist/engine/snapshot/snapshot-transaction-directory.js +16 -0
  82. package/dist/engine/snapshot/snapshot-transaction-plan.d.ts +12 -0
  83. package/dist/engine/snapshot/snapshot-transaction-plan.js +68 -0
  84. package/dist/engine/snapshot/snapshot-transaction.d.ts +15 -0
  85. package/dist/engine/snapshot/snapshot-transaction.js +787 -0
  86. package/dist/engine/snapshot/snapshot-types.d.ts +48 -0
  87. package/dist/engine/snapshot/snapshot-types.js +1 -0
  88. package/dist/engine/snapshot/snapshot.d.ts +30 -0
  89. package/dist/engine/snapshot/snapshot.js +364 -0
  90. package/dist/engine/state/json-file.d.ts +6 -0
  91. package/dist/engine/state/json-file.js +49 -0
  92. package/dist/engine/state/lock-policy.d.ts +2 -0
  93. package/dist/engine/state/lock-policy.js +2 -0
  94. package/dist/engine/state/lock.d.ts +20 -0
  95. package/dist/engine/state/lock.js +259 -0
  96. package/dist/engine/state/lockfile-fs.d.ts +13 -0
  97. package/dist/engine/state/lockfile-fs.js +13 -0
  98. package/dist/engine/state/merge-baseline-store.d.ts +11 -0
  99. package/dist/engine/state/merge-baseline-store.js +187 -0
  100. package/dist/engine/state/mutation-directory-sync.d.ts +5 -0
  101. package/dist/engine/state/mutation-directory-sync.js +34 -0
  102. package/dist/engine/state/operation-availability.d.ts +49 -0
  103. package/dist/engine/state/operation-availability.js +40 -0
  104. package/dist/engine/state/state-directory.d.ts +14 -0
  105. package/dist/engine/state/state-directory.js +225 -0
  106. package/dist/engine/state/state-types.d.ts +27 -0
  107. package/dist/engine/state/state-types.js +1 -0
  108. package/dist/engine/state/sync-state-store.d.ts +11 -0
  109. package/dist/engine/state/sync-state-store.js +54 -0
  110. package/dist/engine/sync/agent-candidate.d.ts +44 -0
  111. package/dist/engine/sync/agent-candidate.js +207 -0
  112. package/dist/engine/sync/agent-plan.d.ts +8 -0
  113. package/dist/engine/sync/agent-plan.js +84 -0
  114. package/dist/engine/sync/agent-policy.d.ts +9 -0
  115. package/dist/engine/sync/agent-policy.js +10 -0
  116. package/dist/engine/sync/agent-refusal-retry.d.ts +4 -0
  117. package/dist/engine/sync/agent-refusal-retry.js +39 -0
  118. package/dist/engine/sync/agent-request.d.ts +14 -0
  119. package/dist/engine/sync/agent-request.js +13 -0
  120. package/dist/engine/sync/agent-runner.d.ts +6 -0
  121. package/dist/engine/sync/agent-runner.js +183 -0
  122. package/dist/engine/sync/agent-store.d.ts +7 -0
  123. package/dist/engine/sync/agent-store.js +177 -0
  124. package/dist/engine/sync/agent-sync.d.ts +4 -0
  125. package/dist/engine/sync/agent-sync.js +132 -0
  126. package/dist/engine/sync/apply-review.d.ts +8 -0
  127. package/dist/engine/sync/apply-review.js +51 -0
  128. package/dist/engine/sync/conflict-artifact-ownership.d.ts +4 -0
  129. package/dist/engine/sync/conflict-artifact-ownership.js +53 -0
  130. package/dist/engine/sync/conflict-artifacts.d.ts +32 -0
  131. package/dist/engine/sync/conflict-artifacts.js +158 -0
  132. package/dist/engine/sync/conflict-groups.d.ts +9 -0
  133. package/dist/engine/sync/conflict-groups.js +76 -0
  134. package/dist/engine/sync/conflict-preview.d.ts +4 -0
  135. package/dist/engine/sync/conflict-preview.js +53 -0
  136. package/dist/engine/sync/conflict-resolution.d.ts +13 -0
  137. package/dist/engine/sync/conflict-resolution.js +53 -0
  138. package/dist/engine/sync/conflict-retention.d.ts +5 -0
  139. package/dist/engine/sync/conflict-retention.js +61 -0
  140. package/dist/engine/sync/conflict-review.d.ts +4 -0
  141. package/dist/engine/sync/conflict-review.js +73 -0
  142. package/dist/engine/sync/content-conflicts.d.ts +10 -0
  143. package/dist/engine/sync/content-conflicts.js +70 -0
  144. package/dist/engine/sync/continuous-errors.d.ts +14 -0
  145. package/dist/engine/sync/continuous-errors.js +66 -0
  146. package/dist/engine/sync/continuous-lease.d.ts +9 -0
  147. package/dist/engine/sync/continuous-lease.js +206 -0
  148. package/dist/engine/sync/continuous-record.d.ts +31 -0
  149. package/dist/engine/sync/continuous-record.js +199 -0
  150. package/dist/engine/sync/continuous-storage.d.ts +14 -0
  151. package/dist/engine/sync/continuous-storage.js +59 -0
  152. package/dist/engine/sync/continuous-sync.d.ts +15 -0
  153. package/dist/engine/sync/continuous-sync.js +496 -0
  154. package/dist/engine/sync/continuous-watch.d.ts +3 -0
  155. package/dist/engine/sync/continuous-watch.js +65 -0
  156. package/dist/engine/sync/exclude-policy.d.ts +5 -0
  157. package/dist/engine/sync/exclude-policy.js +79 -0
  158. package/dist/engine/sync/field-migration.d.ts +5 -0
  159. package/dist/engine/sync/field-migration.js +20 -0
  160. package/dist/engine/sync/file-merge-planner.d.ts +36 -0
  161. package/dist/engine/sync/file-merge-planner.js +123 -0
  162. package/dist/engine/sync/initialization.d.ts +12 -0
  163. package/dist/engine/sync/initialization.js +75 -0
  164. package/dist/engine/sync/json-document.d.ts +29 -0
  165. package/dist/engine/sync/json-document.js +172 -0
  166. package/dist/engine/sync/local-field-policy.d.ts +2 -0
  167. package/dist/engine/sync/local-field-policy.js +26 -0
  168. package/dist/engine/sync/local-fields.d.ts +9 -0
  169. package/dist/engine/sync/local-fields.js +116 -0
  170. package/dist/engine/sync/merge-apply.d.ts +5 -0
  171. package/dist/engine/sync/merge-apply.js +386 -0
  172. package/dist/engine/sync/merge-journal.d.ts +31 -0
  173. package/dist/engine/sync/merge-journal.js +179 -0
  174. package/dist/engine/sync/merge-transfer-error.d.ts +3 -0
  175. package/dist/engine/sync/merge-transfer-error.js +64 -0
  176. package/dist/engine/sync/merged-sync.d.ts +6 -0
  177. package/dist/engine/sync/merged-sync.js +618 -0
  178. package/dist/engine/sync/mutation-owner.d.ts +2 -0
  179. package/dist/engine/sync/mutation-owner.js +18 -0
  180. package/dist/engine/sync/package-merge.d.ts +3 -0
  181. package/dist/engine/sync/package-merge.js +82 -0
  182. package/dist/engine/sync/partial-progress.d.ts +15 -0
  183. package/dist/engine/sync/partial-progress.js +39 -0
  184. package/dist/engine/sync/remote-snapshot.d.ts +28 -0
  185. package/dist/engine/sync/remote-snapshot.js +62 -0
  186. package/dist/engine/sync/resolver-stream.d.ts +4 -0
  187. package/dist/engine/sync/resolver-stream.js +34 -0
  188. package/dist/engine/sync/session-merge.d.ts +3 -0
  189. package/dist/engine/sync/session-merge.js +178 -0
  190. package/dist/engine/sync/session-push.d.ts +5 -0
  191. package/dist/engine/sync/session-push.js +32 -0
  192. package/dist/engine/sync/settings-conflicts.d.ts +8 -0
  193. package/dist/engine/sync/settings-conflicts.js +56 -0
  194. package/dist/engine/sync/settings-merge.d.ts +13 -0
  195. package/dist/engine/sync/settings-merge.js +93 -0
  196. package/dist/engine/sync/signals.d.ts +2 -0
  197. package/dist/engine/sync/signals.js +8 -0
  198. package/dist/engine/sync/startup-timings.d.ts +11 -0
  199. package/dist/engine/sync/startup-timings.js +44 -0
  200. package/dist/engine/sync/sync-decision.d.ts +35 -0
  201. package/dist/engine/sync/sync-decision.js +66 -0
  202. package/dist/engine/sync/sync-error-guidance.d.ts +2 -0
  203. package/dist/engine/sync/sync-error-guidance.js +55 -0
  204. package/dist/engine/sync/sync-errors.d.ts +9 -0
  205. package/dist/engine/sync/sync-errors.js +18 -0
  206. package/dist/engine/sync/sync-inspection.d.ts +26 -0
  207. package/dist/engine/sync/sync-inspection.js +40 -0
  208. package/dist/engine/sync/sync-loaders.d.ts +7 -0
  209. package/dist/engine/sync/sync-loaders.js +8 -0
  210. package/dist/engine/sync/sync-local.d.ts +5 -0
  211. package/dist/engine/sync/sync-local.js +40 -0
  212. package/dist/engine/sync/sync-mutations.d.ts +30 -0
  213. package/dist/engine/sync/sync-mutations.js +589 -0
  214. package/dist/engine/sync/sync-operations.d.ts +2 -0
  215. package/dist/engine/sync/sync-operations.js +3 -0
  216. package/dist/engine/sync/sync-policy.d.ts +85 -0
  217. package/dist/engine/sync/sync-policy.js +356 -0
  218. package/dist/engine/sync/sync-queries.d.ts +7 -0
  219. package/dist/engine/sync/sync-queries.js +195 -0
  220. package/dist/engine/sync/sync-state.d.ts +31 -0
  221. package/dist/engine/sync/sync-state.js +92 -0
  222. package/dist/engine/sync/text-merge.d.ts +19 -0
  223. package/dist/engine/sync/text-merge.js +124 -0
  224. package/dist/engine/types.d.ts +5 -0
  225. package/dist/engine/types.js +2 -0
  226. package/dist/engine/ui/merge-review.d.ts +2 -0
  227. package/dist/engine/ui/merge-review.js +7 -0
  228. package/dist/engine/ui/merged-sync-summary.d.ts +25 -0
  229. package/dist/engine/ui/merged-sync-summary.js +86 -0
  230. package/dist/engine/ui/sync-format.d.ts +13 -0
  231. package/dist/engine/ui/sync-format.js +150 -0
  232. package/dist/engine/ui/sync-status.d.ts +9 -0
  233. package/dist/engine/ui/sync-status.js +30 -0
  234. package/dist/engine/ui/terminal-text.d.ts +3 -0
  235. package/dist/engine/ui/terminal-text.js +9 -0
  236. package/dist/engine/ui/transfer-changes.d.ts +12 -0
  237. package/dist/engine/ui/transfer-changes.js +24 -0
  238. package/dist/engine/ui/transfer-review.d.ts +3 -0
  239. package/dist/engine/ui/transfer-review.js +19 -0
  240. package/dist/engine-service.d.ts +14 -0
  241. package/dist/engine-service.js +322 -0
  242. package/dist/identity.d.ts +20 -0
  243. package/dist/identity.js +133 -0
  244. package/dist/idle-exit.d.ts +17 -0
  245. package/dist/idle-exit.js +77 -0
  246. package/dist/index.d.ts +8 -0
  247. package/dist/index.js +4 -0
  248. package/dist/lifecycle-log.d.ts +7 -0
  249. package/dist/lifecycle-log.js +53 -0
  250. package/dist/lifecycle.d.ts +2 -0
  251. package/dist/lifecycle.js +21 -0
  252. package/dist/model-signature.d.ts +2 -0
  253. package/dist/model-signature.js +7 -0
  254. package/dist/monitor.d.ts +14 -0
  255. package/dist/monitor.js +272 -0
  256. package/dist/participant-admission.d.ts +5 -0
  257. package/dist/participant-admission.js +30 -0
  258. package/dist/protocol.d.ts +102 -0
  259. package/dist/protocol.js +97 -0
  260. package/dist/resolver-host.d.ts +11 -0
  261. package/dist/resolver-host.js +78 -0
  262. package/dist/server.d.ts +24 -0
  263. package/dist/server.js +808 -0
  264. package/dist/service-host.d.ts +7 -0
  265. package/dist/service-host.js +174 -0
  266. package/docs/architecture.md +162 -0
  267. package/package.json +54 -4
@@ -0,0 +1,326 @@
1
+ import { XMLParser } from "fast-xml-parser";
2
+ import { ContinuousError, continuousFailure, retryAfter } from "../../sync/continuous-errors.js";
3
+ import { throwIfAborted } from "../../sync/signals.js";
4
+ const JSON_LIMIT = 1024 * 1024;
5
+ const ERROR_LIMIT = 64 * 1024;
6
+ const SNAPSHOT_LIMIT = 256 * 1024 * 1024;
7
+ const XML_LIMIT = 1024 * 1024;
8
+ const REQUEST_TIMEOUT_MS = 30_000;
9
+ const MAX_REDIRECTS = 3;
10
+ export class WebDavHttpError extends Error {
11
+ status;
12
+ retryAfterMs;
13
+ constructor(message, status, options, retryAfterMs) {
14
+ super(message, options);
15
+ this.status = status;
16
+ this.retryAfterMs = retryAfterMs;
17
+ this.name = "WebDavHttpError";
18
+ }
19
+ }
20
+ export class WebDavPreconditionError extends WebDavHttpError {
21
+ constructor(message = "WebDAV precondition failed.") {
22
+ super(message, 412);
23
+ this.name = "WebDavPreconditionError";
24
+ }
25
+ }
26
+ export class WebDavClient {
27
+ config;
28
+ signal;
29
+ timeoutMs;
30
+ baseUrl;
31
+ authorization;
32
+ constructor(config, signal, timeoutMs = REQUEST_TIMEOUT_MS) {
33
+ this.config = config;
34
+ this.signal = signal;
35
+ this.timeoutMs = timeoutMs;
36
+ this.baseUrl = new URL(config.profile.url);
37
+ assertSafeAuthenticatedUrl(this.baseUrl);
38
+ if (!config.profile.username ||
39
+ !config.profile.password ||
40
+ config.profile.username.includes(":") ||
41
+ hasControlCharacter(config.profile.username) ||
42
+ hasControlCharacter(config.profile.password)) {
43
+ throw new Error("Invalid WebDAV credentials.");
44
+ }
45
+ this.authorization = `Basic ${Buffer.from(`${config.profile.username}:${config.profile.password}`).toString("base64")}`;
46
+ }
47
+ async getBuffer(remotePath) {
48
+ const response = await this.request(remotePath, { method: "GET" });
49
+ if (response.status === 404) {
50
+ await response.body?.cancel();
51
+ return { missing: true };
52
+ }
53
+ await this.requireOk(response, "read");
54
+ return {
55
+ value: await readBounded(response, SNAPSHOT_LIMIT, "WebDAV response is too large"),
56
+ etag: response.headers.get("etag") ?? undefined,
57
+ missing: false,
58
+ };
59
+ }
60
+ async getJson(remotePath) {
61
+ const response = await this.request(remotePath, { method: "GET" });
62
+ if (response.status === 404) {
63
+ await response.body?.cancel();
64
+ return { missing: true };
65
+ }
66
+ await this.requireOk(response, "read");
67
+ const bytes = await readBounded(response, JSON_LIMIT, "WebDAV JSON response is too large");
68
+ try {
69
+ return {
70
+ value: JSON.parse(bytes.toString("utf8")),
71
+ etag: response.headers.get("etag") ?? undefined,
72
+ missing: false,
73
+ };
74
+ }
75
+ catch (error) {
76
+ throw new Error("WebDAV JSON response is malformed.", { cause: error });
77
+ }
78
+ }
79
+ async putBuffer(remotePath, body, contentType, options = {}) {
80
+ const headers = { "content-type": contentType };
81
+ if (options.ifAbsent)
82
+ headers["if-none-match"] = "*";
83
+ if (options.ifMatch)
84
+ headers["if-match"] = options.ifMatch;
85
+ const response = await this.request(remotePath, {
86
+ method: "PUT",
87
+ headers,
88
+ body: body,
89
+ });
90
+ if (response.status === 412) {
91
+ await response.body?.cancel();
92
+ throw new WebDavPreconditionError();
93
+ }
94
+ await this.requireOk(response, "write");
95
+ await response.body?.cancel();
96
+ return response.headers.get("etag") ?? undefined;
97
+ }
98
+ async putJson(remotePath, value, options = {}) {
99
+ return this.putBuffer(remotePath, Buffer.from(JSON.stringify(value)), "application/json", options);
100
+ }
101
+ async makeCollection(remotePath) {
102
+ const response = await this.request(remotePath, { method: "MKCOL" });
103
+ if (response.status === 405) {
104
+ await response.body?.cancel();
105
+ return false;
106
+ }
107
+ await this.requireOk(response, "create collection");
108
+ await response.body?.cancel();
109
+ return true;
110
+ }
111
+ async ensureCollection(remotePath) {
112
+ const segments = safeSegments(remotePath);
113
+ for (let index = 1; index <= segments.length; index += 1) {
114
+ await this.makeCollection(segments.slice(0, index).join("/"));
115
+ }
116
+ }
117
+ async listCollection(remotePath) {
118
+ const response = await this.request(remotePath, {
119
+ method: "PROPFIND",
120
+ headers: { depth: "1", "content-type": "application/xml; charset=utf-8" },
121
+ body: '<?xml version="1.0"?><d:propfind xmlns:d="DAV:"><d:prop><d:getetag/><d:resourcetype/></d:prop></d:propfind>',
122
+ });
123
+ if (response.status === 404) {
124
+ await response.body?.cancel();
125
+ throw new WebDavHttpError("WebDAV collection is missing.", 404);
126
+ }
127
+ if (response.status !== 207)
128
+ await this.requireOk(response, "list collection");
129
+ const xml = (await readBounded(response, XML_LIMIT, "WebDAV directory response is too large")).toString("utf8");
130
+ try {
131
+ const parsed = new XMLParser({
132
+ removeNSPrefix: true,
133
+ ignoreAttributes: false,
134
+ processEntities: false,
135
+ }).parse(xml);
136
+ if (!parsed.multistatus || parsed.multistatus.response === undefined) {
137
+ throw new Error("Missing DAV multistatus response.");
138
+ }
139
+ const responses = asArray(parsed.multistatus.response);
140
+ return responses.map(parseEntry);
141
+ }
142
+ catch (error) {
143
+ throw new Error("WebDAV directory response is malformed.", { cause: error });
144
+ }
145
+ }
146
+ async delete(remotePath) {
147
+ const response = await this.request(remotePath, { method: "DELETE" });
148
+ if (response.status === 404) {
149
+ await response.body?.cancel();
150
+ return;
151
+ }
152
+ if (response.status === 207) {
153
+ await response.body?.cancel();
154
+ throw new WebDavHttpError("WebDAV probe cleanup returned a partial response.", 207);
155
+ }
156
+ await this.requireOk(response, "delete probe resource");
157
+ await response.body?.cancel();
158
+ }
159
+ async request(remotePath, init) {
160
+ throwIfAborted(this.signal);
161
+ let url = appendRemotePath(this.baseUrl, remotePath);
162
+ for (let redirects = 0;; redirects += 1) {
163
+ const timeout = AbortSignal.timeout(this.timeoutMs);
164
+ const signal = this.signal ? AbortSignal.any([this.signal, timeout]) : timeout;
165
+ let response;
166
+ try {
167
+ response = await fetch(url, {
168
+ ...init,
169
+ headers: {
170
+ accept: "*/*",
171
+ authorization: this.authorization,
172
+ ...headersObject(init.headers),
173
+ },
174
+ redirect: "manual",
175
+ signal,
176
+ });
177
+ }
178
+ catch (error) {
179
+ throwIfAborted(this.signal);
180
+ throw new Error(`WebDAV ${String(init.method ?? "GET")} request failed for ${redactText(safeUrl(url), this.config)}.`, {
181
+ cause: redactError(error, this.config),
182
+ });
183
+ }
184
+ if (![301, 302, 303, 307, 308].includes(response.status))
185
+ return response;
186
+ await response.body?.cancel();
187
+ const method = String(init.method ?? "GET").toUpperCase();
188
+ if ([301, 302, 303].includes(response.status) && method !== "GET" && method !== "HEAD") {
189
+ throw new Error(`WebDAV refused an ambiguous HTTP ${response.status} redirect for ${method}; configure the canonical collection URL or require HTTP 307/308.`);
190
+ }
191
+ if (redirects >= MAX_REDIRECTS)
192
+ throw new Error("WebDAV redirect limit exceeded.");
193
+ const location = response.headers.get("location");
194
+ if (!location)
195
+ throw new Error("WebDAV redirect is missing Location.");
196
+ const next = new URL(location, url);
197
+ if (next.origin !== this.baseUrl.origin) {
198
+ throw new Error("WebDAV refused a cross-origin authenticated redirect.");
199
+ }
200
+ url = next;
201
+ }
202
+ }
203
+ async requireOk(response, action) {
204
+ if (response.ok)
205
+ return;
206
+ const body = (await readBounded(response, ERROR_LIMIT, "WebDAV error body is too large"))
207
+ .toString("utf8")
208
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: Remote error text is untrusted terminal input.
209
+ .replace(/[\u0000-\u001f\u007f-\u009f]/gu, " ")
210
+ .trim();
211
+ const detail = body ? `: ${redactText(body, this.config)}` : "";
212
+ throw new WebDavHttpError(`WebDAV ${action} failed with HTTP ${response.status}${detail}`, response.status, undefined, retryAfter(response));
213
+ }
214
+ }
215
+ function assertSafeAuthenticatedUrl(url) {
216
+ const loopback = url.hostname === "127.0.0.1" || url.hostname === "localhost" || url.hostname === "[::1]" || url.hostname === "::1";
217
+ if (url.username ||
218
+ url.password ||
219
+ url.search ||
220
+ url.hash ||
221
+ (url.protocol !== "https:" && !(url.protocol === "http:" && loopback))) {
222
+ throw new Error("Invalid WebDAV URL: HTTPS is required and embedded credentials, query, or fragment are not allowed.");
223
+ }
224
+ }
225
+ function hasControlCharacter(value) {
226
+ return [...value].some((character) => {
227
+ const code = character.codePointAt(0) ?? 0;
228
+ return code < 0x20 || (code >= 0x7f && code <= 0x9f);
229
+ });
230
+ }
231
+ function appendRemotePath(base, remotePath) {
232
+ const url = new URL(base);
233
+ const suffix = safeSegments(remotePath).map(encodeURIComponent).join("/");
234
+ url.pathname = `${base.pathname.replace(/\/+$/u, "")}/${suffix}`;
235
+ return url;
236
+ }
237
+ function safeSegments(value) {
238
+ const segments = value
239
+ .replace(/^\/+|\/+$/gu, "")
240
+ .split("/")
241
+ .filter(Boolean);
242
+ if (segments.some((segment) => segment === "." ||
243
+ segment === ".." ||
244
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: Remote path segments cannot contain controls.
245
+ /[\u0000-\u001f]/u.test(segment))) {
246
+ throw new Error("Invalid WebDAV remote path.");
247
+ }
248
+ return segments;
249
+ }
250
+ async function readBounded(response, limit, message) {
251
+ const length = Number(response.headers.get("content-length"));
252
+ if (Number.isFinite(length) && length > limit) {
253
+ await response.body?.cancel();
254
+ throw new Error(message);
255
+ }
256
+ if (!response.body)
257
+ return Buffer.alloc(0);
258
+ const reader = response.body.getReader();
259
+ const chunks = [];
260
+ let total = 0;
261
+ try {
262
+ while (true) {
263
+ const { done, value } = await reader.read();
264
+ if (done)
265
+ break;
266
+ total += value.byteLength;
267
+ if (total > limit)
268
+ throw new Error(message);
269
+ chunks.push(Buffer.from(value));
270
+ }
271
+ }
272
+ catch (error) {
273
+ await reader.cancel().catch(() => undefined);
274
+ throw error;
275
+ }
276
+ return Buffer.concat(chunks, total);
277
+ }
278
+ function parseEntry(value) {
279
+ if (!value || typeof value !== "object")
280
+ throw new Error("Invalid WebDAV response entry.");
281
+ const record = value;
282
+ const href = typeof record.href === "string" ? record.href : undefined;
283
+ if (!href)
284
+ throw new Error("Invalid WebDAV response href.");
285
+ const propstat = asArray(record.propstat).find((item) => {
286
+ if (!item || typeof item !== "object")
287
+ return false;
288
+ return String(item.status ?? "").includes(" 200 ");
289
+ });
290
+ const prop = propstat?.prop;
291
+ return {
292
+ href,
293
+ etag: typeof prop?.getetag === "string" ? prop.getetag : undefined,
294
+ collection: !!prop?.resourcetype && typeof prop.resourcetype === "object" && Object.hasOwn(prop.resourcetype, "collection"),
295
+ };
296
+ }
297
+ function asArray(value) {
298
+ if (value === undefined)
299
+ return [];
300
+ return Array.isArray(value) ? value : [value];
301
+ }
302
+ function headersObject(headers) {
303
+ return Object.fromEntries(new Headers(headers).entries());
304
+ }
305
+ function safeUrl(url) {
306
+ return `${url.protocol}//${url.host}${url.pathname}`;
307
+ }
308
+ function redactError(error, config) {
309
+ const message = error instanceof Error ? error.message : String(error);
310
+ const failure = continuousFailure(error);
311
+ return new ContinuousError(failure.kind, redactText(message, config), failure.delay);
312
+ }
313
+ function redactText(value, config) {
314
+ let result = value;
315
+ for (const secret of [config.profile.username, config.profile.password, config.profile.url]) {
316
+ if (!secret)
317
+ continue;
318
+ for (const variant of new Set([secret, encodeURIComponent(secret)])) {
319
+ result = result.replace(new RegExp(escapeRegExp(variant), "giu"), "[redacted]");
320
+ }
321
+ }
322
+ return result.replace(/basic\s+[a-z0-9+/=]+/giu, "Basic [redacted]").replace(/\?[^\s]*/gu, "?[redacted]");
323
+ }
324
+ function escapeRegExp(value) {
325
+ return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
326
+ }
@@ -0,0 +1,5 @@
1
+ export declare function normalizeWebDavIdentityUrl(value: string): string;
2
+ export declare function normalizeWebDavUrl(value: string | undefined): string | undefined;
3
+ export declare function normalizeWebDavPath(value: string | undefined): string;
4
+ export declare function validateWebDavNamespace(value: string): void;
5
+ export declare function validateWebDavCredentials(username: string, password?: string): void;
@@ -0,0 +1,73 @@
1
+ const DEFAULT_PATH = "pi-sync";
2
+ export function normalizeWebDavIdentityUrl(value) {
3
+ try {
4
+ const url = new URL(value.trim());
5
+ url.username = "";
6
+ url.password = "";
7
+ url.search = "";
8
+ url.hash = "";
9
+ url.pathname = `${url.pathname.replace(/\/+$/u, "")}/`;
10
+ return url.toString();
11
+ }
12
+ catch {
13
+ return value.trim();
14
+ }
15
+ }
16
+ export function normalizeWebDavUrl(value) {
17
+ const normalized = normalizeOptionalString(value);
18
+ if (!normalized)
19
+ return undefined;
20
+ let url;
21
+ try {
22
+ url = new URL(normalized);
23
+ }
24
+ catch {
25
+ throw new Error("Invalid pi-sync WebDAV URL.");
26
+ }
27
+ if (url.username || url.password || url.search || url.hash) {
28
+ throw new Error("Invalid pi-sync WebDAV URL: credentials, query, and fragment are not allowed.");
29
+ }
30
+ const loopback = url.hostname === "127.0.0.1" || url.hostname === "localhost" || url.hostname === "[::1]" || url.hostname === "::1";
31
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
32
+ throw new Error("Invalid pi-sync WebDAV URL: HTTPS is required except for loopback.");
33
+ }
34
+ url.pathname = `${url.pathname.replace(/\/+$/u, "")}/`;
35
+ return url.toString();
36
+ }
37
+ export function normalizeWebDavPath(value) {
38
+ if (value?.trim() === "." || value?.trim() === "./")
39
+ return "./";
40
+ const normalized = trimSlashes(normalizeOptionalString(value) ?? DEFAULT_PATH);
41
+ if (!normalized ||
42
+ normalized.includes("\\") ||
43
+ hasControlCharacter(normalized) ||
44
+ normalized.split("/").some((segment) => !segment || segment === "." || segment === "..")) {
45
+ throw new Error("Invalid pi-sync WebDAV path.");
46
+ }
47
+ return normalized;
48
+ }
49
+ export function validateWebDavNamespace(value) {
50
+ if (value === "." || value === ".." || value.includes("/") || value.includes("\\") || hasControlCharacter(value)) {
51
+ throw new Error("Invalid pi-sync WebDAV namespace.");
52
+ }
53
+ }
54
+ export function validateWebDavCredentials(username, password) {
55
+ if (username.includes(":") ||
56
+ hasControlCharacter(username) ||
57
+ (password !== undefined && hasControlCharacter(password))) {
58
+ throw new Error("Invalid pi-sync WebDAV credentials.");
59
+ }
60
+ }
61
+ function normalizeOptionalString(value) {
62
+ const normalized = value?.trim();
63
+ return normalized || undefined;
64
+ }
65
+ function trimSlashes(value) {
66
+ return value.replace(/^\/+|\/+$/gu, "");
67
+ }
68
+ function hasControlCharacter(value) {
69
+ return [...value].some((character) => {
70
+ const code = character.codePointAt(0) ?? 0;
71
+ return code < 0x20 || (code >= 0x7f && code <= 0x9f);
72
+ });
73
+ }
@@ -0,0 +1,31 @@
1
+ import type { AnySyncConfig } from "../settings/settings-types.js";
2
+ import type { AgentAcceptance } from "../sync/agent-request.js";
3
+ import type { StartupTimings } from "../sync/startup-timings.js";
4
+ export interface CommandOptions {
5
+ yes: boolean;
6
+ force: boolean;
7
+ stale: boolean;
8
+ silent: boolean;
9
+ reload: boolean;
10
+ auto: boolean;
11
+ setup?: string;
12
+ signal?: AbortSignal;
13
+ onCommit?: () => void;
14
+ /** In-memory startup diagnostics only; never persisted or sent to a backend. */
15
+ startupTimings?: StartupTimings;
16
+ /** Internal validated resolver result; never parsed from command arguments. */
17
+ agentAcceptance?: AgentAcceptance;
18
+ /** Internal cycle authorization, ownership and durable request reservation; never command arguments. */
19
+ background?: {
20
+ validate(config?: AnySyncConfig): void;
21
+ reserve(key: string, signal?: AbortSignal): Promise<void>;
22
+ };
23
+ /** Manager-only, separately confirmed retry; never parsed from command arguments. */
24
+ agentRetryRefusal?: boolean;
25
+ args: string[];
26
+ }
27
+ export interface CommandArgumentCompletion {
28
+ value: string;
29
+ label: string;
30
+ description?: string;
31
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,70 @@
1
+ import type { Api, AssistantMessage, AssistantMessageEvent, Model } from "@earendil-works/pi-ai";
2
+ import type { ModelRegistry } from "@earendil-works/pi-coding-agent";
3
+ import type { AnySyncConfig } from "./settings/settings-types.js";
4
+ export interface EngineModelStream extends AsyncIterable<AssistantMessageEvent> {
5
+ result(): Promise<AssistantMessage>;
6
+ }
7
+ export interface EngineModelRegistry {
8
+ streamSimple(...args: Parameters<ModelRegistry["streamSimple"]>): EngineModelStream;
9
+ }
10
+ export interface EngineSession {
11
+ getSessionFile?(): string | undefined;
12
+ getSessionId?(): string;
13
+ getCwd?(): string;
14
+ getSessionDir?(): string;
15
+ usesDefaultSessionDir?(): boolean;
16
+ }
17
+ export interface EngineContext {
18
+ cwd: string;
19
+ mode: "tui" | "rpc" | "json" | "print";
20
+ hasUI: boolean;
21
+ model?: Model<Api>;
22
+ modelUnavailableReason?: string;
23
+ modelRegistry: EngineModelRegistry;
24
+ sessionManager: EngineSession;
25
+ isIdle(): boolean;
26
+ validateModel?(): Promise<void>;
27
+ backgroundAuthorized?(config?: AnySyncConfig): boolean;
28
+ reload?(): Promise<void>;
29
+ /** Additional sessions are protected by the service, including disconnected live clients. */
30
+ protectedSessionFiles?: readonly string[];
31
+ ui: {
32
+ notify(message: string, level?: "info" | "warning" | "error"): void;
33
+ setStatus(key: string, value: string | undefined): void;
34
+ confirm(title: string, message: string, options?: {
35
+ signal?: AbortSignal;
36
+ timeout?: number;
37
+ }): Promise<boolean>;
38
+ select(title: string, items: string[], options?: {
39
+ signal?: AbortSignal;
40
+ timeout?: number;
41
+ helpText?: string;
42
+ }): Promise<string | undefined>;
43
+ };
44
+ }
45
+ export interface ReviewRequest {
46
+ title: string;
47
+ content: string;
48
+ confirmationLabel: string;
49
+ summaryLines?: readonly string[];
50
+ }
51
+ export interface ConfigAuthority {
52
+ read(repair?: boolean): Promise<import("./settings/config-file.js").LocalConfigDocument | undefined>;
53
+ update<T extends Record<string, unknown>>(fallback: T, update: (value: T) => T, validate: (value: Record<string, unknown>) => void, signal?: AbortSignal): Promise<T>;
54
+ create(value: Record<string, unknown>, signal?: AbortSignal): Promise<void>;
55
+ replace(document: import("./settings/config-file.js").LocalConfigDocument, value: Record<string, unknown>): Promise<void>;
56
+ }
57
+ export interface EngineHost {
58
+ root(): string;
59
+ config?: ConfigAuthority;
60
+ allowConfigMigration?(): boolean;
61
+ mutate<T>(target: string, action: () => Promise<T>): Promise<T>;
62
+ reserveTargets?<T>(targets: readonly string[], action: () => Promise<T>): Promise<T>;
63
+ review(ctx: EngineContext, request: ReviewRequest, signal: AbortSignal | undefined, isCurrent: () => boolean): Promise<boolean>;
64
+ status?(ctx: EngineContext, value: string | undefined, presentation?: unknown): void;
65
+ }
66
+ /** One explicit host per process. A daemon process serves exactly one canonical root. */
67
+ export declare function configureEngineHost(value: EngineHost): void;
68
+ export declare function engineHost(): EngineHost;
69
+ export declare function getEngineRoot(): string;
70
+ export declare function withEngineMutationQueue<T>(target: string, action: () => Promise<T>): Promise<T>;
@@ -0,0 +1,16 @@
1
+ let host;
2
+ /** One explicit host per process. A daemon process serves exactly one canonical root. */
3
+ export function configureEngineHost(value) {
4
+ host = value;
5
+ }
6
+ export function engineHost() {
7
+ if (!host)
8
+ throw new Error("Synchronization engine host is not configured.");
9
+ return host;
10
+ }
11
+ export function getEngineRoot() {
12
+ return engineHost().root();
13
+ }
14
+ export function withEngineMutationQueue(target, action) {
15
+ return engineHost().mutate(target, action);
16
+ }
@@ -0,0 +1,9 @@
1
+ export declare function isDeniedPath(relativePath: string): boolean;
2
+ export declare function isPathInside(parent: string, child: string): boolean;
3
+ export declare function safeJoin(root: string, relativePath: string): string;
4
+ export declare function assertWithinRoot(root: string, target: string, label?: string): void;
5
+ export declare function encodeKey(key: string): string;
6
+ export declare function posixJoin(...parts: string[]): string;
7
+ export declare function parentPaths(relativePath: string): string[];
8
+ export declare function toPosix(value: string): string;
9
+ export declare function safeName(value: string): string;
@@ -0,0 +1,71 @@
1
+ import path from "node:path";
2
+ export function isDeniedPath(relativePath) {
3
+ const normalized = toPosix(relativePath);
4
+ const lower = normalized.toLowerCase();
5
+ const segments = lower.split("/");
6
+ const base = path.posix.basename(lower);
7
+ return (segments.includes("node_modules") ||
8
+ segments.includes(".git") ||
9
+ segments.includes(".pisync") ||
10
+ segments.includes("pi-sync") ||
11
+ segments.includes(".pi-sync-state-migration.lock") ||
12
+ base === ".env" ||
13
+ base.startsWith(".env.") ||
14
+ base.endsWith(".env") ||
15
+ base.includes("secret") ||
16
+ base.includes("token") ||
17
+ base === "pi-sync.json" ||
18
+ base.startsWith("pi-sync.json.") ||
19
+ base.startsWith(".pi-sync.json.") ||
20
+ base === "pi-sync.local.json" ||
21
+ base.startsWith("pi-sync.local.json.") ||
22
+ base.startsWith(".pi-sync.local.json."));
23
+ }
24
+ export function isPathInside(parent, child) {
25
+ const relative = path.relative(path.resolve(parent), path.resolve(child));
26
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
27
+ }
28
+ export function safeJoin(root, relativePath) {
29
+ const target = path.resolve(root, relativePath);
30
+ assertWithinRoot(root, target, relativePath);
31
+ return target;
32
+ }
33
+ export function assertWithinRoot(root, target, label = target) {
34
+ const resolvedRoot = path.resolve(root);
35
+ const resolvedTarget = path.resolve(target);
36
+ if (resolvedTarget !== resolvedRoot && !resolvedTarget.startsWith(`${resolvedRoot}${path.sep}`)) {
37
+ throw new Error(`Unsafe path in snapshot: ${label}`);
38
+ }
39
+ }
40
+ export function encodeKey(key) {
41
+ // SigV4 permits only RFC 3986 unreserved characters and key separators.
42
+ return key
43
+ .split("/")
44
+ .map(encodeURIComponent)
45
+ .join("/")
46
+ .replace(/[!'()*]/gu, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
47
+ }
48
+ export function posixJoin(...parts) {
49
+ return parts
50
+ .map((part) => trimSlashes(part))
51
+ .filter(Boolean)
52
+ .join("/");
53
+ }
54
+ export function parentPaths(relativePath) {
55
+ const results = [];
56
+ let index = relativePath.lastIndexOf("/");
57
+ while (index > 0) {
58
+ results.push(relativePath.slice(0, index));
59
+ index = relativePath.lastIndexOf("/", index - 1);
60
+ }
61
+ return results;
62
+ }
63
+ export function toPosix(value) {
64
+ return value.split(path.sep).join("/");
65
+ }
66
+ function trimSlashes(value) {
67
+ return value.replace(/^\/+|\/+$/g, "");
68
+ }
69
+ export function safeName(value) {
70
+ return value.replace(/[^A-Za-z0-9._-]/g, "_");
71
+ }
@@ -0,0 +1 @@
1
+ export declare function isMissingConfigError(error: unknown): boolean;
@@ -0,0 +1,4 @@
1
+ export function isMissingConfigError(error) {
2
+ return (error instanceof Error &&
3
+ (error.message.startsWith("Missing pi-sync settings.") || error.message === "No sync setups are configured."));
4
+ }
@@ -0,0 +1,33 @@
1
+ export declare const CONFIG_FILE_NAME = "pi-sync.json";
2
+ type PublishFile = (source: string, destination: string, expected?: LocalConfigDocument, signal?: AbortSignal) => Promise<void>;
3
+ export type FileIdentity = {
4
+ dev: number;
5
+ ino: number;
6
+ };
7
+ export declare function withConfigFilePublicationForTest<T>(publish: PublishFile, run: () => Promise<T>): Promise<T>;
8
+ export declare function withConfigPublicationReadyHookForTest<T>(hook: () => Promise<void>, run: () => Promise<T>): Promise<T>;
9
+ export declare function withMissingConfigReadProbeHookForTest<T>(hook: () => Promise<void>, run: () => Promise<T>): Promise<T>;
10
+ export declare function withConfigReplacementInstalledHookForTest<T>(hook: () => Promise<void>, run: () => Promise<T>): Promise<T>;
11
+ export declare function withConfigQuarantinedHookForTest<T>(hook: () => Promise<void>, run: () => Promise<T>): Promise<T>;
12
+ type ConfigSnapshot = {
13
+ bytes: Buffer;
14
+ identity: FileIdentity;
15
+ parsed: Record<string, unknown>;
16
+ };
17
+ export type LocalConfigDocument = ConfigSnapshot & {
18
+ path: string;
19
+ };
20
+ export declare function localConfigPath(): string;
21
+ export declare function legacyLocalConfigPath(): string;
22
+ export declare function activeLocalConfigPath(): Promise<string>;
23
+ export declare function consumeLocalConfigMigrationNotice(): string | undefined;
24
+ export declare function readActiveLocalConfigDocumentForRepair(): Promise<LocalConfigDocument | undefined>;
25
+ /** Read-only bootstrap: no authority recursion, migration, or document creation. */
26
+ export declare function peekLocalConfigDocument(): Promise<LocalConfigDocument | undefined>;
27
+ export declare function readMigratingLocalConfigDocument(validateForMigration: (settings: Record<string, unknown>) => void): Promise<LocalConfigDocument | undefined>;
28
+ export declare function updateLocalConfigDocument<T extends Record<string, unknown>>(defaultValue: T, update: (current: T) => T, validate: (value: Record<string, unknown>) => void, signal?: AbortSignal, validateSource?: (document: LocalConfigDocument | undefined) => void): Promise<T>;
29
+ export declare function createLocalConfigDocument(value: Record<string, unknown>, signal?: AbortSignal): Promise<void>;
30
+ export declare function replaceLocalConfigDocument(document: LocalConfigDocument, value: Record<string, unknown>): Promise<void>;
31
+ export declare function quarantineAndRemoveConfigIfMatches(filePath: string, identity: FileIdentity, expectedBytes: Buffer): Promise<boolean>;
32
+ export declare function withLocalConfigFileLock<T>(run: () => Promise<T>): Promise<T>;
33
+ export {};