@narumitw/pi-sync-daemon 0.0.0-stage → 0.2.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 (265) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/LICENSE +21 -0
  3. package/README.md +89 -2
  4. package/dist/cli.d.ts +2 -0
  5. package/dist/cli.js +128 -0
  6. package/dist/client.d.ts +55 -0
  7. package/dist/client.js +484 -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 +11 -0
  241. package/dist/engine-service.js +315 -0
  242. package/dist/identity.d.ts +20 -0
  243. package/dist/identity.js +133 -0
  244. package/dist/index.d.ts +8 -0
  245. package/dist/index.js +4 -0
  246. package/dist/lifecycle-log.d.ts +7 -0
  247. package/dist/lifecycle-log.js +53 -0
  248. package/dist/lifecycle.d.ts +2 -0
  249. package/dist/lifecycle.js +21 -0
  250. package/dist/model-signature.d.ts +2 -0
  251. package/dist/model-signature.js +7 -0
  252. package/dist/monitor.d.ts +11 -0
  253. package/dist/monitor.js +245 -0
  254. package/dist/participant-admission.d.ts +5 -0
  255. package/dist/participant-admission.js +30 -0
  256. package/dist/protocol.d.ts +97 -0
  257. package/dist/protocol.js +90 -0
  258. package/dist/resolver-host.d.ts +11 -0
  259. package/dist/resolver-host.js +78 -0
  260. package/dist/server.d.ts +18 -0
  261. package/dist/server.js +724 -0
  262. package/dist/service-host.d.ts +7 -0
  263. package/dist/service-host.js +174 -0
  264. package/docs/architecture.md +133 -0
  265. package/package.json +54 -4
