@zieglar/pi-chat-exchange 0.3.0 → 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 (40) hide show
  1. package/README.md +10 -6
  2. package/dist/bin/mcp-stdio.js +113 -62
  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/host/bound-endpoint.js +19 -6
  7. package/dist/host/endpoint-host.js +78 -4
  8. package/dist/host/mcp-binding-config.js +27 -4
  9. package/dist/runtime/native-readiness.js +8 -5
  10. package/dist/storage/creation.js +16 -0
  11. package/dist/storage/ownership.js +45 -1
  12. package/dist/tunnel/background-authorization.js +343 -0
  13. package/dist/tunnel/background-manager.js +104 -8
  14. package/dist/tunnel/background-scope.js +69 -0
  15. package/dist/tunnel/codes.js +1 -1
  16. package/dist/tunnel/hooks-management-ui.js +225 -0
  17. package/dist/tunnel/hooks-management.js +431 -0
  18. package/dist/tunnel/live-adoption-observation.js +136 -0
  19. package/dist/tunnel/live-adoption-probe.js +240 -0
  20. package/dist/tunnel/live-connection-status.js +136 -0
  21. package/dist/tunnel/live-mcp-composition.js +143 -0
  22. package/dist/tunnel/live-process-observation.js +98 -0
  23. package/dist/tunnel/live-session-migration.js +169 -0
  24. package/dist/tunnel/live-session-policy.js +578 -0
  25. package/dist/tunnel/manager-panel.js +4 -2
  26. package/dist/tunnel/manager-ui.js +71 -15
  27. package/dist/tunnel/multi-session-admission.js +1 -1
  28. package/dist/tunnel/setup-ui.js +2 -4
  29. package/dist/tunnel/status-ui.js +34 -0
  30. package/package.json +1 -1
  31. package/pi-extension/desktop-target.ts +157 -0
  32. package/pi-extension/index.ts +1053 -135
  33. package/pi-extension/live-session-profile.ts +49 -0
  34. package/pi-extension/live-session-runtime.ts +59 -0
  35. package/pi-extension/multi-session-commands.ts +114 -3
  36. package/pi-extension/multi-session-runtime.ts +63 -11
  37. package/pi-extension/native-inbound.ts +235 -0
  38. package/pi-extension/ownership-feedback.ts +100 -0
  39. package/pi-extension/session-onboarding.ts +154 -0
  40. package/pi-extension/session-recovery.ts +214 -0
