@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.
- package/CHANGELOG.md +13 -0
- package/LICENSE +21 -0
- package/README.md +89 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +128 -0
- package/dist/client.d.ts +55 -0
- package/dist/client.js +484 -0
- package/dist/consent.d.ts +24 -0
- package/dist/consent.js +205 -0
- package/dist/document.d.ts +10 -0
- package/dist/document.js +6 -0
- package/dist/endpoint.d.ts +8 -0
- package/dist/endpoint.js +91 -0
- package/dist/engine/backends/backend-factory.d.ts +6 -0
- package/dist/engine/backends/backend-factory.js +16 -0
- package/dist/engine/backends/backend-identity.d.ts +3 -0
- package/dist/engine/backends/backend-identity.js +38 -0
- package/dist/engine/backends/backend-types.d.ts +70 -0
- package/dist/engine/backends/backend-types.js +1 -0
- package/dist/engine/backends/git/git-backend.d.ts +55 -0
- package/dist/engine/backends/git/git-backend.js +700 -0
- package/dist/engine/backends/git/git-config.d.ts +5 -0
- package/dist/engine/backends/git/git-config.js +118 -0
- package/dist/engine/backends/git/git-runner.d.ts +25 -0
- package/dist/engine/backends/git/git-runner.js +232 -0
- package/dist/engine/backends/git/git-storage.d.ts +39 -0
- package/dist/engine/backends/git/git-storage.js +226 -0
- package/dist/engine/backends/s3/s3-backend.d.ts +32 -0
- package/dist/engine/backends/s3/s3-backend.js +436 -0
- package/dist/engine/backends/s3/s3-client.d.ts +36 -0
- package/dist/engine/backends/s3/s3-client.js +352 -0
- package/dist/engine/backends/s3/s3-conditions.d.ts +4 -0
- package/dist/engine/backends/s3/s3-conditions.js +66 -0
- package/dist/engine/backends/snapshot-pointer.d.ts +6 -0
- package/dist/engine/backends/snapshot-pointer.js +22 -0
- package/dist/engine/backends/sync-backend.d.ts +71 -0
- package/dist/engine/backends/sync-backend.js +23 -0
- package/dist/engine/backends/webdav/webdav-backend.d.ts +34 -0
- package/dist/engine/backends/webdav/webdav-backend.js +534 -0
- package/dist/engine/backends/webdav/webdav-client.d.ts +36 -0
- package/dist/engine/backends/webdav/webdav-client.js +326 -0
- package/dist/engine/backends/webdav/webdav-config.d.ts +5 -0
- package/dist/engine/backends/webdav/webdav-config.js +73 -0
- package/dist/engine/commands/command-types.d.ts +31 -0
- package/dist/engine/commands/command-types.js +1 -0
- package/dist/engine/host.d.ts +70 -0
- package/dist/engine/host.js +16 -0
- package/dist/engine/paths.d.ts +9 -0
- package/dist/engine/paths.js +71 -0
- package/dist/engine/settings/config-errors.d.ts +1 -0
- package/dist/engine/settings/config-errors.js +4 -0
- package/dist/engine/settings/config-file.d.ts +33 -0
- package/dist/engine/settings/config-file.js +630 -0
- package/dist/engine/settings/config.d.ts +24 -0
- package/dist/engine/settings/config.js +200 -0
- package/dist/engine/settings/settings-management.d.ts +24 -0
- package/dist/engine/settings/settings-management.js +191 -0
- package/dist/engine/settings/settings-store.d.ts +8 -0
- package/dist/engine/settings/settings-store.js +41 -0
- package/dist/engine/settings/settings-types.d.ts +134 -0
- package/dist/engine/settings/settings-types.js +1 -0
- package/dist/engine/settings/settings-validation.d.ts +15 -0
- package/dist/engine/settings/settings-validation.js +356 -0
- package/dist/engine/snapshot/session-paths.d.ts +12 -0
- package/dist/engine/snapshot/session-paths.js +91 -0
- package/dist/engine/snapshot/snapshot-apply.d.ts +22 -0
- package/dist/engine/snapshot/snapshot-apply.js +262 -0
- package/dist/engine/snapshot/snapshot-case-replacement.d.ts +15 -0
- package/dist/engine/snapshot/snapshot-case-replacement.js +82 -0
- package/dist/engine/snapshot/snapshot-codec.d.ts +6 -0
- package/dist/engine/snapshot/snapshot-codec.js +53 -0
- package/dist/engine/snapshot/snapshot-exclude-safety.d.ts +7 -0
- package/dist/engine/snapshot/snapshot-exclude-safety.js +47 -0
- package/dist/engine/snapshot/snapshot-mutation-queues.d.ts +9 -0
- package/dist/engine/snapshot/snapshot-mutation-queues.js +133 -0
- package/dist/engine/snapshot/snapshot-paths.d.ts +1 -0
- package/dist/engine/snapshot/snapshot-paths.js +11 -0
- package/dist/engine/snapshot/snapshot-root-transition.d.ts +25 -0
- package/dist/engine/snapshot/snapshot-root-transition.js +122 -0
- package/dist/engine/snapshot/snapshot-transaction-directory.d.ts +2 -0
- package/dist/engine/snapshot/snapshot-transaction-directory.js +16 -0
- package/dist/engine/snapshot/snapshot-transaction-plan.d.ts +12 -0
- package/dist/engine/snapshot/snapshot-transaction-plan.js +68 -0
- package/dist/engine/snapshot/snapshot-transaction.d.ts +15 -0
- package/dist/engine/snapshot/snapshot-transaction.js +787 -0
- package/dist/engine/snapshot/snapshot-types.d.ts +48 -0
- package/dist/engine/snapshot/snapshot-types.js +1 -0
- package/dist/engine/snapshot/snapshot.d.ts +30 -0
- package/dist/engine/snapshot/snapshot.js +364 -0
- package/dist/engine/state/json-file.d.ts +6 -0
- package/dist/engine/state/json-file.js +49 -0
- package/dist/engine/state/lock-policy.d.ts +2 -0
- package/dist/engine/state/lock-policy.js +2 -0
- package/dist/engine/state/lock.d.ts +20 -0
- package/dist/engine/state/lock.js +259 -0
- package/dist/engine/state/lockfile-fs.d.ts +13 -0
- package/dist/engine/state/lockfile-fs.js +13 -0
- package/dist/engine/state/merge-baseline-store.d.ts +11 -0
- package/dist/engine/state/merge-baseline-store.js +187 -0
- package/dist/engine/state/mutation-directory-sync.d.ts +5 -0
- package/dist/engine/state/mutation-directory-sync.js +34 -0
- package/dist/engine/state/operation-availability.d.ts +49 -0
- package/dist/engine/state/operation-availability.js +40 -0
- package/dist/engine/state/state-directory.d.ts +14 -0
- package/dist/engine/state/state-directory.js +225 -0
- package/dist/engine/state/state-types.d.ts +27 -0
- package/dist/engine/state/state-types.js +1 -0
- package/dist/engine/state/sync-state-store.d.ts +11 -0
- package/dist/engine/state/sync-state-store.js +54 -0
- package/dist/engine/sync/agent-candidate.d.ts +44 -0
- package/dist/engine/sync/agent-candidate.js +207 -0
- package/dist/engine/sync/agent-plan.d.ts +8 -0
- package/dist/engine/sync/agent-plan.js +84 -0
- package/dist/engine/sync/agent-policy.d.ts +9 -0
- package/dist/engine/sync/agent-policy.js +10 -0
- package/dist/engine/sync/agent-refusal-retry.d.ts +4 -0
- package/dist/engine/sync/agent-refusal-retry.js +39 -0
- package/dist/engine/sync/agent-request.d.ts +14 -0
- package/dist/engine/sync/agent-request.js +13 -0
- package/dist/engine/sync/agent-runner.d.ts +6 -0
- package/dist/engine/sync/agent-runner.js +183 -0
- package/dist/engine/sync/agent-store.d.ts +7 -0
- package/dist/engine/sync/agent-store.js +177 -0
- package/dist/engine/sync/agent-sync.d.ts +4 -0
- package/dist/engine/sync/agent-sync.js +132 -0
- package/dist/engine/sync/apply-review.d.ts +8 -0
- package/dist/engine/sync/apply-review.js +51 -0
- package/dist/engine/sync/conflict-artifact-ownership.d.ts +4 -0
- package/dist/engine/sync/conflict-artifact-ownership.js +53 -0
- package/dist/engine/sync/conflict-artifacts.d.ts +32 -0
- package/dist/engine/sync/conflict-artifacts.js +158 -0
- package/dist/engine/sync/conflict-groups.d.ts +9 -0
- package/dist/engine/sync/conflict-groups.js +76 -0
- package/dist/engine/sync/conflict-preview.d.ts +4 -0
- package/dist/engine/sync/conflict-preview.js +53 -0
- package/dist/engine/sync/conflict-resolution.d.ts +13 -0
- package/dist/engine/sync/conflict-resolution.js +53 -0
- package/dist/engine/sync/conflict-retention.d.ts +5 -0
- package/dist/engine/sync/conflict-retention.js +61 -0
- package/dist/engine/sync/conflict-review.d.ts +4 -0
- package/dist/engine/sync/conflict-review.js +73 -0
- package/dist/engine/sync/content-conflicts.d.ts +10 -0
- package/dist/engine/sync/content-conflicts.js +70 -0
- package/dist/engine/sync/continuous-errors.d.ts +14 -0
- package/dist/engine/sync/continuous-errors.js +66 -0
- package/dist/engine/sync/continuous-lease.d.ts +9 -0
- package/dist/engine/sync/continuous-lease.js +206 -0
- package/dist/engine/sync/continuous-record.d.ts +31 -0
- package/dist/engine/sync/continuous-record.js +199 -0
- package/dist/engine/sync/continuous-storage.d.ts +14 -0
- package/dist/engine/sync/continuous-storage.js +59 -0
- package/dist/engine/sync/continuous-sync.d.ts +15 -0
- package/dist/engine/sync/continuous-sync.js +496 -0
- package/dist/engine/sync/continuous-watch.d.ts +3 -0
- package/dist/engine/sync/continuous-watch.js +65 -0
- package/dist/engine/sync/exclude-policy.d.ts +5 -0
- package/dist/engine/sync/exclude-policy.js +79 -0
- package/dist/engine/sync/field-migration.d.ts +5 -0
- package/dist/engine/sync/field-migration.js +20 -0
- package/dist/engine/sync/file-merge-planner.d.ts +36 -0
- package/dist/engine/sync/file-merge-planner.js +123 -0
- package/dist/engine/sync/initialization.d.ts +12 -0
- package/dist/engine/sync/initialization.js +75 -0
- package/dist/engine/sync/json-document.d.ts +29 -0
- package/dist/engine/sync/json-document.js +172 -0
- package/dist/engine/sync/local-field-policy.d.ts +2 -0
- package/dist/engine/sync/local-field-policy.js +26 -0
- package/dist/engine/sync/local-fields.d.ts +9 -0
- package/dist/engine/sync/local-fields.js +116 -0
- package/dist/engine/sync/merge-apply.d.ts +5 -0
- package/dist/engine/sync/merge-apply.js +386 -0
- package/dist/engine/sync/merge-journal.d.ts +31 -0
- package/dist/engine/sync/merge-journal.js +179 -0
- package/dist/engine/sync/merge-transfer-error.d.ts +3 -0
- package/dist/engine/sync/merge-transfer-error.js +64 -0
- package/dist/engine/sync/merged-sync.d.ts +6 -0
- package/dist/engine/sync/merged-sync.js +618 -0
- package/dist/engine/sync/mutation-owner.d.ts +2 -0
- package/dist/engine/sync/mutation-owner.js +18 -0
- package/dist/engine/sync/package-merge.d.ts +3 -0
- package/dist/engine/sync/package-merge.js +82 -0
- package/dist/engine/sync/partial-progress.d.ts +15 -0
- package/dist/engine/sync/partial-progress.js +39 -0
- package/dist/engine/sync/remote-snapshot.d.ts +28 -0
- package/dist/engine/sync/remote-snapshot.js +62 -0
- package/dist/engine/sync/resolver-stream.d.ts +4 -0
- package/dist/engine/sync/resolver-stream.js +34 -0
- package/dist/engine/sync/session-merge.d.ts +3 -0
- package/dist/engine/sync/session-merge.js +178 -0
- package/dist/engine/sync/session-push.d.ts +5 -0
- package/dist/engine/sync/session-push.js +32 -0
- package/dist/engine/sync/settings-conflicts.d.ts +8 -0
- package/dist/engine/sync/settings-conflicts.js +56 -0
- package/dist/engine/sync/settings-merge.d.ts +13 -0
- package/dist/engine/sync/settings-merge.js +93 -0
- package/dist/engine/sync/signals.d.ts +2 -0
- package/dist/engine/sync/signals.js +8 -0
- package/dist/engine/sync/startup-timings.d.ts +11 -0
- package/dist/engine/sync/startup-timings.js +44 -0
- package/dist/engine/sync/sync-decision.d.ts +35 -0
- package/dist/engine/sync/sync-decision.js +66 -0
- package/dist/engine/sync/sync-error-guidance.d.ts +2 -0
- package/dist/engine/sync/sync-error-guidance.js +55 -0
- package/dist/engine/sync/sync-errors.d.ts +9 -0
- package/dist/engine/sync/sync-errors.js +18 -0
- package/dist/engine/sync/sync-inspection.d.ts +26 -0
- package/dist/engine/sync/sync-inspection.js +40 -0
- package/dist/engine/sync/sync-loaders.d.ts +7 -0
- package/dist/engine/sync/sync-loaders.js +8 -0
- package/dist/engine/sync/sync-local.d.ts +5 -0
- package/dist/engine/sync/sync-local.js +40 -0
- package/dist/engine/sync/sync-mutations.d.ts +30 -0
- package/dist/engine/sync/sync-mutations.js +589 -0
- package/dist/engine/sync/sync-operations.d.ts +2 -0
- package/dist/engine/sync/sync-operations.js +3 -0
- package/dist/engine/sync/sync-policy.d.ts +85 -0
- package/dist/engine/sync/sync-policy.js +356 -0
- package/dist/engine/sync/sync-queries.d.ts +7 -0
- package/dist/engine/sync/sync-queries.js +195 -0
- package/dist/engine/sync/sync-state.d.ts +31 -0
- package/dist/engine/sync/sync-state.js +92 -0
- package/dist/engine/sync/text-merge.d.ts +19 -0
- package/dist/engine/sync/text-merge.js +124 -0
- package/dist/engine/types.d.ts +5 -0
- package/dist/engine/types.js +2 -0
- package/dist/engine/ui/merge-review.d.ts +2 -0
- package/dist/engine/ui/merge-review.js +7 -0
- package/dist/engine/ui/merged-sync-summary.d.ts +25 -0
- package/dist/engine/ui/merged-sync-summary.js +86 -0
- package/dist/engine/ui/sync-format.d.ts +13 -0
- package/dist/engine/ui/sync-format.js +150 -0
- package/dist/engine/ui/sync-status.d.ts +9 -0
- package/dist/engine/ui/sync-status.js +30 -0
- package/dist/engine/ui/terminal-text.d.ts +3 -0
- package/dist/engine/ui/terminal-text.js +9 -0
- package/dist/engine/ui/transfer-changes.d.ts +12 -0
- package/dist/engine/ui/transfer-changes.js +24 -0
- package/dist/engine/ui/transfer-review.d.ts +3 -0
- package/dist/engine/ui/transfer-review.js +19 -0
- package/dist/engine-service.d.ts +11 -0
- package/dist/engine-service.js +315 -0
- package/dist/identity.d.ts +20 -0
- package/dist/identity.js +133 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +4 -0
- package/dist/lifecycle-log.d.ts +7 -0
- package/dist/lifecycle-log.js +53 -0
- package/dist/lifecycle.d.ts +2 -0
- package/dist/lifecycle.js +21 -0
- package/dist/model-signature.d.ts +2 -0
- package/dist/model-signature.js +7 -0
- package/dist/monitor.d.ts +11 -0
- package/dist/monitor.js +245 -0
- package/dist/participant-admission.d.ts +5 -0
- package/dist/participant-admission.js +30 -0
- package/dist/protocol.d.ts +97 -0
- package/dist/protocol.js +90 -0
- package/dist/resolver-host.d.ts +11 -0
- package/dist/resolver-host.js +78 -0
- package/dist/server.d.ts +18 -0
- package/dist/server.js +724 -0
- package/dist/service-host.d.ts +7 -0
- package/dist/service-host.js +174 -0
- package/docs/architecture.md +133 -0
- package/package.json +54 -4
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { fileHashMap } from "../sync/sync-state.js";
|
|
2
|
+
/** Compare effective before/after snapshots, not raw planner decisions. */
|
|
3
|
+
export function transferChanges(before, after, protectedPaths = new Set()) {
|
|
4
|
+
const beforeMap = before ? fileHashMap(before) : {};
|
|
5
|
+
const afterMap = fileHashMap(after);
|
|
6
|
+
return [...new Set([...Object.keys(beforeMap), ...Object.keys(afterMap)])]
|
|
7
|
+
.sort()
|
|
8
|
+
.flatMap((filePath) => {
|
|
9
|
+
if (protectedPaths.has(filePath))
|
|
10
|
+
return [];
|
|
11
|
+
if (!Object.hasOwn(beforeMap, filePath))
|
|
12
|
+
return [{ path: filePath, action: "Add" }];
|
|
13
|
+
if (!Object.hasOwn(afterMap, filePath))
|
|
14
|
+
return [{ path: filePath, action: "Delete" }];
|
|
15
|
+
return beforeMap[filePath] !== afterMap[filePath] ? [{ path: filePath, action: "Update" }] : [];
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
export function transferCounts(changes) {
|
|
19
|
+
return {
|
|
20
|
+
add: changes.filter((change) => change.action === "Add").length,
|
|
21
|
+
update: changes.filter((change) => change.action === "Update").length,
|
|
22
|
+
remove: changes.filter((change) => change.action === "Delete").length,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { EngineContext } from "../host.js";
|
|
2
|
+
/** Presentation is supplied by the host; RPC keeps its existing directional confirmation. */
|
|
3
|
+
export declare function confirmTransferReview(ctx: EngineContext, title: string, content: string, signal: AbortSignal | undefined, validate: () => void): Promise<boolean>;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { confirmMergeReview } from "./merge-review.js";
|
|
2
|
+
/** Presentation is supplied by the host; RPC keeps its existing directional confirmation. */
|
|
3
|
+
export async function confirmTransferReview(ctx, title, content, signal, validate) {
|
|
4
|
+
validate();
|
|
5
|
+
const isCurrent = () => {
|
|
6
|
+
try {
|
|
7
|
+
validate();
|
|
8
|
+
return true;
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
return false;
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
const confirmed = ctx.mode === "tui" && ctx.hasUI
|
|
15
|
+
? await confirmMergeReview(ctx, title, content, signal, isCurrent, "apply reviewed transfer", content.split("\n"))
|
|
16
|
+
: await ctx.ui.confirm(title, content, { signal });
|
|
17
|
+
validate();
|
|
18
|
+
return confirmed;
|
|
19
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type Execute } from "./protocol.js";
|
|
2
|
+
/** Engine dispatch is loaded only by the service, never by the public IPC client. */
|
|
3
|
+
export declare function createEngineService(root: string): {
|
|
4
|
+
execute: Execute;
|
|
5
|
+
bind: (value: Awaited<ReturnType<typeof import("./server.js").startServer>>) => void;
|
|
6
|
+
hooks: {
|
|
7
|
+
factsChanged: () => Promise<void>;
|
|
8
|
+
idle: () => void;
|
|
9
|
+
close: () => Promise<void>;
|
|
10
|
+
};
|
|
11
|
+
};
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
import { authorizeAfterExit, consentFingerprint, readConsent, requireHandover } from "./consent.js";
|
|
2
|
+
import { documentFingerprint } from "./document.js";
|
|
3
|
+
import { createMonitor } from "./monitor.js";
|
|
4
|
+
import { MAX_SETTINGS_BYTES, record } from "./protocol.js";
|
|
5
|
+
import { createServiceContext, installServiceHost } from "./service-host.js";
|
|
6
|
+
function optionsFrom(value, execution) {
|
|
7
|
+
if (!record(value))
|
|
8
|
+
throw new Error("Invalid operation options.");
|
|
9
|
+
const allowed = new Set(["yes", "force", "stale", "silent", "reload", "setup", "args", "agentRetryRefusal"]);
|
|
10
|
+
if (Object.keys(value).some((key) => !allowed.has(key)) ||
|
|
11
|
+
["yes", "force", "stale", "silent", "reload", "agentRetryRefusal"].some((key) => value[key] !== undefined && typeof value[key] !== "boolean") ||
|
|
12
|
+
(value.setup !== undefined && (typeof value.setup !== "string" || value.setup.length > 512)) ||
|
|
13
|
+
!Array.isArray(value.args) ||
|
|
14
|
+
value.args.length > 16 ||
|
|
15
|
+
value.args.some((arg) => typeof arg !== "string" || arg.length > 4096))
|
|
16
|
+
throw new Error("Invalid operation options.");
|
|
17
|
+
return {
|
|
18
|
+
yes: false,
|
|
19
|
+
force: false,
|
|
20
|
+
stale: false,
|
|
21
|
+
silent: false,
|
|
22
|
+
reload: false,
|
|
23
|
+
auto: false,
|
|
24
|
+
...value,
|
|
25
|
+
args: value.args,
|
|
26
|
+
signal: execution.signal,
|
|
27
|
+
onCommit: execution.committed,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
/** Engine dispatch is loaded only by the service, never by the public IPC client. */
|
|
31
|
+
export function createEngineService(root) {
|
|
32
|
+
const host = installServiceHost(root);
|
|
33
|
+
const monitor = createMonitor(root, host);
|
|
34
|
+
const execute = (operation, payload, execution) => host.run(execution, async () => {
|
|
35
|
+
await monitor.pause();
|
|
36
|
+
execution.validate();
|
|
37
|
+
if (operation === "daemon.authorize")
|
|
38
|
+
return authorizeAfterExit(execution, payload);
|
|
39
|
+
if (operation === "daemon.handover") {
|
|
40
|
+
await requireHandover(execution);
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
if (operation === "daemon.policy") {
|
|
44
|
+
const { loadConfig } = await import("./engine/settings/config.js");
|
|
45
|
+
const config = await loadConfig();
|
|
46
|
+
const fingerprint = consentFingerprint(root, config);
|
|
47
|
+
const saved = readConsent(root)?.setups[config.setupName];
|
|
48
|
+
const facts = execution.facts();
|
|
49
|
+
return {
|
|
50
|
+
setup: config.setupName,
|
|
51
|
+
fingerprint,
|
|
52
|
+
afterExit: Boolean(saved?.afterExit &&
|
|
53
|
+
saved.fingerprint === fingerprint &&
|
|
54
|
+
JSON.stringify(saved.model) === JSON.stringify(facts?.model) &&
|
|
55
|
+
saved.sessionDir === facts?.sessionDir &&
|
|
56
|
+
saved.cwd === facts?.cwd),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
if (operation === "monitor.pause")
|
|
60
|
+
return;
|
|
61
|
+
if (operation === "settings.read" || operation === "settings.repair-read") {
|
|
62
|
+
const { readLocalConfigDocument } = await import("./engine/settings/settings-store.js");
|
|
63
|
+
const { readActiveLocalConfigDocumentForRepair } = await import("./engine/settings/config-file.js");
|
|
64
|
+
const document = await (operation === "settings.read" && readConsent(root)
|
|
65
|
+
? readLocalConfigDocument()
|
|
66
|
+
: readActiveLocalConfigDocumentForRepair());
|
|
67
|
+
execution.validate();
|
|
68
|
+
if (document && operation === "settings.read") {
|
|
69
|
+
const { validateSettingsDocument } = await import("./engine/settings/settings-validation.js");
|
|
70
|
+
execution.validate();
|
|
71
|
+
validateSettingsDocument(document.parsed);
|
|
72
|
+
}
|
|
73
|
+
return document ? { ...document, bytes: document.bytes.toString("base64") } : null;
|
|
74
|
+
}
|
|
75
|
+
if (operation === "settings.cas") {
|
|
76
|
+
if (!record(payload) ||
|
|
77
|
+
(payload.expected !== null &&
|
|
78
|
+
(typeof payload.expected !== "string" || !/^[a-f0-9]{64}$/u.test(payload.expected))) ||
|
|
79
|
+
!record(payload.next))
|
|
80
|
+
throw new Error("Invalid settings mutation.");
|
|
81
|
+
const { updateLocalConfigDocument, peekLocalConfigDocument } = await import("./engine/settings/config-file.js");
|
|
82
|
+
const { localConfigTemplate } = await import("./engine/settings/settings-store.js");
|
|
83
|
+
const { validateSettingsDocument } = await import("./engine/settings/settings-validation.js");
|
|
84
|
+
const next = payload.next;
|
|
85
|
+
validateSettingsDocument(next);
|
|
86
|
+
if (Buffer.byteLength(JSON.stringify(next)) > MAX_SETTINGS_BYTES)
|
|
87
|
+
throw new Error("Settings exceed the editable local API byte limit; no fields were dropped.");
|
|
88
|
+
const validateSource = (document) => {
|
|
89
|
+
execution.validate();
|
|
90
|
+
const view = document ? { bytes: document.bytes.toString("base64"), identity: document.identity } : undefined;
|
|
91
|
+
if (documentFingerprint(view) !== payload.expected)
|
|
92
|
+
throw new Error("Settings changed; reopen the review before saving.");
|
|
93
|
+
};
|
|
94
|
+
validateSource(await peekLocalConfigDocument());
|
|
95
|
+
await requireHandover(execution);
|
|
96
|
+
execution.validate();
|
|
97
|
+
return updateLocalConfigDocument(localConfigTemplate(), () => {
|
|
98
|
+
execution.validate();
|
|
99
|
+
validateSettingsDocument(next);
|
|
100
|
+
return next;
|
|
101
|
+
}, validateSettingsDocument, execution.signal, validateSource);
|
|
102
|
+
}
|
|
103
|
+
const ctx = createServiceContext(execution);
|
|
104
|
+
if (operation === "initialize")
|
|
105
|
+
return initialize(ctx, execution);
|
|
106
|
+
if (operation === "inspect") {
|
|
107
|
+
if (!record(payload) || (payload.setup !== undefined && typeof payload.setup !== "string"))
|
|
108
|
+
throw new Error("Invalid inspection request.");
|
|
109
|
+
const { withStateDirectoryAccess } = await import("./engine/state/state-directory.js");
|
|
110
|
+
const { withLock } = await import("./engine/state/lock.js");
|
|
111
|
+
return withJobTimings(ctx, execution, "daemon inspection", (timings) => withStateDirectoryAccess(() => withLock("startup-check", async () => {
|
|
112
|
+
const { loadConfig, syncCheckConfigFingerprint } = await import("./engine/settings/config.js");
|
|
113
|
+
const config = await loadConfig(payload.setup);
|
|
114
|
+
execution.validate();
|
|
115
|
+
if (payload.fingerprint !== syncCheckConfigFingerprint(config))
|
|
116
|
+
throw new Error("Settings changed before inspection.");
|
|
117
|
+
const { snapshotOptionsForContext } = await import("./engine/snapshot/session-paths.js");
|
|
118
|
+
const { inspectSync } = await import("./engine/sync/sync-inspection.js");
|
|
119
|
+
execution.validate();
|
|
120
|
+
return inspectSync(config, snapshotOptionsForContext(ctx, config), execution.signal, undefined, timings);
|
|
121
|
+
})));
|
|
122
|
+
}
|
|
123
|
+
const supported = [
|
|
124
|
+
"status",
|
|
125
|
+
"diff",
|
|
126
|
+
"doctor",
|
|
127
|
+
"history",
|
|
128
|
+
"push",
|
|
129
|
+
"pull",
|
|
130
|
+
"sync",
|
|
131
|
+
"startup-transfer",
|
|
132
|
+
"shutdown",
|
|
133
|
+
"conflicts",
|
|
134
|
+
"rollback",
|
|
135
|
+
"unlock",
|
|
136
|
+
"migrate-state",
|
|
137
|
+
];
|
|
138
|
+
if (!supported.includes(operation))
|
|
139
|
+
throw new Error("Unsupported engine operation.");
|
|
140
|
+
const options = optionsFrom(payload, execution);
|
|
141
|
+
if (!options.reload)
|
|
142
|
+
ctx.reload = undefined;
|
|
143
|
+
if (operation === "shutdown") {
|
|
144
|
+
const { loadConfigForCheck } = await import("./engine/settings/config.js");
|
|
145
|
+
const { syncSessionsSelected } = await import("./engine/sync/sync-policy.js");
|
|
146
|
+
const config = await loadConfigForCheck();
|
|
147
|
+
execution.validate();
|
|
148
|
+
if (!config.automatic || !syncSessionsSelected(config))
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
if (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode))
|
|
152
|
+
throw new Error("Synchronization requires an observable TUI or RPC client.");
|
|
153
|
+
const { withStateDirectoryAccess, migrateLegacyStateDirectory } = await import("./engine/state/state-directory.js");
|
|
154
|
+
if (operation === "migrate-state") {
|
|
155
|
+
if (!options.yes) {
|
|
156
|
+
const accepted = await ctx.ui.confirm("Migrate pi-sync state directory", "Confirm that every older Pi process is closed. Preserve both roots and pending journals on failure.", { signal: execution.signal });
|
|
157
|
+
execution.validate();
|
|
158
|
+
if (!accepted)
|
|
159
|
+
return { status: "cancelled", message: "pi-sync state migration cancelled." };
|
|
160
|
+
}
|
|
161
|
+
execution.validate();
|
|
162
|
+
const result = await migrateLegacyStateDirectory();
|
|
163
|
+
if (result.status === "migrated")
|
|
164
|
+
execution.committed();
|
|
165
|
+
execution.validate();
|
|
166
|
+
return result;
|
|
167
|
+
}
|
|
168
|
+
return withStateDirectoryAccess(async () => {
|
|
169
|
+
if (["startup-transfer", "shutdown"].includes(operation) && !readConsent(root))
|
|
170
|
+
throw new Error("Automatic work requires reviewed daemon handover first.");
|
|
171
|
+
if (["push", "pull", "sync", "startup-transfer", "shutdown", "conflicts", "rollback"].includes(operation)) {
|
|
172
|
+
await requireHandover(execution);
|
|
173
|
+
await initialize(ctx, execution, false);
|
|
174
|
+
}
|
|
175
|
+
const { withLock, unlock } = await import("./engine/state/lock.js");
|
|
176
|
+
if (operation === "unlock")
|
|
177
|
+
return unlock(ctx, options);
|
|
178
|
+
const operations = await import("./engine/sync/sync-operations.js");
|
|
179
|
+
if (operation === "conflicts") {
|
|
180
|
+
const { showConflicts } = await import("./engine/sync/conflict-review.js");
|
|
181
|
+
return withLock("sync", () => showConflicts(ctx, options));
|
|
182
|
+
}
|
|
183
|
+
if (operation === "shutdown") {
|
|
184
|
+
const { pushSessionsOnShutdown } = await import("./engine/sync/session-push.js");
|
|
185
|
+
return pushSessionsOnShutdown(ctx, options, { operations: async () => operations });
|
|
186
|
+
}
|
|
187
|
+
if (operation === "startup-transfer") {
|
|
188
|
+
const { loadConfig } = await import("./engine/settings/config.js");
|
|
189
|
+
const { startupTransferEnabled } = await import("./engine/sync/agent-policy.js");
|
|
190
|
+
if (!startupTransferEnabled(await loadConfig(options.setup)) || !ctx.isIdle())
|
|
191
|
+
throw new Error("Startup transfer is no longer authorized or idle.");
|
|
192
|
+
options.auto = true;
|
|
193
|
+
options.yes = true;
|
|
194
|
+
options.silent = true;
|
|
195
|
+
options.reload = false;
|
|
196
|
+
}
|
|
197
|
+
if (operation === "sync" || operation === "startup-transfer") {
|
|
198
|
+
const run = async () => {
|
|
199
|
+
const { prepareResolverHost } = await import("./resolver-host.js");
|
|
200
|
+
const { loadConfig } = await import("./engine/settings/config.js");
|
|
201
|
+
const config = await loadConfig(options.setup);
|
|
202
|
+
execution.validate();
|
|
203
|
+
if (operation === "sync" && !options.agentRetryRefusal)
|
|
204
|
+
monitor.explicitSync(config.setupName, execution);
|
|
205
|
+
const binding = JSON.stringify(execution.facts()?.model);
|
|
206
|
+
const resolver = await prepareResolverHost(root, config.agentMode ? execution.facts()?.model : undefined, execution.signal);
|
|
207
|
+
try {
|
|
208
|
+
ctx.modelUnavailableReason = resolver.unavailable;
|
|
209
|
+
Object.defineProperty(ctx, "model", {
|
|
210
|
+
get: () => (JSON.stringify(execution.facts()?.model) === binding ? resolver.model : undefined),
|
|
211
|
+
});
|
|
212
|
+
ctx.validateModel = async () => {
|
|
213
|
+
const fresh = await execution.request("model-binding", {});
|
|
214
|
+
execution.validate();
|
|
215
|
+
if (JSON.stringify(fresh ?? undefined) !== binding)
|
|
216
|
+
throw new Error("Selected provider/model capability changed before dispatch.");
|
|
217
|
+
};
|
|
218
|
+
ctx.modelRegistry = {
|
|
219
|
+
streamSimple: (model, context, options) => {
|
|
220
|
+
execution.validate();
|
|
221
|
+
if (JSON.stringify(execution.facts()?.model) !== binding)
|
|
222
|
+
throw new Error("Selected model changed before dispatch.");
|
|
223
|
+
if (resolver.unavailable)
|
|
224
|
+
throw new Error(resolver.unavailable);
|
|
225
|
+
return resolver.registry.streamSimple(model, context, options);
|
|
226
|
+
},
|
|
227
|
+
};
|
|
228
|
+
const { withAgentSyncLock } = await import("./engine/sync/agent-sync.js");
|
|
229
|
+
return await withAgentSyncLock(ctx, options, async (current) => {
|
|
230
|
+
if (operation === "startup-transfer") {
|
|
231
|
+
const { loadConfig } = await import("./engine/settings/config.js");
|
|
232
|
+
const { startupTransferEnabled } = await import("./engine/sync/agent-policy.js");
|
|
233
|
+
const config = await loadConfig(current.setup);
|
|
234
|
+
execution.validate();
|
|
235
|
+
const { inspectSync } = await import("./engine/sync/sync-inspection.js");
|
|
236
|
+
const { snapshotOptionsForContext } = await import("./engine/snapshot/session-paths.js");
|
|
237
|
+
const inspection = await inspectSync(config, snapshotOptionsForContext(ctx, config), current.signal);
|
|
238
|
+
execution.validate();
|
|
239
|
+
if (!startupTransferEnabled(config) ||
|
|
240
|
+
!ctx.isIdle() ||
|
|
241
|
+
execution.participants().some((peer) => peer.ready !== true) ||
|
|
242
|
+
inspection.firstSync ||
|
|
243
|
+
!inspection.head ||
|
|
244
|
+
inspection.selectionState?.kind !== "same")
|
|
245
|
+
throw new Error("Startup transfer requires a fresh initialized baseline, matching selection, and idle ready clients; use the reviewed foreground command.");
|
|
246
|
+
}
|
|
247
|
+
return operations.syncBoth(ctx, current);
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
finally {
|
|
251
|
+
await resolver.settle();
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
return operation === "startup-transfer"
|
|
255
|
+
? withJobTimings(ctx, execution, "daemon transfer", (timings) => {
|
|
256
|
+
options.startupTimings = timings;
|
|
257
|
+
return run();
|
|
258
|
+
})
|
|
259
|
+
: run();
|
|
260
|
+
}
|
|
261
|
+
if (operation === "push" || operation === "pull" || operation === "rollback")
|
|
262
|
+
return withLock(operation, () => operations[operation](ctx, options));
|
|
263
|
+
if (operation === "status" || operation === "diff" || operation === "doctor" || operation === "history")
|
|
264
|
+
return operations[operation](ctx, options);
|
|
265
|
+
throw new Error("Unreachable operation.");
|
|
266
|
+
});
|
|
267
|
+
});
|
|
268
|
+
return {
|
|
269
|
+
execute,
|
|
270
|
+
bind: monitor.bind,
|
|
271
|
+
hooks: { factsChanged: monitor.factsChanged, idle: monitor.schedule, close: monitor.close },
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
async function withJobTimings(ctx, execution, label, action) {
|
|
275
|
+
const { createStartupTimings } = await import("./engine/sync/startup-timings.js");
|
|
276
|
+
const timings = createStartupTimings((_ctx, report) => execution.emit("timings", { report }));
|
|
277
|
+
let completed = false;
|
|
278
|
+
try {
|
|
279
|
+
const result = await action(timings);
|
|
280
|
+
completed = true;
|
|
281
|
+
return result;
|
|
282
|
+
}
|
|
283
|
+
finally {
|
|
284
|
+
timings.publish(ctx, execution.facts()?.startupDebug ?? false, execution.signal, label, completed ? "completed" : "stopped");
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
async function initialize(ctx, execution, diagnostics = true) {
|
|
288
|
+
const { pendingTransactionEntries } = await import("./engine/snapshot/snapshot-transaction-directory.js");
|
|
289
|
+
const pending = await pendingTransactionEntries();
|
|
290
|
+
execution.validate();
|
|
291
|
+
if (pending.some((entry) => entry.isDirectory()) && !readConsent(execution.root))
|
|
292
|
+
throw new Error("Pending local recovery requires reviewed daemon handover. Close older Pi processes and use /sync daemon handover, then /reload before editing managed files.");
|
|
293
|
+
if (!readConsent(execution.root)) {
|
|
294
|
+
const { stateDirectoryMigrationNotice } = await import("./engine/state/state-directory.js");
|
|
295
|
+
const notice = await stateDirectoryMigrationNotice();
|
|
296
|
+
execution.validate();
|
|
297
|
+
if (notice)
|
|
298
|
+
throw new Error(notice);
|
|
299
|
+
// Before ownership approval, report metadata without filename migration or recovery writes.
|
|
300
|
+
const { peekLocalConfigDocument } = await import("./engine/settings/config-file.js");
|
|
301
|
+
const { validateSettingsDocument } = await import("./engine/settings/settings-validation.js");
|
|
302
|
+
const { configFromSettings } = await import("./engine/settings/config.js");
|
|
303
|
+
const document = await peekLocalConfigDocument();
|
|
304
|
+
execution.validate();
|
|
305
|
+
const settings = document ? validateSettingsDocument(document.parsed) : undefined;
|
|
306
|
+
const config = settings?.activeSyncSetup ? configFromSettings(settings) : undefined;
|
|
307
|
+
return { debug: settings?.debug ?? false, settings, config, handoverRequired: true };
|
|
308
|
+
}
|
|
309
|
+
const { initializeSync } = await import("./engine/sync/initialization.js");
|
|
310
|
+
const initialized = await initializeSync(ctx, execution.signal, (_ctx, report) => {
|
|
311
|
+
if (diagnostics)
|
|
312
|
+
execution.emit("timings", { report });
|
|
313
|
+
});
|
|
314
|
+
return { ...initialized, handoverRequired: !readConsent(execution.root) };
|
|
315
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type Identity } from "./protocol.js";
|
|
2
|
+
export interface RuntimePaths {
|
|
3
|
+
root: string;
|
|
4
|
+
directory: string;
|
|
5
|
+
identity: string;
|
|
6
|
+
startup: string;
|
|
7
|
+
owner: string;
|
|
8
|
+
}
|
|
9
|
+
export declare function canonicalRootGuard(root: string): () => void;
|
|
10
|
+
export declare function runtimePaths(root: string): Promise<RuntimePaths>;
|
|
11
|
+
export interface DaemonPaths extends RuntimePaths {
|
|
12
|
+
endpoint: string;
|
|
13
|
+
endpointDirectory?: string;
|
|
14
|
+
}
|
|
15
|
+
export declare function daemonPaths(paths: RuntimePaths, instance: string): DaemonPaths;
|
|
16
|
+
export declare function privateDirectory(directory: string): Promise<void>;
|
|
17
|
+
export declare function readIdentity(paths: RuntimePaths): Promise<Identity | undefined>;
|
|
18
|
+
export declare function processExists(pid: number): boolean;
|
|
19
|
+
export declare function publishIdentity(paths: RuntimePaths, identity: Identity): Promise<void>;
|
|
20
|
+
export declare function readJsonBody(source: AsyncIterable<Uint8Array>): Promise<unknown>;
|
package/dist/identity.js
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
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
|
+
export async function readIdentity(paths) {
|
|
64
|
+
let handle;
|
|
65
|
+
try {
|
|
66
|
+
const before = await fs.lstat(paths.identity);
|
|
67
|
+
if (!before.isFile() ||
|
|
68
|
+
before.isSymbolicLink() ||
|
|
69
|
+
before.size > 8192 ||
|
|
70
|
+
(process.getuid && before.uid !== process.getuid()) ||
|
|
71
|
+
(process.platform !== "win32" && (before.mode & 0o077) !== 0))
|
|
72
|
+
throw new Error("Unsafe daemon identity file.");
|
|
73
|
+
handle = await fs.open(paths.identity, "r");
|
|
74
|
+
const opened = await handle.stat();
|
|
75
|
+
if (before.dev !== opened.dev || before.ino !== opened.ino)
|
|
76
|
+
throw new Error("Daemon identity changed while opening.");
|
|
77
|
+
const value = JSON.parse(await handle.readFile("utf8"));
|
|
78
|
+
if (!record(value) ||
|
|
79
|
+
value.version !== 1 ||
|
|
80
|
+
value.root !== paths.root ||
|
|
81
|
+
typeof value.instance !== "string" ||
|
|
82
|
+
!/^[a-f0-9-]{36}$/u.test(value.instance) ||
|
|
83
|
+
!Number.isSafeInteger(value.pid) ||
|
|
84
|
+
Number(value.pid) < 1 ||
|
|
85
|
+
Number(value.pid) > 2_147_483_647 ||
|
|
86
|
+
typeof value.token !== "string" ||
|
|
87
|
+
!/^[a-f0-9]{64}$/u.test(value.token))
|
|
88
|
+
throw new Error("Invalid or incompatible daemon identity; state retained.");
|
|
89
|
+
return value;
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
if (error.code === "ENOENT")
|
|
93
|
+
return;
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
finally {
|
|
97
|
+
await handle?.close();
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
export function processExists(pid) {
|
|
101
|
+
try {
|
|
102
|
+
process.kill(pid, 0);
|
|
103
|
+
return true;
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
return error.code !== "ESRCH";
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
export async function publishIdentity(paths, identity) {
|
|
110
|
+
const temporary = path.join(paths.directory, `.${randomUUID()}.json`);
|
|
111
|
+
const handle = await fs.open(temporary, "wx", 0o600);
|
|
112
|
+
try {
|
|
113
|
+
await handle.writeFile(JSON.stringify(identity));
|
|
114
|
+
await handle.sync();
|
|
115
|
+
await handle.close();
|
|
116
|
+
await fs.rename(temporary, paths.identity);
|
|
117
|
+
}
|
|
118
|
+
finally {
|
|
119
|
+
await handle.close().catch(() => { });
|
|
120
|
+
await fs.rm(temporary, { force: true });
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
export async function readJsonBody(source) {
|
|
124
|
+
const chunks = [];
|
|
125
|
+
let size = 0;
|
|
126
|
+
for await (const chunk of source) {
|
|
127
|
+
size += chunk.byteLength;
|
|
128
|
+
if (size > MAX_MESSAGE_BYTES)
|
|
129
|
+
throw new Error("Daemon request exceeds its byte limit.");
|
|
130
|
+
chunks.push(Buffer.from(chunk));
|
|
131
|
+
}
|
|
132
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
133
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export type { ConnectionOptions } from "./client.js";
|
|
2
|
+
export { DaemonConnection, DaemonError, ensureDaemon, findDaemon, requestDaemon, stopDaemon } from "./client.js";
|
|
3
|
+
export type { DocumentView } from "./document.js";
|
|
4
|
+
export { documentFingerprint } from "./document.js";
|
|
5
|
+
export type { EngineContext, EngineHost, EngineSession, ReviewRequest } from "./engine/host.js";
|
|
6
|
+
export { modelSignature } from "./model-signature.js";
|
|
7
|
+
export type { Callback, ClientEvent, ClientFacts, ClientHandoff, Identity, JobView, RemoteError } from "./protocol.js";
|
|
8
|
+
export { MAX_SETTINGS_BYTES, PROTOCOL_VERSION } from "./protocol.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { DaemonConnection, DaemonError, ensureDaemon, findDaemon, requestDaemon, stopDaemon } 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,7 @@
|
|
|
1
|
+
type Phase = "starting" | "ready" | "drained" | "failed";
|
|
2
|
+
/** Bounded lifecycle facts only: never log payloads, credentials, provider output, or exception text. */
|
|
3
|
+
export declare function openLifecycleLog(directory: string): {
|
|
4
|
+
write(phase: Phase): void;
|
|
5
|
+
close(): void;
|
|
6
|
+
};
|
|
7
|
+
export {};
|
|
@@ -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
|
+
}
|