@zieglar/pi-chat-exchange 0.2.2 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +11 -7
  2. package/dist/bin/mcp-stdio.js +124 -56
  3. package/dist/control/mcp/endpoint-discovery.js +60 -0
  4. package/dist/control/mcp/messaging-tools.js +12 -2
  5. package/dist/control/mcp/server.js +10 -2
  6. package/dist/hooks/config.js +106 -0
  7. package/dist/hooks/events.js +19 -0
  8. package/dist/hooks/runner.js +187 -0
  9. package/dist/host/bound-endpoint.js +19 -6
  10. package/dist/host/endpoint-host.js +92 -4
  11. package/dist/host/mcp-binding-config.js +41 -5
  12. package/dist/runtime/native-readiness.js +8 -5
  13. package/dist/storage/creation.js +16 -0
  14. package/dist/storage/ownership.js +45 -1
  15. package/dist/tunnel/background-authorization.js +343 -0
  16. package/dist/tunnel/background-manager.js +104 -8
  17. package/dist/tunnel/background-scope.js +69 -0
  18. package/dist/tunnel/codes.js +1 -1
  19. package/dist/tunnel/hooks-management-ui.js +225 -0
  20. package/dist/tunnel/hooks-management.js +431 -0
  21. package/dist/tunnel/live-adoption-observation.js +136 -0
  22. package/dist/tunnel/live-adoption-probe.js +240 -0
  23. package/dist/tunnel/live-connection-status.js +136 -0
  24. package/dist/tunnel/live-mcp-composition.js +143 -0
  25. package/dist/tunnel/live-process-observation.js +98 -0
  26. package/dist/tunnel/live-session-migration.js +169 -0
  27. package/dist/tunnel/live-session-policy.js +578 -0
  28. package/dist/tunnel/manager-panel.js +4 -2
  29. package/dist/tunnel/manager-ui.js +71 -15
  30. package/dist/tunnel/multi-session-admission.js +1 -1
  31. package/dist/tunnel/multi-session-policy.js +45 -13
  32. package/dist/tunnel/setup-ui.js +2 -4
  33. package/dist/tunnel/status-ui.js +34 -0
  34. package/package.json +4 -1
  35. package/pi-extension/allowlist.example.json +12 -1
  36. package/pi-extension/desktop-target.ts +157 -0
  37. package/pi-extension/index.ts +1128 -132
  38. package/pi-extension/live-session-profile.ts +49 -0
  39. package/pi-extension/live-session-runtime.ts +59 -0
  40. package/pi-extension/multi-session-commands.ts +114 -3
  41. package/pi-extension/multi-session-runtime.ts +63 -11
  42. package/pi-extension/native-inbound.ts +235 -0
  43. package/pi-extension/ownership-feedback.ts +100 -0
  44. package/pi-extension/session-onboarding.ts +154 -0
  45. package/pi-extension/session-recovery.ts +214 -0
  46. package/skills/ce-hook-script/SKILL.md +62 -0
  47. package/skills/ce-hook-script/examples/file-notification.py +79 -0
