@narumitw/pi-sync 0.61.0 → 0.62.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/README.md +24 -17
- package/dist/chunks/{chunk-EMVZL4PH.ts → chunk-3E3TR3JE.ts} +4 -4
- package/dist/chunks/{chunk-JVFCVPPD.ts → chunk-6PFZUEUG.ts} +41 -18
- package/dist/chunks/chunk-6PFZUEUG.ts.map +7 -0
- package/dist/chunks/{chunk-ZIL6PW5L.ts → chunk-6YKOHBSC.ts} +2 -2
- package/dist/chunks/{chunk-OA4NZLSL.ts → chunk-APZVJAEW.ts} +4 -3
- package/dist/chunks/{chunk-4SR3ZYHA.ts → chunk-GELYN4UC.ts} +2 -2
- package/dist/chunks/{chunk-S7F4FOAS.ts → chunk-GSCZ4VXV.ts} +5 -5
- package/dist/chunks/{chunk-YQSFJLJ3.ts → chunk-IBXEM35O.ts} +4 -3
- package/dist/chunks/{chunk-E3YLRLJM.ts → chunk-INECVQNR.ts} +10 -10
- package/dist/chunks/{chunk-2JHAN3ZO.ts → chunk-JREGWM2B.ts} +3 -3
- package/dist/chunks/{chunk-277VHM2P.ts → chunk-MNYRU5U5.ts} +5 -2
- package/dist/chunks/{chunk-277VHM2P.ts.map → chunk-MNYRU5U5.ts.map} +2 -2
- package/dist/chunks/{chunk-2ZGV5KNC.ts → chunk-NHFGAZEC.ts} +11 -8
- package/dist/chunks/chunk-NHFGAZEC.ts.map +7 -0
- package/dist/chunks/{chunk-EMRFVLZM.ts → chunk-NXWHPVXR.ts} +2 -2
- package/dist/chunks/{chunk-SMVKMYLK.ts → chunk-P4GI7LTT.ts} +2 -2
- package/dist/chunks/{chunk-PJMM75W5.ts → chunk-PWESMTH6.ts} +6 -6
- package/dist/chunks/{chunk-ZVGRZD4C.ts → chunk-R3SAMXB6.ts} +2 -2
- package/dist/chunks/{chunk-RNIEVDTR.ts → chunk-T3LABNHF.ts} +2 -2
- package/dist/chunks/{chunk-S3R3W3KF.ts → chunk-UMPA5S7X.ts} +2 -2
- package/dist/chunks/{chunk-WP2M67XZ.ts → chunk-WBIOSK76.ts} +2 -2
- package/dist/chunks/{chunk-4KTJLJSJ.ts → chunk-ZB3GNX3P.ts} +11 -11
- package/dist/chunks/{chunk-HEB6YT64.ts → chunk-ZO52JM4H.ts} +2 -2
- package/dist/chunks/{command-handler-K4XJOGYC.ts → command-handler-6ATREPG7.ts} +16 -16
- package/dist/chunks/command-handler-6ATREPG7.ts.map +7 -0
- package/dist/chunks/{conflict-review-IGKY2TOJ.ts → conflict-review-MAOGTIAI.ts} +4 -4
- package/dist/chunks/{continuous-record-3XDXDOMV.ts → continuous-record-3SKJ6I3V.ts} +2 -2
- package/dist/chunks/{continuous-storage-HLKCHF6Z.ts → continuous-storage-3EU6I7Z3.ts} +2 -2
- package/dist/chunks/{file-selection-MGGVOKM7.ts → file-selection-QR2KZVGD.ts} +10 -10
- package/dist/chunks/manager-result-dispatcher-MC6EQOQY.ts +19 -0
- package/dist/chunks/{manager-ui-KYQ5AZJS.ts → manager-ui-AOFUNXAJ.ts} +547 -135
- package/dist/chunks/manager-ui-AOFUNXAJ.ts.map +7 -0
- package/dist/chunks/remote-selection-ui-4BTP2OJR.ts +18 -0
- package/dist/chunks/{setup-switch-D6K6PBPC.ts → setup-switch-Y6AMFFNK.ts} +7 -7
- package/dist/chunks/{setup-wizard-4DYUDHJR.ts → setup-wizard-5G426MOZ.ts} +10 -10
- package/dist/chunks/{snapshot-5HY3M2NL.ts → snapshot-ZUJJZCFW.ts} +2 -2
- package/dist/chunks/{snapshot-transaction-directory-OU2D7R7A.ts → snapshot-transaction-directory-F46JWRAU.ts} +2 -2
- package/dist/chunks/{state-directory-XXHU73Z3.ts → state-directory-CMAIF34J.ts} +2 -2
- package/dist/chunks/{sync-inspection-J3CRBORL.ts → sync-inspection-ITZ6Z4DE.ts} +5 -5
- package/dist/chunks/{sync-operations-BVWYYKH3.ts → sync-operations-NMVKF7SE.ts} +13 -9
- package/dist/chunks/sync-operations-NMVKF7SE.ts.map +7 -0
- package/dist/chunks/{sync-state-2LMIXJ2C.ts → sync-state-QIT64TKV.ts} +2 -2
- package/dist/daemon/LICENSE +21 -0
- package/dist/daemon/dist/build-version.js +8 -0
- package/dist/daemon/dist/child-sdk.mjs +17 -0
- package/dist/daemon/dist/cli.js +169 -0
- package/dist/daemon/dist/client.js +909 -0
- package/dist/daemon/dist/consent.js +265 -0
- package/dist/daemon/dist/document.js +6 -0
- package/dist/daemon/dist/endpoint.js +91 -0
- package/dist/daemon/dist/engine/backends/backend-factory.js +16 -0
- package/dist/daemon/dist/engine/backends/backend-identity.js +38 -0
- package/dist/daemon/dist/engine/backends/backend-types.js +1 -0
- package/dist/daemon/dist/engine/backends/git/git-backend.js +715 -0
- package/dist/daemon/dist/engine/backends/git/git-config.js +118 -0
- package/dist/daemon/dist/engine/backends/git/git-runner.js +232 -0
- package/dist/daemon/dist/engine/backends/git/git-storage.js +252 -0
- package/dist/daemon/dist/engine/backends/s3/s3-backend.js +444 -0
- package/dist/daemon/dist/engine/backends/s3/s3-client.js +352 -0
- package/dist/daemon/dist/engine/backends/s3/s3-conditions.js +66 -0
- package/dist/daemon/dist/engine/backends/snapshot-pointer.js +22 -0
- package/dist/daemon/dist/engine/backends/sync-backend.js +23 -0
- package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +542 -0
- package/dist/daemon/dist/engine/backends/webdav/webdav-client.js +326 -0
- package/dist/daemon/dist/engine/backends/webdav/webdav-config.js +73 -0
- package/dist/daemon/dist/engine/commands/command-types.js +1 -0
- package/dist/daemon/dist/engine/host.js +16 -0
- package/dist/daemon/dist/engine/ignore/effective-ignore-policy.js +33 -0
- package/dist/daemon/dist/engine/ignore/ignore-edit.js +102 -0
- package/dist/daemon/dist/engine/ignore/ignore-initialization.js +186 -0
- package/dist/daemon/dist/engine/ignore/ignore-migration-prompt.js +139 -0
- package/dist/daemon/dist/engine/ignore/ignore-settings.js +322 -0
- package/dist/daemon/dist/engine/ignore/ignore-source.js +250 -0
- package/dist/daemon/dist/engine/paths.js +71 -0
- package/dist/daemon/dist/engine/settings/config-errors.js +4 -0
- package/dist/daemon/dist/engine/settings/config-file.js +736 -0
- package/dist/daemon/dist/engine/settings/config.js +301 -0
- package/dist/daemon/dist/engine/settings/settings-management.js +193 -0
- package/dist/daemon/dist/engine/settings/settings-store.js +41 -0
- package/dist/daemon/dist/engine/settings/settings-types.js +1 -0
- package/dist/daemon/dist/engine/settings/settings-validation.js +384 -0
- package/dist/daemon/dist/engine/snapshot/session-paths.js +160 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +348 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-bounds.js +20 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-case-replacement.js +82 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +61 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-entry-projection.js +78 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-exclude-safety.js +262 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-mutation-queues.js +133 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-paths.js +11 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-payload.js +10 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-reviewed-preimages.js +60 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-root-transition.js +138 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-transaction-directory.js +16 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-transaction-images.js +387 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-transaction-plan.js +68 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-transaction-policy.js +276 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-transaction-stage.js +303 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-transaction-verification.js +78 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-transaction.js +813 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-types.js +9 -0
- package/dist/daemon/dist/engine/snapshot/snapshot.js +678 -0
- package/dist/daemon/dist/engine/state/json-file.js +49 -0
- package/dist/daemon/dist/engine/state/lock-policy.js +2 -0
- package/dist/daemon/dist/engine/state/lock.js +259 -0
- package/dist/daemon/dist/engine/state/lockfile-fs.js +13 -0
- package/dist/daemon/dist/engine/state/merge-baseline-store.js +198 -0
- package/dist/daemon/dist/engine/state/mutation-directory-sync.js +34 -0
- package/dist/daemon/dist/engine/state/operation-availability.js +40 -0
- package/dist/daemon/dist/engine/state/state-directory.js +227 -0
- package/dist/daemon/dist/engine/state/state-types.js +1 -0
- package/dist/daemon/dist/engine/state/sync-state-store.js +54 -0
- package/dist/daemon/dist/engine/sync/agent-candidate.js +207 -0
- package/dist/daemon/dist/engine/sync/agent-plan.js +84 -0
- package/dist/daemon/dist/engine/sync/agent-policy.js +10 -0
- package/dist/daemon/dist/engine/sync/agent-refusal-retry.js +39 -0
- package/dist/daemon/dist/engine/sync/agent-request.js +13 -0
- package/dist/daemon/dist/engine/sync/agent-runner.js +183 -0
- package/dist/daemon/dist/engine/sync/agent-store.js +177 -0
- package/dist/daemon/dist/engine/sync/agent-sync.js +132 -0
- package/dist/daemon/dist/engine/sync/apply-review.js +52 -0
- package/dist/daemon/dist/engine/sync/conflict-artifact-ownership.js +53 -0
- package/dist/daemon/dist/engine/sync/conflict-artifacts.js +158 -0
- package/dist/daemon/dist/engine/sync/conflict-groups.js +76 -0
- package/dist/daemon/dist/engine/sync/conflict-preview.js +53 -0
- package/dist/daemon/dist/engine/sync/conflict-resolution.js +53 -0
- package/dist/daemon/dist/engine/sync/conflict-retention.js +61 -0
- package/dist/daemon/dist/engine/sync/conflict-review.js +73 -0
- package/dist/daemon/dist/engine/sync/content-conflicts.js +70 -0
- package/dist/daemon/dist/engine/sync/continuous-errors.js +66 -0
- package/dist/daemon/dist/engine/sync/continuous-lease.js +206 -0
- package/dist/daemon/dist/engine/sync/continuous-record.js +199 -0
- package/dist/daemon/dist/engine/sync/continuous-storage.js +59 -0
- package/dist/daemon/dist/engine/sync/continuous-sync.js +521 -0
- package/dist/daemon/dist/engine/sync/continuous-watch.js +140 -0
- package/dist/daemon/dist/engine/sync/exclude-policy.js +86 -0
- package/dist/daemon/dist/engine/sync/field-migration.js +20 -0
- package/dist/daemon/dist/engine/sync/file-merge-planner.js +123 -0
- package/dist/daemon/dist/engine/sync/initialization.js +80 -0
- package/dist/daemon/dist/engine/sync/json-document.js +172 -0
- package/dist/daemon/dist/engine/sync/local-field-policy.js +26 -0
- package/dist/daemon/dist/engine/sync/local-fields.js +196 -0
- package/dist/daemon/dist/engine/sync/merge-apply.js +529 -0
- package/dist/daemon/dist/engine/sync/merge-journal.js +295 -0
- package/dist/daemon/dist/engine/sync/merge-transfer-error.js +64 -0
- package/dist/daemon/dist/engine/sync/merged-sync.js +674 -0
- package/dist/daemon/dist/engine/sync/mutation-owner.js +18 -0
- package/dist/daemon/dist/engine/sync/package-merge.js +82 -0
- package/dist/daemon/dist/engine/sync/partial-progress.js +41 -0
- package/dist/daemon/dist/engine/sync/remote-snapshot.js +104 -0
- package/dist/daemon/dist/engine/sync/resolver-stream.js +34 -0
- package/dist/daemon/dist/engine/sync/session-merge.js +178 -0
- package/dist/daemon/dist/engine/sync/session-push.js +33 -0
- package/dist/daemon/dist/engine/sync/settings-conflicts.js +56 -0
- package/dist/daemon/dist/engine/sync/settings-merge.js +93 -0
- package/dist/daemon/dist/engine/sync/signals.js +8 -0
- package/dist/daemon/dist/engine/sync/startup-timings.js +44 -0
- package/dist/daemon/dist/engine/sync/sync-decision.js +81 -0
- package/dist/daemon/dist/engine/sync/sync-error-guidance.js +55 -0
- package/dist/daemon/dist/engine/sync/sync-errors.js +18 -0
- package/dist/daemon/dist/engine/sync/sync-inspection.js +42 -0
- package/dist/daemon/dist/engine/sync/sync-loaders.js +8 -0
- package/dist/daemon/dist/engine/sync/sync-local.js +40 -0
- package/dist/daemon/dist/engine/sync/sync-mutations.js +733 -0
- package/dist/daemon/dist/engine/sync/sync-operations.js +3 -0
- package/dist/daemon/dist/engine/sync/sync-policy.js +621 -0
- package/dist/daemon/dist/engine/sync/sync-queries.js +212 -0
- package/dist/daemon/dist/engine/sync/sync-state.js +129 -0
- package/dist/daemon/dist/engine/sync/text-merge.js +124 -0
- package/dist/daemon/dist/engine/types.js +2 -0
- package/dist/daemon/dist/engine/ui/merge-review.js +7 -0
- package/dist/daemon/dist/engine/ui/merged-sync-summary.js +86 -0
- package/dist/daemon/dist/engine/ui/sync-format.js +165 -0
- package/dist/daemon/dist/engine/ui/sync-status.js +30 -0
- package/dist/daemon/dist/engine/ui/terminal-text.js +9 -0
- package/dist/daemon/dist/engine/ui/transfer-changes.js +24 -0
- package/dist/daemon/dist/engine/ui/transfer-review.js +19 -0
- package/dist/daemon/dist/engine-service.js +344 -0
- package/dist/daemon/dist/identity.js +241 -0
- package/dist/daemon/dist/idle-exit.js +77 -0
- package/dist/daemon/dist/index.js +4 -0
- package/dist/daemon/dist/lifecycle-log.js +53 -0
- package/dist/daemon/dist/lifecycle.js +21 -0
- package/dist/daemon/dist/model-signature.js +7 -0
- package/dist/daemon/dist/monitor.js +272 -0
- package/dist/daemon/dist/participant-admission.js +30 -0
- package/dist/daemon/dist/protocol.js +104 -0
- package/dist/daemon/dist/resolver-host.js +78 -0
- package/dist/daemon/dist/server.js +953 -0
- package/dist/daemon/dist/service-host.js +174 -0
- package/dist/daemon/dist/upgrade-repair.js +55 -0
- package/dist/daemon/package.json +3 -0
- package/dist/index.ts +21 -21
- package/dist/package.json +6 -0
- package/docs/daemon-migration.md +27 -16
- package/package.json +9 -3
- package/skills/configure-pi-sync/SKILL.md +38 -13
- package/skills/configure-pi-sync/references/configuration.md +2 -2
- package/src/commands/command-execution.ts +1 -1
- package/src/settings/config.ts +1 -0
- package/src/sync/sync-operations.ts +18 -10
- package/src/ui/excluded-paths-ui.ts +4 -1
- package/src/ui/ignore-file-ui.ts +271 -0
- package/src/ui/ignore-migration-prompt.ts +65 -0
- package/src/ui/manager-state.ts +27 -13
- package/src/ui/manager-ui.ts +38 -19
- package/src/ui/remote-selection-ui.ts +41 -8
- package/src/ui/settings-review.ts +26 -0
- package/src/ui/settings-ui.ts +316 -213
- package/src/ui/storage-connections-ui.ts +20 -12
- package/src/ui/sync-setups-ui.ts +45 -27
- package/dist/chunks/chunk-2ZGV5KNC.ts.map +0 -7
- package/dist/chunks/chunk-JVFCVPPD.ts.map +0 -7
- package/dist/chunks/command-handler-K4XJOGYC.ts.map +0 -7
- package/dist/chunks/manager-result-dispatcher-4VJVDEUD.ts +0 -19
- package/dist/chunks/manager-ui-KYQ5AZJS.ts.map +0 -7
- package/dist/chunks/remote-selection-ui-W3KOZM3W.ts +0 -18
- package/dist/chunks/sync-operations-BVWYYKH3.ts.map +0 -7
- /package/dist/chunks/{chunk-EMVZL4PH.ts.map → chunk-3E3TR3JE.ts.map} +0 -0
- /package/dist/chunks/{chunk-ZIL6PW5L.ts.map → chunk-6YKOHBSC.ts.map} +0 -0
- /package/dist/chunks/{chunk-OA4NZLSL.ts.map → chunk-APZVJAEW.ts.map} +0 -0
- /package/dist/chunks/{chunk-4SR3ZYHA.ts.map → chunk-GELYN4UC.ts.map} +0 -0
- /package/dist/chunks/{chunk-S7F4FOAS.ts.map → chunk-GSCZ4VXV.ts.map} +0 -0
- /package/dist/chunks/{chunk-YQSFJLJ3.ts.map → chunk-IBXEM35O.ts.map} +0 -0
- /package/dist/chunks/{chunk-E3YLRLJM.ts.map → chunk-INECVQNR.ts.map} +0 -0
- /package/dist/chunks/{chunk-2JHAN3ZO.ts.map → chunk-JREGWM2B.ts.map} +0 -0
- /package/dist/chunks/{chunk-EMRFVLZM.ts.map → chunk-NXWHPVXR.ts.map} +0 -0
- /package/dist/chunks/{chunk-SMVKMYLK.ts.map → chunk-P4GI7LTT.ts.map} +0 -0
- /package/dist/chunks/{chunk-PJMM75W5.ts.map → chunk-PWESMTH6.ts.map} +0 -0
- /package/dist/chunks/{chunk-ZVGRZD4C.ts.map → chunk-R3SAMXB6.ts.map} +0 -0
- /package/dist/chunks/{chunk-RNIEVDTR.ts.map → chunk-T3LABNHF.ts.map} +0 -0
- /package/dist/chunks/{chunk-S3R3W3KF.ts.map → chunk-UMPA5S7X.ts.map} +0 -0
- /package/dist/chunks/{chunk-WP2M67XZ.ts.map → chunk-WBIOSK76.ts.map} +0 -0
- /package/dist/chunks/{chunk-4KTJLJSJ.ts.map → chunk-ZB3GNX3P.ts.map} +0 -0
- /package/dist/chunks/{chunk-HEB6YT64.ts.map → chunk-ZO52JM4H.ts.map} +0 -0
- /package/dist/chunks/{conflict-review-IGKY2TOJ.ts.map → conflict-review-MAOGTIAI.ts.map} +0 -0
- /package/dist/chunks/{continuous-record-3XDXDOMV.ts.map → continuous-record-3SKJ6I3V.ts.map} +0 -0
- /package/dist/chunks/{continuous-storage-HLKCHF6Z.ts.map → continuous-storage-3EU6I7Z3.ts.map} +0 -0
- /package/dist/chunks/{file-selection-MGGVOKM7.ts.map → file-selection-QR2KZVGD.ts.map} +0 -0
- /package/dist/chunks/{manager-result-dispatcher-4VJVDEUD.ts.map → manager-result-dispatcher-MC6EQOQY.ts.map} +0 -0
- /package/dist/chunks/{remote-selection-ui-W3KOZM3W.ts.map → remote-selection-ui-4BTP2OJR.ts.map} +0 -0
- /package/dist/chunks/{setup-switch-D6K6PBPC.ts.map → setup-switch-Y6AMFFNK.ts.map} +0 -0
- /package/dist/chunks/{setup-wizard-4DYUDHJR.ts.map → setup-wizard-5G426MOZ.ts.map} +0 -0
- /package/dist/chunks/{snapshot-5HY3M2NL.ts.map → snapshot-ZUJJZCFW.ts.map} +0 -0
- /package/dist/chunks/{snapshot-transaction-directory-OU2D7R7A.ts.map → snapshot-transaction-directory-F46JWRAU.ts.map} +0 -0
- /package/dist/chunks/{state-directory-XXHU73Z3.ts.map → state-directory-CMAIF34J.ts.map} +0 -0
- /package/dist/chunks/{sync-inspection-J3CRBORL.ts.map → sync-inspection-ITZ6Z4DE.ts.map} +0 -0
- /package/dist/chunks/{sync-state-2LMIXJ2C.ts.map → sync-state-QIT64TKV.ts.map} +0 -0
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { lstatSync, realpathSync } from "node:fs";
|
|
3
|
+
import fs from "node:fs/promises";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { MAX_MESSAGE_BYTES, record } from "./protocol.js";
|
|
7
|
+
export function canonicalRootGuard(root) {
|
|
8
|
+
const identity = lstatSync(root);
|
|
9
|
+
return () => {
|
|
10
|
+
const current = lstatSync(root);
|
|
11
|
+
if (!current.isDirectory() ||
|
|
12
|
+
current.isSymbolicLink() ||
|
|
13
|
+
current.dev !== identity.dev ||
|
|
14
|
+
current.ino !== identity.ino ||
|
|
15
|
+
realpathSync(root) !== root)
|
|
16
|
+
throw new Error("Canonical agent root changed; work stopped and recovery evidence retained.");
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
export async function runtimePaths(root) {
|
|
20
|
+
const canonical = await fs.realpath(path.resolve(root));
|
|
21
|
+
const hash = createHash("sha256").update(canonical).digest("hex");
|
|
22
|
+
const user = process.getuid?.() ?? createHash("sha256").update(os.homedir()).digest("hex").slice(0, 12);
|
|
23
|
+
const base = process.platform === "win32" ? path.join(os.homedir(), "AppData", "Local") : "/tmp";
|
|
24
|
+
// Keep the original namespace so the package rename cannot create a second root owner.
|
|
25
|
+
const directory = path.join(base, `sync-daemon-${user}`, hash);
|
|
26
|
+
return {
|
|
27
|
+
root: canonical,
|
|
28
|
+
directory,
|
|
29
|
+
identity: path.join(directory, "identity.json"),
|
|
30
|
+
startup: path.join(directory, "startup.lock"),
|
|
31
|
+
owner: path.join(directory, "owner.lock"),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export function daemonPaths(paths, instance) {
|
|
35
|
+
const nonce = createHash("sha256").update(instance).digest("hex").slice(0, 16);
|
|
36
|
+
const root = path.basename(paths.directory).slice(0, 16);
|
|
37
|
+
const endpointDirectory = path.join(path.dirname(paths.directory), `${root}-${nonce}`);
|
|
38
|
+
const endpoint = process.platform === "win32"
|
|
39
|
+
? `\\\\.\\pipe\\sync-daemon-${path.basename(path.dirname(paths.directory))}-${root}-${nonce}`
|
|
40
|
+
: path.join(endpointDirectory, "api.sock");
|
|
41
|
+
if (process.platform !== "win32" && Buffer.byteLength(endpoint) > 103)
|
|
42
|
+
throw new Error("Daemon endpoint path is too long.");
|
|
43
|
+
return { ...paths, endpoint, ...(process.platform === "win32" ? {} : { endpointDirectory }) };
|
|
44
|
+
}
|
|
45
|
+
export async function privateDirectory(directory) {
|
|
46
|
+
const parent = path.dirname(directory);
|
|
47
|
+
if (parent !== path.dirname(parent) && path.basename(parent).startsWith("sync-daemon-"))
|
|
48
|
+
await privateDirectory(parent);
|
|
49
|
+
try {
|
|
50
|
+
await fs.mkdir(directory, { mode: 0o700 });
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
if (error.code !== "EEXIST")
|
|
54
|
+
throw error;
|
|
55
|
+
}
|
|
56
|
+
const stat = await fs.lstat(directory);
|
|
57
|
+
if (!stat.isDirectory() ||
|
|
58
|
+
stat.isSymbolicLink() ||
|
|
59
|
+
(process.getuid && stat.uid !== process.getuid()) ||
|
|
60
|
+
(process.platform !== "win32" && (stat.mode & 0o077) !== 0))
|
|
61
|
+
throw new Error("Unsafe daemon runtime directory.");
|
|
62
|
+
}
|
|
63
|
+
const birthPattern = /^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}:([1-9][0-9]{0,9})\.([1-9][0-9]{0,9}):(0|[1-9][0-9]{0,19})$/u;
|
|
64
|
+
export function upgradeFile(paths) {
|
|
65
|
+
return path.join(paths.directory, "upgrade-owner.json");
|
|
66
|
+
}
|
|
67
|
+
/** One private archive per upgrade instance, including across partial repair retries. */
|
|
68
|
+
export function upgradeArchivePath(paths, owner) {
|
|
69
|
+
return path.join(paths.directory, `upgrade-recovery-${owner.instance}`);
|
|
70
|
+
}
|
|
71
|
+
/** A repair must finish explicitly once it starts changing consent or moving evidence. */
|
|
72
|
+
export async function upgradeRepairStarted(paths, owner) {
|
|
73
|
+
try {
|
|
74
|
+
await fs.lstat(upgradeArchivePath(paths, owner));
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
if (error.code === "ENOENT")
|
|
79
|
+
return false;
|
|
80
|
+
throw error;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
export async function readUpgradeOwner(paths) {
|
|
84
|
+
const value = await readPrivateRecord(upgradeFile(paths));
|
|
85
|
+
if (value === undefined)
|
|
86
|
+
return;
|
|
87
|
+
if (!validOwner(value, paths.root) || (value.birth !== undefined && !validBirth(value.birth)))
|
|
88
|
+
throw new Error("Invalid daemon upgrade record; state retained.");
|
|
89
|
+
const { version, root, instance, pid, birth } = value;
|
|
90
|
+
return birth === undefined ? { version, root, instance, pid } : { version, root, instance, pid, birth };
|
|
91
|
+
}
|
|
92
|
+
export function recordUpgradeOwner(paths, { version, root, instance, pid, birth }) {
|
|
93
|
+
return publishPrivateRecord(paths, upgradeFile(paths), { version, root, instance, pid, birth });
|
|
94
|
+
}
|
|
95
|
+
export function clearUpgradeOwner(paths) {
|
|
96
|
+
return fs.rm(upgradeFile(paths), { force: true });
|
|
97
|
+
}
|
|
98
|
+
export async function readIdentity(paths) {
|
|
99
|
+
const value = await readPrivateRecord(paths.identity);
|
|
100
|
+
if (value === undefined)
|
|
101
|
+
return;
|
|
102
|
+
if (!validOwner(value, paths.root) || typeof value.token !== "string" || !/^[a-f0-9]{64}$/u.test(value.token))
|
|
103
|
+
throw new Error("Invalid or incompatible daemon identity; state retained.");
|
|
104
|
+
return { ...value, token: value.token };
|
|
105
|
+
}
|
|
106
|
+
function validBirth(value) {
|
|
107
|
+
const fields = typeof value === "string" && birthPattern.exec(value);
|
|
108
|
+
return (!!fields &&
|
|
109
|
+
Number(fields[1]) <= 0xffff_ffff &&
|
|
110
|
+
Number(fields[2]) <= 0xffff_ffff &&
|
|
111
|
+
BigInt(fields[3]) <= 0xffffffffffffffffn);
|
|
112
|
+
}
|
|
113
|
+
function validOwner(value, root) {
|
|
114
|
+
return (record(value) &&
|
|
115
|
+
value.version === 1 &&
|
|
116
|
+
value.root === root &&
|
|
117
|
+
typeof value.instance === "string" &&
|
|
118
|
+
/^[a-f0-9-]{36}$/u.test(value.instance) &&
|
|
119
|
+
Number.isSafeInteger(value.pid) &&
|
|
120
|
+
Number(value.pid) >= 1 &&
|
|
121
|
+
Number(value.pid) <= 2_147_483_647);
|
|
122
|
+
}
|
|
123
|
+
async function readPrivateRecord(file) {
|
|
124
|
+
let handle;
|
|
125
|
+
try {
|
|
126
|
+
const before = await fs.lstat(file);
|
|
127
|
+
if (!before.isFile() ||
|
|
128
|
+
before.isSymbolicLink() ||
|
|
129
|
+
before.size > 8192 ||
|
|
130
|
+
(process.getuid && before.uid !== process.getuid()) ||
|
|
131
|
+
(process.platform !== "win32" && (before.mode & 0o077) !== 0))
|
|
132
|
+
throw new Error("Unsafe daemon identity file.");
|
|
133
|
+
handle = await fs.open(file, "r");
|
|
134
|
+
const opened = await handle.stat();
|
|
135
|
+
if (before.dev !== opened.dev || before.ino !== opened.ino)
|
|
136
|
+
throw new Error("Daemon identity changed while opening.");
|
|
137
|
+
return JSON.parse(await handle.readFile("utf8"));
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
if (error.code === "ENOENT")
|
|
141
|
+
return;
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
finally {
|
|
145
|
+
await handle?.close();
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
export function processExists(pid) {
|
|
149
|
+
try {
|
|
150
|
+
process.kill(pid, 0);
|
|
151
|
+
return true;
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
return error.code !== "ESRCH";
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
async function readPidNamespace() {
|
|
158
|
+
const scope = await fs.readlink("/proc/self/ns/pid");
|
|
159
|
+
return /^pid:\[([0-9]+)\]$/u.exec(scope)?.[1];
|
|
160
|
+
}
|
|
161
|
+
/** Linux start ticks from a procfs view that agrees with the caller's PID namespace. */
|
|
162
|
+
export async function readProcessBirth(pid) {
|
|
163
|
+
if (process.platform !== "linux")
|
|
164
|
+
return;
|
|
165
|
+
try {
|
|
166
|
+
const [status, pidNamespace, timeScope, boot, stat] = await Promise.all([
|
|
167
|
+
fs.readFile("/proc/self/status", "utf8"),
|
|
168
|
+
readPidNamespace(),
|
|
169
|
+
fs.readlink("/proc/self/ns/time"),
|
|
170
|
+
fs.readFile("/proc/sys/kernel/random/boot_id", "utf8"),
|
|
171
|
+
fs.readFile(`/proc/${pid}/stat`, "utf8"),
|
|
172
|
+
]);
|
|
173
|
+
if (/^NSpid:[\t ]+([0-9]+)[\t ]*$/mu.exec(status)?.[1] !== String(process.pid))
|
|
174
|
+
return;
|
|
175
|
+
// The kernel offsets start ticks using the reader's time namespace.
|
|
176
|
+
const timeNamespace = /^time:\[([0-9]+)\]$/u.exec(timeScope)?.[1];
|
|
177
|
+
if (pidNamespace === undefined || timeNamespace === undefined || !stat.startsWith(`${pid} (`))
|
|
178
|
+
return;
|
|
179
|
+
// The parenthesized comm can contain spaces, parentheses, and newlines. Starttime is field 22.
|
|
180
|
+
const end = stat.lastIndexOf(") ");
|
|
181
|
+
if (end < String(pid).length + 2)
|
|
182
|
+
return;
|
|
183
|
+
const ticks = stat
|
|
184
|
+
.slice(end + 2)
|
|
185
|
+
.trim()
|
|
186
|
+
.split(/\s+/u)[19];
|
|
187
|
+
const birth = `${boot.trim()}:${pidNamespace}.${timeNamespace}:${ticks}`;
|
|
188
|
+
if (validBirth(birth))
|
|
189
|
+
return birth;
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
// Missing or unreadable procfs is not evidence of process exit.
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
/** A marked owner must be visible in the same PID namespace before absence proves exit. */
|
|
196
|
+
export async function processExited({ pid, birth }) {
|
|
197
|
+
const exists = processExists(pid);
|
|
198
|
+
if (birth === undefined)
|
|
199
|
+
return !exists; // Legacy PID-only records.
|
|
200
|
+
if (process.platform !== "linux" || !validBirth(birth))
|
|
201
|
+
return false;
|
|
202
|
+
const namespaces = birth.split(":")[1];
|
|
203
|
+
if (!exists) {
|
|
204
|
+
try {
|
|
205
|
+
return (await readPidNamespace()) === namespaces.split(".")[0];
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
return false;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
const current = await readProcessBirth(pid);
|
|
212
|
+
return current !== undefined && current !== birth && current.split(":")[1] === namespaces;
|
|
213
|
+
}
|
|
214
|
+
export function publishIdentity(paths, identity) {
|
|
215
|
+
return publishPrivateRecord(paths, paths.identity, identity);
|
|
216
|
+
}
|
|
217
|
+
async function publishPrivateRecord(paths, file, value) {
|
|
218
|
+
const temporary = path.join(paths.directory, `.${randomUUID()}.json`);
|
|
219
|
+
const handle = await fs.open(temporary, "wx", 0o600);
|
|
220
|
+
try {
|
|
221
|
+
await handle.writeFile(JSON.stringify(value));
|
|
222
|
+
await handle.sync();
|
|
223
|
+
await handle.close();
|
|
224
|
+
await fs.rename(temporary, file);
|
|
225
|
+
}
|
|
226
|
+
finally {
|
|
227
|
+
await handle.close().catch(() => { });
|
|
228
|
+
await fs.rm(temporary, { force: true });
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
export async function readJsonBody(source) {
|
|
232
|
+
const chunks = [];
|
|
233
|
+
let size = 0;
|
|
234
|
+
for await (const chunk of source) {
|
|
235
|
+
size += chunk.byteLength;
|
|
236
|
+
if (size > MAX_MESSAGE_BYTES)
|
|
237
|
+
throw new Error("Daemon request exceeds its byte limit.");
|
|
238
|
+
chunks.push(Buffer.from(chunk));
|
|
239
|
+
}
|
|
240
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
241
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
export const IDLE_EXIT_GRACE_MS = 30_000;
|
|
2
|
+
/** The server heartbeat owns timing; this controller owns only one guarded deadline and evaluation. */
|
|
3
|
+
export function createIdleExit(hooks) {
|
|
4
|
+
let generation = 0;
|
|
5
|
+
let stopped = false;
|
|
6
|
+
let failed = false;
|
|
7
|
+
let emptySince;
|
|
8
|
+
let running;
|
|
9
|
+
const changed = () => {
|
|
10
|
+
generation++;
|
|
11
|
+
if (hooks.live())
|
|
12
|
+
emptySince = undefined;
|
|
13
|
+
};
|
|
14
|
+
async function evaluate() {
|
|
15
|
+
if (stopped || failed)
|
|
16
|
+
return;
|
|
17
|
+
if (hooks.live()) {
|
|
18
|
+
emptySince = undefined;
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
const epoch = generation;
|
|
22
|
+
const current = () => !stopped && !failed && generation === epoch && !hooks.live();
|
|
23
|
+
let quiesced = false;
|
|
24
|
+
try {
|
|
25
|
+
const policy = await hooks.policy();
|
|
26
|
+
if (!current())
|
|
27
|
+
return;
|
|
28
|
+
if (policy !== "exit") {
|
|
29
|
+
emptySince = undefined;
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
emptySince ??= Date.now();
|
|
33
|
+
if (Date.now() - emptySince < IDLE_EXIT_GRACE_MS)
|
|
34
|
+
return;
|
|
35
|
+
quiesced = true;
|
|
36
|
+
await hooks.quiesce();
|
|
37
|
+
if (!current())
|
|
38
|
+
return;
|
|
39
|
+
const latest = await hooks.policy();
|
|
40
|
+
if (!current())
|
|
41
|
+
return;
|
|
42
|
+
if (latest !== "exit") {
|
|
43
|
+
emptySince = undefined;
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
if (await hooks.close(current))
|
|
47
|
+
stopped = true;
|
|
48
|
+
else if (hooks.live())
|
|
49
|
+
emptySince = undefined;
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
// A failed drain must not be cleared by an implicit restart or another heartbeat.
|
|
53
|
+
failed = true;
|
|
54
|
+
hooks.failed();
|
|
55
|
+
}
|
|
56
|
+
finally {
|
|
57
|
+
if (quiesced && !stopped && !failed)
|
|
58
|
+
hooks.resume();
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
changed,
|
|
63
|
+
tick() {
|
|
64
|
+
if (!running) {
|
|
65
|
+
running = evaluate().finally(() => {
|
|
66
|
+
running = undefined;
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
return running;
|
|
70
|
+
},
|
|
71
|
+
async dispose() {
|
|
72
|
+
stopped = true;
|
|
73
|
+
generation++;
|
|
74
|
+
await running;
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { DaemonConnection, DaemonError, ensureDaemon, findDaemon, requestDaemon, stopDaemon, waitForDaemonExit, } from "./client.js";
|
|
2
|
+
export { documentFingerprint } from "./document.js";
|
|
3
|
+
export { modelSignature } from "./model-signature.js";
|
|
4
|
+
export { MAX_SETTINGS_BYTES, PROTOCOL_VERSION } from "./protocol.js";
|
|
@@ -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,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,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,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
|
+
}
|