@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.
- package/README.md +10 -6
- package/dist/bin/mcp-stdio.js +113 -62
- package/dist/control/mcp/endpoint-discovery.js +60 -0
- package/dist/control/mcp/messaging-tools.js +12 -2
- package/dist/control/mcp/server.js +10 -2
- package/dist/host/bound-endpoint.js +19 -6
- package/dist/host/endpoint-host.js +78 -4
- package/dist/host/mcp-binding-config.js +27 -4
- package/dist/runtime/native-readiness.js +8 -5
- package/dist/storage/creation.js +16 -0
- package/dist/storage/ownership.js +45 -1
- package/dist/tunnel/background-authorization.js +343 -0
- package/dist/tunnel/background-manager.js +104 -8
- package/dist/tunnel/background-scope.js +69 -0
- package/dist/tunnel/codes.js +1 -1
- package/dist/tunnel/hooks-management-ui.js +225 -0
- package/dist/tunnel/hooks-management.js +431 -0
- package/dist/tunnel/live-adoption-observation.js +136 -0
- package/dist/tunnel/live-adoption-probe.js +240 -0
- package/dist/tunnel/live-connection-status.js +136 -0
- package/dist/tunnel/live-mcp-composition.js +143 -0
- package/dist/tunnel/live-process-observation.js +98 -0
- package/dist/tunnel/live-session-migration.js +169 -0
- package/dist/tunnel/live-session-policy.js +578 -0
- package/dist/tunnel/manager-panel.js +4 -2
- package/dist/tunnel/manager-ui.js +71 -15
- package/dist/tunnel/multi-session-admission.js +1 -1
- package/dist/tunnel/setup-ui.js +2 -4
- package/dist/tunnel/status-ui.js +34 -0
- package/package.json +1 -1
- package/pi-extension/desktop-target.ts +157 -0
- package/pi-extension/index.ts +1053 -135
- package/pi-extension/live-session-profile.ts +49 -0
- package/pi-extension/live-session-runtime.ts +59 -0
- package/pi-extension/multi-session-commands.ts +114 -3
- package/pi-extension/multi-session-runtime.ts +63 -11
- package/pi-extension/native-inbound.ts +235 -0
- package/pi-extension/ownership-feedback.ts +100 -0
- package/pi-extension/session-onboarding.ts +154 -0
- package/pi-extension/session-recovery.ts +214 -0
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from "node:util";
|
|
2
|
+
import { parseTunnelMcpCommand } from "../dist/tunnel/profile.js";
|
|
3
|
+
import { parseTunnelProfile } from "../dist/tunnel/background-manager.js";
|
|
4
|
+
import { TunnelRefusal } from "../dist/tunnel/codes.js";
|
|
5
|
+
import { buildPiAllowlistDocument, readMessagingGeneration } from "../dist/tunnel/messaging-config.js";
|
|
6
|
+
import { readLivePolicy, type LiveSnapshot, type LiveReaderWatermark } from "../dist/tunnel/live-session-policy.js";
|
|
7
|
+
|
|
8
|
+
const credentials = new Map<string, string>();
|
|
9
|
+
const refKey = (snapshot: LiveSnapshot): string => JSON.stringify(snapshot.ref);
|
|
10
|
+
const invalid = (): never => { throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "messaging.liveLaunch"); };
|
|
11
|
+
|
|
12
|
+
/** Runtime reads retain the exact selected credential exclusion and watermark. */
|
|
13
|
+
export function readRuntimeLivePolicy(loaded: LiveSnapshot, watermark: LiveReaderWatermark): LiveSnapshot {
|
|
14
|
+
const credentialFile = credentials.get(refKey(loaded));
|
|
15
|
+
if (credentialFile === undefined) return invalid();
|
|
16
|
+
return readLivePolicy(loaded.ref, { watermark, credentialFile });
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Read the actually selected launch generation, not a newer policy pointer. */
|
|
20
|
+
export function readLiveSelectedSessionPolicy(profilePath: string, text: string): LiveSnapshot | undefined {
|
|
21
|
+
const facts = parseTunnelProfile(text);
|
|
22
|
+
if (facts.mcpCommand === undefined) return undefined;
|
|
23
|
+
const bindingPath = parseTunnelMcpCommand(facts.mcpCommand).bindingPath;
|
|
24
|
+
const pair = readMessagingGeneration(profilePath, bindingPath, facts.keyFile);
|
|
25
|
+
if (pair?.config.admissionPolicy?.kind !== "ce-live-session-v1" && pair?.config.admissionPolicy?.kind !== "ce-live-session-v2") return undefined;
|
|
26
|
+
const ref = pair.config.admissionPolicy;
|
|
27
|
+
if (ref.kind === "ce-live-session-v2" && ref.profilePath !== profilePath) return invalid();
|
|
28
|
+
const doc = pair.document;
|
|
29
|
+
if (Reflect.ownKeys(doc).length !== 3 || !Object.hasOwn(doc, "kind") || !Object.hasOwn(doc, "version") || !Object.hasOwn(doc, "ref") ||
|
|
30
|
+
doc.kind !== (ref.kind === "ce-live-session-v2" ? "ce-live-launch-v2" : "ce-live-launch-v1") || doc.version !== 1 || !isDeepStrictEqual(doc.ref, ref)) return invalid();
|
|
31
|
+
const snapshot = readLivePolicy(ref, { credentialFile: facts.keyFile });
|
|
32
|
+
const m = snapshot.manifest; const c = pair.config;
|
|
33
|
+
if (m.identity.tunnelId !== facts.tunnelId || m.identity.organizationId !== (facts.organizationId ?? null) ||
|
|
34
|
+
!isDeepStrictEqual(m.store, c.store) || !isDeepStrictEqual(m.exchange, c.exchange) || !isDeepStrictEqual(m.chatgptEndpoint, c.endpoint) ||
|
|
35
|
+
m.mcp.payloadRead !== c.payloadRead.enabled || m.mcp.ack !== c.ack.enabled ||
|
|
36
|
+
c.managed !== undefined && (c.managed.tunnelId !== facts.tunnelId || (c.managed.organizationId ?? null) !== m.identity.organizationId || c.managed.adapter !== "chatgpt")) return invalid();
|
|
37
|
+
credentials.set(refKey(snapshot), facts.keyFile);
|
|
38
|
+
return snapshot;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function projectLivePiRegistration(snapshot: LiveSnapshot, runtimeSessionId: string): Record<string, unknown> {
|
|
42
|
+
const r = snapshot.manifest.registrations.find(r => r.runtimeSessionId === runtimeSessionId && r.status === "active");
|
|
43
|
+
if (r === undefined) throw new Error("CE_HOST_AUTHORITY_ABSENT");
|
|
44
|
+
return { ...buildPiAllowlistDocument({ chatgptEndpoint: snapshot.manifest.chatgptEndpoint,
|
|
45
|
+
piEndpoint: { adapter: "pi", endpointId: r.endpointId }, piSessionId: runtimeSessionId,
|
|
46
|
+
exchangeNamespace: snapshot.manifest.exchange.namespace, exchangeIdempotencyKey: snapshot.manifest.exchange.idempotencyKey,
|
|
47
|
+
store: snapshot.manifest.store, payloadRead: r.payloadRead, ack: r.ack }),
|
|
48
|
+
...(r.hooks === undefined ? {} : { hooks: r.hooks }) };
|
|
49
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from "node:util";
|
|
2
|
+
import type { CeMappingIdentifiers } from "../dist/endpoints/pi/session-host.js";
|
|
3
|
+
import type { LiveSnapshot, LiveReaderWatermark } from "../dist/tunnel/live-session-policy.js";
|
|
4
|
+
import { readSelectedMultiSessionPolicy, type MultiSessionSnapshot } from "../dist/tunnel/multi-session-policy.js";
|
|
5
|
+
import type { CeHookRule } from "../dist/hooks/config.js";
|
|
6
|
+
import { PiMultiSessionRuntime, liveRegistration, policyDenied, runtimeEnvironment } from "./multi-session-runtime.js";
|
|
7
|
+
import { readRuntimeLivePolicy } from "./live-session-profile.js";
|
|
8
|
+
|
|
9
|
+
export { effectiveLiveRegistration as liveRegistration } from "./multi-session-runtime.js";
|
|
10
|
+
export type SelectedSessionPolicy = MultiSessionSnapshot | LiveSnapshot;
|
|
11
|
+
export const isLivePolicy = (policy: SelectedSessionPolicy): policy is LiveSnapshot => "ref" in policy;
|
|
12
|
+
|
|
13
|
+
/** Captured factory grants never advance. Only an official replacement can load
|
|
14
|
+
* newer generations; mutex transfer carries identifiers, never CE capabilities. */
|
|
15
|
+
export class PiSessionPolicy {
|
|
16
|
+
readonly loaded: SelectedSessionPolicy;
|
|
17
|
+
readonly #runtimeId: string;
|
|
18
|
+
readonly #currentRuntime: () => string;
|
|
19
|
+
readonly #environment: string;
|
|
20
|
+
readonly #runtime: PiMultiSessionRuntime;
|
|
21
|
+
readonly #watermark: LiveReaderWatermark;
|
|
22
|
+
constructor(loaded: SelectedSessionPolicy, runtimeId: string, currentRuntime: () => string, reload: boolean, mapping: unknown) {
|
|
23
|
+
this.loaded = loaded; this.#runtimeId = runtimeId; this.#currentRuntime = currentRuntime; this.#environment = runtimeEnvironment();
|
|
24
|
+
this.#watermark = isLivePolicy(loaded) ? { sequence: loaded.sequence, digest: loaded.digest, policyId: loaded.ref.policyId } : {};
|
|
25
|
+
this.#runtime = new PiMultiSessionRuntime(loaded, runtimeId, currentRuntime, reload, mapping, () => this.current());
|
|
26
|
+
}
|
|
27
|
+
get store(): MultiSessionSnapshot["manifest"]["store"] { return this.loaded.manifest.store; }
|
|
28
|
+
current(): SelectedSessionPolicy {
|
|
29
|
+
this.assertContext();
|
|
30
|
+
return isLivePolicy(this.loaded) ? readRuntimeLivePolicy(this.loaded, this.#watermark) : readSelectedMultiSessionPolicy(this.loaded.profilePath);
|
|
31
|
+
}
|
|
32
|
+
registration() {
|
|
33
|
+
const r = liveRegistration(this.loaded, this.current(), this.#runtimeId);
|
|
34
|
+
if ((!isLivePolicy(this.loaded) || this.loaded.ref.kind !== "ce-live-session-v2") && !isDeepStrictEqual(r.hooks, this.hooks(this.loaded))) throw policyDenied();
|
|
35
|
+
return r;
|
|
36
|
+
}
|
|
37
|
+
hooks(policy: SelectedSessionPolicy) { return policy.manifest.registrations.find(r => r.runtimeSessionId === this.#runtimeId)?.hooks; }
|
|
38
|
+
hookAllowed(rule: CeHookRule): boolean {
|
|
39
|
+
const current = this.current();
|
|
40
|
+
const registration = liveRegistration(this.loaded, current, this.#runtimeId);
|
|
41
|
+
const original = this.loaded.manifest.registrations.find(r => r.runtimeSessionId === this.#runtimeId);
|
|
42
|
+
if (isLivePolicy(this.loaded) && this.loaded.ref.kind === "ce-live-session-v2") {
|
|
43
|
+
const captured = this.loaded.manifest.registrations.find(r => r.runtimeSessionId === this.#runtimeId);
|
|
44
|
+
const latest = isLivePolicy(current) ? current.manifest.registrations.find(r => r.runtimeSessionId === this.#runtimeId) : undefined;
|
|
45
|
+
if (captured?.hookGeneration === undefined || captured.hookGeneration !== latest?.hookGeneration) return false;
|
|
46
|
+
}
|
|
47
|
+
return (original?.hooks ?? []).some(candidate => candidate.enabled && isDeepStrictEqual(candidate, rule)) &&
|
|
48
|
+
(registration.hooks ?? []).some(candidate => candidate.enabled && isDeepStrictEqual(candidate, rule));
|
|
49
|
+
}
|
|
50
|
+
run<T>(kind: string, operation: () => T): T { return this.#runtime.run(kind, operation); }
|
|
51
|
+
closeAdmission(): void { this.#runtime.closeAdmission(); }
|
|
52
|
+
drain(): Promise<void> { return this.#runtime.drain(); }
|
|
53
|
+
transfer(mapping: CeMappingIdentifiers): void { this.#runtime.transfer(mapping); }
|
|
54
|
+
release(cleanup: { readonly released: boolean; readonly detached: boolean }): void { this.#runtime.release(cleanup); }
|
|
55
|
+
fail(): void { this.#runtime.fail(); }
|
|
56
|
+
assertContext(): void {
|
|
57
|
+
if (this.#currentRuntime() !== this.#runtimeId || runtimeEnvironment() !== this.#environment) throw policyDenied();
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
/** Operator-only, configuration-only commands. Never polls inboxes or controls transport. */
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { createLivePolicyRegistration, type LiveSnapshot } from "../dist/tunnel/live-session-policy.js";
|
|
4
|
+
import { readLiveSelectedSessionPolicy } from "./live-session-profile.js";
|
|
2
5
|
import { sanitizeTerminalText } from "@narumitw/pi-tui-kit";
|
|
3
6
|
import { createMultiSessionRegistration, readSelectedMultiSessionPolicy } from "../dist/tunnel/multi-session-policy.js";
|
|
4
7
|
import { readGeneratedPiAllowlist } from "../dist/tunnel/setup.js";
|
|
@@ -14,15 +17,47 @@ interface CommandPort {
|
|
|
14
17
|
}
|
|
15
18
|
const safe = (s: string): string => sanitizeTerminalText(s).replace(/[\x00-\x1f\x7f-\x9f]/g, " ");
|
|
16
19
|
function refuse(): never { throw new TunnelRefusal("CE_TUNNEL_CONFIG_CONFLICT"); }
|
|
20
|
+
function cancelled(ctx: CommandPort, signal: AbortSignal, action: string): void {
|
|
21
|
+
if (!signal.aborted) ctx.ui.notify(`ce-tunnel: ${action} cancelled; no configuration was published`, "info");
|
|
22
|
+
}
|
|
17
23
|
export async function runSessionConfiguration(args: string, ctx: CommandPort, options: {
|
|
18
24
|
readonly profilePath: string;
|
|
19
25
|
readonly manager: BackgroundTunnelManager;
|
|
20
26
|
readonly signal: AbortSignal;
|
|
27
|
+
readonly onProgress?: (text: string) => void;
|
|
21
28
|
/** Trusted runtime composition keeps enumeration AND publication admitted. */
|
|
22
29
|
readonly withTargetAdmission: <T>(operation: () => T) => T;
|
|
23
30
|
}): Promise<void> {
|
|
24
31
|
if (ctx.mode !== "tui" || !ctx.hasUI) throw new TunnelRefusal("CE_TUNNEL_INPUT_UNAVAILABLE");
|
|
25
32
|
const words = args.trim().split(/\s+/); const [command, endpointId, ...flags] = words;
|
|
33
|
+
if (command === "liveSessions") {
|
|
34
|
+
if (words.length !== 1 || options.signal.aborted || process.env.CE_ALLOWLIST) refuse();
|
|
35
|
+
return options.withTargetAdmission(() => {
|
|
36
|
+
const runtime = ctx.sessionManager.getSessionId();
|
|
37
|
+
const text = readFileSync(options.profilePath, "utf8");
|
|
38
|
+
const selected = readLiveSelectedSessionPolicy(options.profilePath, text);
|
|
39
|
+
if (selected === undefined) refuse();
|
|
40
|
+
const own = selected.manifest.registrations.find(r => r.runtimeSessionId === runtime && r.status === "active");
|
|
41
|
+
if (own === undefined || options.signal.aborted || ctx.sessionManager.getSessionId() !== runtime) refuse();
|
|
42
|
+
ctx.ui.notify(`ce-tunnel: own Endpoint ${safe(own.endpointId)}; payload read=${own.payloadRead}; ACK=${own.ack}. ` +
|
|
43
|
+
"Discovery unavailable; Active=unknown; Reachable=unknown. Registered is not delivery or task completion evidence. " +
|
|
44
|
+
"Choose the exact intended recipient; no latest-Session or pi/main fallback.", "info");
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
if (command === "register" || command === "revoke" || command === "reauthorize") {
|
|
48
|
+
const text = readFileSync(options.profilePath, "utf8");
|
|
49
|
+
const selected = readLiveSelectedSessionPolicy(options.profilePath, text);
|
|
50
|
+
if (selected !== undefined) {
|
|
51
|
+
try {
|
|
52
|
+
return await liveConfiguration(command, endpointId, flags, ctx, options, selected, text);
|
|
53
|
+
} catch (error) {
|
|
54
|
+
// Live policy publication does not require the shared STOPPED transport lock.
|
|
55
|
+
if (error instanceof TunnelRefusal && error.field === "messaging.livePolicy.globalCeiling") throw error;
|
|
56
|
+
throw new TunnelRefusal(error instanceof TunnelRefusal ? error.code : "CE_TUNNEL_CONFIG_CONFLICT", "messaging.livePolicy");
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
if (command === "reauthorize") refuse();
|
|
60
|
+
}
|
|
26
61
|
const api = createMultiSessionRegistration({ profilePath: options.profilePath, env: process.env, manager: {
|
|
27
62
|
withProfileConfigurationLock: operation => options.manager.withProfileConfigurationLock(guard => {
|
|
28
63
|
current(); // lock acquisition/process inventory may await; fence again inside it
|
|
@@ -36,10 +71,15 @@ export async function runSessionConfiguration(args: string, ctx: CommandPort, op
|
|
|
36
71
|
if (options.signal.aborted || runtimeEnvironment() !== environment || ctx.sessionManager.getSessionId() !== runtimeSessionId || api.revision() !== expectedRevision) refuse();
|
|
37
72
|
};
|
|
38
73
|
const confirm = async (message: string): Promise<boolean> => {
|
|
74
|
+
if (options.signal.aborted) return false;
|
|
39
75
|
current();
|
|
40
76
|
if (typeof ctx.ui.confirm !== "function") throw new TunnelRefusal("CE_TUNNEL_INPUT_UNAVAILABLE");
|
|
77
|
+
options.onProgress?.("Waiting for configuration consent");
|
|
41
78
|
const accepted = await ctx.ui.confirm("Chat Exchange · configuration only", message, { signal: options.signal, timeout: 120_000 });
|
|
42
|
-
|
|
79
|
+
if (options.signal.aborted) return false;
|
|
80
|
+
current();
|
|
81
|
+
if (accepted !== true) cancelled(ctx, options.signal, command!);
|
|
82
|
+
return accepted === true;
|
|
43
83
|
};
|
|
44
84
|
if (command === "sessions") {
|
|
45
85
|
if (words.length !== 1) refuse();
|
|
@@ -62,6 +102,7 @@ export async function runSessionConfiguration(args: string, ctx: CommandPort, op
|
|
|
62
102
|
if (!await confirm("Explicitly convert the existing single-session registration to multi-session mode, preserving its Endpoint, real Session mapping, Store, Exchange and read/ACK grants? Existing registration: " + safe(JSON.stringify(legacy.sessions)) +
|
|
63
103
|
". Other sessions will require distinct Endpoints and separate confirmation. Shared ChatGPT inbox is not conversation isolation.")) return;
|
|
64
104
|
current();
|
|
105
|
+
options.onProgress?.("Saving session policy under the Profile configuration lock");
|
|
65
106
|
const result = await api.convert({ expectedRevision, confirm: true });
|
|
66
107
|
ctx.ui.notify(`ce-tunnel: multi-session configuration selected (${result.durability}); reload Pi explicitly; explicit Stop then Start loads MCP grants. Configured only, not delivery evidence.`, "warning");
|
|
67
108
|
return;
|
|
@@ -76,18 +117,88 @@ export async function runSessionConfiguration(args: string, ctx: CommandPort, op
|
|
|
76
117
|
`Store: ${safe(selected.manifest.store.directory)}/${safe(selected.manifest.store.file)}\n` +
|
|
77
118
|
`Exchange: ${safe(selected.manifest.exchange.namespace)} / ${safe(selected.manifest.exchange.idempotencyKey)}\n` +
|
|
78
119
|
`Peer: ${safe(selected.manifest.chatgptEndpoint.endpointId)}; payload read=${flags.includes("--payload-read")}; ACK=${flags.includes("--ack")} (reception only).\n` +
|
|
79
|
-
"
|
|
120
|
+
"Hooks are preserved only if separately authorized; registration enables no Hooks. Exact Endpoint labels are visible to the configured peer; real first send outcomes may reveal first join/addressability. " +
|
|
121
|
+
"Shared ChatGPT inbox, not conversation isolation. Publication only; explicit Pi reload and separate transport Start required. No delivery or task execution is implied.";
|
|
80
122
|
} else {
|
|
81
123
|
if (flags.length !== 0) refuse();
|
|
82
124
|
const r = selected.manifest.registrations.find(r => r.endpointId === endpointId && r.status === "active");
|
|
83
125
|
if (r === undefined) refuse();
|
|
84
126
|
message = `Revoke exact stable Endpoint ${safe(endpointId)} (Session ${safe(r.runtimeSessionId)}, epoch ${r.epoch})?\n` +
|
|
85
|
-
"New-gated runtime operations will be denied after publication; already admitted operations may finish. Other registrations and shared ChatGPT history remain. No retroactive removal or old-binary revocation."
|
|
127
|
+
"New-gated runtime operations will be denied after publication; already admitted operations may finish. Other registrations and shared ChatGPT history remain. No retroactive removal or old-binary revocation. " +
|
|
128
|
+
"Reauthorization requires fresh explicit confirmation and a new runtime projection; Connect cannot restore a revoked registration.";
|
|
86
129
|
}
|
|
87
130
|
if (!await confirm(message)) return;
|
|
88
131
|
current();
|
|
132
|
+
options.onProgress?.("Saving session policy under the Profile configuration lock");
|
|
89
133
|
const result = command === "register"
|
|
90
134
|
? await api.register({ expectedRevision, registration: { endpointId, runtimeSessionId, payloadRead: flags.includes("--payload-read"), ack: flags.includes("--ack") } })
|
|
91
135
|
: await api.revoke({ expectedRevision, endpointId });
|
|
92
136
|
ctx.ui.notify(`ce-tunnel: selected configuration saved (${result.durability}); reload Pi explicitly to load grants; MCP loaded: unknown, use controlled Stop then Start. No transport lifecycle side effects.`, "warning");
|
|
93
137
|
}
|
|
138
|
+
|
|
139
|
+
async function liveConfiguration(command: "register" | "revoke" | "reauthorize", endpointId: string | undefined, flags: readonly string[], ctx: CommandPort,
|
|
140
|
+
options: Parameters<typeof runSessionConfiguration>[2], selected: LiveSnapshot, profileText: string): Promise<void> {
|
|
141
|
+
if (options.signal.aborted) return;
|
|
142
|
+
if (process.env.CE_ALLOWLIST || typeof endpointId !== "string" || endpointId.length > 256 || /[\x00-\x20\x7f-\x9f]/.test(endpointId) || /cap_[0-9a-f]{16,}/i.test(endpointId)) refuse();
|
|
143
|
+
const runtimeSessionId = ctx.sessionManager.getSessionId(); const environment = runtimeEnvironment();
|
|
144
|
+
const api = createLivePolicyRegistration({ ref: selected.ref });
|
|
145
|
+
const current = (): void => {
|
|
146
|
+
if (options.signal.aborted || ctx.sessionManager.getSessionId() !== runtimeSessionId || runtimeEnvironment() !== environment ||
|
|
147
|
+
readFileSync(options.profilePath, "utf8") !== profileText) refuse();
|
|
148
|
+
};
|
|
149
|
+
const own = selected.manifest.registrations.find(r => r.runtimeSessionId === runtimeSessionId);
|
|
150
|
+
if (api.reconcile({ runtimeSessionId }).some(r => r.outcome === "NOT_OBSERVED" || r.outcome === "UNKNOWN")) refuse();
|
|
151
|
+
if (typeof ctx.ui.confirm !== "function") throw new TunnelRefusal("CE_TUNNEL_INPUT_UNAVAILABLE");
|
|
152
|
+
current();
|
|
153
|
+
if ((command === "register" || command === "reauthorize") &&
|
|
154
|
+
(flags.includes("--payload-read") && !selected.manifest.mcp.payloadRead || flags.includes("--ack") && !selected.manifest.mcp.ack)) {
|
|
155
|
+
throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "messaging.livePolicy.globalCeiling");
|
|
156
|
+
}
|
|
157
|
+
if (command === "reauthorize") {
|
|
158
|
+
if (!runtimeSessionId || own?.status !== "revoked" || own.endpointId !== endpointId ||
|
|
159
|
+
new Set(flags).size !== flags.length || flags.some(f => f !== "--payload-read" && f !== "--ack")) refuse();
|
|
160
|
+
const payloadRead = flags.includes("--payload-read"); const ack = flags.includes("--ack");
|
|
161
|
+
options.onProgress?.("Waiting for configuration consent");
|
|
162
|
+
if (!await ctx.ui.confirm("Chat Exchange · reauthorize current Session", `Reauthorize exact Endpoint ${safe(endpointId)} for ONLY this current native Session? Epoch ${own.epoch} -> ${own.epoch + 1}; payload read=${payloadRead}; ACK=${ack} (reception only). ` +
|
|
163
|
+
"Hooks are preserved unchanged. Exact labels are visible to the peer; real send outcomes may reveal first join/addressability. Old factories remain denied until official reload. " +
|
|
164
|
+
"No Owner, capability or takeover changes. A held/expired old Owner requires normal release or separate operator recovery. No delivery or task execution is implied.", { signal: options.signal, timeout: 120_000 })) {
|
|
165
|
+
cancelled(ctx, options.signal, "live reauthorize"); return;
|
|
166
|
+
}
|
|
167
|
+
if (options.signal.aborted) return;
|
|
168
|
+
current();
|
|
169
|
+
options.onProgress?.("Waiting for configuration consent");
|
|
170
|
+
const presenceDisclosure = await ctx.ui.confirm("Chat Exchange · optional presence disclosure", "Also disclose Exchange membership/first join and current Owner/lease liveness to authorized peers? Decline keeps presence-dependent Active/Reachable unknown.", { signal: options.signal, timeout: 120_000 });
|
|
171
|
+
if (options.signal.aborted) return;
|
|
172
|
+
current();
|
|
173
|
+
options.onProgress?.("Publishing live session policy");
|
|
174
|
+
const result = await api.reauthorize({ expectedDigest: selected.digest, registration: { endpointId, runtimeSessionId, payloadRead, ack, presenceDisclosure: presenceDisclosure === true } });
|
|
175
|
+
ctx.ui.notify(`ce-tunnel: reauthorization saved (${result.durability}); official reload required; old factories remain denied. No Owner recovery or transport action.`, "warning");
|
|
176
|
+
} else if (command === "register") {
|
|
177
|
+
if (!runtimeSessionId || own?.status === "revoked" || selected.manifest.registrations.some(r => r.endpointId === endpointId && r !== own) ||
|
|
178
|
+
new Set(flags).size !== flags.length || flags.some(f => f !== "--payload-read" && f !== "--ack")) refuse();
|
|
179
|
+
const payloadRead = flags.includes("--payload-read"); const ack = flags.includes("--ack");
|
|
180
|
+
options.onProgress?.("Waiting for configuration consent");
|
|
181
|
+
if (!await ctx.ui.confirm("Chat Exchange · live configuration only", `Register current Session as ${safe(endpointId)}; payload read=${payloadRead}; ACK=${ack}. ` +
|
|
182
|
+
"Presence disclosure remains disabled unless separately consented. Hooks are preserved, never enabled. Publication is not delivery or task completion evidence.", { signal: options.signal, timeout: 120_000 })) {
|
|
183
|
+
cancelled(ctx, options.signal, "live register"); return;
|
|
184
|
+
}
|
|
185
|
+
if (options.signal.aborted) return;
|
|
186
|
+
current();
|
|
187
|
+
options.onProgress?.("Publishing live session policy");
|
|
188
|
+
const result = await api.register({ expectedDigest: selected.digest, registration: { endpointId, runtimeSessionId, payloadRead, ack, presenceDisclosure: false } });
|
|
189
|
+
ctx.ui.notify(`ce-tunnel: live registration saved (${result.durability}); explicit reload is required. No transport action or delivery claim.`, "warning");
|
|
190
|
+
} else {
|
|
191
|
+
if (flags.length !== 0) refuse();
|
|
192
|
+
const r = selected.manifest.registrations.find(r => r.endpointId === endpointId && r.status === "active");
|
|
193
|
+
if (r === undefined) return;
|
|
194
|
+
options.onProgress?.("Waiting for configuration consent");
|
|
195
|
+
if (!await ctx.ui.confirm("Chat Exchange · live configuration only", `Revoke exact Endpoint ${safe(endpointId)}? Already admitted operations may finish; reauthorization requires a fresh explicit confirmation. Revoking the last registration can permanently stop MCP renewal for this incarnation. An expired Owner requires separate operator recovery; no automatic takeover or heartbeat restart.`, { signal: options.signal, timeout: 120_000 })) {
|
|
196
|
+
cancelled(ctx, options.signal, "live revoke"); return;
|
|
197
|
+
}
|
|
198
|
+
if (options.signal.aborted) return;
|
|
199
|
+
current();
|
|
200
|
+
options.onProgress?.("Publishing live session policy");
|
|
201
|
+
const result = await api.revoke({ expectedDigest: selected.digest, endpointId });
|
|
202
|
+
ctx.ui.notify(`ce-tunnel: live registration revoked (${result.durability}); explicit reload is required. No transport action.`, "warning");
|
|
203
|
+
}
|
|
204
|
+
}
|
|
@@ -1,11 +1,15 @@
|
|
|
1
|
-
/** Pi composition only. Deny-only policy + local process exclusion, never CE authority. */
|
|
2
1
|
import { isDeepStrictEqual } from "node:util";
|
|
3
2
|
import { CeHostRefusal, type CeMappingIdentifiers } from "../dist/endpoints/pi/session-host.js";
|
|
4
3
|
import { intersectRegistration, readSelectedMultiSessionPolicy, type MultiSessionSnapshot } from "../dist/tunnel/multi-session-policy.js";
|
|
4
|
+
import { type LiveSnapshot, type LiveReaderWatermark } from "../dist/tunnel/live-session-policy.js";
|
|
5
|
+
|
|
6
|
+
import { readRuntimeLivePolicy } from "./live-session-profile.js";
|
|
5
7
|
import { acquireSessionProcessMutex, type SessionProcessMutex } from "../dist/tunnel/session-process-mutex.js";
|
|
6
8
|
|
|
9
|
+
export type RuntimePolicy = MultiSessionSnapshot | LiveSnapshot;
|
|
10
|
+
const live = (policy: RuntimePolicy): policy is LiveSnapshot => "ref" in policy;
|
|
7
11
|
interface Transfer {
|
|
8
|
-
readonly loaded:
|
|
12
|
+
readonly loaded: RuntimePolicy;
|
|
9
13
|
readonly mapping: CeMappingIdentifiers;
|
|
10
14
|
readonly mutex: SessionProcessMutex;
|
|
11
15
|
}
|
|
@@ -15,29 +19,47 @@ const KEY = Symbol.for("ce-chat-exchange.pi-multi-session-handoff-v1");
|
|
|
15
19
|
const state = ((globalThis as typeof globalThis & { [KEY]?: { transfers: Map<string, Transfer>; failed: Set<string> } })[KEY] ??= {
|
|
16
20
|
transfers: new Map(), failed: new Set(),
|
|
17
21
|
});
|
|
22
|
+
/** Read-only refusal probe; recovery must never clear or bypass this cache. */
|
|
23
|
+
export function runtimeHasFailed(loaded: RuntimePolicy, runtimeId: string, allScopes = false): boolean {
|
|
24
|
+
if (allScopes) {
|
|
25
|
+
for (const key of state.failed) {
|
|
26
|
+
try {
|
|
27
|
+
const scope: unknown = JSON.parse(key);
|
|
28
|
+
if (!Array.isArray(scope) || scope.length !== 3 || typeof scope[2] !== "string") return true;
|
|
29
|
+
if (scope[2] === runtimeId) return true;
|
|
30
|
+
} catch { return true; }
|
|
31
|
+
}
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
const registration = loaded.manifest.registrations.find(r => r.runtimeSessionId === runtimeId);
|
|
35
|
+
return registration !== undefined && state.failed.has(JSON.stringify([loaded.manifest.store, registration.endpointId, runtimeId]));
|
|
36
|
+
}
|
|
18
37
|
export const policyDenied = (): CeHostRefusal => new CeHostRefusal("CE_HOST_AUTHORITY_ABSENT", false, "ADMISSION_POLICY_DENIED");
|
|
19
38
|
export function runtimeEnvironment(): string {
|
|
20
39
|
return JSON.stringify([process.env.CE_ALLOWLIST, process.env.CE_STORE_DIR, process.env.CE_STORE_FILE,
|
|
21
40
|
process.env.CE_LEASE_TTL_SECONDS, process.env.CE_TUNNEL_PROFILE]);
|
|
22
41
|
}
|
|
23
42
|
export class PiMultiSessionRuntime {
|
|
24
|
-
readonly #loaded:
|
|
43
|
+
readonly #loaded: RuntimePolicy;
|
|
25
44
|
readonly #runtimeId: string;
|
|
26
45
|
readonly #currentRuntime: () => string;
|
|
27
46
|
readonly #environment: string;
|
|
28
47
|
readonly #key: string;
|
|
29
48
|
readonly #mutex: SessionProcessMutex;
|
|
30
|
-
|
|
49
|
+
readonly #currentPolicy: () => RuntimePolicy;
|
|
50
|
+
constructor(loaded: RuntimePolicy, runtimeId: string, currentRuntime: () => string, reload: boolean, mapping: unknown, currentPolicy?: () => RuntimePolicy) {
|
|
31
51
|
this.#loaded = loaded; this.#runtimeId = runtimeId; this.#currentRuntime = currentRuntime; this.#environment = runtimeEnvironment();
|
|
32
|
-
const
|
|
52
|
+
const watermark: LiveReaderWatermark = live(loaded) ? { sequence: loaded.sequence, digest: loaded.digest, policyId: loaded.ref.policyId } : {};
|
|
53
|
+
this.#currentPolicy = currentPolicy ?? (() => live(loaded) ? readRuntimeLivePolicy(loaded, watermark) : readSelectedMultiSessionPolicy(loaded.profilePath));
|
|
54
|
+
const r = liveRegistration(loaded, this.#currentPolicy(), runtimeId);
|
|
33
55
|
this.#key = JSON.stringify([loaded.manifest.store, r.endpointId, runtimeId]);
|
|
34
56
|
if (state.failed.has(this.#key)) throw policyDenied();
|
|
35
57
|
const pending = state.transfers.get(this.#key);
|
|
36
58
|
if (pending !== undefined) {
|
|
37
|
-
if (!reload || !isDeepStrictEqual(mapping, pending.mapping)) throw policyDenied();
|
|
38
|
-
//
|
|
39
|
-
|
|
40
|
-
intersectRegistration(pending.loaded, loaded, runtimeId);
|
|
59
|
+
if (!reload || !isDeepStrictEqual(mapping, pending.mapping) || live(pending.loaded) !== live(loaded)) throw policyDenied();
|
|
60
|
+
// Identity/epoch continuity; permission generations are checked again on each call.
|
|
61
|
+
if (live(pending.loaded) && live(loaded)) assertLiveRegistrationContinuity(pending.loaded, loaded, runtimeId);
|
|
62
|
+
else if (!live(pending.loaded) && !live(loaded)) intersectRegistration(pending.loaded, loaded, runtimeId);
|
|
41
63
|
pending.mutex.assertOwnership();
|
|
42
64
|
this.#mutex = pending.mutex;
|
|
43
65
|
state.transfers.delete(this.#key); // one consumer, no second handle
|
|
@@ -49,7 +71,7 @@ export class PiMultiSessionRuntime {
|
|
|
49
71
|
return this.#mutex.run(() => {
|
|
50
72
|
try {
|
|
51
73
|
if (runtimeEnvironment() !== this.#environment || this.#currentRuntime() !== this.#runtimeId) throw policyDenied();
|
|
52
|
-
const r =
|
|
74
|
+
const r = liveRegistration(this.#loaded, this.#currentPolicy(), this.#runtimeId);
|
|
53
75
|
if ((kind === "payload" && !r.payloadRead) || (kind === "ack" && !r.ack)) throw policyDenied();
|
|
54
76
|
} catch { throw policyDenied(); }
|
|
55
77
|
return operation();
|
|
@@ -66,10 +88,40 @@ export class PiMultiSessionRuntime {
|
|
|
66
88
|
}
|
|
67
89
|
private runPolicyForTransfer(): void {
|
|
68
90
|
if (this.#currentRuntime() !== this.#runtimeId || runtimeEnvironment() !== this.#environment) throw policyDenied();
|
|
69
|
-
|
|
91
|
+
continuity(this.#loaded, this.#currentPolicy(), this.#runtimeId);
|
|
70
92
|
}
|
|
71
93
|
release(cleanup: { readonly released: boolean; readonly detached: boolean }): void {
|
|
72
94
|
try { this.#mutex.release(cleanup); } catch (error) { this.fail(); throw error; }
|
|
73
95
|
}
|
|
74
96
|
fail(): void { state.failed.add(this.#key); }
|
|
75
97
|
}
|
|
98
|
+
|
|
99
|
+
/** Generic policy entry point used by callers without the PiSessionPolicy facade. */
|
|
100
|
+
export function liveRegistration(loaded: RuntimePolicy, current: RuntimePolicy, runtimeId: string) {
|
|
101
|
+
if (live(loaded) && live(current)) return effectiveLiveRegistration(loaded, current, runtimeId);
|
|
102
|
+
if (!live(loaded) && !live(current)) return intersectRegistration(loaded, current, runtimeId);
|
|
103
|
+
throw policyDenied();
|
|
104
|
+
}
|
|
105
|
+
function continuity(loaded: RuntimePolicy, current: RuntimePolicy, runtimeId: string) {
|
|
106
|
+
if (live(loaded) && live(current)) return assertLiveRegistrationContinuity(loaded, current, runtimeId);
|
|
107
|
+
if (!live(loaded) && !live(current)) return intersectRegistration(loaded, current, runtimeId);
|
|
108
|
+
throw policyDenied();
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Reload may capture newer permission/Hook generations; identity and epoch stay fixed. */
|
|
112
|
+
export function assertLiveRegistrationContinuity(loaded: LiveSnapshot, current: LiveSnapshot, runtimeId: string) {
|
|
113
|
+
if (!isDeepStrictEqual(loaded.ref, current.ref) || !isDeepStrictEqual(loaded.manifest.identity, current.manifest.identity) ||
|
|
114
|
+
!isDeepStrictEqual(loaded.manifest.store, current.manifest.store) || !isDeepStrictEqual(loaded.manifest.exchange, current.manifest.exchange) ||
|
|
115
|
+
!isDeepStrictEqual(loaded.manifest.chatgptEndpoint, current.manifest.chatgptEndpoint)) throw policyDenied();
|
|
116
|
+
const a = loaded.manifest.registrations.find(r => r.runtimeSessionId === runtimeId);
|
|
117
|
+
const b = current.manifest.registrations.find(r => r.runtimeSessionId === runtimeId);
|
|
118
|
+
if (a === undefined || b === undefined || a.status !== "active" || b.status !== "active" || a.endpointId !== b.endpointId ||
|
|
119
|
+
a.epoch !== b.epoch || (loaded.ref.kind !== "ce-live-session-v2" && !isDeepStrictEqual(a.hooks, b.hooks)) || b.payloadReadGeneration < a.payloadReadGeneration || b.ackGeneration < a.ackGeneration) throw policyDenied();
|
|
120
|
+
return b;
|
|
121
|
+
}
|
|
122
|
+
export function effectiveLiveRegistration(loaded: LiveSnapshot, current: LiveSnapshot, runtimeId: string) {
|
|
123
|
+
const b = assertLiveRegistrationContinuity(loaded, current, runtimeId);
|
|
124
|
+
const a = loaded.manifest.registrations.find(r => r.runtimeSessionId === runtimeId)!;
|
|
125
|
+
return Object.freeze({ ...b, payloadRead: b.payloadRead && a.payloadRead && b.payloadReadGeneration === a.payloadReadGeneration,
|
|
126
|
+
ack: b.ack && a.ack && b.ackGeneration === a.ackGeneration });
|
|
127
|
+
}
|