@narumitw/pi-sync-daemon 0.8.0 → 0.9.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 +10 -0
- package/dist/cli.js +1 -1
- package/dist/consent.d.ts +14 -2
- package/dist/consent.js +134 -16
- package/dist/engine/backends/git/git-backend.d.ts +1 -2
- package/dist/engine/backends/git/git-backend.js +61 -30
- package/dist/engine/commands/command-types.d.ts +2 -1
- package/dist/engine/host.d.ts +1 -0
- package/dist/engine/ignore/ignore-initialization.d.ts +3 -0
- package/dist/engine/ignore/ignore-initialization.js +93 -27
- package/dist/engine/ignore/ignore-settings.d.ts +16 -1
- package/dist/engine/ignore/ignore-settings.js +85 -14
- package/dist/engine/settings/config-file.js +1 -1
- package/dist/engine/settings/config.d.ts +3 -2
- package/dist/engine/settings/config.js +71 -28
- package/dist/engine/settings/settings-management.d.ts +3 -1
- package/dist/engine/settings/settings-management.js +8 -2
- package/dist/engine/settings/settings-types.d.ts +2 -0
- package/dist/engine/snapshot/session-paths.js +7 -2
- package/dist/engine/snapshot/snapshot-apply.d.ts +1 -1
- package/dist/engine/snapshot/snapshot-transaction-policy.d.ts +7 -2
- package/dist/engine/snapshot/snapshot-transaction-policy.js +37 -17
- package/dist/engine/snapshot/snapshot-transaction.js +55 -13
- package/dist/engine/snapshot/snapshot-types.d.ts +4 -0
- package/dist/engine/sync/agent-plan.js +1 -0
- package/dist/engine/sync/agent-sync.js +8 -1
- package/dist/engine/sync/continuous-sync.d.ts +3 -1
- package/dist/engine/sync/continuous-sync.js +32 -15
- package/dist/engine/sync/merge-acceptance.d.ts +8 -0
- package/dist/engine/sync/merge-acceptance.js +29 -0
- package/dist/engine/sync/merge-apply.js +7 -4
- package/dist/engine/sync/merge-journal.d.ts +6 -0
- package/dist/engine/sync/merge-journal.js +33 -14
- package/dist/engine/sync/merged-sync.js +31 -39
- package/dist/engine/sync/remote-snapshot.d.ts +2 -1
- package/dist/engine/sync/remote-snapshot.js +17 -2
- package/dist/engine/sync/session-push.js +20 -6
- package/dist/engine/sync/sync-mutations.js +71 -50
- package/dist/engine/sync/sync-policy.d.ts +5 -0
- package/dist/engine/sync/sync-policy.js +28 -3
- package/dist/engine/sync/sync-state.d.ts +2 -0
- package/dist/engine/sync/sync-state.js +3 -8
- package/dist/engine/sync/transfer-freshness.d.ts +31 -0
- package/dist/engine/sync/transfer-freshness.js +82 -0
- package/dist/engine-service.d.ts +1 -1
- package/dist/engine-service.js +124 -27
- package/dist/monitor.d.ts +4 -1
- package/dist/monitor.js +84 -32
- package/dist/server.d.ts +1 -0
- package/dist/server.js +46 -5
- package/dist/service-host.d.ts +1 -1
- package/dist/service-host.js +2 -1
- package/docs/architecture.md +13 -5
- package/package.json +1 -1
package/dist/engine-service.js
CHANGED
|
@@ -1,18 +1,29 @@
|
|
|
1
|
-
import { authorizeAfterExit, consentFingerprint, readConsent, requireHandover } from "./consent.js";
|
|
1
|
+
import { authorizeAfterExit, automaticPolicyAuthorized, captureAutomaticAuthorization, consentFingerprint, readConsent, requireHandover, reviewAutomaticPolicy, revokeAfterExitGrants, } from "./consent.js";
|
|
2
2
|
import { documentFingerprint } from "./document.js";
|
|
3
3
|
import { createMonitor } from "./monitor.js";
|
|
4
4
|
import { MAX_SETTINGS_BYTES, record } from "./protocol.js";
|
|
5
5
|
import { createServiceContext, installServiceHost } from "./service-host.js";
|
|
6
|
-
function optionsFrom(value, execution) {
|
|
6
|
+
function optionsFrom(value, execution, automatic) {
|
|
7
7
|
if (!record(value))
|
|
8
8
|
throw new Error("Invalid operation options.");
|
|
9
9
|
const allowed = new Set(["yes", "force", "stale", "silent", "reload", "setup", "args", "agentRetryRefusal"]);
|
|
10
|
+
if (automatic)
|
|
11
|
+
allowed.add("automaticFingerprint");
|
|
10
12
|
if (Object.keys(value).some((key) => !allowed.has(key)) ||
|
|
11
13
|
["yes", "force", "stale", "silent", "reload", "agentRetryRefusal"].some((key) => value[key] !== undefined && typeof value[key] !== "boolean") ||
|
|
12
14
|
(value.setup !== undefined && (typeof value.setup !== "string" || value.setup.length > 512)) ||
|
|
13
15
|
!Array.isArray(value.args) ||
|
|
14
16
|
value.args.length > 16 ||
|
|
15
|
-
value.args.some((arg) => typeof arg !== "string" || arg.length > 4096)
|
|
17
|
+
value.args.some((arg) => typeof arg !== "string" || arg.length > 4096) ||
|
|
18
|
+
(value.automaticFingerprint !== undefined &&
|
|
19
|
+
(typeof value.automaticFingerprint !== "string" || !/^[a-f0-9]{64}$/u.test(value.automaticFingerprint))) ||
|
|
20
|
+
(automatic &&
|
|
21
|
+
(value.setup !== undefined ||
|
|
22
|
+
value.force ||
|
|
23
|
+
value.stale ||
|
|
24
|
+
value.reload ||
|
|
25
|
+
value.agentRetryRefusal ||
|
|
26
|
+
value.args.length !== 0)))
|
|
16
27
|
throw new Error("Invalid operation options.");
|
|
17
28
|
return {
|
|
18
29
|
yes: false,
|
|
@@ -23,18 +34,19 @@ function optionsFrom(value, execution) {
|
|
|
23
34
|
auto: false,
|
|
24
35
|
...value,
|
|
25
36
|
args: value.args,
|
|
37
|
+
...(typeof value.automaticFingerprint === "string" ? { automaticFingerprint: value.automaticFingerprint } : {}),
|
|
26
38
|
signal: execution.signal,
|
|
27
39
|
onCommit: execution.committed,
|
|
28
40
|
};
|
|
29
41
|
}
|
|
30
42
|
/** Engine dispatch is loaded only by the service, never by the public IPC client. */
|
|
31
|
-
export function createEngineService(root) {
|
|
32
|
-
const host = installServiceHost(root);
|
|
43
|
+
export function createEngineService(root, ignoreFileSettingsAvailable = false) {
|
|
44
|
+
const host = installServiceHost(root, ignoreFileSettingsAvailable);
|
|
33
45
|
const monitor = createMonitor(root, host);
|
|
34
46
|
const execute = (operation, payload, execution) => host.run(execution, async () => {
|
|
35
47
|
if (operation === "ignore.capabilities") {
|
|
36
48
|
execution.validate();
|
|
37
|
-
return { available:
|
|
49
|
+
return { available: ignoreFileSettingsAvailable };
|
|
38
50
|
}
|
|
39
51
|
if (operation === "ignore.migration-offer" || operation === "ignore.migration-defer") {
|
|
40
52
|
execution.validate();
|
|
@@ -47,23 +59,60 @@ export function createEngineService(root) {
|
|
|
47
59
|
execution.validate();
|
|
48
60
|
throw new Error("Daemon ignore-file saves are unavailable. Edit the existing rule file manually.");
|
|
49
61
|
}
|
|
62
|
+
const ignoreFileChange = operation === "ignore.migrate" || operation === "ignore.switch";
|
|
63
|
+
if (ignoreFileChange && !ignoreFileSettingsAvailable) {
|
|
64
|
+
execution.validate();
|
|
65
|
+
throw new Error("Unsupported engine operation.");
|
|
66
|
+
}
|
|
50
67
|
await monitor.pause();
|
|
51
68
|
execution.validate();
|
|
52
|
-
if (
|
|
53
|
-
|
|
69
|
+
if (ignoreFileChange) {
|
|
70
|
+
const { runIgnorePolicyChange } = await import("./engine/ignore/ignore-settings.js");
|
|
71
|
+
execution.validate();
|
|
72
|
+
return runIgnorePolicyChange(operation, payload, {
|
|
73
|
+
...execution,
|
|
74
|
+
committed() {
|
|
75
|
+
execution.committed();
|
|
76
|
+
monitor.settingsCommitted(true);
|
|
77
|
+
},
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
if (operation === "daemon.authorize") {
|
|
81
|
+
const authorized = await authorizeAfterExit(execution, payload);
|
|
82
|
+
if (authorized?.afterExit)
|
|
83
|
+
monitor.reviewedPolicy(authorized.config);
|
|
84
|
+
return Boolean(authorized);
|
|
85
|
+
}
|
|
86
|
+
if (operation === "daemon.authorize-connected") {
|
|
87
|
+
const facts = execution.facts();
|
|
88
|
+
if (!record(payload) ||
|
|
89
|
+
typeof payload.fingerprint !== "string" ||
|
|
90
|
+
!facts?.hasUI ||
|
|
91
|
+
!["tui", "rpc"].includes(facts.mode))
|
|
92
|
+
throw new Error("Automatic policy authorization requires an interactive review.");
|
|
93
|
+
const { loadConfigForCheck } = await import("./engine/settings/config.js");
|
|
94
|
+
const config = await loadConfigForCheck(undefined, execution.signal);
|
|
95
|
+
execution.validate();
|
|
96
|
+
const approved = await reviewAutomaticPolicy(execution, config, payload.fingerprint);
|
|
97
|
+
if (approved)
|
|
98
|
+
monitor.reviewedPolicy(config);
|
|
99
|
+
return approved;
|
|
100
|
+
}
|
|
54
101
|
if (operation === "daemon.handover") {
|
|
55
102
|
await requireHandover(execution);
|
|
56
103
|
return true;
|
|
57
104
|
}
|
|
58
105
|
if (operation === "daemon.policy") {
|
|
59
|
-
const {
|
|
60
|
-
const config = await
|
|
106
|
+
const { loadConfigForCheck } = await import("./engine/settings/config.js");
|
|
107
|
+
const config = await loadConfigForCheck(undefined, execution.signal);
|
|
108
|
+
execution.validate();
|
|
61
109
|
const fingerprint = consentFingerprint(root, config);
|
|
62
110
|
const saved = readConsent(root)?.setups[config.setupName];
|
|
63
111
|
const facts = execution.facts();
|
|
64
112
|
return {
|
|
65
113
|
setup: config.setupName,
|
|
66
114
|
fingerprint,
|
|
115
|
+
automatic: automaticPolicyAuthorized(root, config),
|
|
67
116
|
afterExit: Boolean(saved?.afterExit &&
|
|
68
117
|
saved.fingerprint === fingerprint &&
|
|
69
118
|
JSON.stringify(saved.model) === JSON.stringify(facts?.model) &&
|
|
@@ -98,11 +147,12 @@ export function createEngineService(root) {
|
|
|
98
147
|
(typeof payload.expected !== "string" || !/^[a-f0-9]{64}$/u.test(payload.expected))) ||
|
|
99
148
|
!record(payload.next))
|
|
100
149
|
throw new Error("Invalid settings mutation.");
|
|
101
|
-
const { updateLocalConfigDocument, peekLocalConfigDocument } = await import("./engine/settings/config-file.js");
|
|
150
|
+
const { localConfigPath, updateLocalConfigDocument, peekLocalConfigDocument } = await import("./engine/settings/config-file.js");
|
|
102
151
|
const { localConfigTemplate } = await import("./engine/settings/settings-store.js");
|
|
103
152
|
const { validateSettingsDocument } = await import("./engine/settings/settings-validation.js");
|
|
104
153
|
const next = validateSettingsDocument(payload.next);
|
|
105
|
-
|
|
154
|
+
const nextMixed = Object.values(next.syncSetups).some((setup) => setup.sync.pathPolicy === "ignore-file");
|
|
155
|
+
if (!ignoreFileSettingsAvailable && nextMixed) {
|
|
106
156
|
throw new Error("Ignore-file setup activation is not available in this Daemon build.");
|
|
107
157
|
}
|
|
108
158
|
if (Buffer.byteLength(JSON.stringify(next)) > MAX_SETTINGS_BYTES)
|
|
@@ -113,14 +163,44 @@ export function createEngineService(root) {
|
|
|
113
163
|
if (documentFingerprint(view) !== payload.expected)
|
|
114
164
|
throw new Error("Settings changed; reopen the review before saving.");
|
|
115
165
|
};
|
|
116
|
-
|
|
166
|
+
const original = await peekLocalConfigDocument();
|
|
167
|
+
validateSource(original);
|
|
168
|
+
const before = original && validateSettingsDocument(original.parsed);
|
|
169
|
+
const wasMixed = before && Object.values(before.syncSetups).some((setup) => setup.sync.pathPolicy === "ignore-file");
|
|
170
|
+
let prepareSource;
|
|
171
|
+
if (ignoreFileSettingsAvailable && (nextMixed || wasMixed)) {
|
|
172
|
+
if (original && original.path !== localConfigPath())
|
|
173
|
+
throw new Error("This settings change requires pi-sync.json. No settings were saved; use the canonical filename and reopen the review.");
|
|
174
|
+
const { newIgnoreFilename, reviewNewIgnoreSource, prepareReviewedIgnoreSource } = await import("./engine/ignore/ignore-settings.js");
|
|
175
|
+
execution.validate();
|
|
176
|
+
const filename = newIgnoreFilename(before, next);
|
|
177
|
+
if (filename) {
|
|
178
|
+
const reviewed = await reviewNewIgnoreSource(root, filename, execution);
|
|
179
|
+
validateSource(await peekLocalConfigDocument());
|
|
180
|
+
prepareSource = async () => {
|
|
181
|
+
await prepareReviewedIgnoreSource(root, reviewed, execution);
|
|
182
|
+
execution.validate();
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
else if (wasMixed && !nextMixed) {
|
|
186
|
+
prepareSource = async () => {
|
|
187
|
+
execution.validate();
|
|
188
|
+
revokeAfterExitGrants(root);
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
}
|
|
117
192
|
await requireHandover(execution);
|
|
118
193
|
execution.validate();
|
|
119
|
-
|
|
194
|
+
const saved = await updateLocalConfigDocument(localConfigTemplate(), () => {
|
|
120
195
|
execution.validate();
|
|
121
196
|
validateSettingsDocument(next);
|
|
122
197
|
return next;
|
|
123
|
-
}, validateSettingsDocument, execution.signal, validateSource);
|
|
198
|
+
}, validateSettingsDocument, execution.signal, validateSource, prepareSource);
|
|
199
|
+
if (!original || JSON.stringify(original.parsed) !== JSON.stringify(saved)) {
|
|
200
|
+
monitor.settingsCommitted(Boolean(wasMixed || nextMixed));
|
|
201
|
+
execution.committed();
|
|
202
|
+
}
|
|
203
|
+
return saved;
|
|
124
204
|
}
|
|
125
205
|
const ctx = createServiceContext(execution);
|
|
126
206
|
if (operation === "initialize")
|
|
@@ -131,8 +211,8 @@ export function createEngineService(root) {
|
|
|
131
211
|
const { withStateDirectoryAccess } = await import("./engine/state/state-directory.js");
|
|
132
212
|
const { withLock } = await import("./engine/state/lock.js");
|
|
133
213
|
return withJobTimings(ctx, execution, "daemon inspection", (timings) => withStateDirectoryAccess(() => withLock("startup-check", async () => {
|
|
134
|
-
const {
|
|
135
|
-
const config = await
|
|
214
|
+
const { loadConfigForCheck, syncCheckConfigFingerprint } = await import("./engine/settings/config.js");
|
|
215
|
+
const config = await loadConfigForCheck(payload.setup, execution.signal);
|
|
136
216
|
execution.validate();
|
|
137
217
|
if (payload.fingerprint !== syncCheckConfigFingerprint(config))
|
|
138
218
|
throw new Error("Settings changed before inspection.");
|
|
@@ -159,13 +239,14 @@ export function createEngineService(root) {
|
|
|
159
239
|
];
|
|
160
240
|
if (!supported.includes(operation))
|
|
161
241
|
throw new Error("Unsupported engine operation.");
|
|
162
|
-
const
|
|
242
|
+
const isAutomatic = operation === "startup-transfer" || operation === "shutdown";
|
|
243
|
+
const options = optionsFrom(payload, execution, isAutomatic);
|
|
163
244
|
if (!options.reload)
|
|
164
245
|
ctx.reload = undefined;
|
|
165
246
|
if (operation === "shutdown") {
|
|
166
247
|
const { loadConfigForCheck } = await import("./engine/settings/config.js");
|
|
167
248
|
const { syncSessionsSelected } = await import("./engine/sync/sync-policy.js");
|
|
168
|
-
const config = await loadConfigForCheck();
|
|
249
|
+
const config = await loadConfigForCheck(undefined, execution.signal);
|
|
169
250
|
execution.validate();
|
|
170
251
|
if (!config.automatic || !syncSessionsSelected(config))
|
|
171
252
|
return;
|
|
@@ -188,11 +269,16 @@ export function createEngineService(root) {
|
|
|
188
269
|
return result;
|
|
189
270
|
}
|
|
190
271
|
return withStateDirectoryAccess(async () => {
|
|
191
|
-
|
|
192
|
-
|
|
272
|
+
const automatic = isAutomatic
|
|
273
|
+
? await captureAutomaticAuthorization(execution, options.automaticFingerprint)
|
|
274
|
+
: undefined;
|
|
275
|
+
if (automatic)
|
|
276
|
+
options.background = { validate: automatic.validate };
|
|
193
277
|
if (["push", "pull", "sync", "startup-transfer", "shutdown", "conflicts", "rollback"].includes(operation)) {
|
|
194
278
|
await requireHandover(execution);
|
|
279
|
+
await automatic?.refresh();
|
|
195
280
|
await initialize(ctx, execution, false);
|
|
281
|
+
await automatic?.refresh();
|
|
196
282
|
}
|
|
197
283
|
const { withLock, unlock } = await import("./engine/state/lock.js");
|
|
198
284
|
if (operation === "unlock")
|
|
@@ -207,9 +293,8 @@ export function createEngineService(root) {
|
|
|
207
293
|
return pushSessionsOnShutdown(ctx, options, { operations: async () => operations });
|
|
208
294
|
}
|
|
209
295
|
if (operation === "startup-transfer") {
|
|
210
|
-
const { loadConfig } = await import("./engine/settings/config.js");
|
|
211
296
|
const { startupTransferEnabled } = await import("./engine/sync/agent-policy.js");
|
|
212
|
-
if (!startupTransferEnabled(
|
|
297
|
+
if (!automatic || !startupTransferEnabled(automatic.config) || !ctx.isIdle())
|
|
213
298
|
throw new Error("Startup transfer is no longer authorized or idle.");
|
|
214
299
|
options.auto = true;
|
|
215
300
|
options.yes = true;
|
|
@@ -220,25 +305,33 @@ export function createEngineService(root) {
|
|
|
220
305
|
const run = async () => {
|
|
221
306
|
const { prepareResolverHost } = await import("./resolver-host.js");
|
|
222
307
|
const { loadConfig } = await import("./engine/settings/config.js");
|
|
223
|
-
const config = await loadConfig(options.setup);
|
|
308
|
+
const config = await loadConfig(options.setup, execution.signal);
|
|
309
|
+
await automatic?.refresh();
|
|
310
|
+
automatic?.validate(config);
|
|
224
311
|
execution.validate();
|
|
312
|
+
if (config.agentMode && !automaticPolicyAuthorized(root, config)) {
|
|
313
|
+
throw new Error("Autonomous sync requires a separate policy review. Use Settings → Review automatic transfers, or choose a reviewed push or pull.");
|
|
314
|
+
}
|
|
225
315
|
if (operation === "sync" && !options.agentRetryRefusal)
|
|
226
|
-
monitor.explicitSync(config
|
|
316
|
+
monitor.explicitSync(config, execution);
|
|
227
317
|
const binding = JSON.stringify(execution.facts()?.model);
|
|
228
318
|
const resolver = await prepareResolverHost(root, config.agentMode ? execution.facts()?.model : undefined, execution.signal);
|
|
229
319
|
try {
|
|
320
|
+
await automatic?.refresh();
|
|
230
321
|
ctx.modelUnavailableReason = resolver.unavailable;
|
|
231
322
|
Object.defineProperty(ctx, "model", {
|
|
232
323
|
get: () => (JSON.stringify(execution.facts()?.model) === binding ? resolver.model : undefined),
|
|
233
324
|
});
|
|
234
325
|
ctx.validateModel = async () => {
|
|
235
326
|
const fresh = await execution.request("model-binding", {});
|
|
327
|
+
await automatic?.refresh();
|
|
236
328
|
execution.validate();
|
|
237
329
|
if (JSON.stringify(fresh ?? undefined) !== binding)
|
|
238
330
|
throw new Error("Selected provider/model capability changed before dispatch.");
|
|
239
331
|
};
|
|
240
332
|
ctx.modelRegistry = {
|
|
241
333
|
streamSimple: (model, context, options) => {
|
|
334
|
+
automatic?.validate();
|
|
242
335
|
execution.validate();
|
|
243
336
|
if (JSON.stringify(execution.facts()?.model) !== binding)
|
|
244
337
|
throw new Error("Selected model changed before dispatch.");
|
|
@@ -250,13 +343,17 @@ export function createEngineService(root) {
|
|
|
250
343
|
const { withAgentSyncLock } = await import("./engine/sync/agent-sync.js");
|
|
251
344
|
return await withAgentSyncLock(ctx, options, async (current) => {
|
|
252
345
|
if (operation === "startup-transfer") {
|
|
253
|
-
const { loadConfig } = await import("./engine/settings/config.js");
|
|
254
346
|
const { startupTransferEnabled } = await import("./engine/sync/agent-policy.js");
|
|
255
|
-
|
|
347
|
+
if (!automatic)
|
|
348
|
+
throw new Error("Missing startup transfer authorization.");
|
|
349
|
+
await automatic.refresh();
|
|
350
|
+
const config = automatic.config;
|
|
256
351
|
execution.validate();
|
|
257
352
|
const { inspectSync } = await import("./engine/sync/sync-inspection.js");
|
|
258
353
|
const { snapshotOptionsForContext } = await import("./engine/snapshot/session-paths.js");
|
|
354
|
+
await automatic.refresh();
|
|
259
355
|
const inspection = await inspectSync(config, snapshotOptionsForContext(ctx, config), current.signal);
|
|
356
|
+
await automatic.refresh();
|
|
260
357
|
execution.validate();
|
|
261
358
|
if (!startupTransferEnabled(config) ||
|
|
262
359
|
!ctx.isIdle() ||
|
package/dist/monitor.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { AnySyncConfig } from "./engine/settings/settings-types.js";
|
|
1
2
|
import type { IdleExitPolicy } from "./idle-exit.js";
|
|
2
3
|
import type { Execution } from "./protocol.js";
|
|
3
4
|
import type { startServer } from "./server.js";
|
|
@@ -7,7 +8,9 @@ export declare function createMonitor(root: string, host: ReturnType<typeof inst
|
|
|
7
8
|
schedule: () => void;
|
|
8
9
|
lifetime: () => Promise<IdleExitPolicy>;
|
|
9
10
|
blockAutomatic: () => void;
|
|
10
|
-
explicitSync(
|
|
11
|
+
explicitSync(config: AnySyncConfig, execution: Execution): void;
|
|
12
|
+
reviewedPolicy(config: AnySyncConfig): void;
|
|
13
|
+
settingsCommitted(blockNewPolicy: boolean): void;
|
|
11
14
|
pause(): Promise<void>;
|
|
12
15
|
factsChanged(): Promise<void>;
|
|
13
16
|
close(): Promise<void>;
|
package/dist/monitor.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import { ConsentPublicationError, consentFingerprint, readConsent, revokeChangedBindings } from "./consent.js";
|
|
4
|
-
import { loadConfigForCheck } from "./engine/settings/config.js";
|
|
3
|
+
import { automaticPolicyAuthorized, ConsentPublicationError, consentFingerprint, participantBinding, readConsent, revokeChangedBindings, } from "./consent.js";
|
|
4
|
+
import { loadConfigForCheck, syncCheckConfigFingerprint } from "./engine/settings/config.js";
|
|
5
5
|
import { createEngineLoaders } from "./engine/sync/sync-loaders.js";
|
|
6
6
|
import { createServiceContext } from "./service-host.js";
|
|
7
7
|
export function createMonitor(root, host) {
|
|
@@ -11,12 +11,19 @@ export function createMonitor(root, host) {
|
|
|
11
11
|
let closed = false;
|
|
12
12
|
let authorizationFailed = false;
|
|
13
13
|
let scheduled = false;
|
|
14
|
-
|
|
14
|
+
let settingsGeneration = 0;
|
|
15
|
+
let blockedParticipants;
|
|
16
|
+
const participatingSessions = () => JSON.stringify(server
|
|
17
|
+
?.participants()
|
|
18
|
+
.map(({ id, generation }) => `${id}:${generation}`)
|
|
19
|
+
.sort() ?? []);
|
|
20
|
+
const policyNeedsReview = () => blockedParticipants === participatingSessions();
|
|
21
|
+
let monitoredPolicy;
|
|
15
22
|
const retries = new Map();
|
|
23
|
+
const retryOwner = (peer) => JSON.stringify([peer.generation, peer.cwd, peer.sessionId, peer.sessionFile, peer.sessionDir, peer.model]);
|
|
16
24
|
let epoch;
|
|
17
25
|
const timingOwners = new WeakMap();
|
|
18
26
|
const loaders = createEngineLoaders();
|
|
19
|
-
const operations = loaders.operations;
|
|
20
27
|
let continuous;
|
|
21
28
|
function schedule() {
|
|
22
29
|
if (closed || scheduled || !server)
|
|
@@ -42,7 +49,7 @@ export function createMonitor(root, host) {
|
|
|
42
49
|
await current.promise;
|
|
43
50
|
}
|
|
44
51
|
function unattendedGrant(config) {
|
|
45
|
-
if (!config.continuous || !config.agentMode)
|
|
52
|
+
if (!config.continuous || !config.agentMode || !automaticPolicyAuthorized(root, config))
|
|
46
53
|
return undefined;
|
|
47
54
|
const saved = readConsent(root)?.setups[config.setupName];
|
|
48
55
|
return saved?.afterExit && saved.fingerprint === consentFingerprint(root, config) ? saved : undefined;
|
|
@@ -57,7 +64,7 @@ export function createMonitor(root, host) {
|
|
|
57
64
|
const config = await loadConfigForCheck();
|
|
58
65
|
if (closed || authorizationFailed)
|
|
59
66
|
return "pause";
|
|
60
|
-
return unattendedGrant(config) ? "keep" : "exit";
|
|
67
|
+
return !policyNeedsReview() && unattendedGrant(config) ? "keep" : "exit";
|
|
61
68
|
}
|
|
62
69
|
catch {
|
|
63
70
|
// Invalid evidence is not an implicit revocation or permission to discard a safety barrier.
|
|
@@ -68,14 +75,25 @@ export function createMonitor(root, host) {
|
|
|
68
75
|
const service = server;
|
|
69
76
|
if (!service)
|
|
70
77
|
return;
|
|
71
|
-
|
|
72
|
-
if (!available())
|
|
78
|
+
if (closed || authorizationFailed || policyNeedsReview() || task || !service.isIdle())
|
|
73
79
|
return;
|
|
74
|
-
const
|
|
75
|
-
|
|
80
|
+
const generation = settingsGeneration;
|
|
81
|
+
const participants = service.participantGeneration?.();
|
|
82
|
+
const participantsToken = participantBinding(service);
|
|
83
|
+
const consentToken = JSON.stringify(readConsent(root));
|
|
84
|
+
const sameAuthorization = () => !closed &&
|
|
85
|
+
!authorizationFailed &&
|
|
86
|
+
!policyNeedsReview() &&
|
|
87
|
+
server === service &&
|
|
88
|
+
generation === settingsGeneration &&
|
|
89
|
+
participants === service.participantGeneration?.() &&
|
|
90
|
+
participantsToken === participantBinding(service) &&
|
|
91
|
+
consentToken === JSON.stringify(readConsent(root));
|
|
92
|
+
const available = () => !task && service.isIdle() && sameAuthorization();
|
|
93
|
+
if (!consentToken || !available())
|
|
76
94
|
return;
|
|
77
95
|
const config = await loadConfigForCheck();
|
|
78
|
-
if (!available())
|
|
96
|
+
if (!available() || !automaticPolicyAuthorized(root, config))
|
|
79
97
|
return;
|
|
80
98
|
if (!config.continuous || !config.agentMode) {
|
|
81
99
|
retries.clear();
|
|
@@ -87,6 +105,9 @@ export function createMonitor(root, host) {
|
|
|
87
105
|
const peers = service.participants();
|
|
88
106
|
if (peers.some((peer) => !peer.idle || peer.ready !== true))
|
|
89
107
|
return;
|
|
108
|
+
const fingerprint = syncCheckConfigFingerprint(config);
|
|
109
|
+
if (config.reservedIgnoreNames !== undefined && monitoredPolicy !== undefined && monitoredPolicy !== fingerprint)
|
|
110
|
+
return;
|
|
90
111
|
const authorized = unattendedGrant(config);
|
|
91
112
|
const selected = peers.toSorted((a, b) => a.id.localeCompare(b.id))[0];
|
|
92
113
|
if (!selected && !authorized)
|
|
@@ -135,7 +156,9 @@ export function createMonitor(root, host) {
|
|
|
135
156
|
};
|
|
136
157
|
const execution = { ...original, facts: () => stableFacts };
|
|
137
158
|
const allowed = (currentConfig = config) => {
|
|
138
|
-
if (
|
|
159
|
+
if (controller.signal.aborted ||
|
|
160
|
+
!sameAuthorization() ||
|
|
161
|
+
syncCheckConfigFingerprint(currentConfig) !== fingerprint)
|
|
139
162
|
return false;
|
|
140
163
|
const current = service.participants();
|
|
141
164
|
if (current.length)
|
|
@@ -159,12 +182,11 @@ export function createMonitor(root, host) {
|
|
|
159
182
|
timingOwners.set(ctx, execution);
|
|
160
183
|
ctx.backgroundAuthorized = allowed;
|
|
161
184
|
ctx.isIdle = () => Boolean(service.isIdle() && allowed());
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
};
|
|
185
|
+
const refresh = async () => {
|
|
186
|
+
execution.validate();
|
|
187
|
+
if (!allowed(await loadConfigForCheck(undefined, controller.signal)))
|
|
188
|
+
throw new Error("Daemon automatic authorization changed.");
|
|
189
|
+
execution.validate();
|
|
168
190
|
};
|
|
169
191
|
const sessionSignal = epoch.controller.signal;
|
|
170
192
|
const debug = epoch.debug;
|
|
@@ -177,30 +199,47 @@ export function createMonitor(root, host) {
|
|
|
177
199
|
void host
|
|
178
200
|
.run(execution, async () => {
|
|
179
201
|
const { prepareResolverHost } = await import("./resolver-host.js");
|
|
202
|
+
await refresh();
|
|
180
203
|
const resolver = await prepareResolverHost(root, binding, controller.signal);
|
|
181
204
|
try {
|
|
182
|
-
|
|
183
|
-
|
|
205
|
+
await refresh();
|
|
206
|
+
if (config.reservedIgnoreNames !== undefined)
|
|
207
|
+
monitoredPolicy = fingerprint;
|
|
184
208
|
ctx.model = resolver.model;
|
|
185
209
|
ctx.modelUnavailableReason = resolver.unavailable;
|
|
186
|
-
ctx.modelRegistry =
|
|
210
|
+
ctx.modelRegistry = {
|
|
211
|
+
streamSimple: (model, context, options) => {
|
|
212
|
+
execution.validate();
|
|
213
|
+
if (!allowed())
|
|
214
|
+
throw new Error("Daemon authorization changed before model dispatch.");
|
|
215
|
+
return resolver.registry.streamSimple(model, context, options);
|
|
216
|
+
},
|
|
217
|
+
};
|
|
187
218
|
ctx.validateModel = async () => {
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
for (const peer of service.participants()) {
|
|
219
|
+
await refresh();
|
|
220
|
+
for (const peer of peers) {
|
|
191
221
|
const fresh = await execution.request("model-binding", { background: true }, peer.id);
|
|
192
222
|
if (JSON.stringify(fresh ?? undefined) !== JSON.stringify(binding))
|
|
193
223
|
throw new Error("Participating model changed before dispatch.");
|
|
194
|
-
|
|
195
|
-
throw new Error("Daemon authorization changed during model validation.");
|
|
224
|
+
await refresh();
|
|
196
225
|
}
|
|
197
226
|
};
|
|
198
227
|
const explicitRetry = service.participants().some((peer) => {
|
|
199
228
|
const retry = retries.get(peer.id);
|
|
200
|
-
return retry?.
|
|
229
|
+
return retry?.fingerprint === fingerprint && retry.owner === retryOwner(peer) && !retry.signal.aborted;
|
|
201
230
|
});
|
|
202
231
|
retries.clear();
|
|
203
|
-
activeContinuous.start(ctx, sessionSignal, explicitRetry ? config.setupName : false, debug)
|
|
232
|
+
activeContinuous.start(ctx, sessionSignal, explicitRetry ? config.setupName : false, debug, async (run) => {
|
|
233
|
+
await refresh();
|
|
234
|
+
const attempt = new AbortController();
|
|
235
|
+
const owner = service.backgroundExecution(AbortSignal.any([attempt.signal, controller.signal]));
|
|
236
|
+
try {
|
|
237
|
+
return await host.run({ ...owner, facts: execution.facts }, () => run(owner.committed));
|
|
238
|
+
}
|
|
239
|
+
finally {
|
|
240
|
+
attempt.abort();
|
|
241
|
+
}
|
|
242
|
+
});
|
|
204
243
|
await new Promise((resolve) => {
|
|
205
244
|
if (controller.signal.aborted)
|
|
206
245
|
resolve();
|
|
@@ -229,10 +268,23 @@ export function createMonitor(root, host) {
|
|
|
229
268
|
schedule,
|
|
230
269
|
lifetime,
|
|
231
270
|
blockAutomatic,
|
|
232
|
-
explicitSync(
|
|
271
|
+
explicitSync(config, execution) {
|
|
233
272
|
const peer = execution.facts();
|
|
234
|
-
if (
|
|
235
|
-
|
|
273
|
+
if (closed || !peer)
|
|
274
|
+
return;
|
|
275
|
+
const fingerprint = syncCheckConfigFingerprint(config);
|
|
276
|
+
retries.set(peer.id, { fingerprint, owner: retryOwner(peer), signal: execution.signal });
|
|
277
|
+
},
|
|
278
|
+
reviewedPolicy(config) {
|
|
279
|
+
blockedParticipants = undefined;
|
|
280
|
+
monitoredPolicy = config.reservedIgnoreNames === undefined ? undefined : syncCheckConfigFingerprint(config);
|
|
281
|
+
},
|
|
282
|
+
settingsCommitted(blockNewPolicy) {
|
|
283
|
+
settingsGeneration++;
|
|
284
|
+
retries.clear();
|
|
285
|
+
if (blockNewPolicy)
|
|
286
|
+
blockedParticipants = participatingSessions();
|
|
287
|
+
task?.controller.abort(new DOMException("Sync settings committed", "AbortError"));
|
|
236
288
|
},
|
|
237
289
|
async pause() {
|
|
238
290
|
transition = transition.then(stop);
|
|
@@ -244,7 +296,7 @@ export function createMonitor(root, host) {
|
|
|
244
296
|
if (server) {
|
|
245
297
|
const peers = server.participants();
|
|
246
298
|
for (const [id, retry] of retries)
|
|
247
|
-
if (retry.signal.aborted || !peers.some((peer) => peer.id === id && peer
|
|
299
|
+
if (retry.signal.aborted || !peers.some((peer) => peer.id === id && retryOwner(peer) === retry.owner))
|
|
248
300
|
retries.delete(id);
|
|
249
301
|
revokeChangedBindings(root, peers);
|
|
250
302
|
}
|
package/dist/server.d.ts
CHANGED
|
@@ -16,6 +16,7 @@ export declare function startServer(root: string, execute: Execute, hooks?: Serv
|
|
|
16
16
|
backgroundExecution: (signal: AbortSignal) => Execution;
|
|
17
17
|
readonly retainedEndpoint: string | undefined;
|
|
18
18
|
participants: () => ClientFacts[];
|
|
19
|
+
participantGeneration: () => number;
|
|
19
20
|
liveClients: () => ClientFacts[];
|
|
20
21
|
expireClients: () => Promise<void>;
|
|
21
22
|
checkLifetime: () => Promise<void>;
|