@zieglar/pi-chat-exchange 0.3.2 → 0.3.4

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.
@@ -27,6 +27,7 @@
27
27
  */
28
28
  import { createNativeInbound, isNativeFeedback, type NativeInboundToolContext } from "./native-inbound.js";
29
29
  import { createNativeReadProtocol } from "./native-read-protocol.js";
30
+ import { runRuntimeBindingCommand } from "./runtime-binding-command.js";
30
31
  import { createOwnershipFeedbackBridge } from "./ownership-feedback.js";
31
32
  import { createCaptureScheduler, createDeliveryGuard, createDesktopTargetBridge, deliverAfterDesktopCapture, type DesktopTargetBridge } from "./desktop-target.js";
32
33
  import { runSessionConfiguration } from "./multi-session-commands.js";
@@ -39,6 +40,8 @@ import { createHooksManagement, runSafeHookFixture } from "../dist/tunnel/hooks-
39
40
  import { runHooksManagementUi } from "../dist/tunnel/hooks-management-ui.js";
40
41
  import { createBackgroundAuthorizationStore } from "../dist/tunnel/background-authorization.js";
41
42
  import { readLivePolicy } from "../dist/tunnel/live-session-policy.js";
43
+ import { observeSessionDeparture, observeSessionArrival } from "../dist/tunnel/session-switch-observation.js";
44
+ import { createCurrentRuntimeObserver } from "../dist/tunnel/current-runtime-binding.js";
42
45
  import { readLiveSelectedSessionPolicy, projectLivePiRegistration } from "./live-session-profile.js";
43
46
  import { readSelectedMultiSessionPolicy, projectPiRegistration, effectivePiHookRules } from "../dist/tunnel/multi-session-policy.js";
44
47
  import { runSetupWizard, presentTunnelStatus } from "../dist/tunnel/setup-ui.js";
