@zieglar/pi-chat-exchange 0.3.1 → 0.3.3
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/dist/bin/ce-runtime-binding.js +33 -0
- package/dist/bin/mcp-stdio.js +32 -23
- package/dist/bin/task-owner-composition.js +47 -0
- package/dist/control/mcp/endpoint-discovery.js +45 -5
- package/dist/control/mcp/server.js +23 -4
- package/dist/control/mcp/source-metadata-probe.js +46 -0
- package/dist/control/mcp/task-owner-registry.js +113 -0
- package/dist/control/mcp/task-owner.js +49 -0
- package/dist/runtime/runtime-group.js +10 -0
- package/dist/runtime/source-metadata-probe-opt-in.js +6 -0
- package/dist/tunnel/current-runtime-binding.js +120 -0
- package/dist/tunnel/endpoint-runtime-binding.js +218 -0
- package/dist/tunnel/live-mcp-composition.js +41 -3
- package/dist/tunnel/session-switch-observation.js +218 -0
- package/package.json +1 -1
- package/pi-extension/index.ts +86 -8
- package/pi-extension/native-read-protocol.ts +44 -0
- package/pi-extension/runtime-binding-command.ts +104 -0
package/pi-extension/index.ts
CHANGED
|
@@ -26,6 +26,8 @@
|
|
|
26
26
|
* seam from packages/pi-chat-exchange/dist.
|
|
27
27
|
*/
|
|
28
28
|
import { createNativeInbound, isNativeFeedback, type NativeInboundToolContext } from "./native-inbound.js";
|
|
29
|
+
import { createNativeReadProtocol } from "./native-read-protocol.js";
|
|
30
|
+
import { runRuntimeBindingCommand } from "./runtime-binding-command.js";
|
|
29
31
|
import { createOwnershipFeedbackBridge } from "./ownership-feedback.js";
|
|
30
32
|
import { createCaptureScheduler, createDeliveryGuard, createDesktopTargetBridge, deliverAfterDesktopCapture, type DesktopTargetBridge } from "./desktop-target.js";
|
|
31
33
|
import { runSessionConfiguration } from "./multi-session-commands.js";
|
|
@@ -38,6 +40,8 @@ import { createHooksManagement, runSafeHookFixture } from "../dist/tunnel/hooks-
|
|
|
38
40
|
import { runHooksManagementUi } from "../dist/tunnel/hooks-management-ui.js";
|
|
39
41
|
import { createBackgroundAuthorizationStore } from "../dist/tunnel/background-authorization.js";
|
|
40
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";
|
|
41
45
|
import { readLiveSelectedSessionPolicy, projectLivePiRegistration } from "./live-session-profile.js";
|
|
42
46
|
import { readSelectedMultiSessionPolicy, projectPiRegistration, effectivePiHookRules } from "../dist/tunnel/multi-session-policy.js";
|
|
43
47
|
import { runSetupWizard, presentTunnelStatus } from "../dist/tunnel/setup-ui.js";
|
|
@@ -153,7 +157,7 @@ interface ToolDefinitionView {
|
|
|
153
157
|
interface ExtensionApiView {
|
|
154
158
|
on(
|
|
155
159
|
event: "session_start" | "session_shutdown",
|
|
156
|
-
handler: (event: { reason: string }, ctx: ExtensionContextView) => Promise<void> | void,
|
|
160
|
+
handler: (event: { reason: string; previousSessionFile?: string; targetSessionFile?: string }, ctx: ExtensionContextView) => Promise<void> | void,
|
|
157
161
|
): void;
|
|
158
162
|
on(
|
|
159
163
|
event: "agent_settled",
|
|
@@ -433,8 +437,15 @@ function openHostStore(allowlist: AllowlistFile) {
|
|
|
433
437
|
// recently observed (always simulated in B1.1) client activity.
|
|
434
438
|
const TUNNEL_STATUS_KEYS = ["ce", "ce-tunnel", "ce-client"] as const;
|
|
435
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
|
+
|
|
436
446
|
export default function ceChatExchange(pi: ExtensionApiView): void {
|
|
437
447
|
let operationSequence = 0;
|
|
448
|
+
const activeRuntimeId = process.env.CE_RUNTIME_ID ?? processRuntimeId;
|
|
438
449
|
const operationFeedback = new Map<string, () => void>();
|
|
439
450
|
let clearCommandResult = (): void => {};
|
|
440
451
|
// Feedback has its own lifetime and never controls transport or admission.
|
|
@@ -704,12 +715,42 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
|
|
|
704
715
|
// CE_ALLOWLIST keeps its explicit legacy precedence.
|
|
705
716
|
let multiPolicy: SelectedSessionPolicy | undefined;
|
|
706
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
|
+
};
|
|
707
744
|
let explicitlySelectedProfile = Boolean(process.env.CE_TUNNEL_PROFILE);
|
|
745
|
+
let loadedBindingProfile: string | undefined;
|
|
746
|
+
let loadedBindingProfileText: string | undefined;
|
|
708
747
|
if (!process.env.CE_ALLOWLIST) {
|
|
709
748
|
try {
|
|
710
749
|
explicitlySelectedProfile ||= createBackgroundAuthorizationStore().readSelection().kind === "valid";
|
|
711
750
|
const profilePath = resolveTunnelProfilePath({ env: process.env });
|
|
712
|
-
|
|
751
|
+
const profileText = readFileSync(profilePath, "utf8");
|
|
752
|
+
multiPolicy = readLiveSelectedSessionPolicy(profilePath, profileText);
|
|
753
|
+
if (multiPolicy !== undefined) { loadedBindingProfile = profilePath; loadedBindingProfileText = profileText; }
|
|
713
754
|
if (multiPolicy === undefined) { try { multiPolicy = readSelectedMultiSessionPolicy(profilePath); } catch { /* existing legacy loader validates its own selected pair */ } }
|
|
714
755
|
} catch (error) { selectedPolicyInvalid = (error as NodeJS.ErrnoException).code !== "ENOENT" || explicitlySelectedProfile; }
|
|
715
756
|
}
|
|
@@ -761,6 +802,7 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
|
|
|
761
802
|
failure: CeHostRefusal | undefined;
|
|
762
803
|
};
|
|
763
804
|
let generation: Generation | undefined;
|
|
805
|
+
const nativeReadProtocol = createNativeReadProtocol();
|
|
764
806
|
let nativeInbound: ReturnType<typeof createNativeInbound> | undefined;
|
|
765
807
|
let inboundEnabled = false;
|
|
766
808
|
const closeNativeInbound = (): void => {
|
|
@@ -1287,6 +1329,7 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
|
|
|
1287
1329
|
};
|
|
1288
1330
|
|
|
1289
1331
|
pi.on("session_start", async (event, ctx) => {
|
|
1332
|
+
startCurrentRuntime(ctx);
|
|
1290
1333
|
// The warning is about the Native default path only. An explicit node-sqlite
|
|
1291
1334
|
// compatibility selection keeps messaging available, so it must not be told
|
|
1292
1335
|
// that messaging is disabled.
|
|
@@ -1313,6 +1356,10 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
|
|
|
1313
1356
|
inboxBinding = undefined;
|
|
1314
1357
|
advisoryState = undefined;
|
|
1315
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
|
+
}
|
|
1316
1363
|
if (multiPolicy !== undefined) {
|
|
1317
1364
|
// Project only this trusted runtime, never all manifest registrations.
|
|
1318
1365
|
try { allowlist = (isLivePolicy(multiPolicy) ? projectLivePiRegistration(multiPolicy, piSessionId) : projectPiRegistration(multiPolicy, piSessionId)) as AllowlistFile; }
|
|
@@ -1440,7 +1487,22 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
|
|
|
1440
1487
|
await continueConnect();
|
|
1441
1488
|
});
|
|
1442
1489
|
|
|
1443
|
-
pi.on("session_shutdown", (event) =>
|
|
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
|
+
});
|
|
1444
1506
|
|
|
1445
1507
|
pi.on("agent_settled", (_event, ctx) => {
|
|
1446
1508
|
checkInboxAdvisory(ctx);
|
|
@@ -1532,7 +1594,8 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
|
|
|
1532
1594
|
if (generation === undefined || generation.stopping || generation.failure !== undefined || nativeInbound === undefined) throw Error("INBOUND_DISABLED");
|
|
1533
1595
|
const messageId = (params as { messageId?: unknown }).messageId;
|
|
1534
1596
|
if (typeof messageId !== "string") throw Error("INBOUND_INVALID_MESSAGE_ID");
|
|
1535
|
-
const
|
|
1597
|
+
const receiver = nativeInbound;
|
|
1598
|
+
const task = await nativeReadProtocol.run(_toolCallId, messageId, ctx, protocol => receiver.receive(messageId, protocol));
|
|
1536
1599
|
if (ctx.sessionManager.getSessionId() !== generation.piSessionId || endpointId !== generation.endpointId) throw Error("INBOUND_SESSION_CHANGED");
|
|
1537
1600
|
if (!("text" in task)) {
|
|
1538
1601
|
// Pi extensions.md: terminate suppresses the automatic follow-up when every tool in the batch agrees.
|
|
@@ -1595,7 +1658,7 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
|
|
|
1595
1658
|
try {
|
|
1596
1659
|
const endpointId = guardedEndpoint(ctx);
|
|
1597
1660
|
const result = withHost("metadata", () => getHost().readMetadata(endpointId, params));
|
|
1598
|
-
return {
|
|
1661
|
+
return nativeReadProtocol.capture(_toolCallId, "ce_read", result.messageId, {
|
|
1599
1662
|
content: [
|
|
1600
1663
|
{
|
|
1601
1664
|
type: "text",
|
|
@@ -1606,7 +1669,7 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
|
|
|
1606
1669
|
},
|
|
1607
1670
|
],
|
|
1608
1671
|
details: { ...result },
|
|
1609
|
-
};
|
|
1672
|
+
});
|
|
1610
1673
|
} catch (error) {
|
|
1611
1674
|
return refusalResult(error);
|
|
1612
1675
|
}
|
|
@@ -1708,7 +1771,7 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
|
|
|
1708
1771
|
}
|
|
1709
1772
|
// No await between context validation and the synchronous Host call.
|
|
1710
1773
|
const result = withHost("payload", () => getHost().readPayload(endpointId, { messageId: field.value }));
|
|
1711
|
-
return {
|
|
1774
|
+
return nativeReadProtocol.capture(_toolCallId, "ce_read_payload", result.messageId, {
|
|
1712
1775
|
content: [
|
|
1713
1776
|
{
|
|
1714
1777
|
type: "text",
|
|
@@ -1735,7 +1798,7 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
|
|
|
1735
1798
|
createdAt: result.createdAt,
|
|
1736
1799
|
auditSequence: result.auditSequence,
|
|
1737
1800
|
},
|
|
1738
|
-
};
|
|
1801
|
+
});
|
|
1739
1802
|
} catch (error) {
|
|
1740
1803
|
return refusalResult(error);
|
|
1741
1804
|
}
|
|
@@ -1846,6 +1909,21 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
|
|
|
1846
1909
|
});
|
|
1847
1910
|
|
|
1848
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
|
+
|
|
1849
1927
|
pi.registerCommand("ce-status", {
|
|
1850
1928
|
description: "Show this session's chat-exchange endpoint, ownership lease, and fencing status",
|
|
1851
1929
|
async handler(_args, ctx) {
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { NativeInboundToolContext } from "./native-inbound.js";
|
|
2
|
+
|
|
3
|
+
type ReadName = "ce_read" | "ce_read_payload";
|
|
4
|
+
type ReadResult = { content: Array<{ type: "text"; text: string }>; details: unknown };
|
|
5
|
+
|
|
6
|
+
/** Exact, invocation-local CE protocol data, independent of model-facing presentation.
|
|
7
|
+
* Registered tools and all SDK call/result hooks still run. Refusals are never restored.
|
|
8
|
+
*/
|
|
9
|
+
export function createNativeReadProtocol() {
|
|
10
|
+
const scopes = new Map<string, { messageId: string; results: Map<string, { name: ReadName; result: ReadResult }> }>();
|
|
11
|
+
return {
|
|
12
|
+
capture<T extends ReadResult>(toolCallId: string, name: ReadName, messageId: string, result: T): T {
|
|
13
|
+
// Pi owns nested identities: <parent toolCallId>/<ordinal>. Ordinary model reads
|
|
14
|
+
// have no active native receive scope and must never retain a private payload copy.
|
|
15
|
+
const separator = toolCallId.lastIndexOf("/");
|
|
16
|
+
const scope = scopes.get(toolCallId.slice(0, separator));
|
|
17
|
+
if (separator > 0 && scope?.messageId === messageId && /^[1-9]\d*$/.test(toolCallId.slice(separator + 1))) {
|
|
18
|
+
scope.results.set(toolCallId, { name, result: structuredClone(result) });
|
|
19
|
+
}
|
|
20
|
+
return result;
|
|
21
|
+
},
|
|
22
|
+
async run<T>(parentId: string, messageId: string, ctx: NativeInboundToolContext, receive: (ctx: NativeInboundToolContext) => Promise<T>): Promise<T> {
|
|
23
|
+
if (scopes.has(parentId)) throw Error("INBOUND_PROTOCOL_SCOPE_ACTIVE");
|
|
24
|
+
const scope = { messageId, results: new Map<string, { name: ReadName; result: ReadResult }>() };
|
|
25
|
+
scopes.set(parentId, scope);
|
|
26
|
+
try {
|
|
27
|
+
return await receive({
|
|
28
|
+
executeTool: async (name, args, options) => {
|
|
29
|
+
const outcome = await ctx.executeTool(name, args, options);
|
|
30
|
+
const exact = scope.results.get(outcome.toolCall.id);
|
|
31
|
+
scope.results.delete(outcome.toolCall.id);
|
|
32
|
+
if (outcome.isError || exact?.name !== name) return outcome;
|
|
33
|
+
// Only the native consumer receives the original owned protocol result.
|
|
34
|
+
// ce_receive_task's final response still goes through normal presentation hooks.
|
|
35
|
+
return { ...outcome, result: exact.result };
|
|
36
|
+
},
|
|
37
|
+
});
|
|
38
|
+
} finally {
|
|
39
|
+
scope.results.clear();
|
|
40
|
+
scopes.delete(parentId);
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
}
|
|
@@ -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
|
+
}
|