@zieglar/pi-chat-exchange 0.3.5 → 0.3.6

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.
@@ -26,7 +26,7 @@ import { callMessagingTool, CE_ACK_TOOL, CE_SEND_TOOL_NAME, SendArgsSchema, isAc
26
26
  import { callEndpointDiscovery, CE_ENDPOINTS_TOOL, CE_ENDPOINTS_TOOL_NAME } from "./endpoint-discovery.js";
27
27
  import { callTaskOwner, CE_TASK_OWNER_TOOL, CE_TASK_OWNER_TOOL_NAME } from "./task-owner.js";
28
28
  export const SERVER_NAME = "pi-chat-exchange";
29
- export const SERVER_VERSION = "0.3.5";
29
+ export const SERVER_VERSION = "0.3.6";
30
30
  const PING_TOOL = {
31
31
  name: PING_TOOL_NAME,
32
32
  description: "Read-only liveness probe for the pi-chat-exchange service. " +
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zieglar/pi-chat-exchange",
3
- "version": "0.3.5",
3
+ "version": "0.3.6",
4
4
  "license": "MIT",
5
5
  "publishConfig": {
6
6
  "access": "public",
@@ -26,6 +26,7 @@
26
26
  * seam from packages/pi-chat-exchange/dist.
27
27
  */
28
28
  import { createNativeInbound, isNativeFeedback, type NativeInboundToolContext } from "./native-inbound.js";
29
+ import { disableNativeInboundPolicy, enableNativeInboundPolicy, inspectNativeInboundPolicy, nativeInboundPolicyPath } from "./native-inbound-policy.js";
29
30
  import { createNativeReadProtocol } from "./native-read-protocol.js";
30
31
  import { runRuntimeBindingCommand } from "./runtime-binding-command.js";
31
32
  import { createOwnershipFeedbackBridge } from "./ownership-feedback.js";
@@ -120,6 +121,8 @@ interface UiView {
120
121
  /** Pi 1.3.0 built-in cancellable operator dialog; never a model tool. */
121
122
  confirm?(title: string, message: string, options?: { signal?: AbortSignal; timeout?: number }): Promise<boolean>;
122
123
  select?(title: string, options: string[], config?: { signal?: AbortSignal; timeout?: number }): Promise<string | undefined>;
124
+ /** Pi 1.3.0 non-secret text dialog; used here only for an explicit sender Endpoint label. */
125
+ input?(title: string, placeholder?: string, options?: { signal?: AbortSignal; timeout?: number }): Promise<string | undefined>;
123
126
  }
124
127
 
125
128
  interface ExtensionContextView {
@@ -485,18 +488,19 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
485
488
  };
486
489
  // Management is registered independently of subsequent Store/session activation.
487
490
  let nativeStartupWarned = false;
491
+ const runNativeCommand = async (args: string, ctx: ExtensionContextView): Promise<void> => {
492
+ const feedback = beginOperation(ctx, "CE Native");
493
+ const command = args.trim();
494
+ feedback.stage(command === "check-updates" ? "Checking release metadata"
495
+ : command === "install" || command === "repair confirm" ? "Preparing and verifying the trusted Native artifact" : "Inspecting Native command");
496
+ try {
497
+ const result = await runNativeCommandOutcome(args);
498
+ if (feedback.current()) notify(ctx, result.message, result.kind === "ok" ? "info" : "warning");
499
+ } finally { feedback.finish(); }
500
+ };
488
501
  pi.registerCommand("ce-native", {
489
- description: "Inspect, install or verify the trusted Native driver; check release discovery",
490
- async handler(args, ctx) {
491
- const feedback = beginOperation(ctx, "CE Native");
492
- const command = args.trim();
493
- feedback.stage(command === "check-updates" ? "Checking release metadata"
494
- : command === "install" || command === "repair confirm" ? "Preparing and verifying the trusted Native artifact" : "Inspecting Native command");
495
- try {
496
- const result = await runNativeCommandOutcome(args);
497
- if (feedback.current()) notify(ctx, result.message, result.kind === "ok" ? "info" : "warning");
498
- } finally { feedback.finish(); }
499
- },
502
+ description: "Compatibility command; use /ce advanced native",
503
+ handler: runNativeCommand,
500
504
  });
501
505
  // Transport UI, the offline manager, and any in-flight credential capture
502
506
  // belong to THIS factory instance, independently of CE generation.
@@ -1939,7 +1943,7 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
1939
1943
  });
1940
1944
  }
1941
1945
  pi.registerCommand("ce-hooks", {
1942
- description: "Manage Hooks with explicit native consent; headless sessions inspect loaded rules only",
1946
+ description: "Compatibility command; use /ce advanced hooks",
1943
1947
  async handler(_args, ctx) {
1944
1948
  if (ctx.mode === "tui" && ctx.hasUI && typeof ctx.ui.custom === "function") { await runHooksCommand(ctx); return; }
1945
1949
  const audit = hookSnapshot();
@@ -1952,11 +1956,7 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
1952
1956
  },
1953
1957
  });
1954
1958
 