@@ -0,0 +1,214 @@
1
+ import * as fs from "node:fs";
2
+ import { isDeepStrictEqual } from "node:util";
3
+ import { CeHostRefusal, type CeMappingIdentifiers } from "../dist/endpoints/pi/session-host.js";
4
+
5
+ type Entry = Record<string, unknown>;
6
+ type Store = { readonly directory: string; readonly file: string };
7
+ export interface RecoveryAttempt {
8
+ readonly version: 1;
9
+ readonly attemptId: string;
10
+ readonly piSessionId: string;
11
+ readonly endpointId: string;
12
+ readonly store: Store;
13
+ readonly oldMapping: CeMappingIdentifiers;
14
+ readonly failureIds: readonly string[];
15
+ readonly policyIdentity: string;
16
+ }
17
+ export interface AutomaticRecoveryAttempt extends Omit<RecoveryAttempt, "version"> {
18
+ readonly version: 2;
19
+ readonly mode: "automatic";
20
+ readonly sourceMappingEntryId: string;
21
+ }
22
+ type Attempt = RecoveryAttempt | AutomaticRecoveryAttempt;
23
+ function deny(): never { throw new CeHostRefusal("CE_HOST_MAPPING_INVALID"); }
24
+ const record = (value: unknown): value is Entry => typeof value === "object" && value !== null && !Array.isArray(value);
25
+ const id = (value: unknown): value is string => typeof value === "string" && value.length > 0 && value.length <= 4096;
26
+ const exact = (value: Entry, keys: readonly string[]) => Object.keys(value).length === keys.length && keys.every(key => Object.hasOwn(value, key));
27
+ const mappingKeys = ["endpointId", "participantId", "sessionId", "exchangeId"] as const;
28
+ export const mappingIdentifiers = (value: unknown): value is CeMappingIdentifiers => record(value) && exact(value, mappingKeys) && mappingKeys.every(key => id(value[key]));
29
+ const attemptKeys = ["version", "attemptId", "piSessionId", "endpointId", "store", "oldMapping", "failureIds", "policyIdentity"];
30
+ function attempt(value: unknown): value is Attempt {
31
+ if (!record(value)) return false;
32
+ const keys = value.version === 1 ? attemptKeys : value.version === 2 ? [...attemptKeys, "mode", "sourceMappingEntryId"] : [];
33
+ return exact(value, keys) && (value.version === 1 || (value.version === 2 && value.mode === "automatic" && id(value.sourceMappingEntryId))) &&
34
+ id(value.attemptId) && id(value.piSessionId) && id(value.endpointId) && record(value.store) && exact(value.store, ["directory", "file"]) &&
35
+ id(value.store.directory) && id(value.store.file) && mappingIdentifiers(value.oldMapping) && value.oldMapping.endpointId === value.endpointId &&
36
+ Array.isArray(value.failureIds) && value.failureIds.length > 0 && value.failureIds.every(id) && new Set(value.failureIds).size === value.failureIds.length &&
37
+ typeof value.policyIdentity === "string" && /^[a-f0-9]{64}$/.test(value.policyIdentity);
38
+ }
39
+ export interface RecoveryDiagnostics {
40
+ readonly invalid: boolean;
41
+ readonly failures: readonly Entry[];
42
+ }
43
+ export interface NativeSessionLifecycle extends RecoveryDiagnostics {
44
+ readonly mapping?: CeMappingIdentifiers;
45
+ readonly sourceMappingEntryId?: string;
46
+ readonly releaseIntent?: "shutdown" | "deactivate" | "legacy";
47
+ readonly hasRecovery: boolean;
48
+ readonly initialRepairEligible: boolean;
49
+ }
50
+
51
+ /** Native append order is evidence only. The caller still needs ordinary
52
+ * policy, process mutex and Host authority checks before adopting a binding. */
53
+ export function nativeSessionLifecycle(history: readonly unknown[], piSessionId: string, store: Store): NativeSessionLifecycle {
54
+ const failures: Entry[] = [];
55
+ let hasRecovery = false;
56
+ try {
57
+ if (!id(piSessionId)) deny();
58
+ const entries = new Map<string, { entry: Entry; index: number }>();
59
+ for (const [index, e] of history.entries()) {
60
+ if (!record(e) || !id(e.id) || entries.has(e.id)) deny();
61
+ entries.set(e.id, { entry: e, index });
62
+ }
63
+ const resolved = new Set<string>(), attemptIds = new Set<string>();
64
+ const tuples = new Map<string, string>();
65
+ let mapping: CeMappingIdentifiers | undefined;
66
+ let sourceMappingEntryId: string | undefined;
67
+ let releaseIntent: NativeSessionLifecycle["releaseIntent"];
68
+ let anyRelease = false;
69
+ let pending: { data: Attempt; id: string; index: number; mappingId?: string; newMapping?: CeMappingIdentifiers } | undefined;
70
+ for (const [index, raw] of history.entries()) {
71
+ const e = raw as Entry;
72
+ if (e.type !== "custom") continue;
73
+ const data = e.data;
74
+ switch (e.customType) {
75
+ case "ce-lifecycle-blocked":
76
+ if (!record(data) || !exact(data, ["piSessionId", "endpointId", "code"]) || data.piSessionId !== piSessionId || !id(data.endpointId) || !id(data.code) || pending) deny();
77
+ failures.push(e);
78
+ break;
79
+ case "ce-messaging-released":
80
+ if (!record(data) || !exact(data, [...mappingKeys, "piSessionId", ...(Object.hasOwn(data, "intent") ? ["intent"] : [])]) ||
81
+ data.piSessionId !== piSessionId || !mapping || !mappingKeys.every(key => data[key] === mapping![key]) || pending ||
82
+ (Object.hasOwn(data, "intent") && data.intent !== "shutdown" && data.intent !== "deactivate")) deny();
83
+ releaseIntent = data.intent === undefined ? "legacy" : data.intent as "shutdown" | "deactivate";
84
+ anyRelease = true;
85
+ break;
86
+ case "ce-recovery-attempt": {
87
+ hasRecovery = true;
88
+ if (pending || !attempt(data) || data.piSessionId !== piSessionId || !isDeepStrictEqual(data.store, store) ||
89
+ !isDeepStrictEqual(mapping, data.oldMapping) || releaseIntent || attemptIds.has(data.attemptId)) deny();
90
+ const applicable = failures.filter(f => !resolved.has(String(f.id)));
91
+ if (applicable.some(f => (f.data as Entry).endpointId !== data.endpointId) ||
92
+ !isDeepStrictEqual(new Set(data.failureIds), new Set(applicable.map(f => f.id)))) deny();
93
+ if (data.version === 2 && (tuples.size !== 1 || anyRelease || attemptIds.size !== 0 || data.sourceMappingEntryId !== sourceMappingEntryId)) deny();
94
+ attemptIds.add(data.attemptId);
95
+ pending = { data, id: String(e.id), index };
96
+ break;
97
+ }
98
+ case "ce-mapping": {
99
+ if (!mappingIdentifiers(data)) deny();
100
+ const changed = mapping !== undefined && !isDeepStrictEqual(mapping, data);
101
+ if (pending) {
102
+ if (pending.mappingId || !changed || data.endpointId !== pending.data.endpointId || data.participantId !== pending.data.oldMapping.participantId ||
103
+ data.exchangeId !== pending.data.oldMapping.exchangeId || data.sessionId === pending.data.oldMapping.sessionId) deny();
104
+ pending.mappingId = String(e.id); pending.newMapping = data;
105
+ } else if (changed && !releaseIntent) deny();
106
+ mapping = data;
107
+ const key = JSON.stringify(mappingKeys.map(k => data[k]));
108
+ if (!tuples.has(key)) tuples.set(key, String(e.id));
109
+ sourceMappingEntryId = tuples.get(key)!;
110
+ releaseIntent = undefined;
111
+ break;
112
+ }
113
+ case "ce-recovery-resolved": {
114
+ hasRecovery = true;
115
+ if (!pending || !record(data)) deny();
116
+ const { attemptEntryId, mappingEntryId, newMapping, ...copy } = data;
117
+ if (!attempt(copy) || !isDeepStrictEqual(copy, pending.data) || attemptEntryId !== pending.id || mappingEntryId !== pending.mappingId ||
118
+ !pending.newMapping || !isDeepStrictEqual(newMapping, pending.newMapping) || index <= pending.index ||
119
+ !id(mappingEntryId) || entries.get(mappingEntryId)!.index >= index) deny();
120
+ for (const failureId of pending.data.failureIds) resolved.add(failureId);
121
+ pending = undefined;
122
+ break;
123
+ }
124
+ }
125
+ }
126
+ if (pending || failures.some(f => mapping && (f.data as Entry).endpointId !== mapping.endpointId)) deny();
127
+ const unresolved = failures.filter(f => !resolved.has(String(f.id)));
128
+ return { invalid: false, failures: unresolved, hasRecovery, initialRepairEligible: !hasRecovery && tuples.size === 1 && unresolved.length > 0 && !anyRelease,
129
+ ...(mapping ? { mapping } : {}), ...(sourceMappingEntryId ? { sourceMappingEntryId } : {}), ...(releaseIntent ? { releaseIntent } : {}) };
130
+ } catch {
131
+ return { invalid: true, failures, hasRecovery, initialRepairEligible: false };
132
+ }
133
+ }
134
+
135
+ /** Retained shape for callers migrating from branch-scoped diagnostics. */
136
+ export function recoveryDiagnostics(branch: readonly Entry[], history: readonly Entry[] | undefined, piSessionId: string, store: Store): RecoveryDiagnostics {
137
+ const result = nativeSessionLifecycle(history ?? branch, piSessionId, store);
138
+ return { invalid: result.invalid || (history === undefined && result.hasRecovery), failures: result.failures };
139
+ }
140
+
141
+ // Pi owns writes. This descriptor is only a consistency/durability witness,
142
+ // never a lock or a substitute for Host admission.
143
+ export function openRecoveryJournal(path: string | undefined) {
144
+ if (!path) deny();
145
+ const fd = fs.openSync(path, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
146
+ const initial = fs.fstatSync(fd);
147
+ const assertIdentity = () => {
148
+ const current = fs.fstatSync(fd), named = fs.lstatSync(path);
149
+ if (!current.isFile() || !named.isFile() || current.uid !== process.geteuid?.() || (current.mode & 0o022) !== 0 ||
150
+ current.dev !== initial.dev || current.ino !== initial.ino || current.uid !== initial.uid ||
151
+ named.dev !== current.dev || named.ino !== current.ino || named.uid !== current.uid || named.mode !== current.mode || current.size === 0) deny();
152
+ return current;
153
+ };
154
+ try { assertIdentity(); } catch (error) { fs.closeSync(fd); throw error; }
155
+ let nativeId: string | undefined;
156
+ const readHistory = (piSessionId?: string) => {
157
+ const before = assertIdentity();
158
+ if (before.size > 64 * 1024 * 1024) deny();
159
+ const buffer = Buffer.alloc(before.size);
160
+ if (fs.readSync(fd, buffer, 0, buffer.length, 0) !== buffer.length) deny();
161
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(buffer);
162
+ const lines = text.split("\n");
163
+ if (lines.pop() !== "") deny();
164
+ let values: unknown[];
165
+ try { values = lines.map(line => JSON.parse(line)); } catch { deny(); }
166
+ const header = values.shift();
167
+ if (!record(header) || header.type !== "session" || header.version !== 3 || !id(header.id) ||
168
+ (piSessionId !== undefined && header.id !== piSessionId) || (nativeId !== undefined && header.id !== nativeId) || !id(header.timestamp) || !id(header.cwd) ||
169
+ !exact(header, ["type", "version", "id", "timestamp", "cwd", ...(Object.hasOwn(header, "parentSession") ? ["parentSession"] : [])]) ||
170
+ (Object.hasOwn(header, "parentSession") && !id(header.parentSession))) deny();
171
+ const ids = new Set<string>([header.id]);
172
+ for (const e of values) {
173
+ if (!record(e) || !id(e.id) || !id(e.type) || e.type === "session" || ids.has(e.id)) deny();
174
+ ids.add(e.id);
175
+ }
176
+ const assertUnchanged = () => {
177
+ const after = assertIdentity();
178
+ if (after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs) deny();
179
+ };
180
+ assertUnchanged();
181
+ return { values, nativeId: header.id, assertUnchanged };
182
+ };
183
+ let expected: unknown[] | undefined;
184
+ return {
185
+ assertIdentity,
186
+ verifyHistory(entries: readonly unknown[], piSessionId: string): void {
187
+ let snapshot: unknown[];
188
+ try { snapshot = JSON.parse(JSON.stringify(entries)); } catch { deny(); }
189
+ const read = readHistory(piSessionId);
190
+ if (!Array.isArray(snapshot) || !isDeepStrictEqual(read.values, snapshot) ||
191
+ (expected && !isDeepStrictEqual(snapshot, expected))) deny();
192
+ read.assertUnchanged();
193
+ nativeId = read.nativeId;
194
+ expected = snapshot;
195
+ },
196
+ verify(entry: unknown): void {
197
+ if (!record(entry) || !id(entry.id)) deny();
198
+ let snapshot: Entry;
199
+ try { snapshot = JSON.parse(JSON.stringify(entry)); } catch { deny(); }
200
+ const read = readHistory();
201
+ if (expected) {
202
+ const next = [...expected, snapshot];
203
+ // Callers may have verified the just-appended full snapshot already.
204
+ if (!isDeepStrictEqual(read.values, next) && !isDeepStrictEqual(read.values, expected)) deny();
205
+ if (!isDeepStrictEqual(read.values.at(-1), snapshot)) deny();
206
+ } else if (read.values.filter(e => record(e) && e.id === entry.id).length !== 1 || !isDeepStrictEqual(read.values.at(-1), snapshot)) deny();
207
+ fs.fsyncSync(fd);
208
+ read.assertUnchanged();
209
+ nativeId = read.nativeId;
210
+ expected = read.values;
211
+ },
212
+ close(): void { fs.closeSync(fd); },
213
+ };
214
+ }