@@ -154,7 +157,7 @@ interface ToolDefinitionView {
154
157
  interface ExtensionApiView {
155
158
  on(
156
159
  event: "session_start" | "session_shutdown",
157
- handler: (event: { reason: string }, ctx: ExtensionContextView) => Promise<void> | void,
160
+ handler: (event: { reason: string; previousSessionFile?: string; targetSessionFile?: string }, ctx: ExtensionContextView) => Promise<void> | void,
158
161
  ): void;
159
162
  on(
160
163
  event: "agent_settled",
@@ -434,8 +437,15 @@ function openHostStore(allowlist: AllowlistFile) {
434
437
  // recently observed (always simulated in B1.1) client activity.
435
438
  const TUNNEL_STATUS_KEYS = ["ce", "ce-tunnel", "ce-client"] as const;
436
439
 
440
+ interface RuntimeIdentityState { runtimeId: string; observerId: ReturnType<typeof randomUUID>; }
441
+ const runtimeIdentityKey = Symbol.for("pi-chat-exchange.runtime-identity.v1");
442
+ const runtimeIdentityState = globalThis as typeof globalThis & { [key: symbol]: RuntimeIdentityState | undefined };
443
+ const processRuntimeIdentity = runtimeIdentityState[runtimeIdentityKey] ??= { runtimeId: `runtime-${randomUUID()}`, observerId: randomUUID() };
444
+ const processRuntimeId = processRuntimeIdentity.runtimeId;
445
+
437
446
  export default function ceChatExchange(pi: ExtensionApiView): void {
438
447
  let operationSequence = 0;
448
+ const activeRuntimeId = process.env.CE_RUNTIME_ID ?? processRuntimeId;
439
449
  const operationFeedback = new Map<string, () => void>();
440
450
  let clearCommandResult = (): void => {};
441
451
  // Feedback has its own lifetime and never controls transport or admission.
@@ -705,12 +715,42 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
705
715
  // CE_ALLOWLIST keeps its explicit legacy precedence.
706
716
  let multiPolicy: SelectedSessionPolicy | undefined;
707
717
  let selectedPolicyInvalid = false;
718
+ let currentRuntimeObserver: ReturnType<typeof createCurrentRuntimeObserver> | undefined;
719
+ let currentRuntimeScope: string | undefined;
720
+ let currentRuntimeTimer: ReturnType<typeof setInterval> | undefined;
721
+ const stopCurrentRuntime = (): void => {
722
+ if (currentRuntimeTimer !== undefined) clearInterval(currentRuntimeTimer);
723
+ currentRuntimeTimer = undefined;
724
+ currentRuntimeObserver?.stop();
725
+ };
726
+ const startCurrentRuntime = (ctx: ExtensionContextView): void => {
727
+ stopCurrentRuntime();
728
+ if (multiPolicy === undefined || !isLivePolicy(multiPolicy)) return;
729
+ try {
730
+ const scope = `${multiPolicy.ref.root}:${multiPolicy.ref.policyId}:${multiPolicy.ref.genesisDigest}`;
731
+ if (currentRuntimeObserver === undefined || currentRuntimeScope !== scope) {
732
+ currentRuntimeObserver = createCurrentRuntimeObserver(multiPolicy.ref, activeRuntimeId, Date.now, processRuntimeIdentity.observerId);
733
+ currentRuntimeScope = scope;
734
+ }
735
+ const sessionId = ctx.sessionManager.getSessionId();
736
+ if (!currentRuntimeObserver.observe(sessionId)) return;
737
+ currentRuntimeTimer = setInterval(() => {
738
+ try { if (ctx.sessionManager.getSessionId() !== sessionId || !currentRuntimeObserver?.observe(sessionId)) stopCurrentRuntime(); }
739
+ catch { stopCurrentRuntime(); }
740
+ }, 1_000);
741
+ currentRuntimeTimer.unref();
742
+ } catch { /* Observation never grants CE admission. */ }
743
+ };
708
744
  let explicitlySelectedProfile = Boolean(process.env.CE_TUNNEL_PROFILE);
745
+ let loadedBindingProfile: string | undefined;
746
+ let loadedBindingProfileText: string | undefined;
709
747
  if (!process.env.CE_ALLOWLIST) {
710
748
  try {
711
749
  explicitlySelectedProfile ||= createBackgroundAuthorizationStore().readSelection().kind === "valid";
712
750
  const profilePath = resolveTunnelProfilePath({ env: process.env });
713
- multiPolicy = readLiveSelectedSessionPolicy(profilePath, readFileSync(profilePath, "utf8"));
751
+ const profileText = readFileSync(profilePath, "utf8");
752
+ multiPolicy = readLiveSelectedSessionPolicy(profilePath, profileText);
753
+ if (multiPolicy !== undefined) { loadedBindingProfile = profilePath; loadedBindingProfileText = profileText; }
714
754
  if (multiPolicy === undefined) { try { multiPolicy = readSelectedMultiSessionPolicy(profilePath); } catch { /* existing legacy loader validates its own selected pair */ } }
715
755
  } catch (error) { selectedPolicyInvalid = (error as NodeJS.ErrnoException).code !== "ENOENT" || explicitlySelectedProfile; }
716
756
  }
@@ -1289,6 +1329,7 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
1289
1329
  };
1290
1330
 
1291
1331
  pi.on("session_start", async (event, ctx) => {
1332
+ startCurrentRuntime(ctx);
1292
1333
  // The warning is about the Native default path only. An explicit node-sqlite
1293
1334
  // compatibility selection keeps messaging available, so it must not be told
1294
1335
  // that messaging is disabled.
@@ -1315,6 +1356,10 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
1315
1356
  inboxBinding = undefined;
1316
1357
  advisoryState = undefined;
1317
1358
  const piSessionId = ctx.sessionManager.getSessionId();
1359
+ if (event.reason === "new" && multiPolicy !== undefined && isLivePolicy(multiPolicy)) {
1360
+ observeSessionArrival(multiPolicy.ref, { runtimeSessionId: piSessionId,
1361
+ sessionFile: ctx.sessionManager.getSessionFile(), previousSessionFile: event.previousSessionFile });
1362
+ }
1318
1363
  if (multiPolicy !== undefined) {
1319
1364
  // Project only this trusted runtime, never all manifest registrations.
1320
1365
  try { allowlist = (isLivePolicy(multiPolicy) ? projectLivePiRegistration(multiPolicy, piSessionId) : projectPiRegistration(multiPolicy, piSessionId)) as AllowlistFile; }
@@ -1442,7 +1487,22 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
1442
1487
  await continueConnect();
1443
1488
  });
1444
1489
 
1445
- pi.on("session_shutdown", (event) => shutdown(event.reason));
1490
+ pi.on("session_shutdown", (event, ctx) => {
1491
+ stopCurrentRuntime();
1492
+ const state = generation;
1493
+ let observation: Parameters<typeof observeSessionDeparture> | undefined;
1494
+ try {
1495
+ if (event.reason === "new" && state !== undefined && !state.stopping && state.failure === undefined &&
1496
+ state.piSessionId === ctx.sessionManager.getSessionId() && multiPolicy !== undefined && isLivePolicy(multiPolicy)) {
1497
+ const registration = multiPolicy.manifest.registrations.find(r => r.status === "active" && r.runtimeSessionId === state.piSessionId && r.endpointId === state.endpointId);
1498
+ if (registration !== undefined) observation = [multiPolicy.ref, { runtimeSessionId: state.piSessionId,
1499
+ endpointId: state.endpointId, epoch: registration.epoch, sessionFile: ctx.sessionManager.getSessionFile(), targetSessionFile: event.targetSessionFile }];
1500
+ }
1501
+ } catch { /* Missing observation never changes cleanup. */ }
1502
+ return shutdown(event.reason).then(() => {
1503
+ if (observation !== undefined && state?.failure === undefined) observeSessionDeparture(...observation);
1504
+ });
1505
+ });
1446
1506
 
1447
1507
  pi.on("agent_settled", (_event, ctx) => {
1448
1508
  checkInboxAdvisory(ctx);
@@ -1849,6 +1909,21 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
1849
1909
  });
1850
1910
 
1851
1911
 
1912
+ pi.registerCommand("ce-bind", {
1913
+ description: "Manage named Runtime groups: status [group], bind/rebind/revoke <group>, rename <old> <new>; shared CE Endpoint scope, independent grants",
1914
+ getArgumentCompletions: prefix => ["status", "bind", "rebind", "revoke", "rename"].filter(value => value.startsWith(prefix)).map(value => ({ value, label: value })),
1915
+ async handler(args, ctx) {
1916
+ await runRuntimeBindingCommand(args, ctx, {
1917
+ ...(loadedBindingProfile === undefined ? {} : { profilePath: loadedBindingProfile }),
1918
+ ...(loadedBindingProfileText === undefined ? {} : { profileText: loadedBindingProfileText }),
1919
+ ...(multiPolicy !== undefined && isLivePolicy(multiPolicy) ? { ref: multiPolicy.ref } : {}),
1920
+ runtimeId: activeRuntimeId,
1921
+ isCurrent: () => !selectedPolicyInvalid && runtimeEnvironment() === loadedRuntimeEnvironment &&
1922
+ loadedBindingProfile !== undefined && resolveTunnelProfilePath({ env: process.env }) === loadedBindingProfile,
1923
+ });
1924
+ },
1925
+ });
1926
+
1852
1927
  pi.registerCommand("ce-status", {
1853
1928
  description: "Show this session's chat-exchange endpoint, ownership lease, and fencing status",
1854
1929
  async handler(_args, ctx) {
@@ -0,0 +1,104 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { isDeepStrictEqual, parseArgs } from "node:util";
3
+ import { parseTunnelProfile } from "../dist/tunnel/background-manager.js";
4
+ import { parseTunnelMcpCommand } from "../dist/tunnel/profile.js";
5
+ import { readMessagingGeneration } from "../dist/tunnel/messaging-config.js";
6
+ import { createEndpointRuntimeBinding, normalizeRuntimeGroup, type RuntimeSelection } from "../dist/tunnel/endpoint-runtime-binding.js";
7
+ import { discoverCurrentRuntimes } from "../dist/tunnel/current-runtime-binding.js";
8
+ import type { LivePolicyRef } from "../dist/tunnel/live-session-policy.js";
9
+ import { readLiveSelectedSessionPolicy } from "./live-session-profile.js";
10
+
11
+ interface CommandContext {
12
+ readonly hasUI: boolean;
13
+ readonly sessionManager: {getSessionId(): string};
14
+ readonly ui: {
15
+ notify(message: string, level: "info" | "warning"): void;
16
+ confirm?(title: string, message: string): Promise<boolean>;
17
+ };
18
+ }
19
+ interface RuntimeContext {
20
+ readonly profilePath?: string;
21
+ readonly profileText?: string;
22
+ readonly ref?: LivePolicyRef;
23
+ readonly runtimeId: string;
24
+ readonly isCurrent: () => boolean;
25
+ }
26
+ const scopeNotice = "CE Endpoint-level binding shared by all callers of this launch; no ChatGPT conversation identity is attested; no permissions granted";
27
+ const refuse = (code: string): never => {throw Error(`CE_BIND_${code}`);};
28
+
29
+ /** Local operator command only. Caller scope comes from the loaded private launch,
30
+ * never command arguments, message metadata or a global latest Runtime. */
31
+ export async function runRuntimeBindingCommand(args: string, ctx: CommandContext, runtime: RuntimeContext): Promise<void> {
32
+ try {
33
+ let parsed;
34
+ try {parsed = parseArgs({args: args.trim() ? args.trim().split(/\s+/) : [], allowPositionals: true,
35
+ options: {"expected-revision": {type: "string"}, "accept-endpoint-scope": {type: "boolean"}}});}
36
+ catch {return refuse("INVALID");}
37
+ const [action = "status", rawGroup, rawNext] = parsed.positionals, values = parsed.values;
38
+ if (!["status", "bind", "rebind", "revoke", "rename"].includes(action) ||
39
+ (action === "rename" ? parsed.positionals.length !== 3 : parsed.positionals.length > 2) ||
40
+ action === "status" && Object.keys(values).length > 0 ||
41
+ values["expected-revision"] !== undefined && !/^(unbound|[a-f0-9]{64})$/.test(values["expected-revision"]) ||
42
+ values["accept-endpoint-scope"] && values["expected-revision"] === undefined) return refuse("INVALID");
43
+ const group = rawGroup === undefined ? undefined : normalizeRuntimeGroup(rawGroup);
44
+ const nextName = rawNext === undefined ? undefined : normalizeRuntimeGroup(rawNext);
45
+ if (runtime.profilePath === undefined || runtime.profileText === undefined || runtime.ref === undefined) return refuse("SCOPE_UNAVAILABLE");
46
+ const profilePath = runtime.profilePath, sessionId = ctx.sessionManager.getSessionId();
47
+ // Pin the launch selected when the extension loaded, including changes made
48
+ // before this command starts. A new generation requires explicit reload.
49
+ const profile = runtime.profileText;
50
+ const assertCurrent = (): void => {
51
+ if (!runtime.isCurrent() || ctx.sessionManager.getSessionId() !== sessionId || readFileSync(profilePath, "utf8") !== profile) refuse("CONTEXT_CHANGED");
52
+ };
53
+ assertCurrent();
54
+ const snapshot = readLiveSelectedSessionPolicy(profilePath, profile);
55
+ if (snapshot === undefined || !isDeepStrictEqual(snapshot.ref, runtime.ref)) return refuse("SCOPE_UNAVAILABLE");
56
+ const facts = parseTunnelProfile(profile);
57
+ if (facts.mcpCommand === undefined) return refuse("SCOPE_UNAVAILABLE");
58
+ const bindingPath = parseTunnelMcpCommand(facts.mcpCommand).bindingPath;
59
+ const pair = readMessagingGeneration(profilePath, bindingPath, facts.keyFile);
60
+ if (pair === undefined || pair.config.endpoint.adapter !== "chatgpt" || !isDeepStrictEqual(pair.config.admissionPolicy, runtime.ref)) return refuse("SCOPE_UNAVAILABLE");
61
+ const binding = createEndpointRuntimeBinding(bindingPath, pair.config), before = group === undefined ? binding.read() : binding.readGroup(group);
62
+ if (before.status === "unavailable") return refuse("SCOPE_UNAVAILABLE");
63
+ const visible = snapshot.manifest.registrations.filter(r => r.status === "active" && r.presenceDisclosure).map(r => r.endpointId);
64
+ const describe = (selection: RuntimeSelection): string => {
65
+ if (selection.status === "unavailable") return refuse("SCOPE_UNAVAILABLE");
66
+ const target = selection.status === "bound" ? discoverCurrentRuntimes(snapshot, visible, selection.runtimeId).currentBinding : undefined;
67
+ return `group=${selection.group ?? "(legacy)"}; selection=${selection.status}; revision=${selection.revision}` +
68
+ (selection.status === "bound" ? `; boundRuntime=${selection.runtimeId}` : "") +
69
+ (action === "status" ? `; target=${target?.status ?? "unbound"}${target?.status === "verified" ? `; endpoint=${target.endpointId}` : ""}` : "");
70
+ };
71
+ const show = (selections: RuntimeSelection[]): void => ctx.ui.notify(
72
+ `ce-bind: ${scopeNotice}\ncaller=${pair.config.endpoint.endpointId}; thisRuntime=${runtime.runtimeId}\n${selections.map(describe).join("\n")}`, "info");
73
+ if (action === "status") {show(group === undefined ? [before, ...binding.listGroups()] : [before]); return;}
74
+ const expectedRevision = values["expected-revision"] ?? before.revision;
75
+ if (expectedRevision !== before.revision) return refuse("CONFLICT");
76
+ if (action === "bind" && before.status === "bound") return refuse("USE_REBIND");
77
+ if ((action === "rebind" || action === "revoke") && before.status === "unbound") return refuse("ALREADY_UNBOUND");
78
+ // Consent covers the exact revision displayed here. A competing operator is
79
+ // resolved by the existing CAS writer; never reread and retry a mutation.
80
+ if (!values["accept-endpoint-scope"]) {
81
+ if (!ctx.hasUI || ctx.ui.confirm === undefined) return refuse("CONFIRMATION_REQUIRED");
82
+ const accepted = await ctx.ui.confirm("CE Runtime binding", `${scopeNotice}\n${action}: caller=${pair.config.endpoint.endpointId}; group=${group ?? "(legacy)"}${nextName === undefined ? "" : `; newGroup=${nextName}`}; previous=${before.status === "bound" ? before.runtimeId : "unbound"}; next=${action === "rename" ? "same Runtime" : action === "revoke" ? "unbound" : runtime.runtimeId}; revision=${expectedRevision}`);
83
+ if (!accepted) {ctx.ui.notify("ce-bind: cancelled", "info"); return;}
84
+ }
85
+ assertCurrent();
86
+ if (action === "bind" || action === "rebind") {
87
+ const fresh = readLiveSelectedSessionPolicy(profilePath, profile);
88
+ if (fresh === undefined || !isDeepStrictEqual(fresh.ref, runtime.ref)) return refuse("SCOPE_UNAVAILABLE");
89
+ const registration = fresh.manifest.registrations.find(r => r.runtimeSessionId === sessionId && r.status === "active" && r.presenceDisclosure);
90
+ const current = discoverCurrentRuntimes(fresh, registration === undefined ? [] : [registration.endpointId], runtime.runtimeId).currentBinding;
91
+ if (registration === undefined || current?.status !== "verified" || current.endpointId !== registration.endpointId) return refuse("RUNTIME_UNAVAILABLE");
92
+ }
93
+ const result = group === undefined
94
+ ? binding.update({runtimeId: action === "revoke" ? null : runtime.runtimeId, expectedRevision, acceptEndpointScope: true})
95
+ : binding.updateGroup({action, group, ...(action === "rename" ? {nextName} : {}),
96
+ ...(action === "bind" || action === "rebind" ? {runtimeId: runtime.runtimeId} : {}), expectedRevision, acceptEndpointScope: true});
97
+ if (result.status === "unavailable") return refuse("SCOPE_UNAVAILABLE");
98
+ show([result]);
99
+ } catch (error) {
100
+ const code = error instanceof Error && /^CE_(BIND_(INVALID|SCOPE_UNAVAILABLE|CONTEXT_CHANGED|CONFLICT|USE_REBIND|ALREADY_UNBOUND|CONFIRMATION_REQUIRED|RUNTIME_UNAVAILABLE)|RUNTIME_BINDING_(INVALID|CONFLICT|RUNTIME_UNAVAILABLE|WRITE_UNCERTAIN|GROUP_EXISTS|GROUP_UNBOUND|GROUP_LIMIT))$/.test(error.message)
101
+ ? error.message : "CE_BIND_SCOPE_UNAVAILABLE";
102
+ ctx.ui.notify(`ce-bind: refused (${code})`, "warning");
103
+ }
104
+ }