1955
-
1956
- pi.registerCommand("ce-bind", {
1957
- description: "Manage named Runtime groups: status [group], bind/rebind/revoke <group>, rename <old> <new>; shared CE Endpoint scope, independent grants",
1958
- getArgumentCompletions: prefix => ["status", "bind", "rebind", "revoke", "rename"].filter(value => value.startsWith(prefix)).map(value => ({ value, label: value })),
1959
- async handler(args, ctx) {
1959
+ const runBindingsCommand = async (args: string, ctx: ExtensionContextView): Promise<void> => {
1960
1960
  await runRuntimeBindingCommand(args, ctx, {
1961
1961
  ...(loadedBindingProfile === undefined ? {} : { profilePath: loadedBindingProfile }),
1962
1962
  ...(loadedBindingProfileText === undefined ? {} : { profileText: loadedBindingProfileText }),
@@ -1965,12 +1965,13 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
1965
1965
  isCurrent: () => !selectedPolicyInvalid && runtimeEnvironment() === loadedRuntimeEnvironment &&
1966
1966
  loadedBindingProfile !== undefined && resolveTunnelProfilePath({ env: process.env }) === loadedBindingProfile,
1967
1967
  });
1968
- },
1968
+ };
1969
+ pi.registerCommand("ce-bind", {
1970
+ description: "Compatibility command; use /ce advanced bindings",
1971
+ handler: runBindingsCommand,
1969
1972
  });
1970
1973
 
1971
- pi.registerCommand("ce-status", {
1972
- description: "Show this session's chat-exchange endpoint, ownership lease, and fencing status",
1973
- async handler(_args, ctx) {
1974
+ const runCeStatus = async (ctx: ExtensionContextView): Promise<void> => {
1974
1975
  if (startupFailure !== undefined) {
1975
1976
  notify(ctx, `ce-chat-exchange: session start failed closed (${startupFailure.code})${startupRuntimeRepair === undefined ? "" : `; ${startupRuntimeRepair}`}`, "warning");
1976
1977
  return;
@@ -1987,10 +1988,18 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
1987
1988
  notify(ctx, "ce-chat-exchange: status unavailable (CE_HOST_UNAVAILABLE)", "warning");
1988
1989
  return;
1989
1990
  }
1991
+ const policyPath = nativeInboundPolicyPath(resolveTunnelProfilePath({ env: process.env }), ctx.sessionManager.getSessionId());
1992
+ const inbound = status.exchangeId === undefined ? { status: "invalid" as const } : inspectNativeInboundPolicy(policyPath, {
1993
+ runtimeSessionId: ctx.sessionManager.getSessionId(), endpointId: status.endpointId, exchangeId: status.exchangeId,
1994
+ }, Date.now());
1995
+ const native = inspectNativeReadiness();
1996
+ let tunnel = "UNKNOWN";
1997
+ try { tunnel = (await readTunnelUi(ctx)).runtimeState; } catch { /* Unknown is the truthful fallback. */ }
1990
1998
  const message = `ce-chat-exchange: piSession=${ctx.sessionManager.getSessionId()} exchange=${status.exchangeId ?? "none"} ` +
1991
1999
  `endpoint=${status.endpointId} registered=${status.registered} ` +
1992
2000
  `participant=${status.participantId ?? "none"} session=${status.sessionId ?? "none"} ` +
1993
- `lease=${status.lease} fencing=${status.fencingToken ?? "none"}`;
2001
+ `lease=${status.lease} fencing=${status.fencingToken ?? "none"} ` +
2002
+ `tunnel=${tunnel} native=${native.state} inbound=${inbound.status} mcpSource=UNKNOWN`;
1994
2003
  notify(ctx, message);
1995
2004
  if (ctx.mode === "tui" && ctx.hasUI && typeof ctx.ui.custom === "function" && managerUiTask === undefined && activationTask === undefined) {
1996
2005
  const controller = new AbortController(); managerUiCapture = controller;
@@ -1999,6 +2008,7 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
1999
2008
  `Endpoint: ${status.endpointId}`, `Registered: ${status.registered}`,
2000
2009
  `Participant: ${status.participantId ?? "none"}`, `Session: ${status.sessionId ?? "none"}`,
2001
2010
  `Lease: ${status.lease}`, `Fencing: ${status.fencingToken ?? "none"}`,
2011
+ `Tunnel: ${tunnel}`, `Native: ${native.state} (${native.code})`, `Inbound: ${inbound.status}`, "MCP source: UNKNOWN",
2002
2012
  ], { signal: controller.signal });
2003
2013
  managerUiTask = task;
2004
2014
  try { await task; } finally {
@@ -2006,7 +2016,10 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
2006
2016
  if (managerUiCapture === controller) managerUiCapture = undefined;
2007
2017
  }
2008
2018
  }
2009
- },
2019
+ };
2020
+ pi.registerCommand("ce-status", {
2021
+ description: "Compatibility command; use /ce status",
2022
+ async handler(_args, ctx) { await runCeStatus(ctx); },
2010
2023
  });
2011
2024
  // Real setup persists an operator-confirmed profile; synthetic Keychain
2012
2025
  // capture remains reachable only through the explicit offline test harness.
@@ -3022,6 +3035,45 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
3022
3035
  }
3023
3036
  };
3024
3037
 
