@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,53 @@
1
+ import { closeSync, constants, fstatSync, ftruncateSync, lstatSync, openSync, writeSync } from "node:fs";
2
+ import path from "node:path";
3
+ const MAX_BYTES = 8192;
4
+ /** Bounded lifecycle facts only: never log payloads, credentials, provider output, or exception text. */
5
+ export function openLifecycleLog(directory) {
6
+ const parent = lstatSync(directory);
7
+ const privateOwner = (value) => (!process.getuid || value.uid === process.getuid()) && (process.platform === "win32" || (value.mode & 0o077) === 0);
8
+ if (!parent.isDirectory() || parent.isSymbolicLink() || !privateOwner(parent))
9
+ throw new Error("Unsafe lifecycle log directory.");
10
+ const target = path.join(directory, "lifecycle.log");
11
+ const handle = openSync(target, constants.O_CREAT | constants.O_APPEND | constants.O_RDWR | (constants.O_NOFOLLOW ?? 0), 0o600);
12
+ let closed = false;
13
+ const validate = () => {
14
+ const current = lstatSync(target);
15
+ const opened = fstatSync(handle);
16
+ const owner = lstatSync(directory);
17
+ if (!current.isFile() ||
18
+ current.isSymbolicLink() ||
19
+ !privateOwner(current) ||
20
+ current.dev !== opened.dev ||
21
+ current.ino !== opened.ino ||
22
+ owner.dev !== parent.dev ||
23
+ owner.ino !== parent.ino ||
24
+ owner.isSymbolicLink() ||
25
+ !privateOwner(owner) ||
26
+ current.size > MAX_BYTES)
27
+ throw new Error("Lifecycle log ownership changed; unknown evidence retained.");
28
+ return opened.size;
29
+ };
30
+ try {
31
+ validate();
32
+ }
33
+ catch (error) {
34
+ closeSync(handle);
35
+ throw error;
36
+ }
37
+ return {
38
+ write(phase) {
39
+ if (closed)
40
+ return;
41
+ const line = `${JSON.stringify({ time: new Date().toISOString(), phase })}\n`;
42
+ if (validate() + Buffer.byteLength(line) > MAX_BYTES)
43
+ ftruncateSync(handle, 0);
44
+ writeSync(handle, line);
45
+ },
46
+ close() {
47
+ if (!closed) {
48
+ closed = true;
49
+ closeSync(handle);
50
+ }
51
+ },
52
+ };
53
+ }
@@ -0,0 +1,2 @@
1
+ /** Complete cleanup without hiding the primary failure or treating cleanup failure as success. */
2
+ export declare function withCleanup<T>(action: () => Promise<T>, cleanup: () => Promise<unknown>): Promise<T>;
@@ -0,0 +1,21 @@
1
+ /** Complete cleanup without hiding the primary failure or treating cleanup failure as success. */
2
+ export async function withCleanup(action, cleanup) {
3
+ let result;
4
+ try {
5
+ result = { ok: true, value: await action() };
6
+ }
7
+ catch (error) {
8
+ result = { ok: false, error };
9
+ }
10
+ try {
11
+ await cleanup();
12
+ }
13
+ catch (error) {
14
+ if (!result.ok)
15
+ throw new AggregateError([result.error, error], "Operation and cleanup both failed; recovery evidence retained.");
16
+ throw error;
17
+ }
18
+ if (!result.ok)
19
+ throw result.error;
20
+ return result.value;
21
+ }
@@ -0,0 +1,2 @@
1
+ /** Preserve the engine's existing JSON model identity without copying credential-bearing values. */
2
+ export declare function modelSignature(model: unknown): string;
@@ -0,0 +1,7 @@
1
+ import { createHash } from "node:crypto";
2
+ /** Preserve the engine's existing JSON model identity without copying credential-bearing values. */
3
+ export function modelSignature(model) {
4
+ return createHash("sha256")
5
+ .update(JSON.stringify(model) ?? "null")
6
+ .digest("hex");
7
+ }
@@ -0,0 +1,14 @@
1
+ import type { IdleExitPolicy } from "./idle-exit.js";
2
+ import type { Execution } from "./protocol.js";
3
+ import type { startServer } from "./server.js";
4
+ import type { installServiceHost } from "./service-host.js";
5
+ export declare function createMonitor(root: string, host: ReturnType<typeof installServiceHost>): {
6
+ bind(value: Awaited<ReturnType<typeof startServer>>): void;
7
+ schedule: () => void;
8
+ lifetime: () => Promise<IdleExitPolicy>;
9
+ blockAutomatic: () => void;
10
+ explicitSync(setup: string, execution: Execution): void;
11
+ pause(): Promise<void>;
12
+ factsChanged(): Promise<void>;
13
+ close(): Promise<void>;
14
+ };
@@ -0,0 +1,272 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import path from "node:path";
3
+ import { ConsentPublicationError, consentFingerprint, readConsent, revokeChangedBindings } from "./consent.js";
4
+ import { loadConfigForCheck } from "./engine/settings/config.js";
5
+ import { createEngineLoaders } from "./engine/sync/sync-loaders.js";
6
+ import { createServiceContext } from "./service-host.js";
7
+ export function createMonitor(root, host) {
8
+ let server;
9
+ let task;
10
+ let transition = Promise.resolve();
11
+ let closed = false;
12
+ let authorizationFailed = false;
13
+ let scheduled = false;
14
+ // Keep each client's last validated route, not its Pi context or completed execution.
15
+ const retries = new Map();
16
+ let epoch;
17
+ const timingOwners = new WeakMap();
18
+ const loaders = createEngineLoaders();
19
+ const operations = loaders.operations;
20
+ let continuous;
21
+ function schedule() {
22
+ if (closed || scheduled || !server)
23
+ return;
24
+ scheduled = true;
25
+ setImmediate(() => {
26
+ scheduled = false;
27
+ transition = transition.then(start).catch(() => { });
28
+ });
29
+ }
30
+ function blockAutomatic() {
31
+ authorizationFailed = true;
32
+ retries.clear();
33
+ task?.controller.abort(new DOMException("Daemon safety barrier", "AbortError"));
34
+ }
35
+ async function stop() {
36
+ const current = task;
37
+ if (!current)
38
+ return;
39
+ task = undefined;
40
+ current.controller.abort(new DOMException("Daemon monitoring interrupted", "AbortError"));
41
+ await current.continuous.stop();
42
+ await current.promise;
43
+ }
44
+ function unattendedGrant(config) {
45
+ if (!config.continuous || !config.agentMode)
46
+ return undefined;
47
+ const saved = readConsent(root)?.setups[config.setupName];
48
+ return saved?.afterExit && saved.fingerprint === consentFingerprint(root, config) ? saved : undefined;
49
+ }
50
+ async function lifetime() {
51
+ if (closed || authorizationFailed)
52
+ return "pause";
53
+ try {
54
+ const consent = readConsent(root);
55
+ if (!consent || !Object.values(consent.setups).some((saved) => saved.afterExit))
56
+ return "exit";
57
+ const config = await loadConfigForCheck();
58
+ if (closed || authorizationFailed)
59
+ return "pause";
60
+ return unattendedGrant(config) ? "keep" : "exit";
61
+ }
62
+ catch {
63
+ // Invalid evidence is not an implicit revocation or permission to discard a safety barrier.
64
+ return "pause";
65
+ }
66
+ }
67
+ async function start() {
68
+ const service = server;
69
+ if (!service)
70
+ return;
71
+ const available = () => !closed && !authorizationFailed && !task && server === service && service.isIdle();
72
+ if (!available())
73
+ return;
74
+ const consent = readConsent(root);
75
+ if (!consent)
76
+ return;
77
+ const config = await loadConfigForCheck();
78
+ if (!available())
79
+ return;
80
+ if (!config.continuous || !config.agentMode) {
81
+ retries.clear();
82
+ return;
83
+ }
84
+ const { pendingTransactionEntries } = await import("./engine/snapshot/snapshot-transaction-directory.js");
85
+ if ((await pendingTransactionEntries()).some((entry) => entry.isDirectory()) || !available())
86
+ return;
87
+ const peers = service.participants();
88
+ if (peers.some((peer) => !peer.idle || peer.ready !== true))
89
+ return;
90
+ const authorized = unattendedGrant(config);
91
+ const selected = peers.toSorted((a, b) => a.id.localeCompare(b.id))[0];
92
+ if (!selected && !authorized)
93
+ return;
94
+ if (!continuous) {
95
+ const { createContinuousSync } = await import("./engine/sync/continuous-sync.js");
96
+ if (!available())
97
+ return;
98
+ continuous = createContinuousSync(loaders, undefined, (ctx, report) => timingOwners.get(ctx)?.emit("timings", { report }));
99
+ // Re-enter every eligibility branch after importing the full engine graph.
100
+ return start();
101
+ }
102
+ const activeContinuous = continuous;
103
+ const binding = selected?.model ?? authorized?.model;
104
+ const sessionDir = selected ? selected.sessionDir : authorized?.sessionDir;
105
+ const cwd = selected?.cwd ?? authorized?.cwd ?? root;
106
+ const key = peers
107
+ .map((peer) => `${peer.id}:${peer.generation}`)
108
+ .sort()
109
+ .join(",") || "unattended";
110
+ if (epoch?.key !== key) {
111
+ epoch?.controller.abort(new DOMException("Participating sessions changed", "AbortError"));
112
+ const location = { sessionDir, cwd };
113
+ const manager = {
114
+ getSessionId: () => key,
115
+ getCwd: () => location.cwd,
116
+ getSessionDir: () => location.sessionDir ?? path.join(root, "sessions"),
117
+ usesDefaultSessionDir: () => location.sessionDir === undefined,
118
+ };
119
+ epoch = { key, controller: new AbortController(), manager, location, debug: selected?.startupDebug ?? false };
120
+ }
121
+ epoch.location.sessionDir = sessionDir;
122
+ epoch.location.cwd = cwd;
123
+ const controller = new AbortController();
124
+ const original = service.backgroundExecution(controller.signal);
125
+ const stableFacts = {
126
+ id: randomUUID(),
127
+ generation: randomUUID(),
128
+ pid: process.pid,
129
+ cwd,
130
+ mode: "rpc",
131
+ hasUI: false,
132
+ idle: true,
133
+ sessionDir,
134
+ model: binding,
135
+ };
136
+ const execution = { ...original, facts: () => stableFacts };
137
+ const allowed = (currentConfig = config) => {
138
+ if (closed || authorizationFailed || server !== service || controller.signal.aborted || !readConsent(root))
139
+ return false;
140
+ const current = service.participants();
141
+ if (current.length)
142
+ return current.every((peer) => peer.idle &&
143
+ peer.ready === true &&
144
+ JSON.stringify(peer.model) === JSON.stringify(binding) &&
145
+ peer.sessionDir === sessionDir &&
146
+ peer.cwd === cwd);
147
+ const saved = unattendedGrant(currentConfig);
148
+ return Boolean(saved &&
149
+ JSON.stringify(saved.model) === JSON.stringify(binding) &&
150
+ saved.sessionDir === sessionDir &&
151
+ (saved.cwd ?? root) === cwd);
152
+ };
153
+ const ctx = createServiceContext(execution);
154
+ ctx.reload = undefined;
155
+ ctx.sessionManager = epoch.manager;
156
+ Object.defineProperty(ctx, "hasUI", {
157
+ get: () => service.participants().some((peer) => peer.hasUI && peer.ready === true),
158
+ });
159
+ timingOwners.set(ctx, execution);
160
+ ctx.backgroundAuthorized = allowed;
161
+ ctx.isIdle = () => Boolean(service.isIdle() && allowed());
162
+ loaders.operations = async () => {
163
+ const loaded = await operations();
164
+ return {
165
+ ...loaded,
166
+ syncBoth: (context, options, ...rest) => loaded.syncBoth(context, { ...options, onCommit: execution.committed }, ...rest),
167
+ };
168
+ };
169
+ const sessionSignal = epoch.controller.signal;
170
+ const debug = epoch.debug;
171
+ let finish;
172
+ const promise = new Promise((resolve) => {
173
+ finish = resolve;
174
+ });
175
+ const current = { controller, continuous: activeContinuous, promise };
176
+ task = current;
177
+ void host
178
+ .run(execution, async () => {
179
+ const { prepareResolverHost } = await import("./resolver-host.js");
180
+ const resolver = await prepareResolverHost(root, binding, controller.signal);
181
+ try {
182
+ if (!allowed())
183
+ return;
184
+ ctx.model = resolver.model;
185
+ ctx.modelUnavailableReason = resolver.unavailable;
186
+ ctx.modelRegistry = resolver.registry;
187
+ ctx.validateModel = async () => {
188
+ if (!allowed())
189
+ throw new Error("Daemon authorization changed before model dispatch.");
190
+ for (const peer of service.participants()) {
191
+ const fresh = await execution.request("model-binding", { background: true }, peer.id);
192
+ if (JSON.stringify(fresh ?? undefined) !== JSON.stringify(binding))
193
+ throw new Error("Participating model changed before dispatch.");
194
+ if (!allowed())
195
+ throw new Error("Daemon authorization changed during model validation.");
196
+ }
197
+ };
198
+ const explicitRetry = service.participants().some((peer) => {
199
+ const retry = retries.get(peer.id);
200
+ return retry?.setup === config.setupName && retry.generation === peer.generation && !retry.signal.aborted;
201
+ });
202
+ retries.clear();
203
+ activeContinuous.start(ctx, sessionSignal, explicitRetry ? config.setupName : false, debug);
204
+ await new Promise((resolve) => {
205
+ if (controller.signal.aborted)
206
+ resolve();
207
+ else
208
+ controller.signal.addEventListener("abort", () => resolve(), { once: true });
209
+ });
210
+ await activeContinuous.stop();
211
+ }
212
+ finally {
213
+ await resolver.settle();
214
+ }
215
+ })
216
+ .catch(() => { })
217
+ .finally(() => {
218
+ controller.abort();
219
+ if (task === current)
220
+ task = undefined;
221
+ finish();
222
+ });
223
+ }
224
+ return {
225
+ bind(value) {
226
+ server = value;
227
+ schedule();
228
+ },
229
+ schedule,
230
+ lifetime,
231
+ blockAutomatic,
232
+ explicitSync(setup, execution) {
233
+ const peer = execution.facts();
234
+ if (!closed && peer)
235
+ retries.set(peer.id, { setup, generation: peer.generation, signal: execution.signal });
236
+ },
237
+ async pause() {
238
+ transition = transition.then(stop);
239
+ await transition;
240
+ },
241
+ async factsChanged() {
242
+ let failure;
243
+ try {
244
+ if (server) {
245
+ const peers = server.participants();
246
+ for (const [id, retry] of retries)
247
+ if (retry.signal.aborted || !peers.some((peer) => peer.id === id && peer.generation === retry.generation))
248
+ retries.delete(id);
249
+ revokeChangedBindings(root, peers);
250
+ }
251
+ }
252
+ catch (error) {
253
+ blockAutomatic();
254
+ // Recovery barriers must not prevent passive clients from registering protection.
255
+ if (error instanceof ConsentPublicationError)
256
+ failure = error;
257
+ }
258
+ transition = transition.then(stop);
259
+ await transition;
260
+ if (failure)
261
+ throw new Error("Daemon authorization could not be saved. Automatic work is blocked for this instance; repair and revoke permission before an explicit restart.", { cause: failure });
262
+ schedule();
263
+ },
264
+ async close() {
265
+ closed = true;
266
+ retries.clear();
267
+ transition = transition.then(stop);
268
+ await transition;
269
+ epoch?.controller.abort();
270
+ },
271
+ };
272
+ }
@@ -0,0 +1,5 @@
1
+ /** Keep client publication outside complete mutation-queue reservation lifetimes. */
2
+ export declare class ParticipantAdmission {
3
+ private tail;
4
+ run<T>(action: () => Promise<T>, signal?: AbortSignal): Promise<T>;
5
+ }
@@ -0,0 +1,30 @@
1
+ /** Keep client publication outside complete mutation-queue reservation lifetimes. */
2
+ export class ParticipantAdmission {
3
+ tail = Promise.resolve();
4
+ async run(action, signal) {
5
+ signal?.throwIfAborted();
6
+ const previous = this.tail;
7
+ let release;
8
+ const held = new Promise((resolve) => {
9
+ release = resolve;
10
+ });
11
+ this.tail = previous.then(() => held);
12
+ let abort;
13
+ try {
14
+ await new Promise((resolve, reject) => {
15
+ void previous.then(resolve);
16
+ abort = () => reject(signal?.reason);
17
+ signal?.addEventListener("abort", abort, { once: true });
18
+ if (signal?.aborted)
19
+ abort();
20
+ });
21
+ signal?.throwIfAborted();
22
+ return await action();
23
+ }
24
+ finally {
25
+ if (abort)
26
+ signal?.removeEventListener("abort", abort);
27
+ release();
28
+ }
29
+ }
30
+ }
@@ -0,0 +1,102 @@
1
+ import type { Api, Model } from "@earendil-works/pi-ai";
2
+ export declare const PROTOCOL_VERSION = 1;
3
+ /** Authenticated idle shutdown after work is drained; callers may wait for this owner to exit. */
4
+ export declare class DaemonStoppingError extends Error {
5
+ name: string;
6
+ constructor();
7
+ }
8
+ export declare const MAX_MESSAGE_BYTES: number;
9
+ export declare const REVIEW_PAGE_CHARS: number;
10
+ export declare const MAX_REVIEW_BYTES: number;
11
+ export declare const MAX_SETTINGS_BYTES: number;
12
+ export type Json = null | boolean | number | string | Json[] | {
13
+ [key: string]: Json;
14
+ };
15
+ export interface Identity {
16
+ version: 1;
17
+ root: string;
18
+ instance: string;
19
+ pid: number;
20
+ token: string;
21
+ }
22
+ export interface ClientFacts {
23
+ id: string;
24
+ pid: number;
25
+ generation: string;
26
+ cwd: string;
27
+ mode: "tui" | "rpc" | "json" | "print";
28
+ hasUI: boolean;
29
+ idle: boolean;
30
+ ready?: boolean;
31
+ startupDebug?: boolean;
32
+ sessionFile?: string;
33
+ sessionId?: string;
34
+ sessionDir?: string;
35
+ model?: Pick<Model<Api>, "provider" | "id"> & {
36
+ signature: string;
37
+ authSource: "stored" | "environment" | "models_json_key" | "models_json_command";
38
+ };
39
+ }
40
+ export interface ClientHandoff {
41
+ kind: "replace" | "exit";
42
+ file?: string;
43
+ sessionId?: string;
44
+ cwd?: string;
45
+ }
46
+ export declare function validateHandoff(value: unknown): asserts value is ClientHandoff;
47
+ export interface Request {
48
+ version: 1;
49
+ instance: string;
50
+ root: string;
51
+ token: string;
52
+ method: string;
53
+ params: unknown;
54
+ }
55
+ export interface Callback {
56
+ id: string;
57
+ job: string;
58
+ kind: string;
59
+ payload: unknown;
60
+ review?: {
61
+ pages: number;
62
+ bytes: number;
63
+ sha256: string;
64
+ };
65
+ }
66
+ export interface ClientEvent {
67
+ id: number;
68
+ kind: "notify" | "status" | "commit" | "release" | "timings";
69
+ payload: unknown;
70
+ }
71
+ export interface RemoteError {
72
+ name: string;
73
+ message: string;
74
+ properties?: Record<string, unknown>;
75
+ }
76
+ export interface JobView {
77
+ id: string;
78
+ phase: "queued" | "running" | "done" | "failed";
79
+ result?: unknown;
80
+ error?: RemoteError;
81
+ }
82
+ export interface Execution {
83
+ readonly root: string;
84
+ readonly clientId: string | undefined;
85
+ readonly signal: AbortSignal;
86
+ facts(): ClientFacts | undefined;
87
+ participants(): readonly ClientFacts[];
88
+ /** All live PIDs, including retired clients that must no longer authorize work. */
89
+ liveClients(): readonly ClientFacts[];
90
+ /** Fence attach publication until every queue grant and release in the action settles. */
91
+ withParticipants<T>(action: (peers: readonly ClientFacts[]) => Promise<T>): Promise<T>;
92
+ validate(): void;
93
+ request(kind: string, payload: unknown, clientId?: string, signal?: AbortSignal): Promise<unknown>;
94
+ emit(kind: ClientEvent["kind"], payload: unknown, clientId?: string): void;
95
+ committed(): void;
96
+ }
97
+ export type Execute = (operation: string, payload: unknown, execution: Execution) => Promise<unknown>;
98
+ export declare function record(value: unknown): value is Record<string, unknown>;
99
+ export declare function operationPrefix(identity: Pick<Identity, "instance">): string;
100
+ export declare function validId(value: unknown): value is string;
101
+ export declare function validateFacts(value: unknown): asserts value is ClientFacts;
102
+ export declare function remoteError(error: unknown): RemoteError;
@@ -0,0 +1,97 @@
1
+ import { createHash } from "node:crypto";
2
+ import path from "node:path";
3
+ export const PROTOCOL_VERSION = 1;
4
+ /** Authenticated idle shutdown after work is drained; callers may wait for this owner to exit. */
5
+ export class DaemonStoppingError extends Error {
6
+ name = "DaemonStoppingError";
7
+ constructor() {
8
+ super("Daemon is closing after its idle grace period; wait for owner exit before reconnecting.");
9
+ }
10
+ }
11
+ export const MAX_MESSAGE_BYTES = 4 * 1024 * 1024;
12
+ export const REVIEW_PAGE_CHARS = 64 * 1024;
13
+ export const MAX_REVIEW_BYTES = 16 * 1024 * 1024;
14
+ export const MAX_SETTINGS_BYTES = 512 * 1024;
15
+ export function validateHandoff(value) {
16
+ if (!record(value) ||
17
+ !["replace", "exit"].includes(String(value.kind)) ||
18
+ ["file", "sessionId", "cwd"].some((key) => value[key] !== undefined &&
19
+ (typeof value[key] !== "string" || value[key].length > 32768 || value[key].includes("\0"))) ||
20
+ ["file", "cwd"].some((key) => typeof value[key] === "string" && !path.isAbsolute(value[key])))
21
+ throw new Error("Invalid client handoff.");
22
+ }
23
+ export function record(value) {
24
+ return typeof value === "object" && value !== null && !Array.isArray(value);
25
+ }
26
+ export function operationPrefix(identity) {
27
+ return `${createHash("sha256").update(identity.instance).digest("hex").slice(0, 16)}-`;
28
+ }
29
+ export function validId(value) {
30
+ return typeof value === "string" && /^[a-f0-9-]{16,64}$/u.test(value);
31
+ }
32
+ export function validateFacts(value) {
33
+ if (!record(value) ||
34
+ Object.keys(value).some((key) => ![
35
+ "id",
36
+ "pid",
37
+ "generation",
38
+ "cwd",
39
+ "mode",
40
+ "hasUI",
41
+ "idle",
42
+ "ready",
43
+ "startupDebug",
44
+ "sessionFile",
45
+ "sessionId",
46
+ "sessionDir",
47
+ "model",
48
+ ].includes(key)) ||
49
+ !validId(value.id) ||
50
+ !validId(value.generation) ||
51
+ !Number.isSafeInteger(value.pid) ||
52
+ Number(value.pid) < 1 ||
53
+ Number(value.pid) > 2_147_483_647 ||
54
+ typeof value.cwd !== "string" ||
55
+ value.cwd.length > 32768 ||
56
+ value.cwd.includes("\0") ||
57
+ !path.isAbsolute(value.cwd) ||
58
+ !["tui", "rpc", "json", "print"].includes(String(value.mode)) ||
59
+ typeof value.hasUI !== "boolean" ||
60
+ typeof value.idle !== "boolean" ||
61
+ (value.ready !== undefined && typeof value.ready !== "boolean") ||
62
+ (value.startupDebug !== undefined && typeof value.startupDebug !== "boolean") ||
63
+ ["sessionFile", "sessionId", "sessionDir"].some((key) => value[key] !== undefined &&
64
+ (typeof value[key] !== "string" || value[key].length > 32768 || value[key].includes("\0"))) ||
65
+ ["sessionFile", "sessionDir"].some((key) => typeof value[key] === "string" && !path.isAbsolute(value[key])) ||
66
+ (value.model !== undefined &&
67
+ (!record(value.model) ||
68
+ Object.keys(value.model).some((key) => !["provider", "id", "signature", "authSource"].includes(key)) ||
69
+ typeof value.model.provider !== "string" ||
70
+ !value.model.provider.length ||
71
+ value.model.provider.length > 256 ||
72
+ typeof value.model.id !== "string" ||
73
+ !value.model.id.length ||
74
+ value.model.id.length > 4096 ||
75
+ typeof value.model.signature !== "string" ||
76
+ !/^[a-f0-9]{64}$/u.test(value.model.signature) ||
77
+ !["stored", "environment", "models_json_key", "models_json_command"].includes(String(value.model.authSource))))) {
78
+ throw new Error("Invalid client facts.");
79
+ }
80
+ }
81
+ export function remoteError(error) {
82
+ if (!(error instanceof Error))
83
+ return { name: "Error", message: "Synchronization operation failed." };
84
+ const properties = Object.fromEntries(Object.entries(error).filter(([key]) => ["code", "decision", "status", "phase", "snapshotId", "backup", "publication", "snapshotRef"].includes(key)));
85
+ const result = { name: error.name, message: error.message.slice(0, 4096), properties };
86
+ try {
87
+ if (Buffer.byteLength(JSON.stringify(result)) <= MAX_MESSAGE_BYTES / 4)
88
+ return result;
89
+ }
90
+ catch {
91
+ /* Opaque/unserializable details must not escape. */
92
+ }
93
+ return {
94
+ name: "Error",
95
+ message: "Operation details exceed the local API limit; inspect retained recovery evidence. No truncated review was approved.",
96
+ };
97
+ }
@@ -0,0 +1,11 @@
1
+ import type { Api, Model } from "@earendil-works/pi-ai";
2
+ import type { EngineModelRegistry } from "./engine/host.js";
3
+ import type { ClientFacts } from "./protocol.js";
4
+ export interface ResolverHost {
5
+ model?: Model<Api>;
6
+ registry: EngineModelRegistry;
7
+ unavailable?: string;
8
+ settle(): Promise<void>;
9
+ }
10
+ /** No resource discovery or extension loading; credential work starts only for a resolver request. */
11
+ export declare function prepareResolverHost(root: string, binding: ClientFacts["model"], signal?: AbortSignal): Promise<ResolverHost>;