@@ -0,0 +1,11 @@
1
+ import type { Execution } from "./protocol.js";
2
+ import type { startServer } from "./server.js";
3
+ import type { installServiceHost } from "./service-host.js";
4
+ export declare function createMonitor(root: string, host: ReturnType<typeof installServiceHost>): {
5
+ bind(value: Awaited<ReturnType<typeof startServer>>): void;
6
+ schedule: () => void;
7
+ explicitSync(setup: string, execution: Execution): void;
8
+ pause(): Promise<void>;
9
+ factsChanged(): Promise<void>;
10
+ close(): Promise<void>;
11
+ };
@@ -0,0 +1,245 @@
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
+ async function stop() {
31
+ const current = task;
32
+ if (!current)
33
+ return;
34
+ task = undefined;
35
+ current.controller.abort(new DOMException("Daemon monitoring interrupted", "AbortError"));
36
+ await current.continuous.stop();
37
+ await current.promise;
38
+ }
39
+ async function start() {
40
+ const service = server;
41
+ if (!service)
42
+ return;
43
+ const available = () => !closed && !authorizationFailed && !task && server === service && service.isIdle();
44
+ if (!available())
45
+ return;
46
+ const consent = readConsent(root);
47
+ if (!consent)
48
+ return;
49
+ const config = await loadConfigForCheck();
50
+ if (!available())
51
+ return;
52
+ if (!config.continuous || !config.agentMode) {
53
+ retries.clear();
54
+ return;
55
+ }
56
+ const { pendingTransactionEntries } = await import("./engine/snapshot/snapshot-transaction-directory.js");
57
+ if ((await pendingTransactionEntries()).some((entry) => entry.isDirectory()) || !available())
58
+ return;
59
+ const fingerprint = consentFingerprint(root, config);
60
+ const peers = service.participants();
61
+ if (peers.some((peer) => !peer.idle || peer.ready !== true))
62
+ return;
63
+ const authorized = consent.setups[config.setupName];
64
+ const selected = peers.toSorted((a, b) => a.id.localeCompare(b.id))[0];
65
+ if (!selected && (!authorized?.afterExit || authorized.fingerprint !== fingerprint))
66
+ return;
67
+ if (!continuous) {
68
+ const { createContinuousSync } = await import("./engine/sync/continuous-sync.js");
69
+ if (!available())
70
+ return;
71
+ continuous = createContinuousSync(loaders, undefined, (ctx, report) => timingOwners.get(ctx)?.emit("timings", { report }));
72
+ // Re-enter every eligibility branch after importing the full engine graph.
73
+ return start();
74
+ }
75
+ const activeContinuous = continuous;
76
+ const binding = selected?.model ?? authorized?.model;
77
+ const sessionDir = selected ? selected.sessionDir : authorized?.sessionDir;
78
+ const cwd = selected?.cwd ?? authorized?.cwd ?? root;
79
+ const key = peers
80
+ .map((peer) => `${peer.id}:${peer.generation}`)
81
+ .sort()
82
+ .join(",") || "unattended";
83
+ if (epoch?.key !== key) {
84
+ epoch?.controller.abort(new DOMException("Participating sessions changed", "AbortError"));
85
+ const location = { sessionDir, cwd };
86
+ const manager = {
87
+ getSessionId: () => key,
88
+ getCwd: () => location.cwd,
89
+ getSessionDir: () => location.sessionDir ?? path.join(root, "sessions"),
90
+ usesDefaultSessionDir: () => location.sessionDir === undefined,
91
+ };
92
+ epoch = { key, controller: new AbortController(), manager, location, debug: selected?.startupDebug ?? false };
93
+ }
94
+ epoch.location.sessionDir = sessionDir;
95
+ epoch.location.cwd = cwd;
96
+ const controller = new AbortController();
97
+ const original = service.backgroundExecution(controller.signal);
98
+ const stableFacts = {
99
+ id: randomUUID(),
100
+ generation: randomUUID(),
101
+ pid: process.pid,
102
+ cwd,
103
+ mode: "rpc",
104
+ hasUI: false,
105
+ idle: true,
106
+ sessionDir,
107
+ model: binding,
108
+ };
109
+ const execution = { ...original, facts: () => stableFacts };
110
+ const allowed = (currentConfig = config) => {
111
+ if (closed || authorizationFailed || server !== service || controller.signal.aborted || !readConsent(root))
112
+ return false;
113
+ const current = service.participants();
114
+ if (current.length)
115
+ return current.every((peer) => peer.idle &&
116
+ peer.ready === true &&
117
+ JSON.stringify(peer.model) === JSON.stringify(binding) &&
118
+ peer.sessionDir === sessionDir &&
119
+ peer.cwd === cwd);
120
+ const saved = readConsent(root)?.setups[currentConfig.setupName];
121
+ return Boolean(saved?.afterExit &&
122
+ saved.fingerprint === consentFingerprint(root, currentConfig) &&
123
+ JSON.stringify(saved.model) === JSON.stringify(binding) &&
124
+ saved.sessionDir === sessionDir &&
125
+ (saved.cwd ?? root) === cwd);
126
+ };
127
+ const ctx = createServiceContext(execution);
128
+ ctx.reload = undefined;
129
+ ctx.sessionManager = epoch.manager;
130
+ Object.defineProperty(ctx, "hasUI", {
131
+ get: () => service.participants().some((peer) => peer.hasUI && peer.ready === true),
132
+ });
133
+ timingOwners.set(ctx, execution);
134
+ ctx.backgroundAuthorized = allowed;
135
+ ctx.isIdle = () => Boolean(service.isIdle() && allowed());
136
+ loaders.operations = async () => {
137
+ const loaded = await operations();
138
+ return {
139
+ ...loaded,
140
+ syncBoth: (context, options, ...rest) => loaded.syncBoth(context, { ...options, onCommit: execution.committed }, ...rest),
141
+ };
142
+ };
143
+ const sessionSignal = epoch.controller.signal;
144
+ const debug = epoch.debug;
145
+ let finish;
146
+ const promise = new Promise((resolve) => {
147
+ finish = resolve;
148
+ });
149
+ const current = { controller, continuous: activeContinuous, promise };
150
+ task = current;
151
+ void host
152
+ .run(execution, async () => {
153
+ const { prepareResolverHost } = await import("./resolver-host.js");
154
+ const resolver = await prepareResolverHost(root, binding, controller.signal);
155
+ try {
156
+ if (!allowed())
157
+ return;
158
+ ctx.model = resolver.model;
159
+ ctx.modelUnavailableReason = resolver.unavailable;
160
+ ctx.modelRegistry = resolver.registry;
161
+ ctx.validateModel = async () => {
162
+ if (!allowed())
163
+ throw new Error("Daemon authorization changed before model dispatch.");
164
+ for (const peer of service.participants()) {
165
+ const fresh = await execution.request("model-binding", { background: true }, peer.id);
166
+ if (JSON.stringify(fresh ?? undefined) !== JSON.stringify(binding))
167
+ throw new Error("Participating model changed before dispatch.");
168
+ if (!allowed())
169
+ throw new Error("Daemon authorization changed during model validation.");
170
+ }
171
+ };
172
+ const explicitRetry = service.participants().some((peer) => {
173
+ const retry = retries.get(peer.id);
174
+ return retry?.setup === config.setupName && retry.generation === peer.generation && !retry.signal.aborted;
175
+ });
176
+ retries.clear();
177
+ activeContinuous.start(ctx, sessionSignal, explicitRetry ? config.setupName : false, debug);
178
+ await new Promise((resolve) => {
179
+ if (controller.signal.aborted)
180
+ resolve();
181
+ else
182
+ controller.signal.addEventListener("abort", () => resolve(), { once: true });
183
+ });
184
+ await activeContinuous.stop();
185
+ }
186
+ finally {
187
+ await resolver.settle();
188
+ }
189
+ })
190
+ .catch(() => { })
191
+ .finally(() => {
192
+ controller.abort();
193
+ if (task === current)
194
+ task = undefined;
195
+ finish();
196
+ });
197
+ }
198
+ return {
199
+ bind(value) {
200
+ server = value;
201
+ schedule();
202
+ },
203
+ schedule,
204
+ explicitSync(setup, execution) {
205
+ const peer = execution.facts();
206
+ if (!closed && peer)
207
+ retries.set(peer.id, { setup, generation: peer.generation, signal: execution.signal });
208
+ },
209
+ async pause() {
210
+ transition = transition.then(stop);
211
+ await transition;
212
+ },
213
+ async factsChanged() {
214
+ let failure;
215
+ try {
216
+ if (server) {
217
+ const peers = server.participants();
218
+ for (const [id, retry] of retries)
219
+ if (retry.signal.aborted || !peers.some((peer) => peer.id === id && peer.generation === retry.generation))
220
+ retries.delete(id);
221
+ revokeChangedBindings(root, peers);
222
+ }
223
+ }
224
+ catch (error) {
225
+ authorizationFailed = true;
226
+ retries.clear();
227
+ // Recovery barriers must not prevent passive clients from registering protection.
228
+ if (error instanceof ConsentPublicationError)
229
+ failure = error;
230
+ }
231
+ transition = transition.then(stop);
232
+ await transition;
233
+ if (failure)
234
+ 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 });
235
+ schedule();
236
+ },
237
+ async close() {
238
+ closed = true;
239
+ retries.clear();
240
+ transition = transition.then(stop);
241
+ await transition;
242
+ epoch?.controller.abort();
243
+ },
244
+ };
245
+ }
@@ -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,97 @@
1
+ import type { Api, Model } from "@earendil-works/pi-ai";
2
+ export declare const PROTOCOL_VERSION = 1;
3
+ export declare const MAX_MESSAGE_BYTES: number;
4
+ export declare const REVIEW_PAGE_CHARS: number;
5
+ export declare const MAX_REVIEW_BYTES: number;
6
+ export declare const MAX_SETTINGS_BYTES: number;
7
+ export type Json = null | boolean | number | string | Json[] | {
8
+ [key: string]: Json;
9
+ };
10
+ export interface Identity {
11
+ version: 1;
12
+ root: string;
13
+ instance: string;
14
+ pid: number;
15
+ token: string;
16
+ }
17
+ export interface ClientFacts {
18
+ id: string;
19
+ pid: number;
20
+ generation: string;
21
+ cwd: string;
22
+ mode: "tui" | "rpc" | "json" | "print";
23
+ hasUI: boolean;
24
+ idle: boolean;
25
+ ready?: boolean;
26
+ startupDebug?: boolean;
27
+ sessionFile?: string;
28
+ sessionId?: string;
29
+ sessionDir?: string;
30
+ model?: Pick<Model<Api>, "provider" | "id"> & {
31
+ signature: string;
32
+ authSource: "stored" | "environment" | "models_json_key" | "models_json_command";
33
+ };
34
+ }
35
+ export interface ClientHandoff {
36
+ kind: "replace" | "exit";
37
+ file?: string;
38
+ sessionId?: string;
39
+ cwd?: string;
40
+ }
41
+ export declare function validateHandoff(value: unknown): asserts value is ClientHandoff;
42
+ export interface Request {
43
+ version: 1;
44
+ instance: string;
45
+ root: string;
46
+ token: string;
47
+ method: string;
48
+ params: unknown;
49
+ }
50
+ export interface Callback {
51
+ id: string;
52
+ job: string;
53
+ kind: string;
54
+ payload: unknown;
55
+ review?: {
56
+ pages: number;
57
+ bytes: number;
58
+ sha256: string;
59
+ };
60
+ }
61
+ export interface ClientEvent {
62
+ id: number;
63
+ kind: "notify" | "status" | "commit" | "release" | "timings";
64
+ payload: unknown;
65
+ }
66
+ export interface RemoteError {
67
+ name: string;
68
+ message: string;
69
+ properties?: Record<string, unknown>;
70
+ }
71
+ export interface JobView {
72
+ id: string;
73
+ phase: "queued" | "running" | "done" | "failed";
74
+ result?: unknown;
75
+ error?: RemoteError;
76
+ }
77
+ export interface Execution {
78
+ readonly root: string;
79
+ readonly clientId: string | undefined;
80
+ readonly signal: AbortSignal;
81
+ facts(): ClientFacts | undefined;
82
+ participants(): readonly ClientFacts[];
83
+ /** All live PIDs, including retired clients that must no longer authorize work. */
84
+ liveClients(): readonly ClientFacts[];
85
+ /** Fence attach publication until every queue grant and release in the action settles. */
86
+ withParticipants<T>(action: (peers: readonly ClientFacts[]) => Promise<T>): Promise<T>;
87
+ validate(): void;
88
+ request(kind: string, payload: unknown, clientId?: string, signal?: AbortSignal): Promise<unknown>;
89
+ emit(kind: ClientEvent["kind"], payload: unknown, clientId?: string): void;
90
+ committed(): void;
91
+ }
92
+ export type Execute = (operation: string, payload: unknown, execution: Execution) => Promise<unknown>;
93
+ export declare function record(value: unknown): value is Record<string, unknown>;
94
+ export declare function operationPrefix(identity: Pick<Identity, "instance">): string;
95
+ export declare function validId(value: unknown): value is string;
96
+ export declare function validateFacts(value: unknown): asserts value is ClientFacts;
97
+ export declare function remoteError(error: unknown): RemoteError;
@@ -0,0 +1,90 @@
1
+ import { createHash } from "node:crypto";
2
+ import path from "node:path";
3
+ export const PROTOCOL_VERSION = 1;
4
+ export const MAX_MESSAGE_BYTES = 4 * 1024 * 1024;
5
+ export const REVIEW_PAGE_CHARS = 64 * 1024;
6
+ export const MAX_REVIEW_BYTES = 16 * 1024 * 1024;
7
+ export const MAX_SETTINGS_BYTES = 512 * 1024;
8
+ export function validateHandoff(value) {
9
+ if (!record(value) ||
10
+ !["replace", "exit"].includes(String(value.kind)) ||
11
+ ["file", "sessionId", "cwd"].some((key) => value[key] !== undefined &&
12
+ (typeof value[key] !== "string" || value[key].length > 32768 || value[key].includes("\0"))) ||
13
+ ["file", "cwd"].some((key) => typeof value[key] === "string" && !path.isAbsolute(value[key])))
14
+ throw new Error("Invalid client handoff.");
15
+ }
16
+ export function record(value) {
17
+ return typeof value === "object" && value !== null && !Array.isArray(value);
18
+ }
19
+ export function operationPrefix(identity) {
20
+ return `${createHash("sha256").update(identity.instance).digest("hex").slice(0, 16)}-`;
21
+ }
22
+ export function validId(value) {
23
+ return typeof value === "string" && /^[a-f0-9-]{16,64}$/u.test(value);
24
+ }
25
+ export function validateFacts(value) {
26
+ if (!record(value) ||
27
+ Object.keys(value).some((key) => ![
28
+ "id",
29
+ "pid",
30
+ "generation",
31
+ "cwd",
32
+ "mode",
33
+ "hasUI",
34
+ "idle",
35
+ "ready",
36
+ "startupDebug",
37
+ "sessionFile",
38
+ "sessionId",
39
+ "sessionDir",
40
+ "model",
41
+ ].includes(key)) ||
42
+ !validId(value.id) ||
43
+ !validId(value.generation) ||
44
+ !Number.isSafeInteger(value.pid) ||
45
+ Number(value.pid) < 1 ||
46
+ Number(value.pid) > 2_147_483_647 ||
47
+ typeof value.cwd !== "string" ||
48
+ value.cwd.length > 32768 ||
49
+ value.cwd.includes("\0") ||
50
+ !path.isAbsolute(value.cwd) ||
51
+ !["tui", "rpc", "json", "print"].includes(String(value.mode)) ||
52
+ typeof value.hasUI !== "boolean" ||
53
+ typeof value.idle !== "boolean" ||
54
+ (value.ready !== undefined && typeof value.ready !== "boolean") ||
55
+ (value.startupDebug !== undefined && typeof value.startupDebug !== "boolean") ||
56
+ ["sessionFile", "sessionId", "sessionDir"].some((key) => value[key] !== undefined &&
57
+ (typeof value[key] !== "string" || value[key].length > 32768 || value[key].includes("\0"))) ||
58
+ ["sessionFile", "sessionDir"].some((key) => typeof value[key] === "string" && !path.isAbsolute(value[key])) ||
59
+ (value.model !== undefined &&
60
+ (!record(value.model) ||
61
+ Object.keys(value.model).some((key) => !["provider", "id", "signature", "authSource"].includes(key)) ||
62
+ typeof value.model.provider !== "string" ||
63
+ !value.model.provider.length ||
64
+ value.model.provider.length > 256 ||
65
+ typeof value.model.id !== "string" ||
66
+ !value.model.id.length ||
67
+ value.model.id.length > 4096 ||
68
+ typeof value.model.signature !== "string" ||
69
+ !/^[a-f0-9]{64}$/u.test(value.model.signature) ||
70
+ !["stored", "environment", "models_json_key", "models_json_command"].includes(String(value.model.authSource))))) {
71
+ throw new Error("Invalid client facts.");
72
+ }
73
+ }
74
+ export function remoteError(error) {
75
+ if (!(error instanceof Error))
76
+ return { name: "Error", message: "Synchronization operation failed." };
77
+ const properties = Object.fromEntries(Object.entries(error).filter(([key]) => ["code", "decision", "status", "phase", "snapshotId", "backup", "publication", "snapshotRef"].includes(key)));
78
+ const result = { name: error.name, message: error.message.slice(0, 4096), properties };
79
+ try {
80
+ if (Buffer.byteLength(JSON.stringify(result)) <= MAX_MESSAGE_BYTES / 4)
81
+ return result;
82
+ }
83
+ catch {
84
+ /* Opaque/unserializable details must not escape. */
85
+ }
86
+ return {
87
+ name: "Error",
88
+ message: "Operation details exceed the local API limit; inspect retained recovery evidence. No truncated review was approved.",
89
+ };
90
+ }
@@ -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>;
@@ -0,0 +1,78 @@
1
+ import path from "node:path";
2
+ import { modelSignature } from "./model-signature.js";
3
+ const DIFFERENT = "The selected model is unavailable: its definition or auth source differs in the standalone daemon. No fallback model was selected.";
4
+ /** No resource discovery or extension loading; credential work starts only for a resolver request. */
5
+ export async function prepareResolverHost(root, binding, signal) {
6
+ const unavailable = (reason) => ({
7
+ unavailable: reason,
8
+ registry: {
9
+ streamSimple: () => {
10
+ throw new Error(reason);
11
+ },
12
+ },
13
+ settle: async () => { },
14
+ });
15
+ signal?.throwIfAborted();
16
+ if (!binding)
17
+ return unavailable("No independently available daemon resolver model is authorized; parent-only runtime providers are unavailable.");
18
+ const [{ ModelRuntime, ModelRegistry }, { InMemoryCredentialStore }] = await Promise.all([
19
+ import("@earendil-works/pi-coding-agent"),
20
+ import("@earendil-works/pi-ai"),
21
+ ]);
22
+ signal?.throwIfAborted();
23
+ // Read public static definitions without touching auth.json, refreshing OAuth,
24
+ // evaluating credential commands, or discovering catalogs over the network.
25
+ const metadata = await ModelRuntime.create({
26
+ credentials: new InMemoryCredentialStore(),
27
+ modelsPath: path.join(root, "models.json"),
28
+ refreshOnCreate: false,
29
+ });
30
+ signal?.throwIfAborted();
31
+ const model = metadata.getModel(binding.provider, binding.id);
32
+ if (metadata.getError() || !model || modelSignature(model) !== binding.signature)
33
+ return unavailable(DIFFERENT);
34
+ let runtime;
35
+ let loading;
36
+ const load = (requestSignal) => (loading ??= (async () => {
37
+ requestSignal?.throwIfAborted();
38
+ runtime = await ModelRuntime.create({
39
+ authPath: path.join(root, "auth.json"),
40
+ modelsPath: path.join(root, "models.json"),
41
+ refreshOnCreate: false,
42
+ });
43
+ requestSignal?.throwIfAborted();
44
+ if (runtime.getError() || modelSignature(runtime.getModel(binding.provider, binding.id)) !== binding.signature)
45
+ throw new Error(DIFFERENT);
46
+ await runtime.refresh({ allowNetwork: false, providers: [binding.provider], signal: requestSignal });
47
+ requestSignal?.throwIfAborted();
48
+ const actual = runtime.getModel(binding.provider, binding.id);
49
+ if (runtime.getError() ||
50
+ !actual ||
51
+ modelSignature(actual) !== binding.signature ||
52
+ runtime.getProviderAuthStatus(binding.provider).source !== binding.authSource)
53
+ throw new Error(DIFFERENT);
54
+ return { registry: new ModelRegistry(runtime), model: actual };
55
+ })());
56
+ return {
57
+ model,
58
+ registry: {
59
+ streamSimple(_model, context, options) {
60
+ let upstream;
61
+ const get = () => (upstream ??= load(options?.signal ?? signal).then((host) => host.registry.streamSimple(host.model, context, options)));
62
+ return {
63
+ async *[Symbol.asyncIterator]() {
64
+ for await (const event of await get())
65
+ yield event;
66
+ },
67
+ async result() {
68
+ return (await get()).result();
69
+ },
70
+ };
71
+ },
72
+ },
73
+ async settle() {
74
+ await loading?.catch(() => { });
75
+ await runtime?.settleCredentialWrites();
76
+ },
77
+ };
78
+ }
@@ -0,0 +1,18 @@
1
+ import { type ClientFacts, type Execute, type Execution, type Identity } from "./protocol.js";
2
+ export interface ServerHooks {
3
+ factsChanged?(): Promise<void>;
4
+ idle?(): void;
5
+ close?(): Promise<void>;
6
+ }
7
+ export declare function startServer(root: string, execute: Execute, hooks?: ServerHooks): Promise<{
8
+ identity: Identity;
9
+ paths: import("./identity.js").DaemonPaths;
10
+ close: () => Promise<void>;
11
+ backgroundExecution: (signal: AbortSignal) => Execution;
12
+ readonly retainedEndpoint: string | undefined;
13
+ participants: () => ClientFacts[];
14
+ liveClients: () => ClientFacts[];
15
+ expireClients: () => Promise<void>;
16
+ isIdle: () => boolean;
17
+ readonly closed: boolean;
18
+ }>;