3038
+ /** Register/reload/activate the current Session without transport lifecycle work. */
3039
+ const runSessionBind = async (ctx: ExtensionContextView): Promise<void> => {
3040
+ if (dailyTask !== undefined || activationTask !== undefined || setupTask !== undefined || managerUiTask !== undefined || startCapture !== undefined) {
3041
+ notify(ctx, "ce-session: bind refused CE_TUNNEL_MANAGER_BUSY", "warning"); return;
3042
+ }
3043
+ if (ctx.mode !== "tui" || !ctx.hasUI || !isRealBackground() || multiPolicy === undefined) {
3044
+ notify(ctx, "ce-session: bind refused CE_TUNNEL_INPUT_UNAVAILABLE", "warning"); return;
3045
+ }
3046
+ const sessionId = ctx.sessionManager.getSessionId();
3047
+ const environment = runtimeEnvironment();
3048
+ const controller = new AbortController();
3049
+ try {
3050
+ const manager = activeManager();
3051
+ if (!("kind" in manager)) throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID");
3052
+ const profilePath = resolveTunnelProfilePath({ env: process.env });
3053
+ const current = (): void => {
3054
+ if (ctx.sessionManager.getSessionId() !== sessionId || runtimeEnvironment() !== environment || resolveTunnelProfilePath({ env: process.env }) !== profilePath) throw new CeHostRefusal("CE_HOST_MAPPING_INVALID");
3055
+ };
3056
+ const onboarding = await prepareSessionOnboarding(ctx, { profilePath, manager, signal: controller.signal });
3057
+ current();
3058
+ if (onboarding === "cancelled") { notify(ctx, "ce-session: bind cancelled; no transport action"); return; }
3059
+ const selected = isLivePolicy(multiPolicy) ? readLivePolicy(multiPolicy.ref) : readSelectedMultiSessionPolicy(profilePath);
3060
+ const projected = isLivePolicy(selected) ? projectLivePiRegistration(selected, sessionId) : projectPiRegistration(selected, sessionId);
3061
+ if (onboarding === "registered" || !isDeepStrictEqual(projected, allowlist)) {
3062
+ if (typeof ctx.reload !== "function") {
3063
+ notify(ctx, "ce-session: registration saved; reload Pi explicitly, then run /ce session bind again to activate. Tunnel was not started.", "warning"); return;
3064
+ }
3065
+ notify(ctx, "ce-session: registration saved; reloading Pi policy. Run /ce session bind again after reload to activate. Tunnel is unchanged.");
3066
+ await ctx.reload();
3067
+ return;
3068
+ }
3069
+ await runMessagingActivation(ctx);
3070
+ } catch (error) {
3071
+ const code = error instanceof CeHostRefusal || error instanceof TunnelRefusal ? error.code
3072
+ : error instanceof SessionOnboardingRefusal ? "CE_TUNNEL_PROFILE_INVALID" : "CE_HOST_UNAVAILABLE";
3073
+ notify(ctx, `ce-session: bind refused ${code}; no transport action or Owner takeover`, "warning");
3074
+ }
3075
+ };
3076
+
3025
3077
  let hooksDialogOpen = false;
3026
3078
  const runHooksCommand = async (ctx: ExtensionContextView, signal?: AbortSignal): Promise<void> => {
3027
3079
  if (ctx.mode !== "tui" || !ctx.hasUI) {
@@ -3273,15 +3325,16 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
3273
3325
  `authorize = synthetic Keychain fixture only with CE_TUNNEL_OFFLINE_TEST=1; ` +
3274
3326
  `connect = restore this registered Pi session, explicitly authorize persistent background startup if needed, then activate/start or measure selected transport; no shell variable required after grant. ` +
3275
3327
  `permission status|grant|revoke = inspect/confirm/revoke profile-scoped background startup permission; revoke overrides inherited env1 and does not stop an already running client. ` +
3276
- `disconnect = confirm release of this Pi binding and Stop of the selected shared tunnel (other sessions may lose transport); registration/history stay. ` +
3328
+ `live connect may bind/resume this Pi Session and reuse an already running shared Tunnel; legacy connect may start the selected transport after authorization. ` +
3329
+ `live disconnect releases only this Pi Session and retains the shared Tunnel, registration and history; legacy disconnect may stop the selected shared Tunnel. ` +
3277
3330
  `start/stop = with CE_TUNNEL_OFFLINE_TEST=1 the bundled OFFLINE simulator; otherwise the REAL background client ` +
3278
3331
  `(detached, survives this session; ownership record + process-identity verified; manual only — no autostart/reconnect); ` +
3279
3332
  `migrate = repair a saved real profile in place (drop the rejected admin_ui keys + repoint the mcp node); ` +
3280
3333
  `deactivate = confirm normal release of this current Pi binding only, preserving registration/history and transport; explicitly activate afterward. ` +
3281
3334
  `doctor = read-only independent host/MCP child qualification and client metadata admission; no client execution, configuration/Store writes or transport operations. ` +
3282
3335
  `status = separate CE segment plus the measured tunnel state (real background or offline simulator). ` +
3283
- `sessions = exact selected active Endpoints, not loaded MCP evidence; liveSessions = own Endpoint only; register <endpoint> [--payload-read] [--ack] = current real Session only; revoke <endpoint> = exact stable registration; migrate-live = separate STOPPED confirmation, then explicit reload; convert = separate explicit legacy conversion with old-runtime acknowledgement. ` +
3284
- `Registration requires verified STOPPED transport and confirmations; never stops/starts it. Reload Pi explicitly; Stop then Start separately loads MCP grants. Shared ChatGPT inbox is not conversation isolation. ` +
3336
+ `sessions = exact selected active Endpoints, not loaded MCP evidence; liveSessions = own Endpoint only; live register publishes current-Session policy without starting or stopping Tunnel; legacy register requires verified STOPPED transport; revoke <endpoint> = exact stable registration; migrate-live = separate STOPPED confirmation, then explicit reload; convert = separate explicit legacy conversion with old-runtime acknowledgement. ` +
3337
+ `Registration requires confirmation and never proves a loaded runtime. Reload Pi explicitly; Stop then Start separately loads legacy MCP grants. Shared ChatGPT inbox is not conversation isolation. ` +
3285
3338
  `Transport only: never delivery, ACK, reconciliation or completion evidence. ` +
3286
3339
  `The client reads its key file via the profile's file: reference; lifecycle/status never read existing key contents. Configured != Connected.`,
3287
3340
  );
@@ -3455,10 +3508,117 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
3455
3508
  // pasted secret. Fixed text only.
3456
3509
  notify(ctx, `ce-tunnel: unknown subcommand; try: ${SUBCOMMANDS.map((s) => s.value).join(", ")}`, "warning");
3457
3510
  };
