@zieglar/pi-chat-exchange 0.2.2 → 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 +11 -7
- package/dist/bin/mcp-stdio.js +124 -56
- 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/hooks/config.js +106 -0
- package/dist/hooks/events.js +19 -0
- package/dist/hooks/runner.js +187 -0
- package/dist/host/bound-endpoint.js +19 -6
- package/dist/host/endpoint-host.js +92 -4
- package/dist/host/mcp-binding-config.js +41 -5
- 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/multi-session-policy.js +45 -13
- package/dist/tunnel/setup-ui.js +2 -4
- package/dist/tunnel/status-ui.js +34 -0
- package/package.json +4 -1
- package/pi-extension/allowlist.example.json +12 -1
- package/pi-extension/desktop-target.ts +157 -0
- package/pi-extension/index.ts +1128 -132
- 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
- package/skills/ce-hook-script/SKILL.md +62 -0
- package/skills/ce-hook-script/examples/file-notification.py +79 -0
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import type { CeReadResult } from "../dist/endpoints/pi/session-host.js";
|
|
4
|
+
import type { ExtensionToolContext } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { validateFeedbackClassification, validateFeedbackTerminal, type FeedbackAssociation, type OwnershipFeedbackPort } from "./ownership-feedback.js";
|
|
6
|
+
|
|
7
|
+
type Metadata = Omit<CeReadResult, "state">;
|
|
8
|
+
type Entries = ReadonlyArray<Record<string, unknown>>;
|
|
9
|
+
export interface NativeInboundPolicy {
|
|
10
|
+
readonly version: 1;
|
|
11
|
+
readonly enabled: boolean;
|
|
12
|
+
readonly runtimeSessionId: string;
|
|
13
|
+
readonly endpointId: string;
|
|
14
|
+
readonly exchangeId: string;
|
|
15
|
+
readonly from: string;
|
|
16
|
+
readonly activatedAt: string;
|
|
17
|
+
readonly afterAuditSequence: number;
|
|
18
|
+
readonly maxAgeSeconds: number;
|
|
19
|
+
}
|
|
20
|
+
interface InboundOptions {
|
|
21
|
+
readonly policyPath: string;
|
|
22
|
+
readonly runtimeSessionId: string;
|
|
23
|
+
readonly endpointId: string;
|
|
24
|
+
getSessionId(): string;
|
|
25
|
+
getEntries(): Entries;
|
|
26
|
+
append(customType: string, data: unknown): void;
|
|
27
|
+
listInbox(input: { afterAuditSequence: number; pageSize: number; rawScanLimit: number }): { messages: ReadonlyArray<{ messageId: string; auditSequence: number }>; continuationAuditSequence: number | null; scanBudgetExhausted: boolean };
|
|
28
|
+
readMetadata(input: { messageId: string }): Metadata;
|
|
29
|
+
wake(input: { messageId: string; auditSequence: number; policyDigest: string; policyRevision: string }): void;
|
|
30
|
+
readonly feedback?: OwnershipFeedbackPort | undefined;
|
|
31
|
+
controlWake?(input: { messageId: string; auditSequence: number; policyDigest: string; policyRevision: string }): void;
|
|
32
|
+
now(): number;
|
|
33
|
+
}
|
|
34
|
+
export type NativeInboundToolContext = Pick<ExtensionToolContext, "executeTool">;
|
|
35
|
+
interface Claim { readonly policyDigest: string; readonly messageId: string; readonly auditSequence: number; readonly admittedAt: number; readonly metadata: Metadata; readonly association?: FeedbackAssociation }
|
|
36
|
+
const metadataKeys = ["messageId", "exchangeId", "from", "to", "payloadDigest", "payloadLength", "createdAt", "auditSequence"] as const;
|
|
37
|
+
const sha = (text: string) => createHash("sha256").update(text).digest("hex");
|
|
38
|
+
const time = (text: string) => typeof text === "string" && /(?:Z|[+-]\d{2}:\d{2})$/.test(text) ? Date.parse(text) : NaN;
|
|
39
|
+
function failure(code: string): never { throw new Error(code); }
|
|
40
|
+
|
|
41
|
+
function readPolicy(file: string, session: string, endpoint: string, now: number): { policy: NativeInboundPolicy; revision: string } | undefined {
|
|
42
|
+
let raw: string | undefined;
|
|
43
|
+
let revision: string | undefined;
|
|
44
|
+
const stamp = (s: fs.BigIntStats): string => sha([s.dev, s.ino, s.mtimeNs, s.ctimeNs, s.size].join(":"));
|
|
45
|
+
try {
|
|
46
|
+
const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
|
|
47
|
+
try {
|
|
48
|
+
const stat = fs.fstatSync(fd, { bigint: true });
|
|
49
|
+
if (!stat.isFile() || stat.uid !== BigInt(process.getuid!()) || (stat.mode & 0o077n) !== 0n || stat.nlink !== 1n || stat.size > 4096n) failure("INBOUND_POLICY_INVALID");
|
|
50
|
+
revision = stamp(stat);
|
|
51
|
+
raw = fs.readFileSync(fd, "utf8");
|
|
52
|
+
if (stamp(fs.fstatSync(fd, { bigint: true })) !== revision) failure("INBOUND_POLICY_CHANGED");
|
|
53
|
+
} finally { fs.closeSync(fd); }
|
|
54
|
+
} catch (error) {
|
|
55
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
|
56
|
+
failure("INBOUND_POLICY_INVALID");
|
|
57
|
+
}
|
|
58
|
+
let value: unknown;
|
|
59
|
+
try { value = JSON.parse(raw!); } catch { failure("INBOUND_POLICY_INVALID"); }
|
|
60
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) failure("INBOUND_POLICY_INVALID");
|
|
61
|
+
const policy = value as Record<string, unknown>;
|
|
62
|
+
const keys = ["version", "enabled", "runtimeSessionId", "endpointId", "exchangeId", "from", "activatedAt", "afterAuditSequence", "maxAgeSeconds"];
|
|
63
|
+
if (Object.keys(policy).sort().join() !== keys.sort().join() || policy.version !== 1 || typeof policy.enabled !== "boolean" ||
|
|
64
|
+
policy.runtimeSessionId !== session || policy.endpointId !== endpoint ||
|
|
65
|
+
!["exchangeId", "from", "activatedAt"].every(key => typeof policy[key] === "string" && (policy[key] as string).length > 0) ||
|
|
66
|
+
!Number.isSafeInteger(policy.afterAuditSequence) || (policy.afterAuditSequence as number) < 0 ||
|
|
67
|
+
!Number.isSafeInteger(policy.maxAgeSeconds) || (policy.maxAgeSeconds as number) < 1 || (policy.maxAgeSeconds as number) > 300 ||
|
|
68
|
+
!Number.isFinite(time(policy.activatedAt as string)) || time(policy.activatedAt as string) > now) failure("INBOUND_POLICY_INVALID");
|
|
69
|
+
// SAFETY: the closed-key and scalar checks above validate every policy field.
|
|
70
|
+
return policy.enabled ? { policy: policy as unknown as NativeInboundPolicy, revision: revision! } : undefined;
|
|
71
|
+
}
|
|
72
|
+
function metadata(input: unknown, policy: NativeInboundPolicy, messageId: string, now: number): Metadata | undefined {
|
|
73
|
+
if (!input || typeof input !== "object" || Array.isArray(input)) return undefined;
|
|
74
|
+
const value = input as Record<string, unknown>;
|
|
75
|
+
if (value.messageId !== messageId || value.exchangeId !== policy.exchangeId || value.from !== policy.from || value.to !== policy.endpointId ||
|
|
76
|
+
typeof value.payloadDigest !== "string" || !/^[0-9a-f]{64}$/.test(value.payloadDigest) ||
|
|
77
|
+
!Number.isSafeInteger(value.payloadLength) || (value.payloadLength as number) < 1 || (value.payloadLength as number) > 65_536 ||
|
|
78
|
+
!Number.isSafeInteger(value.auditSequence) || (value.auditSequence as number) <= policy.afterAuditSequence) return undefined;
|
|
79
|
+
const created = time(value.createdAt as string);
|
|
80
|
+
if (!Number.isFinite(created) || created < time(policy.activatedAt) || created > now || now - created > policy.maxAgeSeconds * 1000) return undefined;
|
|
81
|
+
// SAFETY: route, scalar fields and creation time were validated above.
|
|
82
|
+
return Object.fromEntries(metadataKeys.map(key => [key, value[key]])) as unknown as Metadata;
|
|
83
|
+
}
|
|
84
|
+
function historyEntries(entries: Entries): Array<{ customType: string; data: Record<string, unknown> }> {
|
|
85
|
+
if (!Array.isArray(entries)) failure("INBOUND_HISTORY_INVALID");
|
|
86
|
+
const records = entries.filter(entry => entry?.type === "custom" && ["ce-inbound-wake", "ce-inbound-receive", "ce-inbound-feedback", "ce-inbound-feedback-blocked", "ce-inbound-feedback-result"].includes(entry.customType as string));
|
|
87
|
+
if (records.some(entry => !entry.data || typeof entry.data !== "object" || Array.isArray(entry.data))) failure("INBOUND_HISTORY_INVALID");
|
|
88
|
+
return records as Array<{ customType: string; data: Record<string, unknown> }>;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Deny-only history survives revocation or a closed controller. */
|
|
92
|
+
export function isNativeFeedback(entries: Entries, messageId: string): boolean {
|
|
93
|
+
return historyEntries(entries).some(entry => entry.data.messageId === messageId &&
|
|
94
|
+
['ce-inbound-feedback', 'ce-inbound-feedback-blocked', 'ce-inbound-feedback-result'].includes(entry.customType));
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function createNativeInbound(options: InboundOptions) {
|
|
98
|
+
let closed = false;
|
|
99
|
+
let watermark: { policyDigest: string; cursor: number } | undefined;
|
|
100
|
+
const history = () => historyEntries(options.getEntries());
|
|
101
|
+
const claim = (messageId: string) => {
|
|
102
|
+
const candidates = history().filter(entry => (entry.customType === "ce-inbound-wake" || entry.customType === "ce-inbound-feedback") && entry.data?.messageId === messageId);
|
|
103
|
+
if (candidates.length !== 1) failure(candidates.length ? "INBOUND_CLAIM_CONFLICT" : "INBOUND_NOT_CLAIMED");
|
|
104
|
+
const data = candidates[0]!.data;
|
|
105
|
+
if (data.version !== 1 || data.runtimeSessionId !== options.runtimeSessionId || data.endpointId !== options.endpointId ||
|
|
106
|
+
typeof data.policyDigest !== "string" || !Number.isSafeInteger(data.auditSequence) || !Number.isSafeInteger(data.admittedAt) || (data.admittedAt as number) > options.now() || !data.metadata || typeof data.metadata !== "object") failure("INBOUND_CLAIM_INVALID");
|
|
107
|
+
// SAFETY: scalar claim fields are validated here; receive validates correlated metadata before use.
|
|
108
|
+
if (candidates[0]!.customType === "ce-inbound-feedback") {
|
|
109
|
+
const association = validateFeedbackClassification(data.association, messageId);
|
|
110
|
+
if (association.kind !== "FEEDBACK") failure("INBOUND_CLAIM_INVALID");
|
|
111
|
+
// SAFETY: claim scalars above and closed association validation establish the persisted claim shape.
|
|
112
|
+
return { ...(data as unknown as Claim), association };
|
|
113
|
+
}
|
|
114
|
+
if (Object.hasOwn(data, "association")) failure("INBOUND_CLAIM_INVALID");
|
|
115
|
+
// SAFETY: scalar claim fields are validated above; receive validates correlated metadata before use.
|
|
116
|
+
return data as unknown as Claim;
|
|
117
|
+
};
|
|
118
|
+
const authorized = (expectedDigest?: string) => {
|
|
119
|
+
if (closed) failure("INBOUND_CLOSED");
|
|
120
|
+
if (options.getSessionId() !== options.runtimeSessionId) failure("INBOUND_SESSION_CHANGED");
|
|
121
|
+
if (typeof process.getuid !== "function") failure("INBOUND_POLICY_INVALID");
|
|
122
|
+
const observed = readPolicy(options.policyPath, options.runtimeSessionId, options.endpointId, options.now());
|
|
123
|
+
if (!observed) { if (expectedDigest) failure("INBOUND_DISABLED"); return undefined; }
|
|
124
|
+
const policy = observed.policy;
|
|
125
|
+
const policyDigest = sha(JSON.stringify(policy));
|
|
126
|
+
if (expectedDigest !== undefined && policyDigest !== expectedDigest) failure("INBOUND_POLICY_CHANGED");
|
|
127
|
+
return { policy, policyDigest, policyRevision: observed.revision };
|
|
128
|
+
};
|
|
129
|
+
const receiveAttempt = (messageId: string) => history().filter(entry => entry.customType === "ce-inbound-receive" && entry.data?.messageId === messageId);
|
|
130
|
+
return {
|
|
131
|
+
feedbackProtocolVersion: 1 as const,
|
|
132
|
+
close() { closed = true; },
|
|
133
|
+
/** Feedback history is deny-only for desktop preparation, including out-of-order terminal records. */
|
|
134
|
+
canPrepareDesktopReply(messageId: string): boolean {
|
|
135
|
+
authorized() ?? failure("INBOUND_DISABLED");
|
|
136
|
+
return !isNativeFeedback(options.getEntries(), messageId);
|
|
137
|
+
},
|
|
138
|
+
poll() {
|
|
139
|
+
const current = authorized();
|
|
140
|
+
if (!current) return false;
|
|
141
|
+
if (watermark?.policyDigest !== current.policyDigest) watermark = { policyDigest: current.policyDigest, cursor: current.policy.afterAuditSequence };
|
|
142
|
+
const result = options.listInbox({ afterAuditSequence: watermark.cursor, pageSize: 20, rawScanLimit: 200 });
|
|
143
|
+
const records = history();
|
|
144
|
+
for (const candidate of result.messages) {
|
|
145
|
+
if (records.some(entry => entry.data.messageId === candidate.messageId)) continue;
|
|
146
|
+
const admittedAt = options.now();
|
|
147
|
+
const fresh = metadata(options.readMetadata({ messageId: candidate.messageId }), current.policy, candidate.messageId, admittedAt);
|
|
148
|
+
if (!fresh) continue;
|
|
149
|
+
let classification: ReturnType<typeof validateFeedbackClassification> = { kind: "NONE" };
|
|
150
|
+
if (options.feedback) {
|
|
151
|
+
try { classification = validateFeedbackClassification(options.feedback.classify(fresh), candidate.messageId); }
|
|
152
|
+
catch { failure("INBOUND_FEEDBACK_UNAVAILABLE"); }
|
|
153
|
+
}
|
|
154
|
+
// Full append history is deny-only across reloads and branch rollback.
|
|
155
|
+
// This is a wake attempt, not a lock or an exactly-once execution guarantee.
|
|
156
|
+
const data = { version: 1, runtimeSessionId: options.runtimeSessionId, endpointId: options.endpointId,
|
|
157
|
+
policyDigest: current.policyDigest, messageId: candidate.messageId, auditSequence: candidate.auditSequence, admittedAt, metadata: fresh };
|
|
158
|
+
if (classification.kind === "BLOCKED") {
|
|
159
|
+
options.append("ce-inbound-feedback-blocked", { ...data, reason: classification.reason });
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
if (classification.kind === "FEEDBACK") {
|
|
163
|
+
options.append("ce-inbound-feedback", { ...data, association: classification });
|
|
164
|
+
try {
|
|
165
|
+
if (!options.controlWake) failure("INBOUND_FEEDBACK_UNAVAILABLE");
|
|
166
|
+
options.controlWake({ messageId: candidate.messageId, auditSequence: candidate.auditSequence, policyDigest: current.policyDigest, policyRevision: current.policyRevision });
|
|
167
|
+
} catch { failure("INBOUND_FEEDBACK_UNAVAILABLE"); }
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
options.append("ce-inbound-wake", data);
|
|
171
|
+
try { options.wake({ messageId: candidate.messageId, auditSequence: candidate.auditSequence, policyDigest: current.policyDigest, policyRevision: current.policyRevision }); }
|
|
172
|
+
catch { failure("INBOUND_WAKE_UNKNOWN"); }
|
|
173
|
+
}
|
|
174
|
+
watermark.cursor = Math.max(watermark.cursor, result.continuationAuditSequence ?? watermark.cursor);
|
|
175
|
+
return true;
|
|
176
|
+
},
|
|
177
|
+
/** Re-reads the live policy so a deferred delivery can detect revocation. */
|
|
178
|
+
stillAuthorized(policyDigest: string, policyRevision: string): boolean {
|
|
179
|
+
try {
|
|
180
|
+
if (closed) return false;
|
|
181
|
+
if (options.getSessionId() !== options.runtimeSessionId) return false;
|
|
182
|
+
const current = authorized();
|
|
183
|
+
return current !== undefined && current.policyDigest === policyDigest && current.policyRevision === policyRevision;
|
|
184
|
+
} catch {
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
},
|
|
188
|
+
async receive(messageId: string, ctx: NativeInboundToolContext) {
|
|
189
|
+
const current = authorized() ?? failure("INBOUND_DISABLED");
|
|
190
|
+
const records = history();
|
|
191
|
+
if (records.some(entry => entry.data.messageId === messageId && entry.customType === "ce-inbound-feedback-blocked")) failure("INBOUND_FEEDBACK_BLOCKED");
|
|
192
|
+
if (receiveAttempt(messageId).length || records.some(entry => entry.data.messageId === messageId && entry.customType === "ce-inbound-feedback-result")) failure("INBOUND_ALREADY_ATTEMPTED");
|
|
193
|
+
const original = claim(messageId); if (original.policyDigest !== current.policyDigest) failure("INBOUND_POLICY_CHANGED");
|
|
194
|
+
const currentMetadata = metadata(original.metadata, current.policy, messageId, original.admittedAt); if (!currentMetadata) failure("INBOUND_NOT_FRESH");
|
|
195
|
+
// Persist before the first uncertain read. Read refusal and crashes are not retried.
|
|
196
|
+
options.append("ce-inbound-receive", { version: 1, runtimeSessionId: options.runtimeSessionId, endpointId: options.endpointId,
|
|
197
|
+
policyDigest: current.policyDigest, messageId, auditSequence: original.auditSequence, status: "STARTED" });
|
|
198
|
+
let code = "INBOUND_READ_UNKNOWN";
|
|
199
|
+
const settle = () => {
|
|
200
|
+
options.append("ce-inbound-receive", { version: 1, runtimeSessionId: options.runtimeSessionId, endpointId: options.endpointId,
|
|
201
|
+
policyDigest: current.policyDigest, messageId, auditSequence: original.auditSequence, status: "STOPPED_NO_REPLAY", code });
|
|
202
|
+
};
|
|
203
|
+
try {
|
|
204
|
+
const read = await ctx.executeTool("ce_read", { messageId }).catch(() => failure(code = "INBOUND_READ_REFUSED"));
|
|
205
|
+
authorized(current.policyDigest); if (read.isError) failure(code = "INBOUND_READ_REFUSED");
|
|
206
|
+
const actual = metadata(read.result.details, current.policy, messageId, original.admittedAt) ?? failure(code = "INBOUND_METADATA_DENIED");
|
|
207
|
+
if (metadataKeys.some(key => actual[key] !== currentMetadata[key])) failure(code = "INBOUND_METADATA_CHANGED");
|
|
208
|
+
const payload = await ctx.executeTool("ce_read_payload", { messageId }).catch(() => failure(code = "INBOUND_READ_REFUSED"));
|
|
209
|
+
authorized(current.policyDigest); if (payload.isError) failure(code = "INBOUND_READ_REFUSED");
|
|
210
|
+
const readPayload = metadata(payload.result.details, current.policy, messageId, original.admittedAt) ?? failure(code = "INBOUND_METADATA_DENIED");
|
|
211
|
+
if (metadataKeys.some(key => readPayload[key] !== actual[key])) failure(code = "INBOUND_METADATA_MISMATCH");
|
|
212
|
+
if (!Array.isArray(payload.result.content)) failure(code = "INBOUND_PAYLOAD_INVALID");
|
|
213
|
+
const part = payload.result.content[1];
|
|
214
|
+
if (part?.type !== "text") failure(code = "INBOUND_PAYLOAD_INVALID");
|
|
215
|
+
const text = part.text;
|
|
216
|
+
if (typeof text !== "string" || Buffer.from(text, "utf8").toString("utf8") !== text || Buffer.byteLength(text) !== actual.payloadLength || sha(text) !== actual.payloadDigest) failure(code = "INBOUND_PAYLOAD_MISMATCH");
|
|
217
|
+
authorized(current.policyDigest);
|
|
218
|
+
options.append("ce-inbound-receive", { version: 1, runtimeSessionId: options.runtimeSessionId, endpointId: options.endpointId,
|
|
219
|
+
policyDigest: current.policyDigest, messageId, auditSequence: original.auditSequence, status: "RETURNED" });
|
|
220
|
+
if (original.association) {
|
|
221
|
+
if (!options.feedback) failure(code = "INBOUND_FEEDBACK_UNAVAILABLE");
|
|
222
|
+
let terminal;
|
|
223
|
+
try { terminal = validateFeedbackTerminal(await options.feedback.consume({ metadata: actual, association: original.association, text }), original.association); }
|
|
224
|
+
catch { failure(code = "INBOUND_FEEDBACK_UNAVAILABLE"); }
|
|
225
|
+
options.append("ce-inbound-feedback-result", terminal);
|
|
226
|
+
return terminal;
|
|
227
|
+
}
|
|
228
|
+
return { messageId, metadata: actual, text };
|
|
229
|
+
} catch (error) {
|
|
230
|
+
settle();
|
|
231
|
+
failure(error instanceof Error && /^INBOUND_[A-Z_]+$/.test(error.message) ? error.message : code);
|
|
232
|
+
}
|
|
233
|
+
},
|
|
234
|
+
};
|
|
235
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { execFile, execFileSync } from 'node:child_process';
|
|
2
|
+
import { constants, closeSync, fstatSync, lstatSync, openSync, readFileSync, realpathSync, statSync } from 'node:fs';
|
|
3
|
+
import { basename, dirname, isAbsolute, join, normalize } from 'node:path';
|
|
4
|
+
import type { CeHookRule } from '../dist/hooks/config.js';
|
|
5
|
+
import type { CeReadResult } from '../dist/endpoints/pi/session-host.js';
|
|
6
|
+
|
|
7
|
+
export type FeedbackMetadata = Omit<CeReadResult, 'state'>;
|
|
8
|
+
export type FeedbackAssociation = { readonly kind: 'FEEDBACK'; readonly messageId: string; readonly requestMessageId: string; readonly outgoingMessageId: string; readonly probeId: string; readonly outcomeHint: 'MATCH' | 'WRONG_CONVERSATION' | 'UNVERIFIED' | 'UNKNOWN' };
|
|
9
|
+
export type FeedbackClassification = { readonly kind: 'NONE' } | { readonly kind: 'BLOCKED'; readonly reason: string } | FeedbackAssociation;
|
|
10
|
+
export type FeedbackTerminal = { readonly kind: 'TERMINAL'; readonly messageId: string; readonly requestMessageId: string; readonly outgoingMessageId: string; readonly probeId: string; readonly outcome: 'MATCH' | 'WRONG_CONVERSATION' | 'UNVERIFIED'; readonly status: 'RECORDED' | 'UNVERIFIED'; readonly suppressOrdinaryReply: true };
|
|
11
|
+
export interface OwnershipFeedbackPort {
|
|
12
|
+
classify(metadata: FeedbackMetadata): FeedbackClassification;
|
|
13
|
+
consume(input: { metadata: FeedbackMetadata; association: FeedbackAssociation; text: string }): Promise<FeedbackTerminal>;
|
|
14
|
+
}
|
|
15
|
+
const unavailable = (): never => { throw new Error('INBOUND_FEEDBACK_UNAVAILABLE'); };
|
|
16
|
+
const object = (value: unknown): value is Record<string, unknown> => !!value && typeof value === 'object' && !Array.isArray(value);
|
|
17
|
+
const keys = (value: Record<string, unknown>, expected: readonly string[]) => Object.keys(value).sort().join(',') === [...expected].sort().join(',');
|
|
18
|
+
const messageId = (value: unknown): value is string => typeof value === 'string' && /^msg_[A-Z0-9]{26}$/.test(value);
|
|
19
|
+
const probeId = (value: unknown): value is string => typeof value === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value);
|
|
20
|
+
const absolute = (value: unknown): value is string => typeof value === 'string' && value.length > 0 && value.length <= 4096 && !/[\x00-\x1f\x7f]/.test(value) && isAbsolute(value) && normalize(value) === value;
|
|
21
|
+
const associationKeys = ['kind', 'messageId', 'requestMessageId', 'outgoingMessageId', 'probeId', 'outcomeHint'];
|
|
22
|
+
const terminalKeys = ['kind', 'messageId', 'requestMessageId', 'outgoingMessageId', 'probeId', 'outcome', 'status', 'suppressOrdinaryReply'];
|
|
23
|
+
export function validateFeedbackClassification(value: unknown, incoming: string): FeedbackClassification {
|
|
24
|
+
if (!object(value)) return unavailable();
|
|
25
|
+
if (value.kind === 'NONE' && keys(value, ['kind'])) return { kind: 'NONE' };
|
|
26
|
+
if (value.kind === 'BLOCKED' && keys(value, ['kind', 'reason']) && typeof value.reason === 'string' && ['FEEDBACK_KEY_INVALID', 'FEEDBACK_PROBE_UNVERIFIED', 'FEEDBACK_OWNER_UNVERIFIED'].includes(value.reason)) return { kind: 'BLOCKED', reason: value.reason };
|
|
27
|
+
if (value.kind !== 'FEEDBACK' || !keys(value, associationKeys) || value.messageId !== incoming || !messageId(value.messageId) || !messageId(value.requestMessageId) || !messageId(value.outgoingMessageId) || !probeId(value.probeId) || !['MATCH', 'WRONG_CONVERSATION', 'UNVERIFIED', 'UNKNOWN'].includes(value.outcomeHint as string)) return unavailable();
|
|
28
|
+
return value as FeedbackAssociation;
|
|
29
|
+
}
|
|
30
|
+
export function validateFeedbackTerminal(value: unknown, association: FeedbackAssociation): FeedbackTerminal {
|
|
31
|
+
if (!object(value) || !keys(value, terminalKeys) || value.kind !== 'TERMINAL' || value.messageId !== association.messageId || value.requestMessageId !== association.requestMessageId || value.outgoingMessageId !== association.outgoingMessageId || value.probeId !== association.probeId || !['MATCH', 'WRONG_CONVERSATION', 'UNVERIFIED'].includes(value.outcome as string) || !['RECORDED', 'UNVERIFIED'].includes(value.status as string) || value.suppressOrdinaryReply !== true || (value.status === 'UNVERIFIED' && value.outcome !== 'UNVERIFIED') || (value.status === 'RECORDED' && value.outcome !== association.outcomeHint) || (association.outcomeHint === 'UNKNOWN' && (value.outcome !== 'UNVERIFIED' || value.status !== 'UNVERIFIED'))) return unavailable();
|
|
32
|
+
return value as FeedbackTerminal;
|
|
33
|
+
}
|
|
34
|
+
function privateJson(path: string): Record<string, unknown> {
|
|
35
|
+
if (!absolute(path) || realpathSync(path) !== path) return unavailable();
|
|
36
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
37
|
+
try {
|
|
38
|
+
const stat = fstatSync(fd);
|
|
39
|
+
if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o077) !== 0 || stat.nlink !== 1 || stat.size > 16384) return unavailable();
|
|
40
|
+
const value: unknown = JSON.parse(readFileSync(fd, 'utf8'));
|
|
41
|
+
if (!object(value)) return unavailable();
|
|
42
|
+
return value;
|
|
43
|
+
} finally { closeSync(fd); }
|
|
44
|
+
}
|
|
45
|
+
function parse<T>(stdout: string, validate: (value: unknown) => T): T {
|
|
46
|
+
if (typeof stdout !== 'string' || Buffer.byteLength(stdout) > 16384) return unavailable();
|
|
47
|
+
try { return validate(JSON.parse(stdout) as unknown); } catch { return unavailable(); }
|
|
48
|
+
}
|
|
49
|
+
function environment(): NodeJS.ProcessEnv {
|
|
50
|
+
const env: NodeJS.ProcessEnv = {};
|
|
51
|
+
for (const key of ['HOME', 'PATH', 'LANG']) if (process.env[key] !== undefined) env[key] = process.env[key];
|
|
52
|
+
return env;
|
|
53
|
+
}
|
|
54
|
+
/** Optional local opt-in. An existing invalid sidecar never becomes an ordinary wake. */
|
|
55
|
+
export function createOwnershipFeedbackBridge(options: { policyPath: string; databasePath?: string | undefined; hooks: readonly CeHookRule[]; runtimeSessionId: string; endpointId: string }): OwnershipFeedbackPort | undefined {
|
|
56
|
+
const sidecarPath = `${options.policyPath}.task-ownership.json`;
|
|
57
|
+
try { lstatSync(sidecarPath); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; return unavailable(); }
|
|
58
|
+
const trusted = () => {
|
|
59
|
+
const sidecar = privateJson(sidecarPath);
|
|
60
|
+
if (!keys(sidecar, ['schemaVersion', 'registryDirectory', 'observerConfig']) || sidecar.schemaVersion !== 1 || !absolute(options.databasePath) || !absolute(sidecar.registryDirectory) || realpathSync(sidecar.registryDirectory) !== sidecar.registryDirectory || !statSync(sidecar.registryDirectory).isDirectory()) return unavailable();
|
|
61
|
+
const selected = options.hooks.filter(hook => hook.enabled && hook.event === 'ce.message.committed.v1' && hook.recipient.adapter === 'chatgpt');
|
|
62
|
+
if (selected.length !== 1) return unavailable();
|
|
63
|
+
const hook = selected[0]!;
|
|
64
|
+
const [flag, wake, configFlag, config, hookFlag] = hook.args;
|
|
65
|
+
if (!absolute(hook.command) || !/^python(?:3(?:\.\d+)?)?$/.test(basename(hook.command)) || hook.args.length !== 5 || flag !== '-B' || configFlag !== '--config' || hookFlag !== '--hook' || !absolute(wake) || !absolute(config)) return unavailable();
|
|
66
|
+
const owner = dirname(config);
|
|
67
|
+
if (config !== join(owner, 'config.json') || wake !== join(owner, 'tools/ce-chatgpt-wake/wake.py')) return unavailable();
|
|
68
|
+
const outer = privateJson(config);
|
|
69
|
+
if (!keys(outer, ['autoWakeConfig']) || outer.autoWakeConfig !== join(owner, 'auto-wake.json') || sidecar.observerConfig !== outer.autoWakeConfig) return unavailable();
|
|
70
|
+
const auto = privateJson(outer.autoWakeConfig as string);
|
|
71
|
+
if (auto.ownerDirectory !== owner || typeof auto.maxWaitSeconds !== 'number' || !Number.isInteger(auto.maxWaitSeconds) || auto.maxWaitSeconds < 1 || auto.maxWaitSeconds > 120 ||
|
|
72
|
+
typeof auto.notificationTimeoutSeconds !== 'number' || !Number.isInteger(auto.notificationTimeoutSeconds) || auto.notificationTimeoutSeconds < 1 || auto.notificationTimeoutSeconds > 900) return unavailable();
|
|
73
|
+
// A permitted manual notification can wait longer than metadata consumption.
|
|
74
|
+
const consumeTimeoutMs = (auto.notificationTimeoutSeconds + auto.maxWaitSeconds + 20) * 1000;
|
|
75
|
+
const base = ['-B', join(owner, 'tools/ce-chatgpt-wake/ownership_feedback.py'), '--sidecar', sidecarPath, '--database-path', options.databasePath, '--runtime-session-id', options.runtimeSessionId, '--endpoint-id', options.endpointId, '--action'];
|
|
76
|
+
return { command: hook.command, base, consumeTimeoutMs };
|
|
77
|
+
};
|
|
78
|
+
try { trusted(); } catch { return unavailable(); }
|
|
79
|
+
return {
|
|
80
|
+
classify(metadata) {
|
|
81
|
+
try {
|
|
82
|
+
const { command, base } = trusted();
|
|
83
|
+
const stdout = execFileSync(command, [...base, 'classify'], { input: JSON.stringify(metadata), encoding: 'utf8', env: environment(), timeout: 5000, maxBuffer: 16384, shell: false, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
84
|
+
return parse(stdout, value => validateFeedbackClassification(value, metadata.messageId));
|
|
85
|
+
} catch { return unavailable(); }
|
|
86
|
+
},
|
|
87
|
+
async consume(input) {
|
|
88
|
+
try {
|
|
89
|
+
const { command, base, consumeTimeoutMs } = trusted();
|
|
90
|
+
const stdout = await new Promise<string>((resolve, reject) => {
|
|
91
|
+
const child = execFile(command, [...base, 'consume'], { encoding: 'utf8', env: environment(), timeout: consumeTimeoutMs, maxBuffer: 16384, shell: false }, (error, output) => error ? reject(error) : resolve(output));
|
|
92
|
+
child.stdin?.on('error', reject);
|
|
93
|
+
if (!child.stdin) { reject(new Error('stdin unavailable')); return; }
|
|
94
|
+
child.stdin.end(JSON.stringify(input));
|
|
95
|
+
});
|
|
96
|
+
return parse(stdout, value => validateFeedbackTerminal(value, input.association));
|
|
97
|
+
} catch { return unavailable(); }
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
/** Configuration-only onboarding. Transport and messaging authority stay with Connect. */
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
4
|
+
import { readLivePolicy, createLivePolicyRegistration, type LiveSnapshot } from "../dist/tunnel/live-session-policy.js";
|
|
5
|
+
import { readLiveSelectedSessionPolicy } from "./live-session-profile.js";
|
|
6
|
+
import { sanitizeTerminalText } from "@narumitw/pi-tui-kit";
|
|
7
|
+
import { createMultiSessionRegistration, readSelectedMultiSessionPolicy } from "../dist/tunnel/multi-session-policy.js";
|
|
8
|
+
import type { BackgroundTunnelManager } from "../dist/tunnel/background-manager.js";
|
|
9
|
+
import { runtimeEnvironment } from "./multi-session-runtime.js";
|
|
10
|
+
|
|
11
|
+
export type SessionOnboardingReason = "legacy-override" | "multi-session-policy-required" | "registration-revoked" |
|
|
12
|
+
"global-ceiling-disabled" | "endpoint-collision" | "input-unavailable" | "context-changed" | "transport-running" | "transport-unknown" | "durability-uncertain";
|
|
13
|
+
export class SessionOnboardingRefusal extends Error {
|
|
14
|
+
readonly reason: SessionOnboardingReason;
|
|
15
|
+
constructor(reason: SessionOnboardingReason, message: string) {
|
|
16
|
+
super(message); this.name = "SessionOnboardingRefusal"; this.reason = reason;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
interface OnboardingContext {
|
|
20
|
+
readonly mode: string;
|
|
21
|
+
readonly hasUI: boolean;
|
|
22
|
+
readonly sessionManager: { getSessionId(): string };
|
|
23
|
+
readonly ui: {
|
|
24
|
+
confirm?(title: string, message: string, options?: { signal?: AbortSignal; timeout?: number }): Promise<boolean>;
|
|
25
|
+
notify(message: string, level: "info" | "warning" | "error"): void;
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
const safe = (text: string): string => sanitizeTerminalText(text).replace(/[\x00-\x1f\x7f-\x9f]/g, " ");
|
|
29
|
+
export async function prepareSessionOnboarding(ctx: OnboardingContext, options: {
|
|
30
|
+
readonly profilePath: string;
|
|
31
|
+
readonly manager: Pick<BackgroundTunnelManager, "refresh" | "withProfileConfigurationLock">;
|
|
32
|
+
readonly signal: AbortSignal;
|
|
33
|
+
readonly onProgress?: (text: string) => void;
|
|
34
|
+
}): Promise<"ready" | "registered" | "cancelled"> {
|
|
35
|
+
if (options.signal.aborted) return "cancelled";
|
|
36
|
+
if (process.env.CE_ALLOWLIST) throw new SessionOnboardingRefusal("legacy-override", "CE_ALLOWLIST selects legacy policy. Remove the override and explicitly select a multi-session profile before Connect.");
|
|
37
|
+
let selected;
|
|
38
|
+
try {
|
|
39
|
+
try { selected = readSelectedMultiSessionPolicy(options.profilePath); }
|
|
40
|
+
catch {
|
|
41
|
+
const text = readFileSync(options.profilePath, "utf8");
|
|
42
|
+
const live = readLiveSelectedSessionPolicy(options.profilePath, text);
|
|
43
|
+
if (live === undefined) throw new Error("No selected policy");
|
|
44
|
+
return prepareLiveSession(ctx, options, live, text);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
catch { throw new SessionOnboardingRefusal("multi-session-policy-required", "A verified multi-session policy is required. Configure or explicitly convert the selected profile before Connect."); }
|
|
48
|
+
const runtimeSessionId = ctx.sessionManager.getSessionId();
|
|
49
|
+
if (typeof runtimeSessionId !== "string" || !runtimeSessionId.length || runtimeSessionId.length > 256 || /[\x00-\x1f\x7f]/.test(runtimeSessionId) || /cap_[0-9a-f]{16,}/i.test(runtimeSessionId)) {
|
|
50
|
+
throw new SessionOnboardingRefusal("context-changed", "A valid current native Pi Session is required. Resume that Session and Connect again.");
|
|
51
|
+
}
|
|
52
|
+
const old = selected.manifest.registrations.find(r => r.runtimeSessionId === runtimeSessionId);
|
|
53
|
+
if (old?.status === "revoked") throw new SessionOnboardingRefusal("registration-revoked", "This Pi Session registration was revoked. Ask the operator to resolve its registration explicitly; Connect cannot restore it.");
|
|
54
|
+
if (old !== undefined) return "ready";
|
|
55
|
+
const endpointId = "pi/session-" + createHash("sha256").update(JSON.stringify(["ce-session-onboarding-v1", runtimeSessionId])).digest("hex").slice(0, 32);
|
|
56
|
+
if (selected.manifest.chatgptEndpoint.endpointId === endpointId || selected.manifest.registrations.some(r => r.endpointId === endpointId)) {
|
|
57
|
+
throw new SessionOnboardingRefusal("endpoint-collision", "The generated Endpoint already belongs to an existing registration or tombstone. Ask the operator to resolve the collision; nothing was overwritten.");
|
|
58
|
+
}
|
|
59
|
+
if (ctx.mode !== "tui" || !ctx.hasUI || typeof ctx.ui.confirm !== "function") throw new SessionOnboardingRefusal("input-unavailable", "Open an interactive Pi TUI and Connect to confirm this Session registration.");
|
|
60
|
+
const environment = runtimeEnvironment();
|
|
61
|
+
const expectedRevision = selected.revision;
|
|
62
|
+
const api = createMultiSessionRegistration({ profilePath: options.profilePath, env: process.env, manager: {
|
|
63
|
+
withProfileConfigurationLock: operation => options.manager.withProfileConfigurationLock(guard => {
|
|
64
|
+
current(); // Lock acquisition includes an awaited process inventory; fence before publication.
|
|
65
|
+
return operation(guard);
|
|
66
|
+
}),
|
|
67
|
+
} });
|
|
68
|
+
const current = (): void => {
|
|
69
|
+
if (options.signal.aborted || ctx.sessionManager.getSessionId() !== runtimeSessionId || runtimeEnvironment() !== environment || api.revision() !== expectedRevision) {
|
|
70
|
+
throw new SessionOnboardingRefusal("context-changed", "Session, profile, environment or cancellation changed during onboarding. Connect again to review the current configuration.");
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
options.onProgress?.("Measuring transport before session registration");
|
|
74
|
+
const status = await options.manager.refresh();
|
|
75
|
+
if (options.signal.aborted) return "cancelled";
|
|
76
|
+
current();
|
|
77
|
+
if (status.state === "UNKNOWN" || status.state === "STOPPED" && status.running) {
|
|
78
|
+
throw new SessionOnboardingRefusal("transport-unknown", "Transport state is unverified. Resolve process/ownership inspection and verify STOPPED before Connect.");
|
|
79
|
+
}
|
|
80
|
+
if (status.state !== "STOPPED") throw new SessionOnboardingRefusal("transport-running", "This current Pi Session is absent from the loaded recipient policy of the running transport. Coordinate Stop then Connect to register and load its Endpoint.");
|
|
81
|
+
// A never-started profile has STOPPED/none; the existing lock verifies process absence.
|
|
82
|
+
options.onProgress?.("Verifying the Profile configuration lock");
|
|
83
|
+
try { await options.manager.withProfileConfigurationLock(() => current()); }
|
|
84
|
+
catch (error) {
|
|
85
|
+
if (error instanceof SessionOnboardingRefusal) throw error;
|
|
86
|
+
throw new SessionOnboardingRefusal("transport-unknown", "STOPPED process absence and ownership could not be verified. Resolve transport inspection before Connect.");
|
|
87
|
+
}
|
|
88
|
+
if (options.signal.aborted) return "cancelled";
|
|
89
|
+
current();
|
|
90
|
+
options.onProgress?.("Waiting for session registration consent");
|
|
91
|
+
const accepted = await ctx.ui.confirm("Chat Exchange · register current Session", `Register this current native Pi Session as Endpoint ${safe(endpointId)}?\n` +
|
|
92
|
+
`Store: ${safe(selected.manifest.store.directory)}/${safe(selected.manifest.store.file)}\n` +
|
|
93
|
+
`Exchange: ${safe(selected.manifest.exchange.namespace)} / ${safe(selected.manifest.exchange.idempotencyKey)}\n` +
|
|
94
|
+
`Peer: ${safe(selected.manifest.chatgptEndpoint.endpointId)}\n` +
|
|
95
|
+
"Payload read: disabled; ACK: disabled; Hooks: none.\nShared ChatGPT inbox; registration saves configuration only. Connect separately checks transport permission and messaging ownership.",
|
|
96
|
+
{ signal: options.signal, timeout: 120_000 });
|
|
97
|
+
if (options.signal.aborted) return "cancelled";
|
|
98
|
+
current();
|
|
99
|
+
if (accepted !== true) return "cancelled";
|
|
100
|
+
options.onProgress?.("Saving the session registration");
|
|
101
|
+
const result = await api.register({ expectedRevision, registration: { endpointId, runtimeSessionId, payloadRead: false, ack: false } });
|
|
102
|
+
// Publication changes revision itself. Never retry or claim rollback after its commit point.
|
|
103
|
+
if (result.durability !== "synced") throw new SessionOnboardingRefusal("durability-uncertain", "Registration durability is uncertain. Inspect the selected profile before another Connect; do not retry registration automatically.");
|
|
104
|
+
if (options.signal.aborted || ctx.sessionManager.getSessionId() !== runtimeSessionId || runtimeEnvironment() !== environment || api.revision() !== result.revision) {
|
|
105
|
+
throw new SessionOnboardingRefusal("context-changed", "Context changed after registration publication. Inspect the selected profile and Connect again in the intended Session.");
|
|
106
|
+
}
|
|
107
|
+
return "registered";
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async function prepareLiveSession(ctx: OnboardingContext, options: Parameters<typeof prepareSessionOnboarding>[1], selected: LiveSnapshot, profileText: string): Promise<"ready" | "registered" | "cancelled"> {
|
|
111
|
+
const runtimeSessionId = ctx.sessionManager.getSessionId();
|
|
112
|
+
if (typeof runtimeSessionId !== "string" || !runtimeSessionId.length || runtimeSessionId.length > 256 || /[\x00-\x1f\x7f]/.test(runtimeSessionId) || /cap_[0-9a-f]{16,}/i.test(runtimeSessionId)) {
|
|
113
|
+
throw new SessionOnboardingRefusal("context-changed", "A valid current native Pi Session is required.");
|
|
114
|
+
}
|
|
115
|
+
if (!selected.manifest.mcp.payloadRead || !selected.manifest.mcp.ack) throw new SessionOnboardingRefusal("global-ceiling-disabled", "Global MCP payload-read or ACK is disabled. Enable both through explicit offline setup before live Connect; no Session grant was changed.");
|
|
116
|
+
const old = selected.manifest.registrations.find(r => r.runtimeSessionId === runtimeSessionId);
|
|
117
|
+
if (old?.status === "revoked") throw new SessionOnboardingRefusal("registration-revoked", "Connect cannot restore a revoked registration. Fresh operator confirmation is required.");
|
|
118
|
+
if (old?.payloadRead && old.ack) return "ready";
|
|
119
|
+
const endpointId = old?.endpointId ?? "pi/session-" + createHash("sha256").update(JSON.stringify(["ce-session-onboarding-v1", runtimeSessionId])).digest("hex").slice(0, 32);
|
|
120
|
+
if (selected.manifest.chatgptEndpoint.endpointId === endpointId || selected.manifest.registrations.some(r => r.endpointId === endpointId && r !== old)) throw new SessionOnboardingRefusal("endpoint-collision", "Endpoint collision; nothing was overwritten.");
|
|
121
|
+
if (ctx.mode !== "tui" || !ctx.hasUI || typeof ctx.ui.confirm !== "function") throw new SessionOnboardingRefusal("input-unavailable", "Open an interactive Pi TUI to confirm live messaging grants.");
|
|
122
|
+
const api = createLivePolicyRegistration({ ref: selected.ref });
|
|
123
|
+
if (api.reconcile({ runtimeSessionId }).some(r => r.outcome === "NOT_OBSERVED" || r.outcome === "UNKNOWN")) {
|
|
124
|
+
throw new SessionOnboardingRefusal("durability-uncertain", "An earlier publication is unresolved. Reconcile it explicitly before new consent or publication.");
|
|
125
|
+
}
|
|
126
|
+
const environment = runtimeEnvironment();
|
|
127
|
+
const current = (): void => {
|
|
128
|
+
if (options.signal.aborted || ctx.sessionManager.getSessionId() !== runtimeSessionId || runtimeEnvironment() !== environment ||
|
|
129
|
+
readFileSync(options.profilePath, "utf8") !== profileText || readLivePolicy(selected.ref).digest !== selected.digest) {
|
|
130
|
+
throw new SessionOnboardingRefusal("context-changed", "Session, selected profile or policy changed; Connect again to review the current grants.");
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
current();
|
|
134
|
+
// The live chain owns publication serialization. No transport-STOPPED lock or lifecycle action.
|
|
135
|
+
options.onProgress?.("Waiting for live session messaging consent");
|
|
136
|
+
const accepted = await ctx.ui.confirm("Chat Exchange · current Session messaging", `Endpoint: ${safe(endpointId)}\n` +
|
|
137
|
+
`Store: ${safe(selected.manifest.store.directory)}/${safe(selected.manifest.store.file)}\n` +
|
|
138
|
+
`Exchange: ${safe(selected.manifest.exchange.namespace)} / ${safe(selected.manifest.exchange.idempotencyKey)}\nPeer: ${safe(selected.manifest.chatgptEndpoint.endpointId)}\n` +
|
|
139
|
+
"Enable payload read and ACK (reception only) for this current Session? Its exact Endpoint label is visible to the configured peer. Real first send outcomes may reveal first join/addressability even when optional presence disclosure is withheld.\n" +
|
|
140
|
+
(old?.hooks?.length ? "Separately authorized Hooks are preserved unchanged; no Hook is enabled by this consent.\n" : "Hooks: none.\n") +
|
|
141
|
+
"Shared ChatGPT inbox; no conversation isolation. Configuration only: explicit reload/Start or transport reuse follows. This is not delivery or task completion evidence.", { signal: options.signal, timeout: 120_000 });
|
|
142
|
+
if (options.signal.aborted) return "cancelled";
|
|
143
|
+
current(); if (accepted !== true) return "cancelled";
|
|
144
|
+
options.onProgress?.("Waiting for optional presence consent");
|
|
145
|
+
const presenceDisclosure = old?.presenceDisclosure === true || await ctx.ui.confirm("Chat Exchange · optional presence disclosure", "Also disclose this Endpoint's Exchange membership/first join and current Owner/lease liveness to authorized peers? Decline keeps Active and membership-dependent Reachable unknown; messaging consent remains separate.", { signal: options.signal, timeout: 120_000 });
|
|
146
|
+
if (options.signal.aborted) return "cancelled";
|
|
147
|
+
current();
|
|
148
|
+
options.onProgress?.("Publishing the live session registration");
|
|
149
|
+
const result = api.register({ expectedDigest: selected.digest,
|
|
150
|
+
registration: { endpointId, runtimeSessionId, payloadRead: true, ack: true, presenceDisclosure } });
|
|
151
|
+
if (result.durability !== "synced") throw new SessionOnboardingRefusal("durability-uncertain", "Live registration publication is uncertain. Reconcile the operation explicitly; do not retry automatically.");
|
|
152
|
+
if (options.signal.aborted || ctx.sessionManager.getSessionId() !== runtimeSessionId || runtimeEnvironment() !== environment || readFileSync(options.profilePath, "utf8") !== profileText || readLivePolicy(selected.ref).digest !== result.snapshot.digest) throw new SessionOnboardingRefusal("context-changed", "Context changed after publication. Grants remain configured; explicitly Connect again.");
|
|
153
|
+
return "registered";
|
|
154
|
+
}
|