@@ -0,0 +1,431 @@
1
+ /**
2
+ * HANDOFF-CE-HOOKS-MANAGEMENT-01 — native Hook configuration orchestration.
3
+ *
4
+ * This module is CONFIGURATION ONLY. It never loads a Host, never starts or
5
+ * stops a transport, never reads a credential value and never executes a
6
+ * configured Hook command. It writes two private, operator-owned artifacts:
7
+ *
8
+ * - the versioned live chain (through the existing expected-tip publisher), and
9
+ * - the selected immutable MCP binding pair plus the Profile pointer.
10
+ *
11
+ * Both are separate commit boundaries. A chain publication that cannot be
12
+ * observed afterwards is reported as pending; it is never retried, rebased or
13
+ * rolled back here.
14
+ */
15
+ import fs from "node:fs";
16
+ import { createHash, randomUUID } from "node:crypto";
17
+ import { basename, dirname } from "node:path";
18
+ import { execFile } from "node:child_process";
19
+ import { isDeepStrictEqual } from "node:util";
20
+ import { parseHookRules } from "../hooks/config.js";
21
+ import { parseMcpBindingConfig } from "../host/mcp-binding-config.js";
22
+ import { parseTunnelProfile } from "./background-manager.js";
23
+ import { TunnelRefusal } from "./codes.js";
24
+ import { parseTunnelMcpCommand, replaceTunnelMcpBindingPath } from "./profile.js";
25
+ import { publishMessagingGeneration, readMessagingGeneration, readPrivateMessagingFile } from "./messaging-config.js";
26
+ import { createLivePolicyRegistration, prepareLivePolicyUpgrade, readLiveHookPublication, readLivePolicy } from "./live-session-policy.js";
27
+ const invalid = (field = "hooks.management") => { throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", field); };
28
+ const conflict = () => { throw new TunnelRefusal("CE_TUNNEL_CONFIG_CONFLICT", "hooks.preview"); };
29
+ const hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
30
+ const MAX_PROFILE_BYTES = 65_536;
31
+ /** Pure candidate edit. The input array is never mutated. */
32
+ export function replaceHookRule(rules, edit) {
33
+ if (edit.kind === "add")
34
+ return parseHookRules([...rules, edit.rule]);
35
+ if (!rules.some(rule => rule.id === edit.id))
36
+ return invalid("hooks.rule.missing");
37
+ if (edit.kind === "remove")
38
+ return parseHookRules(rules.filter(rule => rule.id !== edit.id));
39
+ return parseHookRules(rules.map(rule => rule.id !== edit.id ? rule
40
+ : edit.kind === "edit" ? edit.rule : { ...rule, enabled: edit.kind === "enable" }));
41
+ }
42
+ /** The immutable pair identity: exactly the bytes the writer will publish. */
43
+ function pairGeneration(config, document) {
44
+ const binding = `${JSON.stringify({ version: 1, ...config }, null, 2)}\n`;
45
+ const sidecar = `${JSON.stringify(document, null, 2)}\n`;
46
+ return createHash("sha256").update(binding).update("\u0000").update(sidecar).digest("hex");
47
+ }
48
+ /** Live routing follows active history, including peers registered after launch.
49
+ * Static binding recipients do not enumerate v2 Hook targets. */
50
+ function targetsFor(snapshot, hooks) {
51
+ return Object.freeze(hooks.filter(rule => rule.enabled).map(rule => {
52
+ if (rule.recipient.adapter !== "pi")
53
+ return invalid("hooks.target.recipient");
54
+ const registration = snapshot.manifest.registrations.find(r => r.status === "active" && r.endpointId === rule.recipient.endpointId);
55
+ if (!registration)
56
+ return invalid("hooks.target.active");
57
+ return Object.freeze({ ruleId: rule.id, endpointId: registration.endpointId, runtimeSessionId: registration.runtimeSessionId, epoch: registration.epoch });
58
+ }));
59
+ }
60
+ export function createHooksManagement(options) {
61
+ const { profilePath, runtimeSessionId } = options;
62
+ // A preview is a local one-shot handle. No JSON, model or MCP input is a grant.
63
+ const previews = new WeakMap();
64
+ const io = { openSync: fs.openSync, closeSync: fs.closeSync, writeFileSync: fs.writeFileSync, fsyncSync: fs.fsyncSync, renameSync: fs.renameSync, ...options.io };
65
+ function inspect() {
66
+ options.assertCurrent();
67
+ const bytes = readPrivateMessagingFile(profilePath)?.bytes ?? invalid("hooks.profile");
68
+ const text = bytes.toString("utf8");
69
+ const facts = parseTunnelProfile(text);
70
+ if (!facts.mcpCommand)
71
+ return invalid("hooks.profile.command");
72
+ const bindingPath = parseTunnelMcpCommand(facts.mcpCommand).bindingPath;
73
+ const pair = readMessagingGeneration(profilePath, bindingPath, facts.keyFile) ?? invalid("hooks.binding");
74
+ const ref = pair.config.admissionPolicy;
75
+ if (!ref || (ref.kind !== "ce-live-session-v1" && ref.kind !== "ce-live-session-v2"))
76
+ return invalid("hooks.live.required");
77
+ if (Reflect.ownKeys(pair.document).length !== 3 || !isDeepStrictEqual(pair.document.ref, ref) || pair.document.version !== 1 || pair.document.kind !== (ref.kind === "ce-live-session-v1" ? "ce-live-launch-v1" : "ce-live-launch-v2"))
78
+ return invalid("hooks.launch");
79
+ if (ref.kind === "ce-live-session-v2" && ref.profilePath !== profilePath)
80
+ return invalid("hooks.profile.selection");
81
+ const snapshot = readLivePolicy(ref, { credentialFile: facts.keyFile });
82
+ const m = snapshot.manifest;
83
+ const c = pair.config;
84
+ if (m.identity.tunnelId !== facts.tunnelId || m.identity.organizationId !== (facts.organizationId ?? null) ||
85
+ !isDeepStrictEqual(m.store, c.store) || !isDeepStrictEqual(m.exchange, c.exchange) ||
86
+ !isDeepStrictEqual(m.chatgptEndpoint, c.endpoint) || m.mcp.payloadRead !== c.payloadRead.enabled || m.mcp.ack !== c.ack.enabled)
87
+ return invalid("hooks.identity");
88
+ if (c.managed !== undefined && (c.managed.tunnelId !== facts.tunnelId || (c.managed.organizationId ?? null) !== m.identity.organizationId || c.managed.adapter !== "chatgpt"))
89
+ return invalid("hooks.identity");
90
+ const own = snapshot.manifest.registrations.find(r => r.status === "active" && r.runtimeSessionId === runtimeSessionId);
91
+ return { text, revision: hash(bytes), facts, pair, snapshot, bindingPath, piHooks: own?.hooks ?? [], mcpHooks: pair.config.hooks ?? [] };
92
+ }
93
+ function capture(kind, raw) {
94
+ const selected = inspect();
95
+ const { snapshot } = selected;
96
+ if (kind === "upgrade" ? snapshot.ref.kind !== "ce-live-session-v1" : snapshot.ref.kind !== "ce-live-session-v2")
97
+ return invalid("hooks.explicitUpgradeRequired");
98
+ const hooks = kind === "upgrade" ? selected.mcpHooks : parseHookRules(raw);
99
+ if (kind === "pi") {
100
+ if (!snapshot.manifest.registrations.some(r => r.status === "active" && r.runtimeSessionId === runtimeSessionId))
101
+ return invalid("hooks.currentSession");
102
+ // Outbound Hooks address the ChatGPT peer of THIS registration only.
103
+ if (hooks.some(rule => !isDeepStrictEqual(rule.recipient, snapshot.manifest.chatgptEndpoint)))
104
+ return invalid("hooks.pi.recipient");
105
+ }
106
+ const ref = kind === "upgrade" && snapshot.ref.kind === "ce-live-session-v1" ? prepareLivePolicyUpgrade(snapshot.ref, profilePath) : snapshot.ref;
107
+ const config = parseMcpBindingConfig({ version: 1, ...selected.pair.config, admissionPolicy: ref, ...(kind === "mcp" ? { hooks } : {}) });
108
+ const document = { kind: ref.kind === "ce-live-session-v2" ? "ce-live-launch-v2" : "ce-live-launch-v1", version: 1, ref };
109
+ const targets = kind === "mcp" ? targetsFor(snapshot, hooks) : Object.freeze([]);
110
+ const candidate = Object.freeze({ kind, profilePath, profileRevision: selected.revision, expectedDigest: snapshot.digest, runtimeSessionId, ref, config, document, hooks, targets, bindingGeneration: pairGeneration(config, document) });
111
+ previews.set(candidate, { fingerprint: JSON.stringify(candidate), text: selected.text, credentialFile: selected.facts.keyFile });
112
+ return candidate;
113
+ }
114
+ function previewContinuation(input) {
115
+ options.assertCurrent();
116
+ const bytes = readPrivateMessagingFile(profilePath)?.bytes ?? invalid("hooks.profile");
117
+ const text = bytes.toString("utf8");
118
+ const revision = hash(bytes);
119
+ const facts = parseTunnelProfile(text);
120
+ if (!facts.mcpCommand)
121
+ return invalid("hooks.profile.command");
122
+ const selectedPath = parseTunnelMcpCommand(facts.mcpCommand).bindingPath;
123
+ const selected = readMessagingGeneration(profilePath, selectedPath, facts.keyFile) ?? invalid("hooks.binding");
124
+ const pair = readMessagingGeneration(profilePath, input.bindingPath, facts.keyFile) ?? invalid("hooks.continuation.pair");
125
+ const ref = pair.config.admissionPolicy;
126
+ const priorRef = selected.config.admissionPolicy;
127
+ if (ref?.kind !== "ce-live-session-v2" || ref.profilePath !== profilePath || !priorRef || priorRef.kind === "ce-multi-session-v1")
128
+ return invalid("hooks.continuation.ref");
129
+ for (const [document, r] of [[pair.document, ref], [selected.document, priorRef]]) {
130
+ if (Reflect.ownKeys(document).length !== 3 || document.version !== 1 || !isDeepStrictEqual(document.ref, r) || document.kind !== (r.kind === "ce-live-session-v2" ? "ce-live-launch-v2" : "ce-live-launch-v1"))
131
+ return invalid("hooks.launch");
132
+ }
133
+ if (priorRef.root !== ref.root || priorRef.policyId !== ref.policyId || priorRef.genesisDigest !== ref.genesisDigest || priorRef.kind === "ce-live-session-v2" && !isDeepStrictEqual(priorRef, ref))
134
+ return invalid("hooks.continuation.history");
135
+ const bindingGeneration = basename(input.bindingPath).match(/^messaging-([a-f0-9]{64})\.yaml$/)?.[1] ?? invalid("hooks.continuation.generation");
136
+ const evidence = readLiveHookPublication({ ref, runtimeSessionId, operationId: input.operationId, credentialFile: facts.keyFile });
137
+ if (evidence.intent.bindingGeneration !== bindingGeneration)
138
+ return invalid("hooks.continuation.operation");
139
+ const snapshot = readLivePolicy(ref, { credentialFile: facts.keyFile });
140
+ const m = snapshot.manifest;
141
+ // Only Hooks and the explicit format reference may differ from the selected
142
+ // binding. Sender identity, routing and global ceilings are immutable here.
143
+ const { hooks: _candidateHooks, admissionPolicy: _candidateRef, ...candidateFixed } = pair.config;
144
+ const { hooks: _selectedHooks, admissionPolicy: _selectedRef, ...selectedFixed } = selected.config;
145
+ if (!isDeepStrictEqual(candidateFixed, selectedFixed) || !isDeepStrictEqual(m.store, pair.config.store) || !isDeepStrictEqual(m.exchange, pair.config.exchange) || !isDeepStrictEqual(m.chatgptEndpoint, pair.config.endpoint) || m.mcp.payloadRead !== pair.config.payloadRead.enabled || m.mcp.ack !== pair.config.ack.enabled || m.identity.tunnelId !== facts.tunnelId || m.identity.organizationId !== (facts.organizationId ?? null))
146
+ return invalid("hooks.continuation.identity");
147
+ if (pair.config.managed && (pair.config.managed.adapter !== "chatgpt" || pair.config.managed.tunnelId !== facts.tunnelId || (pair.config.managed.organizationId ?? null) !== m.identity.organizationId))
148
+ return invalid("hooks.continuation.identity");
149
+ const hooks = pair.config.hooks ?? [];
150
+ let targets = [];
151
+ if (evidence.intent.kind === "upgrade") {
152
+ if (evidence.sequence !== ref.upgradeSequence || priorRef.kind === "ce-live-session-v1" && evidence.intent.profileRevision !== revision)
153
+ return invalid("hooks.continuation.upgrade");
154
+ if (selectedPath !== input.bindingPath && priorRef.kind !== "ce-live-session-v1")
155
+ return invalid("hooks.continuation.upgradeSelection");
156
+ if (!isDeepStrictEqual(selected.config.hooks, pair.config.hooks))
157
+ return invalid("hooks.continuation.upgradeHooks");
158
+ if (snapshot.manifest.mcpHookConsent?.generation !== evidence.sequence || snapshot.manifest.mcpHookConsent.bindingGeneration !== null)
159
+ return invalid("hooks.continuation.superseded");
160
+ }
161
+ else {
162
+ if (priorRef.kind !== "ce-live-session-v2")
163
+ return invalid("hooks.continuation.senderRef");
164
+ targets = targetsFor(snapshot, hooks);
165
+ const consent = m.mcpHookConsent;
166
+ if (!consent || consent.generation !== evidence.sequence || consent.bindingGeneration !== bindingGeneration || !isDeepStrictEqual(consent.targets, evidence.intent.targets) || !isDeepStrictEqual(targets, evidence.intent.targets))
167
+ return invalid("hooks.continuation.scope");
168
+ }
169
+ const candidate = Object.freeze({ kind: "continuation", profilePath, profileRevision: revision, expectedDigest: snapshot.digest, runtimeSessionId, ref, config: pair.config, document: pair.document, hooks, targets,
170
+ bindingGeneration, continuation: Object.freeze({ bindingPath: input.bindingPath, operationId: input.operationId, publicationKind: evidence.intent.kind, sequence: evidence.sequence }) });
171
+ previews.set(candidate, { fingerprint: JSON.stringify(candidate), text, credentialFile: facts.keyFile });
172
+ return candidate;
173
+ }
174
+ function hookApi(ref, credentialFile) {
175
+ const api = createLivePolicyRegistration({ ref, credentialFile, ...(options.io === undefined ? {} : { io: options.io }) });
176
+ if (typeof api.upgrade !== "function" || typeof api.setPiHooks !== "function" || typeof api.setMcpHooks !== "function")
177
+ return invalid("hooks.v2Unavailable");
178
+ return api;
179
+ }
180
+ async function save(candidate, confirmed, signal) {
181
+ const assertCurrent = () => {
182
+ if (signal?.aborted)
183
+ return invalid("hooks.cancelled");
184
+ options.assertCurrent();
185
+ };
186
+ const captured = previews.get(candidate);
187
+ if (confirmed !== true || !captured || captured.fingerprint !== JSON.stringify(candidate))
188
+ return invalid("hooks.nativeConfirmation");
189
+ previews.delete(candidate);
190
+ assertCurrent();
191
+ const operationId = candidate.continuation?.operationId ?? randomUUID();
192
+ const base = { adopted: false, eligible: false, executed: false, operationId };
193
+ const perform = (guard) => {
194
+ assertCurrent();
195
+ if (captured.fingerprint !== JSON.stringify(candidate))
196
+ return conflict();
197
+ if (candidate.kind === "continuation") {
198
+ if (!guard || guard.profilePath !== profilePath || !candidate.continuation)
199
+ return invalid("hooks.continuation.lock");
200
+ const verify = () => {
201
+ assertCurrent();
202
+ guard.assertIntact();
203
+ const checked = previewContinuation(candidate.continuation);
204
+ if (JSON.stringify(checked) !== captured.fingerprint || readPrivateMessagingFile(profilePath)?.bytes.toString("utf8") !== captured.text)
205
+ return conflict();
206
+ };
207
+ verify();
208
+ const bindingPath = candidate.continuation.bindingPath;
209
+ const result = { ...base, configured: true, policyDurability: "synced", bindingPath };
210
+ const facts = parseTunnelProfile(captured.text);
211
+ const command = facts.mcpCommand ?? invalid("hooks.profile.command");
212
+ if (parseTunnelMcpCommand(command).bindingPath === bindingPath)
213
+ return { ...result, selection: "unchanged", policyDurability: "unknown", profileDurability: "not-attempted", detail: "exact selected bytes observed; historical durability is not inferred" };
214
+ // Publication staged file data was synced before the exclusive link.
215
+ // Re-establish the directory durability boundary after a lost result;
216
+ // this never links a slot, issues an intent or rewrites history.
217
+ try {
218
+ const policyDirectory = io.openSync(candidate.ref.root, fs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW);
219
+ try {
220
+ io.fsyncSync(policyDirectory);
221
+ }
222
+ finally {
223
+ io.closeSync(policyDirectory);
224
+ }
225
+ }
226
+ catch {
227
+ return { ...result, selection: "pending", policyDurability: "uncertain", profileDurability: "not-attempted", detail: "published policy directory durability uncertain" };
228
+ }
229
+ verify();
230
+ const quoted = `"${command}"`;
231
+ if (captured.text.split(quoted).length !== 2)
232
+ return invalid("hooks.profile.command");
233
+ const next = captured.text.replace(quoted, `"${replaceTunnelMcpBindingPath(command, bindingPath)}"`);
234
+ if (Buffer.byteLength(next) > MAX_PROFILE_BYTES)
235
+ return invalid("hooks.profile.size");
236
+ parseTunnelProfile(next);
237
+ try {
238
+ const temporary = `${profilePath}.${randomUUID()}.tmp`;
239
+ const fd = io.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
240
+ try {
241
+ io.writeFileSync(fd, next, "utf8");
242
+ io.fsyncSync(fd);
243
+ }
244
+ finally {
245
+ io.closeSync(fd);
246
+ }
247
+ const directory = io.openSync(dirname(profilePath), fs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW);
248
+ try {
249
+ io.fsyncSync(directory);
250
+ verify();
251
+ try {
252
+ io.renameSync(temporary, profilePath);
253
+ }
254
+ catch {
255
+ return { ...result, selection: "pending", profileDurability: "uncertain", detail: "continuation rename outcome unknown; reconcile explicitly" };
256
+ }
257
+ try {
258
+ io.fsyncSync(directory);
259
+ }
260
+ catch {
261
+ return { ...result, selection: "pending", profileDurability: "uncertain" };
262
+ }
263
+ return { ...result, selection: "selected", profileDurability: "synced" };
264
+ }
265
+ finally {
266
+ try {
267
+ io.closeSync(directory);
268
+ }
269
+ catch { /* no rollback */ }
270
+ }
271
+ }
272
+ catch (error) {
273
+ if (error instanceof TunnelRefusal && error.code === "CE_TUNNEL_CONFIG_CONFLICT")
274
+ throw error;
275
+ return { ...result, selection: "pending", profileDurability: "not-attempted", detail: "published configuration retained; continuation refused before rename" };
276
+ }
277
+ }
278
+ const current = inspect();
279
+ // The candidate is bound to the exact Profile bytes and chain tip it showed.
280
+ if (current.text !== captured.text || current.revision !== candidate.profileRevision || current.snapshot.digest !== candidate.expectedDigest)
281
+ return conflict();
282
+ if (guard && guard.profilePath !== profilePath)
283
+ return invalid("hooks.profile.lock");
284
+ guard?.assertIntact();
285
+ if (candidate.kind === "mcp" && !isDeepStrictEqual(targetsFor(current.snapshot, candidate.hooks), candidate.targets))
286
+ return conflict();
287
+ const api = hookApi(candidate.ref, captured.credentialFile);
288
+ // Stage the exact immutable candidate pair BEFORE any consent publication.
289
+ let bindingPath;
290
+ if (candidate.kind !== "pi") {
291
+ const staged = publishMessagingGeneration(profilePath, candidate.config, candidate.document, { credentialFile: captured.credentialFile, ...(options.io === undefined ? {} : { io: options.io }) });
292
+ bindingPath = staged.bindingPath;
293
+ if (basename(bindingPath) !== `messaging-${candidate.bindingGeneration}.yaml`)
294
+ return invalid("hooks.candidate.bytes");
295
+ const verified = readMessagingGeneration(profilePath, bindingPath, captured.credentialFile);
296
+ if (!verified || !isDeepStrictEqual(verified.config, candidate.config) || !isDeepStrictEqual(verified.document, candidate.document))
297
+ return invalid("hooks.candidate.bytes");
298
+ if (staged.durability !== "synced")
299
+ return { ...base, configured: false, selection: "pending", policyDurability: "unknown", profileDurability: "not-attempted", bindingPath, detail: "candidate pair durability uncertain; no consent published" };
300
+ }
301
+ assertCurrent();
302
+ guard?.assertIntact();
303
+ if (captured.fingerprint !== JSON.stringify(candidate) || readPrivateMessagingFile(profilePath)?.bytes.toString("utf8") !== captured.text)
304
+ return conflict();
305
+ let publication;
306
+ try {
307
+ if (candidate.kind === "upgrade") {
308
+ const legacy = createLivePolicyRegistration({ ref: current.snapshot.ref, credentialFile: captured.credentialFile });
309
+ // Tombstones remain in the manifest, so every legacy actor namespace
310
+ // can be reconciled before publishing the marker.
311
+ const actors = new Set([runtimeSessionId, ...current.snapshot.manifest.registrations.map(r => r.runtimeSessionId)]);
312
+ for (const actor of actors) {
313
+ const pending = legacy.reconcile({ runtimeSessionId: actor });
314
+ if (pending.some(r => r.outcome === "NOT_OBSERVED" || r.outcome === "UNKNOWN"))
315
+ return invalid("hooks.upgrade.unresolved");
316
+ }
317
+ publication = api.upgrade({ expectedDigest: candidate.expectedDigest, actorRuntimeSessionId: runtimeSessionId, profileRevision: candidate.profileRevision, bindingGeneration: candidate.bindingGeneration, operationId });
318
+ }
319
+ else if (candidate.kind === "mcp") {
320
+ publication = api.setMcpHooks({ expectedDigest: candidate.expectedDigest, actorRuntimeSessionId: runtimeSessionId, bindingGeneration: candidate.bindingGeneration, targets: candidate.targets, operationId });
321
+ }
322
+ else {
323
+ const own = current.snapshot.manifest.registrations.find(r => r.status === "active" && r.runtimeSessionId === runtimeSessionId) ?? invalid("hooks.currentSession");
324
+ publication = api.setPiHooks({ expectedDigest: candidate.expectedDigest, runtimeSessionId, endpointId: own.endpointId, epoch: own.epoch, hooks: candidate.hooks, operationId });
325
+ }
326
+ }
327
+ catch (error) {
328
+ if (error instanceof TunnelRefusal && error.code === "CE_TUNNEL_CONFIG_CONFLICT")
329
+ throw error;
330
+ // The exclusive slot may already carry this operation. Keep the exact
331
+ // operation and candidate for read-only reconciliation; never retry.
332
+ return { ...base, configured: false, selection: "pending", policyDurability: "unknown", profileDurability: "not-attempted", ...(bindingPath === undefined ? {} : { bindingPath }), detail: "policy publication outcome unknown; reconcile the exact operation" };
333
+ }
334
+ const result = { ...base, configured: true, policyDurability: publication.durability, profileDurability: "not-attempted" };
335
+ if (candidate.kind === "pi")
336
+ return { ...result, selection: publication.durability === "synced" ? "unchanged" : "pending" };
337
+ if (publication.durability !== "synced")
338
+ return { ...result, selection: "pending", bindingPath: bindingPath };
339
+ try {
340
+ const verify = () => {
341
+ assertCurrent();
342
+ guard.assertIntact();
343
+ if (readPrivateMessagingFile(profilePath)?.bytes.toString("utf8") !== captured.text)
344
+ return conflict();
345
+ const latest = readLivePolicy(candidate.ref, { credentialFile: captured.credentialFile });
346
+ if (candidate.kind === "mcp") {
347
+ if (!isDeepStrictEqual(targetsFor(latest, candidate.hooks), candidate.targets))
348
+ return conflict();
349
+ if (latest.manifest.mcpHookConsent?.bindingGeneration !== candidate.bindingGeneration || latest.manifest.mcpHookConsent.generation !== publication.snapshot.sequence)
350
+ return conflict();
351
+ }
352
+ if (!readMessagingGeneration(profilePath, bindingPath, captured.credentialFile))
353
+ return invalid("hooks.candidate.missing");
354
+ };
355
+ verify();
356
+ const command = current.facts.mcpCommand;
357
+ const quoted = `"${command}"`;
358
+ if (captured.text.split(quoted).length !== 2)
359
+ return invalid("hooks.profile.command");
360
+ const next = captured.text.replace(quoted, `"${replaceTunnelMcpBindingPath(command, bindingPath)}"`);
361
+ if (Buffer.byteLength(next) > MAX_PROFILE_BYTES)
362
+ return invalid("hooks.profile.size");
363
+ parseTunnelProfile(next);
364
+ const temporary = `${profilePath}.${randomUUID()}.tmp`;
365
+ const fd = io.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
366
+ try {
367
+ io.writeFileSync(fd, next, "utf8");
368
+ io.fsyncSync(fd);
369
+ }
370
+ finally {
371
+ io.closeSync(fd);
372
+ }
373
+ const directory = io.openSync(dirname(profilePath), fs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW);
374
+ try {
375
+ io.fsyncSync(directory);
376
+ verify();
377
+ try {
378
+ io.renameSync(temporary, profilePath);
379
+ }
380
+ catch {
381
+ return { ...result, selection: "pending", profileDurability: "uncertain", bindingPath: bindingPath, detail: "Profile rename outcome unknown; no retry and no rollback" };
382
+ }
383
+ try {
384
+ io.fsyncSync(directory);
385
+ }
386
+ catch {
387
+ return { ...result, selection: "pending", profileDurability: "uncertain", bindingPath: bindingPath };
388
+ }
389
+ return { ...result, selection: "selected", profileDurability: "synced", bindingPath: bindingPath };
390
+ }
391
+ finally {
392
+ try {
393
+ io.closeSync(directory);
394
+ }
395
+ catch { /* a post-commit close cannot roll back */ }
396
+ }
397
+ }
398
+ catch {
399
+ return { ...result, selection: "pending", bindingPath: bindingPath, detail: "policy published; Profile activation pending; explicit reconciliation required" };
400
+ }
401
+ };
402
+ // Only the operations that change the selected binding take the real lock.
403
+ return candidate.kind === "pi" ? perform() : options.manager.withProfileConfigurationLock(guard => perform(guard));
404
+ }
405
+ return { inspect, preview: (kind, hooks) => capture(kind, hooks), previewUpgrade: () => capture("upgrade"), previewContinuation, save };
406
+ }
407
+ /**
408
+ * The safe test runs ONE fixed benign fixture with a fixed argv and an empty
409
+ * environment. It never accepts a configured rule, a Profile, or a command
410
+ * from configuration, so it can never run a personal script.
411
+ */
412
+ export function runSafeHookFixture() {
413
+ // Both the executable program and its synthetic metadata are package-owned.
414
+ // No rule, message, Profile or personal script can supply either one.
415
+ const fixture = { schemaVersion: 1, event: "ce.message.committed.v1", eventId: "fixture-event", eventKey: "fixture/1",
416
+ messageId: "fixture-message", exchangeId: "fixture-exchange", sender: { adapter: "pi", endpointId: "fixture/pi" },
417
+ recipient: { adapter: "chatgpt", endpointId: "fixture/chatgpt" }, createdAt: "2000-01-01T00:00:00.000Z",
418
+ payloadDigest: "0".repeat(64), payloadLength: 0 };
419
+ const program = 'let data="";process.stdin.on("data",b=>data+=b);process.stdin.on("end",()=>{try{const e=JSON.parse(data);if(e.event!=="ce.message.committed.v1"||e.payloadLength!==0||Object.keys(e).length!==11||"payloadText" in e||"payload" in e)process.exitCode=1;else process.stdout.write("CE_HOOK_FIXTURE_OK");}catch{process.exitCode=1;}});';
420
+ return new Promise((resolve, reject) => {
421
+ const child = execFile(process.execPath, ["--input-type=commonjs", "-e", program], { timeout: 5000, maxBuffer: 1024, env: {}, windowsHide: true }, (error, stdout) => {
422
+ if (error || stdout !== "CE_HOOK_FIXTURE_OK")
423
+ reject(new Error("CE_HOOK_FIXTURE_FAILED"));
424
+ else
425
+ resolve({ executed: true, configuredCommandsExecuted: false, metadataOnly: true, exitCode: 0 });
426
+ });
427
+ child.stdin?.on("error", () => { });
428
+ child.stdin?.end(JSON.stringify(fixture));
429
+ });
430
+ }
431
+ //# sourceMappingURL=hooks-management.js.map
@@ -0,0 +1,136 @@
1
+ /** Diagnostic/test-only file records. Production readiness uses the fresh nonce
2
+ * probe; this module must never be used as a file-only readiness source. */
3
+ import fs from "node:fs";
4
+ import { createHash, randomUUID } from "node:crypto";
5
+ import { join } from "node:path";
6
+ import { isDeepStrictEqual } from "node:util";
7
+ import { readLivePolicy } from "./live-session-policy.js";
8
+ import { readPrivateMessagingFile } from "./messaging-config.js";
9
+ import { TunnelRefusal } from "./codes.js";
10
+ const fail = () => { throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "messaging.liveObservation"); };
11
+ const sha = (v) => createHash("sha256").update(v).digest("hex");
12
+ const integer = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
13
+ const text = (v) => typeof v === "string" && v.length > 0 && v.length <= 4096;
14
+ const digest = (v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v);
15
+ const instant = (v) => typeof v === "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(v) && Number.isFinite(Date.parse(v));
16
+ function object(raw, keys) {
17
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
18
+ return fail();
19
+ const row = raw;
20
+ if (Object.keys(row).length !== keys.length || Object.keys(row).some(k => !keys.includes(k)))
21
+ return fail();
22
+ return row;
23
+ }
24
+ function parse(raw) {
25
+ const r = object(raw, ["kind", "ref", "launchDigest", "identity", "writerSequence", "policySequence", "policyDigest", "owner", "bound", "observedAt", "targets"]);
26
+ const refKind = r.ref?.kind;
27
+ const ref = object(r.ref, ["kind", "root", "policyId", "genesisDigest", ...(refKind === "ce-live-session-v2" ? ["profilePath", "upgradeSequence"] : [])]);
28
+ const id = object(r.identity, ["pid", "startedKey"]);
29
+ const owner = object(r.owner, ["endpointId", "registered", "participantId", "sessionId", "exchangeId", "fencingToken", "lease", "leaseExpiresAt"]);
30
+ const bound = object(r.bound, ["state", "renewal"]);
31
+ if (r.kind !== "ce-live-observation-v1" || (ref.kind !== "ce-live-session-v1" && ref.kind !== "ce-live-session-v2") || !text(ref.root) || !text(ref.policyId) || !digest(ref.genesisDigest) ||
32
+ ref.kind === "ce-live-session-v2" && (!text(ref.profilePath) || !integer(ref.upgradeSequence) || ref.upgradeSequence < 1 || ref.upgradeSequence > 65536) ||
33
+ !digest(r.launchDigest) || !digest(r.policyDigest) || !integer(id.pid) || id.pid < 1 || !text(id.startedKey) || !integer(r.writerSequence) || r.writerSequence < 1 || !integer(r.policySequence) || !instant(r.observedAt) ||
34
+ !text(owner.endpointId) || typeof owner.registered !== "boolean" || (owner.participantId !== null && !text(owner.participantId)) || (owner.sessionId !== null && !text(owner.sessionId)) || (owner.exchangeId !== null && !text(owner.exchangeId)) || (owner.fencingToken !== null && (!integer(owner.fencingToken) || owner.fencingToken < 1)) || !text(owner.lease) || (owner.leaseExpiresAt !== null && !instant(owner.leaseExpiresAt)) ||
35
+ !["ACTIVE", "WRITE_BLOCKED", "CLOSING", "CLOSED"].includes(String(bound.state)) || !["RUNNING", "STOPPED"].includes(String(bound.renewal)) || !Array.isArray(r.targets) || r.targets.length > 128)
36
+ return fail();
37
+ const labels = new Set();
38
+ for (const value of r.targets) {
39
+ const t = object(value, ["endpointId", "epoch", "payloadReadGeneration", "ackGeneration"]);
40
+ if (!text(t.endpointId) || labels.has(t.endpointId) || !integer(t.epoch) || !integer(t.payloadReadGeneration) || !integer(t.ackGeneration) || t.payloadReadGeneration > r.policySequence || t.ackGeneration > r.policySequence)
41
+ return fail();
42
+ labels.add(t.endpointId);
43
+ }
44
+ // SAFETY: the closed JSON record and every nested field were checked above.
45
+ return r;
46
+ }
47
+ function pathFor(options) {
48
+ if (!digest(options.launchDigest) || !integer(options.identity.pid) || options.identity.pid < 1 || !text(options.identity.startedKey))
49
+ return fail();
50
+ // Reuse live policy's canonical private directory, ancestor and ACL checks.
51
+ // This read verifies configuration only and changes no registry or Owner.
52
+ readLivePolicy(options.ref, options.credentialFile === undefined ? {} : { credentialFile: options.credentialFile });
53
+ return join(options.ref.root, `.live-observation-${options.identity.pid}-${sha(options.identity.startedKey)}.json`);
54
+ }
55
+ function targets(snapshot) {
56
+ return snapshot.manifest.registrations.filter(r => r.status === "active").map(({ endpointId, epoch, payloadReadGeneration, ackGeneration }) => ({ endpointId, epoch, payloadReadGeneration, ackGeneration }));
57
+ }
58
+ const rank = { ACTIVE: 0, WRITE_BLOCKED: 1, CLOSING: 2, CLOSED: 3 };
59
+ export function createLiveAdoptionRecorder(options) {
60
+ let sequence = 0;
61
+ let state = "ACTIVE";
62
+ let failed = false;
63
+ return Object.freeze({ record(snapshot, owner, bound) {
64
+ if (failed || rank[bound.state] < rank[state] || !isDeepStrictEqual(snapshot.ref, options.ref))
65
+ return fail();
66
+ state = bound.state;
67
+ try {
68
+ const path = pathFor(options);
69
+ readPrivateMessagingFile(path, options.credentialFile);
70
+ const record = parse({ kind: "ce-live-observation-v1", ref: options.ref, launchDigest: options.launchDigest, identity: options.identity, writerSequence: ++sequence, policySequence: snapshot.sequence, policyDigest: snapshot.digest,
71
+ owner: { endpointId: owner.endpointId, registered: owner.registered, participantId: owner.participantId ?? null, sessionId: owner.sessionId ?? null, exchangeId: owner.exchangeId ?? null, fencingToken: owner.fencingToken ?? null, lease: owner.lease, leaseExpiresAt: owner.leaseExpiresAt ?? null },
72
+ bound: { state: bound.state, renewal: bound.renewal }, observedAt: options.now?.() ?? new Date().toISOString(), targets: targets(snapshot) });
73
+ const bytes = Buffer.from(JSON.stringify(record));
74
+ if (bytes.length > 65536)
75
+ return fail();
76
+ const temp = join(options.ref.root, `.live-observation-tmp-${randomUUID()}`);
77
+ let fd;
78
+ try {
79
+ fd = fs.openSync(temp, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
80
+ fs.writeFileSync(fd, bytes);
81
+ fs.fsyncSync(fd);
82
+ fs.closeSync(fd);
83
+ fd = undefined;
84
+ readPrivateMessagingFile(temp, options.credentialFile);
85
+ fs.renameSync(temp, path);
86
+ const directory = fs.openSync(options.ref.root, fs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW);
87
+ try {
88
+ fs.fsyncSync(directory);
89
+ }
90
+ finally {
91
+ fs.closeSync(directory);
92
+ }
93
+ }
94
+ finally {
95
+ if (fd !== undefined)
96
+ fs.closeSync(fd);
97
+ fs.rmSync(temp, { force: true });
98
+ }
99
+ }
100
+ catch {
101
+ failed = true;
102
+ return fail();
103
+ }
104
+ } });
105
+ }
106
+ export function readLiveAdoptionObservation(options) {
107
+ try {
108
+ const file = readPrivateMessagingFile(pathFor(options), options.credentialFile);
109
+ if (!file)
110
+ return { kind: "UNVERIFIED" };
111
+ const record = parse(JSON.parse(file.bytes.toString("utf8")));
112
+ const now = options.now?.() ?? new Date().toISOString();
113
+ if (!instant(now) || Date.parse(now) < Date.parse(record.observedAt) || Date.parse(now) - Date.parse(record.observedAt) > 5000 ||
114
+ !isDeepStrictEqual(record.ref, options.ref) || !isDeepStrictEqual(options.current.ref, options.ref) || !isDeepStrictEqual(record.identity, options.identity) || record.launchDigest !== options.launchDigest ||
115
+ record.policySequence > options.current.sequence || record.policySequence === options.current.sequence && record.policyDigest !== options.current.digest)
116
+ return { kind: "UNVERIFIED" };
117
+ const observed = record.targets.find(t => t.endpointId === options.targetEndpointId);
118
+ const current = targets(options.current).find(t => t.endpointId === options.targetEndpointId);
119
+ if (!observed || !current || !isDeepStrictEqual(observed, current))
120
+ return { kind: "UNVERIFIED" };
121
+ if (record.bound.state !== "ACTIVE" || record.bound.renewal !== "RUNNING")
122
+ return { kind: "BLOCKED" };
123
+ const owner = options.owner;
124
+ if (record.owner.participantId !== owner.participantId || record.owner.sessionId !== owner.sessionId || record.owner.exchangeId !== owner.exchangeId || record.owner.fencingToken !== owner.fencingToken || record.owner.endpointId !== owner.endpointId)
125
+ return { kind: "UNVERIFIED" };
126
+ if (record.bound.state !== "ACTIVE" || record.bound.renewal !== "RUNNING" || !owner.registered || owner.lease !== "ACTIVE" || record.owner.lease !== "ACTIVE" || !owner.leaseExpiresAt || !record.owner.leaseExpiresAt || Date.parse(owner.leaseExpiresAt) <= Date.parse(now) || Date.parse(record.owner.leaseExpiresAt) <= Date.parse(now))
127
+ return { kind: "BLOCKED" };
128
+ if (options.verifyBound?.(record) !== true)
129
+ return { kind: "UNVERIFIED" };
130
+ return { kind: "OBSERVED" };
131
+ }
132
+ catch {
133
+ return { kind: "UNVERIFIED" };
134
+ }
135
+ }
136
+ //# sourceMappingURL=live-adoption-observation.js.map