3511
+ const currentInboundIdentity = (ctx: ExtensionContextView) => {
3512
+ const endpointId = guardedEndpoint(ctx);
3513
+ const status = withHost("status", () => getHost().status(endpointId));
3514
+ if (!status.exchangeId || status.lease !== "ACTIVE") throw new CeHostRefusal("CE_HOST_AUTHORITY_ABSENT");
3515
+ return { runtimeSessionId: ctx.sessionManager.getSessionId(), endpointId, exchangeId: status.exchangeId };
3516
+ };
3517
+ const auditHighWater = (endpointId: string): number => {
3518
+ let cursor = 0;
3519
+ for (let page = 0; page < 10_000; page += 1) {
3520
+ const result = withHost("inbox", () => getHost().listInbox(endpointId, { afterAuditSequence: cursor, pageSize: 20, rawScanLimit: 2000 }));
3521
+ const next = result.continuationAuditSequence;
3522
+ if (next === null) return cursor;
3523
+ if (!Number.isSafeInteger(next) || next <= cursor) throw new CeHostRefusal("CE_HOST_UNAVAILABLE");
3524
+ cursor = next;
3525
+ }
3526
+ throw new CeHostRefusal("CE_HOST_UNAVAILABLE");
3527
+ };
3528
+ const runInboundCommand = async (args: string, ctx: ExtensionContextView): Promise<void> => {
3529
+ const tokens = args.trim().split(/\s+/).filter(Boolean);
3530
+ const action = tokens[0] ?? "status";
3531
+ let identity;
3532
+ try { identity = currentInboundIdentity(ctx); }
3533
+ catch { notify(ctx, "ce-inbound: status UNKNOWN (current Session authority unavailable)", "warning"); return; }
3534
+ const path = nativeInboundPolicyPath(resolveTunnelProfilePath({ env: process.env }), identity.runtimeSessionId);
3535
+ if (action === "status" && tokens.length === 1) {
3536
+ const observed = inspectNativeInboundPolicy(path, identity, Date.now());
3537
+ notify(ctx, `ce-inbound: inbound=${observed.status} session=${identity.runtimeSessionId} endpoint=${identity.endpointId} exchange=${identity.exchangeId}`,
3538
+ observed.status === "invalid" ? "warning" : "info");
3539
+ return;
3540
+ }
3541
+ if (ctx.mode !== "tui" || !ctx.hasUI || typeof ctx.ui.confirm !== "function") {
3542
+ notify(ctx, "ce-inbound: change refused CE_TUNNEL_INPUT_UNAVAILABLE", "warning"); return;
3543
+ }
3544
+ const profilePath = resolveTunnelProfilePath({ env: process.env });
3545
+ const environment = runtimeEnvironment();
3546
+ if (action === "enable") {
3547
+ if (tokens.length !== 3 || tokens[1] !== "--from" || !tokens[2]) {
3548
+ notify(ctx, "ce-inbound: usage: /ce inbound enable --from <sender>", "warning"); return;
3549
+ }
3550
+ const from = tokens[2];
3551
+ const boundary = auditHighWater(identity.endpointId);
3552
+ const accepted = await ctx.ui.confirm("Enable CE native inbound for this Session?",
3553
+ `Sender: ${from}\nSession: ${identity.runtimeSessionId}\nEndpoint: ${identity.endpointId}\nExchange: ${identity.exchangeId}\nOnly messages created after audit #${boundary} and activation time may wake this Pi Session. No history is replayed; Tunnel/MCP are unchanged.`);
3554
+ if (!accepted) return;
3555
+ const current = currentInboundIdentity(ctx);
3556
+ if (!isDeepStrictEqual(current, identity) || runtimeEnvironment() !== environment || resolveTunnelProfilePath({ env: process.env }) !== profilePath || auditHighWater(identity.endpointId) !== boundary) {
3557
+ notify(ctx, "ce-inbound: enable refused CE_HOST_MAPPING_INVALID; authority or audit boundary changed", "warning"); return;
3558
+ }
3559
+ enableNativeInboundPolicy({ path, identity, from, afterAuditSequence: boundary, now: Date.now() });
3560
+ notify(ctx, "ce-inbound: enabled policy saved for this Session; reload Pi explicitly to start intake. Tunnel and MCP were not restarted.");
3561
+ return;
3562
+ }
3563
+ if (action === "disable" && tokens.length === 1) {
3564
+ const observed = inspectNativeInboundPolicy(path, identity, Date.now());
3565
+ if (observed.status !== "enabled") { notify(ctx, `ce-inbound: disable refused; current policy is ${observed.status}`, "warning"); return; }
3566
+ const accepted = await ctx.ui.confirm("Disable CE native inbound for this Session?", "This stops new intake after explicit Pi reload. It does not delete history, release Owner, ACK messages, or stop Tunnel/MCP.");
3567
+ if (!accepted) return;
3568
+ if (!isDeepStrictEqual(currentInboundIdentity(ctx), identity) || runtimeEnvironment() !== environment || resolveTunnelProfilePath({ env: process.env }) !== profilePath) {
3569
+ notify(ctx, "ce-inbound: disable refused CE_HOST_MAPPING_INVALID; authority changed", "warning"); return;
3570
+ }
3571
+ disableNativeInboundPolicy({ path, identity, now: Date.now() });
3572
+ notify(ctx, "ce-inbound: disabled policy saved for this Session; reload Pi explicitly to stop intake. History and Owner are unchanged.");
3573
+ return;
3574
+ }
3575
+ notify(ctx, "ce-inbound: usage: /ce inbound status|enable --from <sender>|disable", "warning");
3576
+ };
3577
+ const CE_ROOTS = ["status", "setup", "session", "inbound", "advanced"] as const;
3578
+ const CE_COMPLETIONS = [
3579
+ "session bind", "session unbind", "session list", "inbound status", "inbound enable --from ", "inbound disable",
3580
+ "advanced transport", "advanced native", "advanced hooks", "advanced bindings", "advanced maintenance",
3581
+ ] as const;
3458
3582
  pi.registerCommand("ce", {
3459
- description: "Open Chat Exchange",
3460
- handler: async (_args, ctx) => {
3583
+ description: "Chat Exchange status, setup, Session, inbound, and advanced management",
3584
+ getArgumentCompletions: (prefix: string) => (prefix.includes(" ") ? CE_COMPLETIONS : CE_ROOTS)
3585
+ .filter(value => value.startsWith(prefix)).map(value => ({ value, label: value })),
3586
+ handler: async (args, ctx) => {
3587
+ const command = args.trim();
3588
+ if (command === "status") { await runCeStatus(ctx); return; }
3589
+ if (command === "setup") { await runTunnelCommand("setup", ctx); return; }
3590
+ if (command === "session bind") { await runSessionBind(ctx); return; }
3591
+ if (command === "session unbind") { await runTunnelCommand("deactivate", ctx); return; }
3592
+ if (command === "session list") { await runTunnelCommand("liveSessions", ctx); return; }
3593
+ if (command === "inbound" || command.startsWith("inbound ")) { await runInboundCommand(command.slice("inbound".length), ctx); return; }
3594
+ if (command === "advanced transport" || command.startsWith("advanced transport ")) { await runTunnelCommand(command.slice("advanced transport".length), ctx); return; }
3595
+ if (command === "advanced native" || command.startsWith("advanced native ")) { await runNativeCommand(command.slice("advanced native".length), ctx); return; }
3596
+ if (command === "advanced hooks") { await runHooksCommand(ctx); return; }
3597
+ if (command === "advanced bindings" || command.startsWith("advanced bindings ")) { await runBindingsCommand(command.slice("advanced bindings".length), ctx); return; }
3598
+ if (command === "advanced maintenance" || command.startsWith("advanced maintenance ")) { await runTunnelCommand(command.slice("advanced maintenance".length) || "help", ctx); return; }
3599
+ if (command !== "") { notify(ctx, "Chat Exchange usage: /ce status|setup|session bind|unbind|list|inbound status|enable|disable|advanced transport|native|hooks|bindings|maintenance", "warning"); return; }
3600
+ await runCeStatus(ctx);
3461
3601
  if (ctx.mode !== "tui" || !ctx.hasUI || typeof ctx.ui.select !== "function") { await runManager(ctx); return; }
3602
+ const menu = ["Send target", "Setup", "Session bind", "Session unbind", "Session list", "Inbound status", "Inbound enable", "Inbound disable", "Transport", "Native", "Hooks", "Bindings", "Maintenance", "Close"];
3603
+ const selectedMenu = await ctx.ui.select("Chat Exchange", menu);
3604
+ if (selectedMenu === undefined || selectedMenu === "Close") return;
3605
+ if (selectedMenu === "Setup") { await runTunnelCommand("setup", ctx); return; }
3606
+ if (selectedMenu === "Session bind") { await runSessionBind(ctx); return; }
3607
+ if (selectedMenu === "Session unbind") { await runTunnelCommand("deactivate", ctx); return; }
3608
+ if (selectedMenu === "Session list") { await runTunnelCommand("liveSessions", ctx); return; }
3609
+ if (selectedMenu === "Inbound status") { await runInboundCommand("status", ctx); return; }
3610
+ if (selectedMenu === "Inbound enable") {
3611
+ if (typeof ctx.ui.input !== "function") { notify(ctx, "ce-inbound: change refused CE_TUNNEL_INPUT_UNAVAILABLE", "warning"); return; }
3612
+ const sender = (await ctx.ui.input("CE inbound sender Endpoint", "chatgpt/main"))?.trim();
3613
+ if (sender === undefined) return;
3614
+ await runInboundCommand(`enable --from ${sender}`, ctx); return;
3615
+ }
3616
+ if (selectedMenu === "Inbound disable") { await runInboundCommand("disable", ctx); return; }
3617
+ if (selectedMenu === "Transport") { await runManager(ctx); return; }
3618
+ if (selectedMenu === "Native") { await runNativeCommand("status", ctx); return; }
3619
+ if (selectedMenu === "Hooks") { await runHooksCommand(ctx); return; }
3620
+ if (selectedMenu === "Bindings") { await runBindingsCommand("status", ctx); return; }
3621
+ if (selectedMenu === "Maintenance") { await runTunnelCommand("help", ctx); return; }
3462
3622
  const loaded = multiPolicy;
3463
3623
  if (loaded === undefined || !isLivePolicy(loaded)) { await runManager(ctx); return; }
3464
3624
  try {
@@ -3496,11 +3656,7 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
3496
3656
  },
3497
3657
  });
3498
3658
  pi.registerCommand("ce-tunnel", {
3499
- description: "Tunnel Manager and real profile setup wizard; manual transport lifecycle only, never delivery/ACK evidence",
3500
- getArgumentCompletions: (prefix: string) =>
3501
- SUBCOMMANDS.filter((sub) => sub.value.startsWith(prefix)).map((sub) => ({
3502
- value: sub.value, label: sub.value, description: sub.description,
3503
- })),
3659
+ description: "Compatibility command; use /ce advanced transport",
3504
3660
  handler: runTunnelCommand,
3505
3661
  });
3506
3662
  }
@@ -0,0 +1,138 @@
1
+ import fs from "node:fs";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { basename, dirname, join } from "node:path";
4
+ import type { NativeInboundPolicy } from "./native-inbound.js";
5
+
6
+ export interface NativeInboundIdentity {
7
+ readonly runtimeSessionId: string;
8
+ readonly endpointId: string;
9
+ readonly exchangeId: string;
10
+ }
11
+ type NativeInboundReadIdentity = Omit<NativeInboundIdentity, "exchangeId"> & { readonly exchangeId?: string };
12
+
13
+ export type NativeInboundPolicyInspection =
14
+ | { readonly status: "missing" }
15
+ | { readonly status: "enabled" | "disabled"; readonly policy: NativeInboundPolicy; readonly revision: string }
16
+ | { readonly status: "invalid"; readonly code: "INBOUND_POLICY_INVALID" };
17
+
18
+ const sha = (text: string): string => createHash("sha256").update(text).digest("hex");
19
+ const fail = (): never => { throw new Error("INBOUND_POLICY_INVALID"); };
20
+ const time = (text: string): number => typeof text === "string" && /(?:Z|[+-]\d{2}:\d{2})$/.test(text) ? Date.parse(text) : NaN;
21
+ const stamp = (stat: fs.BigIntStats): string => sha([stat.dev, stat.ino, stat.mtimeNs, stat.ctimeNs, stat.size].join(":"));
22
+
23
+ export function nativeInboundPolicyPath(profilePath: string, runtimeSessionId: string): string {
24
+ if (!profilePath.startsWith("/") || !runtimeSessionId) fail();
25
+ return join(profilePath + ".native-inbound", `${sha(runtimeSessionId)}.json`);
26
+ }
27
+
28
+ export function readNativeInboundPolicy(
29
+ path: string,
30
+ identity: NativeInboundReadIdentity,
31
+ now: number,
32
+ ): { readonly policy: NativeInboundPolicy; readonly revision: string } | undefined {
33
+ const uid = typeof process.getuid === "function" ? process.getuid() : fail();
34
+ if (!Number.isFinite(now)) fail();
35
+ let raw: string | undefined;
36
+ let revision: string;
37
+ try {
38
+ const fd = fs.openSync(path, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
39
+ try {
40
+ const stat = fs.fstatSync(fd, { bigint: true });
41
+ if (!stat.isFile() || stat.uid !== BigInt(uid) || (stat.mode & 0o077n) !== 0n || stat.nlink !== 1n || stat.size > 4096n) fail();
42
+ revision = stamp(stat);
43
+ raw = fs.readFileSync(fd, "utf8");
44
+ if (stamp(fs.fstatSync(fd, { bigint: true })) !== revision) fail();
45
+ } finally { fs.closeSync(fd); }
46
+ } catch (error) {
47
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
48
+ fail();
49
+ }
50
+ let value: unknown;
51
+ try { value = JSON.parse(raw!); } catch { fail(); }
52
+ if (!value || typeof value !== "object" || Array.isArray(value)) fail();
53
+ const policy = value as Record<string, unknown>;
54
+ const keys = ["version", "enabled", "runtimeSessionId", "endpointId", "exchangeId", "from", "activatedAt", "afterAuditSequence", "maxAgeSeconds"];
55
+ if (Object.keys(policy).sort().join() !== keys.sort().join() || policy.version !== 1 || typeof policy.enabled !== "boolean" ||
56
+ policy.runtimeSessionId !== identity.runtimeSessionId || policy.endpointId !== identity.endpointId ||
57
+ (identity.exchangeId !== undefined && policy.exchangeId !== identity.exchangeId) || typeof policy.exchangeId !== "string" || policy.exchangeId.length === 0 ||
58
+ typeof policy.from !== "string" || policy.from.length === 0 || typeof policy.activatedAt !== "string" ||
59
+ !Number.isSafeInteger(policy.afterAuditSequence) || (policy.afterAuditSequence as number) < 0 ||
60
+ !Number.isSafeInteger(policy.maxAgeSeconds) || (policy.maxAgeSeconds as number) < 1 || (policy.maxAgeSeconds as number) > 300 ||
61
+ !Number.isFinite(time(policy.activatedAt)) || time(policy.activatedAt) > now) fail();
62
+ return { policy: policy as unknown as NativeInboundPolicy, revision: revision! };
63
+ }
64
+
65
+ export function inspectNativeInboundPolicy(path: string, identity: NativeInboundReadIdentity, now: number): NativeInboundPolicyInspection {
66
+ try {
67
+ const observed = readNativeInboundPolicy(path, identity, now);
68
+ if (!observed) return { status: "missing" };
69
+ return { status: observed.policy.enabled ? "enabled" : "disabled", ...observed };
70
+ } catch {
71
+ return { status: "invalid", code: "INBOUND_POLICY_INVALID" };
72
+ }
73
+ }
74
+
75
+ function ensureDirectory(path: string): void {
76
+ const directory = dirname(path);
77
+ try { fs.mkdirSync(directory, { mode: 0o700 }); } catch (error) {
78
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") fail();
79
+ }
80
+ const stat = fs.lstatSync(directory, { bigint: true });
81
+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== BigInt(process.getuid!()) || (stat.mode & 0o077n) !== 0n) fail();
82
+ fs.chmodSync(directory, 0o700);
83
+ }
84
+
85
+ function writePolicy(path: string, policy: NativeInboundPolicy, now: number): NativeInboundPolicy {
86
+ ensureDirectory(path);
87
+ // Replacement is permitted only for a policy that already passes the same
88
+ // ownership, link, mode, shape and current-Session identity checks. A bad
89
+ // target is evidence to stop, not something activation may erase.
90
+ try {
91
+ fs.lstatSync(path);
92
+ if (!readNativeInboundPolicy(path, policy, now)) fail();
93
+ } catch (error) {
94
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") fail();
95
+ }
96
+ const directory = dirname(path);
97
+ const temporary = join(directory, `.${basename(path)}.${randomUUID()}.tmp`);
98
+ let fd: number | undefined;
99
+ try {
100
+ fd = fs.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
101
+ fs.writeFileSync(fd, `${JSON.stringify(policy, null, 2)}\n`, "utf8");
102
+ fs.fsyncSync(fd); fs.closeSync(fd); fd = undefined;
103
+ fs.renameSync(temporary, path);
104
+ const directoryFd = fs.openSync(directory, fs.constants.O_RDONLY | fs.constants.O_DIRECTORY);
105
+ try { fs.fsyncSync(directoryFd); } finally { fs.closeSync(directoryFd); }
106
+ } catch {
107
+ if (fd !== undefined) fs.closeSync(fd);
108
+ try { fs.unlinkSync(temporary); } catch { /* nothing durable to clean */ }
109
+ fail();
110
+ }
111
+ const verified = readNativeInboundPolicy(path, policy, now);
112
+ if (!verified || JSON.stringify(verified.policy) !== JSON.stringify(policy)) return fail();
113
+ return verified.policy;
114
+ }
115
+
116
+ export function enableNativeInboundPolicy(input: {
117
+ readonly path: string;
118
+ readonly identity: NativeInboundIdentity;
119
+ readonly from: string;
120
+ readonly afterAuditSequence: number;
121
+ readonly now: number;
122
+ }): NativeInboundPolicy {
123
+ if (!input.from || !Number.isSafeInteger(input.afterAuditSequence) || input.afterAuditSequence < 0 || !Number.isFinite(input.now)) fail();
124
+ return writePolicy(input.path, {
125
+ version: 1, enabled: true, ...input.identity, from: input.from,
126
+ activatedAt: new Date(input.now).toISOString(), afterAuditSequence: input.afterAuditSequence, maxAgeSeconds: 300,
127
+ }, input.now);
128
+ }
129
+
130
+ export function disableNativeInboundPolicy(input: {
131
+ readonly path: string;
132
+ readonly identity: NativeInboundIdentity;
133
+ readonly now: number;
134
+ }): NativeInboundPolicy {
135
+ const current = readNativeInboundPolicy(input.path, input.identity, input.now);
136
+ if (!current) return fail();
137
+ return writePolicy(input.path, { ...current.policy, enabled: false }, input.now);
138
+ }
@@ -1,8 +1,8 @@
1
- import fs from "node:fs";
2
1
  import { createHash } from "node:crypto";
3
2
  import type { CeReadResult } from "../dist/endpoints/pi/session-host.js";
4
3
  import type { ExtensionToolContext } from "@earendil-works/pi-coding-agent";
5
4
  import { validateFeedbackClassification, validateFeedbackTerminal, type FeedbackAssociation, type OwnershipFeedbackPort } from "./ownership-feedback.js";
5
+ import { readNativeInboundPolicy } from "./native-inbound-policy.js";
6
6
 
7
7
  type Metadata = Omit<CeReadResult, "state">;
8
8
  type Entries = ReadonlyArray<Record<string, unknown>>;
@@ -38,38 +38,6 @@ const metadataKeys = ["messageId", "exchangeId", "from", "to", "payloadDigest",
38
38
  const sha = (text: string) => createHash("sha256").update(text).digest("hex");
39
39
  const time = (text: string) => typeof text === "string" && /(?:Z|[+-]\d{2}:\d{2})$/.test(text) ? Date.parse(text) : NaN;
40
40
  function failure(code: string): never { throw new Error(code); }
41
-
42
- function readPolicy(file: string, session: string, endpoint: string, now: number): { policy: NativeInboundPolicy; revision: string } | undefined {
43
- let raw: string | undefined;
44
- let revision: string | undefined;
45
- const stamp = (s: fs.BigIntStats): string => sha([s.dev, s.ino, s.mtimeNs, s.ctimeNs, s.size].join(":"));
46
- try {
47
- const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
48
- try {
49
- const stat = fs.fstatSync(fd, { bigint: true });
50
- if (!stat.isFile() || stat.uid !== BigInt(process.getuid!()) || (stat.mode & 0o077n) !== 0n || stat.nlink !== 1n || stat.size > 4096n) failure("INBOUND_POLICY_INVALID");
51
- revision = stamp(stat);
52
- raw = fs.readFileSync(fd, "utf8");
53
- if (stamp(fs.fstatSync(fd, { bigint: true })) !== revision) failure("INBOUND_POLICY_CHANGED");
54
- } finally { fs.closeSync(fd); }
55
- } catch (error) {
56
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
57
- failure("INBOUND_POLICY_INVALID");
58
- }
59
- let value: unknown;
60
- try { value = JSON.parse(raw!); } catch { failure("INBOUND_POLICY_INVALID"); }
61
- if (!value || typeof value !== "object" || Array.isArray(value)) failure("INBOUND_POLICY_INVALID");
62
- const policy = value as Record<string, unknown>;
63
- const keys = ["version", "enabled", "runtimeSessionId", "endpointId", "exchangeId", "from", "activatedAt", "afterAuditSequence", "maxAgeSeconds"];
64
- if (Object.keys(policy).sort().join() !== keys.sort().join() || policy.version !== 1 || typeof policy.enabled !== "boolean" ||
65
- policy.runtimeSessionId !== session || policy.endpointId !== endpoint ||
66
- !["exchangeId", "from", "activatedAt"].every(key => typeof policy[key] === "string" && (policy[key] as string).length > 0) ||
67
- !Number.isSafeInteger(policy.afterAuditSequence) || (policy.afterAuditSequence as number) < 0 ||
68
- !Number.isSafeInteger(policy.maxAgeSeconds) || (policy.maxAgeSeconds as number) < 1 || (policy.maxAgeSeconds as number) > 300 ||
69
- !Number.isFinite(time(policy.activatedAt as string)) || time(policy.activatedAt as string) > now) failure("INBOUND_POLICY_INVALID");
70
- // SAFETY: the closed-key and scalar checks above validate every policy field.
71
- return policy.enabled ? { policy: policy as unknown as NativeInboundPolicy, revision: revision! } : undefined;
72
- }
73
41
  function metadata(input: unknown, policy: NativeInboundPolicy, messageId: string, now: number): Metadata | undefined {
74
42
  if (!input || typeof input !== "object" || Array.isArray(input)) return undefined;
75
43
  const value = input as Record<string, unknown>;
@@ -120,8 +88,8 @@ export function createNativeInbound(options: InboundOptions) {
120
88
  if (closed) failure("INBOUND_CLOSED");
121
89
  if (options.getSessionId() !== options.runtimeSessionId) failure("INBOUND_SESSION_CHANGED");
122
90
  if (typeof process.getuid !== "function") failure("INBOUND_POLICY_INVALID");
123
- const observed = readPolicy(options.policyPath, options.runtimeSessionId, options.endpointId, options.now());
124
- if (!observed) { if (expectedDigest) failure("INBOUND_DISABLED"); return undefined; }
91
+ const observed = readNativeInboundPolicy(options.policyPath, { runtimeSessionId: options.runtimeSessionId, endpointId: options.endpointId }, options.now());
92
+ if (!observed || !observed.policy.enabled) { if (expectedDigest) failure("INBOUND_DISABLED"); return undefined; }
125
93
  const policy = observed.policy;
126
94
  const policyDigest = sha(JSON.stringify(policy));
127
95
  if (expectedDigest !== undefined && policyDigest !== expectedDigest) failure("INBOUND_POLICY_CHANGED");