@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
|
@@ -168,6 +168,8 @@ import { TunnelRefusal } from "./codes.js";
|
|
|
168
168
|
import { TUNNEL_ID_PATTERN } from "./tunnel-id.js";
|
|
169
169
|
import { resolveTunnelClient } from "../runtime/executables.js";
|
|
170
170
|
import { resolveWrapperIdentityEvidence } from "../runtime/wrapper-identity.js";
|
|
171
|
+
import { createBackgroundAuthorizationStore } from "./background-authorization.js";
|
|
172
|
+
import { captureBackgroundAuthorizationScope } from "./background-scope.js";
|
|
171
173
|
import { createHealthCompletionRecorder } from "./health.js";
|
|
172
174
|
import { checkKeyFileRequirements, childEnvironment } from "./profile.js";
|
|
173
175
|
import { DEFAULT_TUNNEL_TIMING, initialTunnelState, nextTunnelState, } from "./state.js";
|
|
@@ -564,9 +566,12 @@ function mapStateName(name) {
|
|
|
564
566
|
/** Single path-selection authority for manager, setup and configuration status.
|
|
565
567
|
* Reject control bytes before a path can reach any visible TUI/status surface. */
|
|
566
568
|
export function resolveTunnelProfilePath(options) {
|
|
569
|
+
const selection = createBackgroundAuthorizationStore(options.authorizationDirectory === undefined ? {} : { directory: options.authorizationDirectory }).readSelection();
|
|
570
|
+
if (options.profilePath === undefined && !options.env.CE_TUNNEL_PROFILE && selection.kind === "invalid")
|
|
571
|
+
throw new TunnelRefusal("CE_TUNNEL_BACKGROUND_UNAUTHORIZED", "authorization.selection");
|
|
567
572
|
const path = options.profilePath ??
|
|
568
573
|
(typeof options.env.CE_TUNNEL_PROFILE === "string" && options.env.CE_TUNNEL_PROFILE.length > 0
|
|
569
|
-
? options.env.CE_TUNNEL_PROFILE : defaultProfilePath());
|
|
574
|
+
? options.env.CE_TUNNEL_PROFILE : selection.kind === "valid" ? selection.profilePath : defaultProfilePath());
|
|
570
575
|
if (!isAbsolute(path) || normalize(path) !== path || !/^[\x20\x21\x23-\x5B\x5D-\x7E]+$/.test(path)) {
|
|
571
576
|
throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "profile.path");
|
|
572
577
|
}
|
|
@@ -578,8 +583,13 @@ export function createBackgroundTunnelManager(options) {
|
|
|
578
583
|
const timing = options.timing ?? DEFAULT_BACKGROUND_TUNNEL_TIMING;
|
|
579
584
|
// Constructor overrides remain domain-test dependencies. Operator settings
|
|
580
585
|
// and discovered production executables always cross the trust boundary.
|
|
586
|
+
const selection = options.authorizationDirectory === undefined ? createBackgroundAuthorizationStore().readSelection() : createBackgroundAuthorizationStore({ directory: options.authorizationDirectory }).readSelection();
|
|
581
587
|
const clientPath = options.clientPath ?? (() => {
|
|
582
588
|
try {
|
|
589
|
+
if (env.CE_TUNNEL_CLIENT_PATH !== undefined)
|
|
590
|
+
return resolveTunnelClient({ env });
|
|
591
|
+
if (selection.kind === "valid")
|
|
592
|
+
return resolveTunnelClient({ env: { CE_TUNNEL_CLIENT_PATH: selection.clientPath } });
|
|
583
593
|
return resolveTunnelClient({ env });
|
|
584
594
|
}
|
|
585
595
|
catch {
|
|
@@ -588,6 +598,56 @@ export function createBackgroundTunnelManager(options) {
|
|
|
588
598
|
})();
|
|
589
599
|
const profilePath = resolveTunnelProfilePath(options);
|
|
590
600
|
const stateFilePath = options.stateFilePath ?? `${dirname(profilePath)}/background-state.json`;
|
|
601
|
+
const authorizationStore = createBackgroundAuthorizationStore(options.authorizationDirectory === undefined ? {} : { directory: options.authorizationDirectory });
|
|
602
|
+
const authorizationScope = () => {
|
|
603
|
+
const entry = lstatSync(profilePath);
|
|
604
|
+
if (!entry.isFile() || entry.nlink !== 1)
|
|
605
|
+
throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "profile");
|
|
606
|
+
const profileText = readFileSync(profilePath, "utf8");
|
|
607
|
+
const facts = parseTunnelProfile(profileText);
|
|
608
|
+
checkKeyFileMetadata(facts.keyFile);
|
|
609
|
+
return captureBackgroundAuthorizationScope({ profilePath, profileText, credentialPath: facts.keyFile, mcpCommand: facts.mcpCommand, clientPath });
|
|
610
|
+
};
|
|
611
|
+
const authorizationStatus = () => {
|
|
612
|
+
const selected = authorizationStore.readSelection();
|
|
613
|
+
if (selected.kind === "invalid")
|
|
614
|
+
return "invalid";
|
|
615
|
+
const record = authorizationStore.inspect(profilePath);
|
|
616
|
+
if (record.kind === "invalid")
|
|
617
|
+
return "invalid";
|
|
618
|
+
if (record.kind === "absent")
|
|
619
|
+
return env[BACKGROUND_OPT_IN] === "1" ? "environment" : "absent";
|
|
620
|
+
if (record.state === "revoked")
|
|
621
|
+
return "revoked";
|
|
622
|
+
return record.scopeDigest === authorizationScope().digest ? "granted" : "changed";
|
|
623
|
+
};
|
|
624
|
+
const assertAuthorization = () => {
|
|
625
|
+
const status = authorizationStatus();
|
|
626
|
+
if (status !== "granted" && status !== "environment")
|
|
627
|
+
throw new TunnelRefusal("CE_TUNNEL_BACKGROUND_UNAUTHORIZED", `authorization.${status}`);
|
|
628
|
+
};
|
|
629
|
+
const grantAuthorization = (expectedDigest) => {
|
|
630
|
+
if (authorizationStore.inspect(profilePath).kind === "invalid")
|
|
631
|
+
throw new TunnelRefusal("CE_TUNNEL_BACKGROUND_UNAUTHORIZED", "authorization.invalid");
|
|
632
|
+
const scope = authorizationScope();
|
|
633
|
+
if (scope.digest !== expectedDigest)
|
|
634
|
+
throw new TunnelRefusal("CE_TUNNEL_CONFIG_CONFLICT", "authorization.scope");
|
|
635
|
+
const saved = authorizationStore.write(profilePath, "granted", scope.digest);
|
|
636
|
+
if (saved.durability !== "synced")
|
|
637
|
+
throw new TunnelRefusal("CE_TUNNEL_BACKGROUND_UNAUTHORIZED", "authorization.durability-uncertain");
|
|
638
|
+
if (clientPath === undefined)
|
|
639
|
+
throw new TunnelRefusal("CE_TUNNEL_SPAWN_FAILED");
|
|
640
|
+
const selection = authorizationStore.writeSelection(profilePath, clientPath);
|
|
641
|
+
if (selection.durability !== "synced")
|
|
642
|
+
throw new TunnelRefusal("CE_TUNNEL_BACKGROUND_UNAUTHORIZED", "authorization.selection-uncertain");
|
|
643
|
+
};
|
|
644
|
+
const revokeAuthorization = () => {
|
|
645
|
+
if (authorizationStore.inspect(profilePath).kind === "invalid")
|
|
646
|
+
throw new TunnelRefusal("CE_TUNNEL_BACKGROUND_UNAUTHORIZED", "authorization.invalid");
|
|
647
|
+
const saved = authorizationStore.write(profilePath, "revoked", "0".repeat(64));
|
|
648
|
+
if (saved.durability !== "synced")
|
|
649
|
+
throw new TunnelRefusal("CE_TUNNEL_BACKGROUND_UNAUTHORIZED", "authorization.revocation-uncertain");
|
|
650
|
+
};
|
|
591
651
|
const logPath = `${dirname(stateFilePath)}/background-tunnel.log`;
|
|
592
652
|
const spawnSeam = options.spawn ?? defaultSpawnDaemon(logPath);
|
|
593
653
|
/** Exact command lines this manager's own spawn may show in ps (F2): the
|
|
@@ -1059,7 +1119,7 @@ export function createBackgroundTunnelManager(options) {
|
|
|
1059
1119
|
await sleep(EXIT_POLL_MS);
|
|
1060
1120
|
}
|
|
1061
1121
|
};
|
|
1062
|
-
const refresh = async () => {
|
|
1122
|
+
const refresh = async (observation) => {
|
|
1063
1123
|
reloadRecord();
|
|
1064
1124
|
if (recordCorrupt) {
|
|
1065
1125
|
note = "ownership record unreadable; refusing to guess";
|
|
@@ -1068,6 +1128,10 @@ export function createBackgroundTunnelManager(options) {
|
|
|
1068
1128
|
let current = record;
|
|
1069
1129
|
if (current === undefined || current.state === "stopped")
|
|
1070
1130
|
return status();
|
|
1131
|
+
// Observation must not enter refresh's ledger reconciliation paths.
|
|
1132
|
+
if (observation !== undefined && (current.state !== "running" || current.identityPending === true ||
|
|
1133
|
+
current.termRequestedAt !== undefined))
|
|
1134
|
+
return status();
|
|
1071
1135
|
// C-v2-5: establish the run baseline BEFORE any async measurement so a
|
|
1072
1136
|
// health completion can never predate it.
|
|
1073
1137
|
const baseline = machineStartedAt(current);
|
|
@@ -1079,6 +1143,8 @@ export function createBackgroundTunnelManager(options) {
|
|
|
1079
1143
|
// must never be adopted or signalled).
|
|
1080
1144
|
if (presence.kind === "absent" || (current.identityPending === true && exitedPendingRuns.has(current.runId))) {
|
|
1081
1145
|
observeAbsence(current, runTiming, baseline);
|
|
1146
|
+
if (observation !== undefined)
|
|
1147
|
+
return status();
|
|
1082
1148
|
// R4/C-v2-3: persist ONLY under the lock, re-checking the run inside.
|
|
1083
1149
|
let release;
|
|
1084
1150
|
try {
|
|
@@ -1113,6 +1179,8 @@ export function createBackgroundTunnelManager(options) {
|
|
|
1113
1179
|
note = "process inspection unavailable; ownership retained";
|
|
1114
1180
|
return status();
|
|
1115
1181
|
}
|
|
1182
|
+
if (observation !== undefined && presence.identity.pid !== current.pid)
|
|
1183
|
+
return status();
|
|
1116
1184
|
if (current.identityPending === true) {
|
|
1117
1185
|
// Same re-acquisition rule as terminateOwned (S3-2 + F2: exact membership
|
|
1118
1186
|
// in the evidence-derived spawn-identity set, never substring).
|
|
@@ -1171,18 +1239,39 @@ export function createBackgroundTunnelManager(options) {
|
|
|
1171
1239
|
if (latest.kind !== "ok" || latest.record.runId !== current.runId || latest.record.state === "stopped") {
|
|
1172
1240
|
return status();
|
|
1173
1241
|
}
|
|
1242
|
+
if (observation !== undefined && (latest.record.state !== "running" || latest.record.termRequestedAt !== undefined ||
|
|
1243
|
+
latest.record.pid !== current.pid || latest.record.processStartedKey !== current.processStartedKey ||
|
|
1244
|
+
latest.record.commandIdentity !== current.commandIdentity || latest.record.commandIdentityExec !== current.commandIdentityExec))
|
|
1245
|
+
return status();
|
|
1174
1246
|
state = nextTunnelState(state, {
|
|
1175
1247
|
now: now(), runId: current.runId, managedPid: current.pid, processAlive: true,
|
|
1176
1248
|
userStopped: current.termRequestedAt !== undefined, startedAt: baseline,
|
|
1177
1249
|
exit: undefined, probe, startupLogSeen: false, externalInstance: false,
|
|
1178
1250
|
}, runTiming);
|
|
1251
|
+
observation?.onVerifiedProbe(probe);
|
|
1179
1252
|
return status();
|
|
1180
1253
|
};
|
|
1181
|
-
const
|
|
1254
|
+
const observeLiveTransport = async () => {
|
|
1255
|
+
let health;
|
|
1256
|
+
try {
|
|
1257
|
+
const current = await refresh({ onVerifiedProbe: (probe) => { health = probe; } });
|
|
1258
|
+
// This manager supervises remote `run` only (never dev proxy). Require
|
|
1259
|
+
// explicit current polling evidence; CONNECTED alone does not imply it.
|
|
1260
|
+
if (!disposed && current.state === "CONNECTED" && current.running && health?.connectedEligible === true &&
|
|
1261
|
+
health.controlPlanePollObserved === true && typeof current.runId === "string" && current.runId.trim().length > 0 &&
|
|
1262
|
+
current.pid !== undefined && Number.isSafeInteger(current.pid) && current.pid > 0 &&
|
|
1263
|
+
health.completion?.runId === current.runId && health.completion.managedPid === current.pid) {
|
|
1264
|
+
return { kind: "CONNECTED", runId: current.runId, managedPid: current.pid, identityConfirmed: true };
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
catch { /* Inspection/probe failure exposes no raw diagnostics or identity. */ }
|
|
1268
|
+
return { kind: "UNAVAILABLE" };
|
|
1269
|
+
};
|
|
1270
|
+
const start = (expectedProfileSha256) => {
|
|
1182
1271
|
// R5/C-v2-2: the lifecycle generation is captured AT CALL TIME, so a stop
|
|
1183
1272
|
// submitted before this start executes still invalidates it.
|
|
1184
1273
|
const fenceAtCall = startFence;
|
|
1185
|
-
const op = enqueue(() => startImpl(fenceAtCall));
|
|
1274
|
+
const op = enqueue(() => startImpl(fenceAtCall, undefined, expectedProfileSha256));
|
|
1186
1275
|
activeStart = op;
|
|
1187
1276
|
const settled = op.then((result) => { if (activeStart === op)
|
|
1188
1277
|
activeStart = undefined; return result; }, (error) => { if (activeStart === op)
|
|
@@ -1204,14 +1293,13 @@ export function createBackgroundTunnelManager(options) {
|
|
|
1204
1293
|
activeStart = undefined; rejectAck?.(error); throw error; });
|
|
1205
1294
|
return { ack, settled };
|
|
1206
1295
|
};
|
|
1207
|
-
const startImpl = async (fenceAtCall, onSpawned) => {
|
|
1296
|
+
const startImpl = async (fenceAtCall, onSpawned, expectedProfileSha256) => {
|
|
1208
1297
|
if (fenceAtCall !== startFence)
|
|
1209
1298
|
throw new TunnelRefusal("CE_TUNNEL_READY_TIMEOUT");
|
|
1210
1299
|
if (disposed)
|
|
1211
1300
|
throw new TunnelRefusal("CE_TUNNEL_SPAWN_FAILED");
|
|
1212
|
-
//
|
|
1213
|
-
|
|
1214
|
-
throw new TunnelRefusal("CE_TUNNEL_BACKGROUND_UNAUTHORIZED");
|
|
1301
|
+
// Durable revocation and invalid records override legacy process permission.
|
|
1302
|
+
assertAuthorization();
|
|
1215
1303
|
if (!isAbsolute(profilePath) || normalize(profilePath) !== profilePath) {
|
|
1216
1304
|
throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "profile");
|
|
1217
1305
|
}
|
|
@@ -1225,6 +1313,8 @@ export function createBackgroundTunnelManager(options) {
|
|
|
1225
1313
|
const facts = parseTunnelProfile(profileText);
|
|
1226
1314
|
checkKeyFileMetadata(facts.keyFile);
|
|
1227
1315
|
const profileSha256 = createHash("sha256").update(profileText, "utf8").digest("hex");
|
|
1316
|
+
if (expectedProfileSha256 !== undefined && expectedProfileSha256 !== profileSha256)
|
|
1317
|
+
throw new TunnelRefusal("CE_TUNNEL_CONFIG_CONFLICT", "profile");
|
|
1228
1318
|
// S6/C4: prove the record location is writable BEFORE spawning.
|
|
1229
1319
|
ensureStateDir(dirname(stateFilePath));
|
|
1230
1320
|
const writabilityProbe = `${stateFilePath}.${randomUUID()}.probe`;
|
|
@@ -1290,6 +1380,9 @@ export function createBackgroundTunnelManager(options) {
|
|
|
1290
1380
|
if (currentProfileText !== profileText)
|
|
1291
1381
|
throw new TunnelRefusal("CE_TUNNEL_CONFIG_CONFLICT", "profile");
|
|
1292
1382
|
checkKeyFileMetadata(facts.keyFile);
|
|
1383
|
+
// Admission uses this final grant snapshot. A concurrent revoke cannot
|
|
1384
|
+
// retract an admitted start; Stop is the explicit process cleanup barrier.
|
|
1385
|
+
assertAuthorization();
|
|
1293
1386
|
if (clientPath === undefined)
|
|
1294
1387
|
throw new TunnelRefusal("CE_TUNNEL_SPAWN_FAILED", "client");
|
|
1295
1388
|
const runId = `bg-${randomUUID()}`;
|
|
@@ -1619,6 +1712,8 @@ export function createBackgroundTunnelManager(options) {
|
|
|
1619
1712
|
};
|
|
1620
1713
|
return {
|
|
1621
1714
|
kind: "real-background",
|
|
1715
|
+
profilePath: () => profilePath,
|
|
1716
|
+
authorizationScope, authorizationStatus, grantAuthorization, revokeAuthorization,
|
|
1622
1717
|
start,
|
|
1623
1718
|
startDeferred,
|
|
1624
1719
|
withProfileConfigurationLock: (operation) => enqueue(async () => {
|
|
@@ -1653,6 +1748,7 @@ export function createBackgroundTunnelManager(options) {
|
|
|
1653
1748
|
}),
|
|
1654
1749
|
stop,
|
|
1655
1750
|
refresh,
|
|
1751
|
+
observeLiveTransport,
|
|
1656
1752
|
status,
|
|
1657
1753
|
runId: () => (record !== undefined && record.state !== "stopped" ? record.runId : undefined),
|
|
1658
1754
|
async dispose() {
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync } from "node:fs";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { admitExecutable, qualifyNodeExecutable } from "../runtime/executables.js";
|
|
5
|
+
import { resolveWrapperIdentityEvidence } from "../runtime/wrapper-identity.js";
|
|
6
|
+
import { parseMcpBindingConfig } from "../host/mcp-binding-config.js";
|
|
7
|
+
import { parseTunnelMcpCommand } from "./profile.js";
|
|
8
|
+
import { TunnelRefusal } from "./codes.js";
|
|
9
|
+
const sha = (text) => createHash("sha256").update(text).digest("hex");
|
|
10
|
+
const identity = (stat) => [stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.mode, stat.uid];
|
|
11
|
+
function safeDocument(path, key) {
|
|
12
|
+
let fd;
|
|
13
|
+
try {
|
|
14
|
+
fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
15
|
+
const stat = fstatSync(fd);
|
|
16
|
+
// Exclude credential aliases before reading even a single byte.
|
|
17
|
+
if (!stat.isFile() || (stat.uid !== process.geteuid?.() && stat.uid !== 0) ||
|
|
18
|
+
(stat.mode & 0o022) !== 0 || stat.size > 1_048_576 || (stat.dev === key.dev && stat.ino === key.ino))
|
|
19
|
+
throw new Error("unsafe");
|
|
20
|
+
const text = readFileSync(fd, "utf8");
|
|
21
|
+
if (Buffer.byteLength(text) > 1_048_576)
|
|
22
|
+
throw new Error("oversized");
|
|
23
|
+
return text;
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "authorization.scope");
|
|
27
|
+
}
|
|
28
|
+
finally {
|
|
29
|
+
if (fd !== undefined)
|
|
30
|
+
closeSync(fd);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/** Exact launch scope, never credential contents or messaging authority. The caller
|
|
34
|
+
* admits the selected client; grant validation rechecks these file identities before spawn. */
|
|
35
|
+
export function captureBackgroundAuthorizationScope(input) {
|
|
36
|
+
try {
|
|
37
|
+
if (input.clientPath === undefined || input.mcpCommand === undefined)
|
|
38
|
+
throw new Error("missing");
|
|
39
|
+
const key = lstatSync(input.credentialPath);
|
|
40
|
+
if (safeDocument(input.profilePath, key) !== input.profileText)
|
|
41
|
+
throw new Error("drift");
|
|
42
|
+
const client = lstatSync(input.clientPath);
|
|
43
|
+
if (!client.isFile() || (client.uid !== process.geteuid?.() && client.uid !== 0) || (client.mode & 0o022) !== 0)
|
|
44
|
+
throw new Error("client");
|
|
45
|
+
const wrapper = resolveWrapperIdentityEvidence(input.clientPath);
|
|
46
|
+
const parsed = parseTunnelMcpCommand(input.mcpCommand);
|
|
47
|
+
const scriptPath = fileURLToPath(new URL("../../dist/bin/mcp-stdio.js", import.meta.url));
|
|
48
|
+
// Persistent permission never authorizes an arbitrary script with a familiar basename.
|
|
49
|
+
if (parsed.scriptPath !== scriptPath)
|
|
50
|
+
throw new Error("script");
|
|
51
|
+
admitExecutable(parsed.nodePath);
|
|
52
|
+
qualifyNodeExecutable(parsed.nodePath);
|
|
53
|
+
const binding = safeDocument(parsed.bindingPath, key);
|
|
54
|
+
parseMcpBindingConfig(JSON.parse(binding));
|
|
55
|
+
const profileSha256 = sha(input.profileText);
|
|
56
|
+
const scope = { version: 1, profilePath: input.profilePath, profileSha256,
|
|
57
|
+
credential: [input.credentialPath, ...identity(key)], client: [input.clientPath, ...identity(client)],
|
|
58
|
+
wrapper: wrapper?.execTarget === undefined ? null : [wrapper.execTarget, ...identity(lstatSync(wrapper.execTarget))],
|
|
59
|
+
node: [parsed.nodePath, ...identity(lstatSync(parsed.nodePath))],
|
|
60
|
+
script: [scriptPath, sha(safeDocument(scriptPath, key))], binding: [parsed.bindingPath, sha(binding)] };
|
|
61
|
+
return { digest: sha(JSON.stringify(scope)), profileSha256, clientPath: input.clientPath, credentialPath: input.credentialPath };
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
if (error instanceof TunnelRefusal)
|
|
65
|
+
throw error;
|
|
66
|
+
throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "authorization.scope");
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
//# sourceMappingURL=background-scope.js.map
|
package/dist/tunnel/codes.js
CHANGED
|
@@ -58,7 +58,7 @@ const MESSAGES = Object.freeze({
|
|
|
58
58
|
CE_TUNNEL_CONFIG_CONFLICT: "two configuration sources disagree",
|
|
59
59
|
CE_TUNNEL_KEYCHAIN_AUTH_REQUIRED: "reading the credential needs a one-time macOS keychain authorization for this helper build",
|
|
60
60
|
CE_TUNNEL_KEYCHAIN_USER_CANCELED: "the macOS keychain authorization prompt was dismissed",
|
|
61
|
-
CE_TUNNEL_BACKGROUND_UNAUTHORIZED: "real background
|
|
61
|
+
CE_TUNNEL_BACKGROUND_UNAUTHORIZED: "real background startup permission is absent, revoked, changed, or unsafe; inspect /ce-tunnel permission status",
|
|
62
62
|
CE_TUNNEL_MANAGER_BUSY: "another manager holds this tunnel's ownership lock",
|
|
63
63
|
CE_TUNNEL_STATE_CORRUPT: "the ownership record exists but is unreadable; refusing to guess",
|
|
64
64
|
});
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
/** Native operator dialogs only; no model/MCP grant surface. */
|
|
2
|
+
import { defineMenu, runMenu, sanitizeTerminalText } from "@narumitw/pi-tui-kit";
|
|
3
|
+
import { parseHookRules } from "../hooks/config.js";
|
|
4
|
+
import { replaceHookRule } from "./hooks-management.js";
|
|
5
|
+
const safe = (value) => sanitizeTerminalText(value).replace(/[\x00-\x1f\x7f-\x9f]/g, " ");
|
|
6
|
+
export async function runHooksManagementUi(ctx, options) {
|
|
7
|
+
if (options.signal?.aborted)
|
|
8
|
+
return { status: "cancelled", reason: "superseded" };
|
|
9
|
+
if (ctx.mode !== "tui" || !ctx.hasUI || typeof ctx.ui.custom !== "function")
|
|
10
|
+
return { status: "inspect-only" };
|
|
11
|
+
const controller = new AbortController();
|
|
12
|
+
let cancellationReason = "superseded";
|
|
13
|
+
// Preserve the first cancellation source, including disposal after an abort.
|
|
14
|
+
const abort = (reason) => {
|
|
15
|
+
if (!controller.signal.aborted) {
|
|
16
|
+
cancellationReason = reason;
|
|
17
|
+
controller.abort();
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
const supersede = () => abort("superseded");
|
|
21
|
+
const cancelled = () => ({ status: "cancelled", reason: cancellationReason });
|
|
22
|
+
options.signal?.addEventListener("abort", supersede, { once: true });
|
|
23
|
+
const timer = setTimeout(() => abort("timeout"), 120_000);
|
|
24
|
+
timer.unref?.();
|
|
25
|
+
// Follow the existing native dialogs' disposal/cancellation convention.
|
|
26
|
+
const open = ctx.ui.custom.bind(ctx.ui);
|
|
27
|
+
const menuCtx = { ...ctx, ui: { ...ctx.ui, custom: (factory, customOptions) => open((tui, theme, keybindings, done) => {
|
|
28
|
+
let completed = false;
|
|
29
|
+
let disposed = false;
|
|
30
|
+
const complete = (result) => { if (!completed) {
|
|
31
|
+
completed = true;
|
|
32
|
+
done(result);
|
|
33
|
+
} };
|
|
34
|
+
const produced = factory(tui, theme, keybindings, complete);
|
|
35
|
+
if (typeof produced.then === "function")
|
|
36
|
+
throw new Error("Unsupported component");
|
|
37
|
+
const component = produced;
|
|
38
|
+
const handleInput = component.handleInput?.bind(component);
|
|
39
|
+
const dispose = component.dispose?.bind(component);
|
|
40
|
+
component.handleInput = data => {
|
|
41
|
+
const configured = keybindings;
|
|
42
|
+
if (options.keys.matches(data, options.keys.escape) || options.keys.matches(data, options.keys.ctrlC) || configured.matches?.(data, "tui.select.cancel"))
|
|
43
|
+
abort("user");
|
|
44
|
+
handleInput?.(data);
|
|
45
|
+
};
|
|
46
|
+
component.dispose = () => { if (!disposed) {
|
|
47
|
+
disposed = true;
|
|
48
|
+
dispose?.();
|
|
49
|
+
} if (!completed) {
|
|
50
|
+
supersede();
|
|
51
|
+
complete(undefined);
|
|
52
|
+
} };
|
|
53
|
+
return component;
|
|
54
|
+
}, customOptions) } };
|
|
55
|
+
let direction = "pi";
|
|
56
|
+
let rules = [];
|
|
57
|
+
let selectedRule;
|
|
58
|
+
let editing = false;
|
|
59
|
+
let error = "";
|
|
60
|
+
let candidate;
|
|
61
|
+
let confirmed = false;
|
|
62
|
+
let testConfirmed = false;
|
|
63
|
+
const to = (screen) => ({ kind: "to", screen });
|
|
64
|
+
const close = { kind: "close" };
|
|
65
|
+
try {
|
|
66
|
+
let selected;
|
|
67
|
+
try {
|
|
68
|
+
selected = options.management?.inspect();
|
|
69
|
+
}
|
|
70
|
+
catch { /* A committed upgrade may intentionally invalidate the old v1 selection. */ }
|
|
71
|
+
const v2 = selected?.snapshot.ref.kind === "ce-live-session-v2";
|
|
72
|
+
const cancel = { id: "cancel", label: "Cancel", action: "cancel" };
|
|
73
|
+
const screens = {
|
|
74
|
+
main: () => ({ kind: "actions", title: "Hooks · native configuration", hint: "close", lines: [
|
|
75
|
+
"Configured != adopted != eligible != executed.",
|
|
76
|
+
...(selected ? [`Pi → ChatGPT (this session): ${selected.piHooks.length} rules`,
|
|
77
|
+
`ChatGPT → Pi (sender binding): ${selected.mcpHooks.length} rules`, `Policy: ${selected.snapshot.ref.kind}`]
|
|
78
|
+
: options.management ? ["Selected policy unavailable; a committed upgrade may be pending Profile selection.", "Restricted reconciliation only. Supply the exact candidate path and operation from the prior pending report."]
|
|
79
|
+
: ["Live editing unavailable. Inspect the loaded rules for this Pi process."]),
|
|
80
|
+
"Saving requires explicit confirmation. Reload/start remains a separate operator action.",
|
|
81
|
+
...(selected && !v2 ? ["v1 is inspect-only until an explicit offline upgrade. Close existing Pi bindings through their normal lifecycle first."] : []),
|
|
82
|
+
...(error ? [error] : []),
|
|
83
|
+
], items: [
|
|
84
|
+
{ id: "close", label: "Close", close: true },
|
|
85
|
+
...(selected ? [{ id: "pi", label: "Pi → ChatGPT · current native Session", action: "pi" },
|
|
86
|
+
{ id: "mcp", label: "ChatGPT → Pi · MCP sender binding", action: "mcp" },
|
|
87
|
+
{ id: "test", label: "Safe test · fixed benign fixture", action: "openTest" },
|
|
88
|
+
...(!v2 ? [{ id: "upgrade", label: "Explicit offline v1 → v2 upgrade", action: "upgrade" }] : [])] : []),
|
|
89
|
+
...(options.loadedAudit ? [{ id: "loaded", label: "Loaded rules · this Pi process", action: "loaded" }] : []),
|
|
90
|
+
...(options.management ? [{ id: "recovery", label: "Reconcile / continue exact pending publication", action: "recovery" }] : []),
|
|
91
|
+
] }),
|
|
92
|
+
loaded: () => ({ kind: "detail", title: "Loaded Hook rules · this Pi process", hint: "close", lines: [
|
|
93
|
+
`Source: ${safe(options.loadedAudit?.source ?? "unavailable")}`,
|
|
94
|
+
`Configured=${options.loadedAudit?.snapshot.configured ?? 0} eligible=${options.loadedAudit?.snapshot.active ?? 0} executed=unverified`,
|
|
95
|
+
...(options.loadedAudit?.invalid ? ["Configuration invalid; Hooks refused."] : []),
|
|
96
|
+
...(options.loadedAudit?.snapshot.rules.map(rule => safe(`hook ${rule.id} | event=${rule.event} | recipient=${rule.recipient.adapter}/${rule.recipient.endpointId} | command=${rule.command} | args=${JSON.stringify(rule.args)} | timeout=${rule.timeoutMs}ms | ${rule.enabled ? "enabled" : "disabled"}`)) ?? []),
|
|
97
|
+
"Loaded snapshot only. Viewing does not save configuration or execute commands.",
|
|
98
|
+
] }),
|
|
99
|
+
rules: () => ({ kind: "actions", title: direction === "pi" ? "Pi → ChatGPT · current Session" : "ChatGPT → Pi · sender binding", hint: "close", lines: [
|
|
100
|
+
...(direction === "mcp" ? ["Incoming authority is the sender binding; receiving Pi outbound rules do not grant it."] : []),
|
|
101
|
+
...rules.map(rule => safe(JSON.stringify(rule))),
|
|
102
|
+
...(!v2 ? ["Editing refused until explicit offline upgrade."] : []), ...(error ? [error] : []),
|
|
103
|
+
], items: [cancel, ...rules.map(rule => ({ id: `rule:${rule.id}`, label: safe(`${rule.id} · ${rule.enabled ? "enabled" : "disabled"}`), action: "choose" })),
|
|
104
|
+
...(v2 ? [{ id: "add", label: "Add rule", action: "add" }, { id: "review", label: "Review full candidate", action: "review" }] : []),
|
|
105
|
+
] }),
|
|
106
|
+
rule: () => ({ kind: "actions", title: `Hook · ${safe(selectedRule.id)}`, hint: "close", lines: [safe(JSON.stringify(selectedRule))], items: [cancel,
|
|
107
|
+
...(v2 ? [{ id: "edit", label: "Edit rule", action: "edit" }, { id: "toggle", label: selectedRule.enabled ? "Disable rule" : "Enable rule", action: "toggle" }, { id: "remove", label: "Remove rule", action: "remove" }] : []),
|
|
108
|
+
] }),
|
|
109
|
+
input: () => ({ kind: "input", title: editing ? "Edit Hook · JSON rule" : "Add Hook · JSON rule", hint: "close", lines: [
|
|
110
|
+
"Enter one static JSON rule: id, event, recipient, absolute command, args array, timeoutMs, enabled.",
|
|
111
|
+
"No command runs here. Every argument is literal; no shell evaluation.", ...(error ? [error] : []),
|
|
112
|
+
], initialValue: JSON.stringify(editing ? selectedRule : { id: "notify", event: "ce.message.committed.v1", recipient: direction === "pi" ? selected.snapshot.manifest.chatgptEndpoint : { adapter: "pi", endpointId: "pi/REPLACE" }, command: "/absolute/path/to/executable", args: [], timeoutMs: 30000, enabled: false }), action: "input" }),
|
|
113
|
+
recovery: () => ({ kind: "input", title: "Reconcile pending publication · exact evidence", hint: "close", lines: [
|
|
114
|
+
"Enter JSON with exactly bindingPath and operationId from the prior pending report.",
|
|
115
|
+
"This reads evidence only. No scanning, new consent, upgrade replay or transport operation.", ...(error ? [error] : []),
|
|
116
|
+
], initialValue: '{"bindingPath":"/exact/private/messaging-HASH.yaml","operationId":"exact-operation"}', action: "recoveryInput" }),
|
|
117
|
+
review: () => ({ kind: "review", title: candidate?.kind === "continuation" ? "Continue published configuration · exact evidence" : candidate?.kind === "upgrade" ? "Explicit offline upgrade · exact candidate" : "Hooks · full candidate consent", hint: "close", content: [
|
|
118
|
+
"The entire candidate below is the scope of this confirmation.",
|
|
119
|
+
...(candidate?.kind === "continuation" ? ["The operation is already PUBLISHED. Confirmation selects these exact bytes under a verified STOPPED Profile lock; no new chain fact is published."] : []),
|
|
120
|
+
...(candidate?.kind === "upgrade" ? ["Requires verified STOPPED Profile lock. Retains SAME history, tombstones and Pi Hook facts. Initializes empty MCP consent.", "An upgrade marker cannot be rolled back; Profile selection may remain pending after a crash."] : []),
|
|
121
|
+
JSON.stringify(candidate, null, 2).split("\n").map(safe).join("\n"),
|
|
122
|
+
"Configuration only. No reload, transport operation or configured-command execution.",
|
|
123
|
+
].join("\n"), format: { kind: "text" }, confirm: { id: "confirm", label: "Approve and save this exact candidate", action: "confirm" } }),
|
|
124
|
+
safeTest: () => ({ kind: "actions", title: "Safe Hook test", hint: "close", lines: ["Run one fixed benign fixture with fixed argv and empty environment.", "Configured commands and personal scripts are never run. This does not test their behavior."], items: [cancel, { id: "run", label: "Run fixed benign fixture", action: "test" }] }),
|
|
125
|
+
};
|
|
126
|
+
const review = () => {
|
|
127
|
+
try {
|
|
128
|
+
candidate = options.management.preview(direction, rules);
|
|
129
|
+
error = "";
|
|
130
|
+
return to("review");
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
error = "Candidate refused; check rules, native Session and v2 policy selection.";
|
|
134
|
+
return to("rules");
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
const menu = defineMenu({ start: "main", screens, actions: {
|
|
138
|
+
pi: () => { direction = "pi"; rules = selected.piHooks; return to("rules"); },
|
|
139
|
+
mcp: () => { direction = "mcp"; rules = selected.mcpHooks; return to("rules"); },
|
|
140
|
+
choose: ({ itemId }) => { selectedRule = rules.find(rule => `rule:${rule.id}` === itemId); return selectedRule ? to("rule") : to("rules"); },
|
|
141
|
+
add: () => { editing = false; return to("input"); }, edit: () => { editing = true; return to("input"); },
|
|
142
|
+
input: ({ value = "" }) => {
|
|
143
|
+
try {
|
|
144
|
+
const rule = parseHookRules([JSON.parse(value)])[0];
|
|
145
|
+
rules = replaceHookRule(rules, editing ? { kind: "edit", id: selectedRule.id, rule } : { kind: "add", rule });
|
|
146
|
+
return review();
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
error = "Invalid rule JSON; check the closed Hook schema.";
|
|
150
|
+
return to("input");
|
|
151
|
+
}
|
|
152
|
+
},
|
|
153
|
+
toggle: () => { rules = replaceHookRule(rules, { kind: selectedRule.enabled ? "disable" : "enable", id: selectedRule.id }); return review(); },
|
|
154
|
+
remove: () => { rules = replaceHookRule(rules, { kind: "remove", id: selectedRule.id }); return review(); },
|
|
155
|
+
review,
|
|
156
|
+
loaded: () => to("loaded"),
|
|
157
|
+
recovery: () => to("recovery"),
|
|
158
|
+
recoveryInput: ({ value = "" }) => {
|
|
159
|
+
try {
|
|
160
|
+
const input = JSON.parse(value);
|
|
161
|
+
if (!input || typeof input !== "object" || Array.isArray(input) || Reflect.ownKeys(input).length !== 2 || !Object.hasOwn(input, "bindingPath") || !Object.hasOwn(input, "operationId"))
|
|
162
|
+
throw new Error("input");
|
|
163
|
+
const fields = input;
|
|
164
|
+
if (typeof fields.bindingPath !== "string" || typeof fields.operationId !== "string")
|
|
165
|
+
throw new Error("input");
|
|
166
|
+
candidate = options.management.previewContinuation({ bindingPath: fields.bindingPath, operationId: fields.operationId });
|
|
167
|
+
error = "";
|
|
168
|
+
return to("review");
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
candidate = undefined;
|
|
172
|
+
error = "Pending publication refused: check exact evidence, current target scope and native Session.";
|
|
173
|
+
return to("recovery");
|
|
174
|
+
}
|
|
175
|
+
},
|
|
176
|
+
upgrade: () => { try {
|
|
177
|
+
candidate = options.management.previewUpgrade();
|
|
178
|
+
return to("review");
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
error = "Upgrade preview refused; reconcile the selected policy first.";
|
|
182
|
+
return to("main");
|
|
183
|
+
} },
|
|
184
|
+
confirm: () => { if (!controller.signal.aborted && candidate)
|
|
185
|
+
confirmed = true; return close; },
|
|
186
|
+
cancel: () => { abort("user"); return close; },
|
|
187
|
+
openTest: () => to("safeTest"), test: () => { if (!controller.signal.aborted)
|
|
188
|
+
testConfirmed = true; return close; },
|
|
189
|
+
} });
|
|
190
|
+
let menuFailed = false;
|
|
191
|
+
const result = await runMenu(menuCtx, menu, { getState: () => null, signal: controller.signal, onError: () => { menuFailed = true; supersede(); } });
|
|
192
|
+
if (menuFailed || result.kind === "error")
|
|
193
|
+
return { status: "refused", detail: "Hooks configuration publication refused; check configuration and pending publication evidence." };
|
|
194
|
+
if (controller.signal.aborted)
|
|
195
|
+
return cancelled();
|
|
196
|
+
// The native component has released the terminal. Never run a save or test
|
|
197
|
+
// from a preview renderer, navigation action or a disposed/aborted dialog.
|
|
198
|
+
if (confirmed && candidate) {
|
|
199
|
+
options.onProgress?.("Saving and publishing the Hook candidate");
|
|
200
|
+
return { status: "saved", ...await options.management.save(candidate, true, controller.signal) };
|
|
201
|
+
}
|
|
202
|
+
if (testConfirmed) {
|
|
203
|
+
options.onProgress?.("Running the fixed benign fixture");
|
|
204
|
+
try {
|
|
205
|
+
const test = await options.safeTest();
|
|
206
|
+
if (controller.signal.aborted)
|
|
207
|
+
return cancelled();
|
|
208
|
+
return { status: "tested", executed: test.executed, configuredCommandsExecuted: test.configuredCommandsExecuted };
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
return { status: "test-failed", detail: "The fixed benign fixture test did not successfully complete; configured commands and personal scripts were not executed." };
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return { status: "closed" };
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
return { status: "refused", detail: "Hooks configuration publication refused; check configuration and pending publication evidence." };
|
|
218
|
+
}
|
|
219
|
+
finally {
|
|
220
|
+
clearTimeout(timer);
|
|
221
|
+
options.signal?.removeEventListener("abort", supersede);
|
|
222
|
+
supersede();
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
//# sourceMappingURL=hooks-management-ui.js.map
|