@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
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
* width-adaptive, state-coloured panel is only possible from a component that
|
|
10
10
|
* receives the real render width and the host theme.
|
|
11
11
|
*/
|
|
12
|
+
import { renderBoundedFrame } from "@narumitw/pi-tui-kit";
|
|
12
13
|
import { isTunnelRefusalCode } from "./codes.js";
|
|
13
14
|
import { PLAIN_TUNNEL_PANEL_THEME, clipTunnelPanelText, renderTunnelPanel, tunnelPanelModel, } from "./manager-panel.js";
|
|
14
15
|
/** Presentation is conservative; authorization remains in the injected ports.
|
|
@@ -25,14 +26,14 @@ export function tunnelManagerActions(projection) {
|
|
|
25
26
|
const invalidOrIncomplete = projection.errorCode !== undefined || projection.binding === "invalid"
|
|
26
27
|
|| projection.binding === "missing" || !projection.credentialConfigured;
|
|
27
28
|
const repair = unconfigured ? "setup" : invalidOrIncomplete ? "edit" : undefined;
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
: state === "CONNECTED" ? ["stop"] : [];
|
|
31
|
-
return [...(repair !== undefined ? [repair] : []), ...lifecycle, "refresh", "details", "close"];
|
|
29
|
+
const sessionAction = projection.sessionBinding === "attached" ? "disconnect" : "connect";
|
|
30
|
+
return [...(repair !== undefined ? [repair] : []), sessionAction, "status", "permission", "advanced", "refresh", "details", "close"];
|
|
32
31
|
}
|
|
33
32
|
const LABELS = Object.freeze({
|
|
34
33
|
setup: "Set Up Tunnel", edit: "Edit Configuration", start: "Start Tunnel", stop: "Stop Tunnel",
|
|
35
|
-
|
|
34
|
+
connect: "Connect", disconnect: "Disconnect", status: "Status", permission: "Manage Permission",
|
|
35
|
+
"permission-status": "View Status", "permission-grant": "Grant Permission", "permission-revoke": "Revoke Permission",
|
|
36
|
+
advanced: "Advanced", refresh: "Refresh", details: "Details", close: "Close", back: "Back",
|
|
36
37
|
});
|
|
37
38
|
const DETAIL_ITEMS = Object.freeze(["back", "close"]);
|
|
38
39
|
const MANAGER_HINT = "↑↓ move · Enter select · Esc close";
|
|
@@ -110,26 +111,48 @@ class TunnelManagerPanel {
|
|
|
110
111
|
done;
|
|
111
112
|
projection;
|
|
112
113
|
operationError;
|
|
113
|
-
view
|
|
114
|
+
view;
|
|
114
115
|
cursor = 0;
|
|
115
116
|
finished = false;
|
|
116
117
|
theme;
|
|
117
118
|
key;
|
|
118
|
-
constructor(tui, theme, keybindings, done, projection, operationError) {
|
|
119
|
+
constructor(tui, theme, keybindings, done, projection, operationError, view = "manager") {
|
|
119
120
|
this.tui = tui;
|
|
120
121
|
this.done = done;
|
|
121
122
|
this.projection = projection;
|
|
122
123
|
this.operationError = operationError;
|
|
124
|
+
this.view = view;
|
|
123
125
|
this.theme = panelTheme(theme);
|
|
124
126
|
this.key = keyReader(keybindings);
|
|
125
127
|
}
|
|
126
128
|
items() {
|
|
127
|
-
|
|
129
|
+
if (this.view === "details")
|
|
130
|
+
return DETAIL_ITEMS;
|
|
131
|
+
if (this.view === "advanced")
|
|
132
|
+
return [
|
|
133
|
+
...(this.projection.state === "STOPPED" ? ["start"] : this.projection.state === "CONNECTED" ? ["stop"] : []),
|
|
134
|
+
"back",
|
|
135
|
+
];
|
|
136
|
+
if (this.view === "permission") {
|
|
137
|
+
const permission = this.projection.permission;
|
|
138
|
+
return ["permission-status",
|
|
139
|
+
...(permission !== "granted" && permission !== "invalid" ? ["permission-grant"] : []),
|
|
140
|
+
...(permission === "granted" || permission === "environment" || permission === "changed" ? ["permission-revoke"] : []),
|
|
141
|
+
"back"];
|
|
142
|
+
}
|
|
143
|
+
return tunnelManagerActions(this.projection);
|
|
128
144
|
}
|
|
129
145
|
render(width) {
|
|
130
146
|
const total = Math.max(1, Math.floor(width));
|
|
131
147
|
const panelWidth = Math.min(total, PANEL_MAX_WIDTH);
|
|
132
|
-
const lines =
|
|
148
|
+
const lines = this.view === "advanced"
|
|
149
|
+
? ["Advanced · shared Tunnel", "", "Start/Stop affects all sessions using this Tunnel."].map(line => clipTunnelPanelText(line, total))
|
|
150
|
+
: this.view === "permission"
|
|
151
|
+
? ["Manage Permission", "",
|
|
152
|
+
`Background permission: ${this.projection.permission ?? "unavailable"}`,
|
|
153
|
+
"Revoke denies future starts. Running transport needs Advanced · Stop Tunnel.",
|
|
154
|
+
].map(line => clipTunnelPanelText(line, total))
|
|
155
|
+
: [...renderTunnelPanel(tunnelPanelModel(this.projection, this.view), panelWidth, this.theme)];
|
|
133
156
|
if (this.operationError !== undefined) {
|
|
134
157
|
lines.push("", this.theme.fg("error", clipTunnelPanelText(`Last operation: ${this.operationError}`, total)));
|
|
135
158
|
}
|
|
@@ -139,8 +162,15 @@ class TunnelManagerPanel {
|
|
|
139
162
|
const row = clipTunnelPanelText(`${index === this.cursor ? "❯ " : " "}${LABELS[item]}`, total);
|
|
140
163
|
lines.push(index === this.cursor ? this.theme.bold(this.theme.fg("accent", row)) : this.theme.fg("text", row));
|
|
141
164
|
}
|
|
142
|
-
lines.push("", this.theme.fg("dim", clipTunnelPanelText(this.view
|
|
143
|
-
|
|
165
|
+
lines.push("", this.theme.fg("dim", clipTunnelPanelText(this.view !== "manager" ? DETAILS_HINT : MANAGER_HINT, total)));
|
|
166
|
+
const rows = this.tui.terminal?.rows;
|
|
167
|
+
const budget = rows === undefined ? lines.length : Math.max(1, Math.floor(rows) - 2);
|
|
168
|
+
if (lines.length <= budget)
|
|
169
|
+
return lines;
|
|
170
|
+
return renderBoundedFrame({ width: total, maxRows: budget, rule: "",
|
|
171
|
+
title: [], content: lines.slice(0, -2), hints: [lines.at(-1)],
|
|
172
|
+
compactHint: lines.at(-1), focusedRow: lines.findIndex(line => line.includes("❯ ")),
|
|
173
|
+
priorityRows: [lines.findIndex(line => line.includes("❯ "))], });
|
|
144
174
|
}
|
|
145
175
|
invalidate() {
|
|
146
176
|
// Nothing is cached: every row is rebuilt from the same safe projection.
|
|
@@ -184,9 +214,8 @@ class TunnelManagerPanel {
|
|
|
184
214
|
this.requestRender();
|
|
185
215
|
}
|
|
186
216
|
cancel() {
|
|
187
|
-
// Escape
|
|
188
|
-
|
|
189
|
-
if (this.view === "details") {
|
|
217
|
+
// Escape from a submenu returns; only the landing panel closes the Manager.
|
|
218
|
+
if (this.view !== "manager") {
|
|
190
219
|
this.show("manager");
|
|
191
220
|
return;
|
|
192
221
|
}
|
|
@@ -200,6 +229,14 @@ class TunnelManagerPanel {
|
|
|
200
229
|
this.show("details");
|
|
201
230
|
return;
|
|
202
231
|
}
|
|
232
|
+
if (item === "advanced") {
|
|
233
|
+
this.show("advanced");
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
if (item === "permission") {
|
|
237
|
+
this.show("permission");
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
203
240
|
if (item === "back") {
|
|
204
241
|
this.show("manager");
|
|
205
242
|
return;
|
|
@@ -254,6 +291,7 @@ export async function runTunnelManagerUi(ctx, ports, options = {}) {
|
|
|
254
291
|
}
|
|
255
292
|
let lastProjection;
|
|
256
293
|
let operationError;
|
|
294
|
+
let view = "manager";
|
|
257
295
|
const current = () => !controller.signal.aborted && (options.isCurrent?.() ?? true);
|
|
258
296
|
/** Set while a panel owns the screen so an abort can close it immediately. */
|
|
259
297
|
let closeActive;
|
|
@@ -296,7 +334,7 @@ export async function runTunnelManagerUi(ctx, ports, options = {}) {
|
|
|
296
334
|
let selection;
|
|
297
335
|
try {
|
|
298
336
|
selection = await custom((tui, theme, keybindings, done) => {
|
|
299
|
-
const panel = new TunnelManagerPanel(tui, theme, keybindings, done, projection, operationError);
|
|
337
|
+
const panel = new TunnelManagerPanel(tui, theme, keybindings, done, projection, operationError, view);
|
|
300
338
|
closeActive = () => panel.requestClose();
|
|
301
339
|
// Never call `done` synchronously inside the factory: the runtime has
|
|
302
340
|
// not installed (and therefore cannot dispose) this component yet.
|
|
@@ -320,9 +358,27 @@ export async function runTunnelManagerUi(ctx, ports, options = {}) {
|
|
|
320
358
|
if (selection === undefined || selection.kind === "close")
|
|
321
359
|
return { status: "closed" };
|
|
322
360
|
if (selection.action === "refresh") {
|
|
361
|
+
view = "manager";
|
|
362
|
+
operationError = undefined;
|
|
363
|
+
continue;
|
|
364
|
+
}
|
|
365
|
+
if (selection.action === "connect" || selection.action === "disconnect" || selection.action === "status") {
|
|
366
|
+
return { status: "command", command: selection.action };
|
|
367
|
+
}
|
|
368
|
+
if (selection.action === "permission-status" || selection.action === "permission-grant" || selection.action === "permission-revoke") {
|
|
369
|
+
view = "permission";
|
|
323
370
|
operationError = undefined;
|
|
371
|
+
try {
|
|
372
|
+
if (ports.permission === undefined)
|
|
373
|
+
throw new Error("Permission UI port unavailable");
|
|
374
|
+
await ports.permission(selection.action === "permission-status" ? "status" : selection.action === "permission-grant" ? "grant" : "revoke");
|
|
375
|
+
}
|
|
376
|
+
catch (error) {
|
|
377
|
+
operationError = closedCode(error);
|
|
378
|
+
}
|
|
324
379
|
continue;
|
|
325
380
|
}
|
|
381
|
+
view = "manager";
|
|
326
382
|
await perform(selection.action === "edit" ? "setup" : selection.action);
|
|
327
383
|
}
|
|
328
384
|
return { status: "cancelled" };
|
|
@@ -7,7 +7,7 @@ import { intersectMcpPolicy, readLoadedMultiSessionPolicy, readSelectedMultiSess
|
|
|
7
7
|
* available while any loaded registration survives; it is not partitioned by
|
|
8
8
|
* the sender whose registration was later revoked. */
|
|
9
9
|
export function createMcpPolicyAdmission(config, bindingPath) {
|
|
10
|
-
if (config.admissionPolicy
|
|
10
|
+
if (config.admissionPolicy?.kind !== "ce-multi-session-v1")
|
|
11
11
|
return undefined;
|
|
12
12
|
const profilePath = config.admissionPolicy.profilePath;
|
|
13
13
|
const deny = () => { throw new CeHostRefusal("CE_HOST_AUTHORITY_ABSENT", false, "ADMISSION_POLICY_DENIED"); };
|
package/dist/tunnel/setup-ui.js
CHANGED
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
* extensions and external terminal/process recording are not isolated by this UI.
|
|
13
13
|
*/
|
|
14
14
|
import { defineMenu, runMenu, sanitizeTerminalText } from "@narumitw/pi-tui-kit";
|
|
15
|
+
import { presentCeStatus } from "./status-ui.js";
|
|
15
16
|
import { isTunnelRefusalCode, TunnelRefusal } from "./codes.js";
|
|
16
17
|
import { TUNNEL_ID_PATTERN as TUNNEL } from "./tunnel-id.js";
|
|
17
18
|
import { captureTunnelSecret } from "./secure-input.js";
|
|
@@ -434,10 +435,7 @@ export async function presentTunnelStatus(ctx, view, options = {}) {
|
|
|
434
435
|
...(isTunnelRefusalCode(view.errorCode) ? [`Error: ${view.errorCode}`] : []),
|
|
435
436
|
"Configured != Connected", "transport only; not delivery/ACK/completion evidence.",
|
|
436
437
|
];
|
|
437
|
-
|
|
438
|
-
const menu = defineMenu({ start: "status", screens: { status: () => ({ kind: "detail", title: "Tunnel status", lines, hint: "close" }) }, actions: {} });
|
|
439
|
-
await runMenu(ctx, menu, { getState: () => null, ...(options.signal ? { signal: options.signal } : {}), onError: () => undefined });
|
|
440
|
-
}
|
|
438
|
+
await presentCeStatus(ctx, "Tunnel Status", lines, options);
|
|
441
439
|
return { lines };
|
|
442
440
|
}
|
|
443
441
|
//# sourceMappingURL=setup-ui.js.map
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** Shared read-only status screen; the caller owns admission and status data. */
|
|
2
|
+
import { renderBoundedFrame, runCustomInteraction, sanitizeTerminalText } from "@narumitw/pi-tui-kit";
|
|
3
|
+
import { clipTunnelPanelText } from "./manager-panel.js";
|
|
4
|
+
export async function presentCeStatus(ctx, title, lines, options = {}) {
|
|
5
|
+
if (ctx.mode !== "tui" || !ctx.hasUI || typeof ctx.ui.custom !== "function")
|
|
6
|
+
return;
|
|
7
|
+
const safeLines = lines.map(line => sanitizeTerminalText(line));
|
|
8
|
+
await runCustomInteraction(ctx, {
|
|
9
|
+
...options,
|
|
10
|
+
onError: () => undefined,
|
|
11
|
+
create: ({ tui, theme, keybindings, complete }) => ({
|
|
12
|
+
render(width) {
|
|
13
|
+
const columns = Math.max(1, Math.floor(width));
|
|
14
|
+
// Match Kit's terminal reservation and reserve the close row before body.
|
|
15
|
+
const budget = Math.max(1, Math.floor(tui.terminal.rows) - 2);
|
|
16
|
+
const hint = theme.fg("accent", clipTunnelPanelText("Esc", columns))
|
|
17
|
+
+ theme.fg("muted", clipTunnelPanelText(" Close", Math.max(0, columns - 3)));
|
|
18
|
+
if (budget <= 2)
|
|
19
|
+
return [hint];
|
|
20
|
+
const body = renderBoundedFrame({ width: columns, maxRows: budget - 2, rule: "",
|
|
21
|
+
title: [theme.bold(theme.fg("accent", sanitizeTerminalText(title)))],
|
|
22
|
+
content: safeLines.map(line => theme.fg("text", line)),
|
|
23
|
+
});
|
|
24
|
+
return [...body, theme.fg("border", "─".repeat(columns)), hint];
|
|
25
|
+
},
|
|
26
|
+
invalidate() { },
|
|
27
|
+
handleInput(data) {
|
|
28
|
+
if (data === "\x1b" || data === "\x03" || keybindings.matches(data, "tui.select.cancel"))
|
|
29
|
+
complete();
|
|
30
|
+
},
|
|
31
|
+
}),
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
//# sourceMappingURL=status-ui.js.map
|
package/package.json
CHANGED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { constants, closeSync, fstatSync, openSync, readFileSync, realpathSync } from 'node:fs';
|
|
3
|
+
import { performance } from 'node:perf_hooks';
|
|
4
|
+
import { basename, dirname, isAbsolute, join, normalize } from 'node:path';
|
|
5
|
+
import type { CeHookRule } from '../dist/hooks/config.js';
|
|
6
|
+
|
|
7
|
+
export type DesktopTargetOutcome = {
|
|
8
|
+
readonly status: 'DISABLED' | 'CAPTURED' | 'UNAVAILABLE' | 'PREPARED';
|
|
9
|
+
readonly messageId: string;
|
|
10
|
+
readonly reason?: 'disabled' | 'unavailable' | 'CAPTURE_LOCK_BUSY' | 'CAPTURE_TOO_LATE' | 'BEFORE_CAPTURE_CUTOFF' | 'CAPTURE_QUEUE_FULL' | 'CAPTURE_QUEUE_EXPIRED' | 'INBOUND_AUTHORITY_CHANGED';
|
|
11
|
+
readonly taskId?: string;
|
|
12
|
+
readonly idempotencyKey?: string;
|
|
13
|
+
};
|
|
14
|
+
export interface DesktopTargetRunOptions {
|
|
15
|
+
readonly env: NodeJS.ProcessEnv;
|
|
16
|
+
readonly timeout: number;
|
|
17
|
+
readonly maxBuffer: number;
|
|
18
|
+
readonly shell: false;
|
|
19
|
+
}
|
|
20
|
+
export type DesktopTargetRun = (command: string, args: readonly string[], options: DesktopTargetRunOptions) => Promise<{ stdout: string }>;
|
|
21
|
+
export interface DesktopTargetBridge {
|
|
22
|
+
readonly ready: { readonly runtimeSessionId: string; readonly endpointId: string; readonly captureAfterAuditSequence: number };
|
|
23
|
+
capture(input: { messageId: string; auditSequence: number }): Promise<DesktopTargetOutcome>;
|
|
24
|
+
prepare(input: { messageId: string; taskId: string }): Promise<DesktopTargetOutcome>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Delivery guard: the generation must be current AND the inbound policy must still authorize it. */
|
|
28
|
+
export function createDeliveryGuard(options: { readonly isCurrent: () => boolean; readonly isAuthorized: () => boolean }): () => boolean {
|
|
29
|
+
return () => {
|
|
30
|
+
try {
|
|
31
|
+
return options.isCurrent() === true && options.isAuthorized() === true;
|
|
32
|
+
} catch {
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Serializes at most 20 pending captures; waiting over 10s releases model delivery without sampling. */
|
|
39
|
+
export function createCaptureScheduler(options: { maxPending?: number; maxWaitMs?: number } = {}): { readonly run: (messageId: string, task: () => Promise<DesktopTargetOutcome>) => Promise<DesktopTargetOutcome> } {
|
|
40
|
+
let queue: Promise<unknown> = Promise.resolve();
|
|
41
|
+
let pending = 0;
|
|
42
|
+
return {
|
|
43
|
+
run(messageId, task) {
|
|
44
|
+
if (pending >= (options.maxPending ?? 20)) return Promise.resolve({ status: 'UNAVAILABLE', messageId, reason: 'CAPTURE_QUEUE_FULL' });
|
|
45
|
+
pending++;
|
|
46
|
+
const deadline = performance.now() + (options.maxWaitMs ?? 10000);
|
|
47
|
+
let expired = false;
|
|
48
|
+
let timer: ReturnType<typeof setTimeout>;
|
|
49
|
+
const expiration = new Promise<DesktopTargetOutcome>(resolve => {
|
|
50
|
+
timer = setTimeout(() => { expired = true; resolve({ status: 'UNAVAILABLE', messageId, reason: 'CAPTURE_QUEUE_EXPIRED' }); }, options.maxWaitMs ?? 10000);
|
|
51
|
+
timer.unref?.();
|
|
52
|
+
});
|
|
53
|
+
const start = (): Promise<DesktopTargetOutcome> | DesktopTargetOutcome => {
|
|
54
|
+
clearTimeout(timer);
|
|
55
|
+
if (expired || performance.now() >= deadline) return { status: 'UNAVAILABLE', messageId, reason: 'CAPTURE_QUEUE_EXPIRED' };
|
|
56
|
+
return task();
|
|
57
|
+
};
|
|
58
|
+
const result = queue.then(start, start);
|
|
59
|
+
queue = result.then(() => { pending--; }, () => { pending--; });
|
|
60
|
+
return Promise.race([result, expiration]);
|
|
61
|
+
},
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
const text = (value: unknown): value is string => typeof value === 'string' && value.length > 0 && value.length <= 4096 && !/[\x00-\x1f\x7f]/.test(value);
|
|
65
|
+
const absolute = (value: unknown): value is string => text(value) && isAbsolute(value) && normalize(value) === value;
|
|
66
|
+
function privateJson(path: string): Record<string, unknown> {
|
|
67
|
+
// Refuse symlinked ancestors as well as a symlink at the final component.
|
|
68
|
+
if (realpathSync(path) !== path) throw new Error('config path');
|
|
69
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
70
|
+
try {
|
|
71
|
+
const stat = fstatSync(fd);
|
|
72
|
+
if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o077) !== 0 || stat.size > 16384) throw new Error('private config');
|
|
73
|
+
const value: unknown = JSON.parse(readFileSync(fd, 'utf8'));
|
|
74
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('config object');
|
|
75
|
+
return value as Record<string, unknown>;
|
|
76
|
+
} finally { closeSync(fd); }
|
|
77
|
+
}
|
|
78
|
+
const runPython: DesktopTargetRun = (command, args, options) => new Promise((resolve, reject) => {
|
|
79
|
+
execFile(command, [...args], { ...options, encoding: 'utf8' }, (error, stdout) => error ? reject(error) : resolve({ stdout }));
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
/** Observes desktop targets only; Python retains runtime and desktop authority. */
|
|
83
|
+
export function createDesktopTargetBridge(options: {
|
|
84
|
+
hooks: readonly CeHookRule[];
|
|
85
|
+
runtimeSessionId: string;
|
|
86
|
+
endpointId: string;
|
|
87
|
+
run?: DesktopTargetRun;
|
|
88
|
+
}): DesktopTargetBridge | undefined {
|
|
89
|
+
try {
|
|
90
|
+
const { runtimeSessionId, endpointId } = options;
|
|
91
|
+
if (!text(runtimeSessionId) || !text(endpointId)) return undefined;
|
|
92
|
+
const selected = options.hooks.filter(hook => hook.enabled && hook.event === 'ce.message.committed.v1' && hook.recipient.adapter === 'chatgpt');
|
|
93
|
+
if (selected.length !== 1) return undefined;
|
|
94
|
+
const hook = selected[0]!;
|
|
95
|
+
const [flag, wake, configFlag, config, hookFlag] = hook.args;
|
|
96
|
+
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 undefined;
|
|
97
|
+
const owner = dirname(config);
|
|
98
|
+
if (config !== join(owner, 'config.json') || wake !== join(owner, 'tools/ce-chatgpt-wake/wake.py')) return undefined;
|
|
99
|
+
const outer = privateJson(config);
|
|
100
|
+
if (Object.keys(outer).length !== 1 || outer.autoWakeConfig !== join(owner, 'auto-wake.json')) return undefined;
|
|
101
|
+
const auto = privateJson(outer.autoWakeConfig as string);
|
|
102
|
+
const guard = auto.conversationGuard as Record<string, unknown> | undefined;
|
|
103
|
+
const cutoff = guard?.captureAfterAuditSequence;
|
|
104
|
+
if (auto.ownerDirectory !== owner || guard?.targetSelection !== 'desktop-at-intake' || typeof cutoff !== 'number' || !Number.isSafeInteger(cutoff) || cutoff < 0) return undefined;
|
|
105
|
+
const command = hook.command;
|
|
106
|
+
const base = ['-B', join(dirname(wake), 'receipt_target.py'), '--config', config, '--session-id', runtimeSessionId, '--endpoint-id', endpointId];
|
|
107
|
+
const run = options.run ?? runPython;
|
|
108
|
+
async function invoke(messageId: string, args: string[], prepare?: { taskId: string }): Promise<DesktopTargetOutcome> {
|
|
109
|
+
const unavailable: DesktopTargetOutcome = { status: 'UNAVAILABLE', messageId, reason: 'unavailable' };
|
|
110
|
+
if (!text(messageId) || (prepare && !text(prepare.taskId))) return unavailable;
|
|
111
|
+
try {
|
|
112
|
+
const env: NodeJS.ProcessEnv = {};
|
|
113
|
+
for (const key of ['HOME', 'PATH', 'LANG']) if (process.env[key] !== undefined) env[key] = process.env[key];
|
|
114
|
+
const { stdout } = await run(command, [...base, ...args], { env, timeout: 20000, maxBuffer: 16384, shell: false });
|
|
115
|
+
if (Buffer.byteLength(stdout) > 16384) return unavailable;
|
|
116
|
+
const value: unknown = JSON.parse(stdout);
|
|
117
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return unavailable;
|
|
118
|
+
const result = value as Record<string, unknown>;
|
|
119
|
+
if (result.messageId !== messageId || Object.keys(result).some(key => !['status', 'messageId', 'reason', 'taskId', 'idempotencyKey'].includes(key))) return unavailable;
|
|
120
|
+
if (result.status === 'DISABLED') return { status: 'DISABLED', messageId, reason: 'disabled' };
|
|
121
|
+
if (result.status === 'UNAVAILABLE') {
|
|
122
|
+
const reason = result.reason;
|
|
123
|
+
return reason === 'CAPTURE_LOCK_BUSY' || reason === 'CAPTURE_TOO_LATE' || reason === 'BEFORE_CAPTURE_CUTOFF'
|
|
124
|
+
? { status: 'UNAVAILABLE', messageId, reason } : unavailable;
|
|
125
|
+
}
|
|
126
|
+
if (!prepare && result.status === 'CAPTURED') return { status: 'CAPTURED', messageId };
|
|
127
|
+
if (prepare && result.status === 'PREPARED' && result.taskId === prepare.taskId && typeof result.idempotencyKey === 'string' && /^ce-desktop-[a-f0-9]{64}$/.test(result.idempotencyKey)) return { status: 'PREPARED', messageId, taskId: prepare.taskId, idempotencyKey: result.idempotencyKey };
|
|
128
|
+
return unavailable;
|
|
129
|
+
} catch { return unavailable; }
|
|
130
|
+
}
|
|
131
|
+
return {
|
|
132
|
+
ready: Object.freeze({ runtimeSessionId, endpointId, captureAfterAuditSequence: cutoff }),
|
|
133
|
+
async capture({ messageId, auditSequence }) {
|
|
134
|
+
if (!Number.isSafeInteger(auditSequence) || auditSequence <= cutoff) return { status: 'DISABLED', messageId, reason: 'disabled' };
|
|
135
|
+
return invoke(messageId, ['--capture', messageId]);
|
|
136
|
+
},
|
|
137
|
+
prepare({ messageId, taskId }) {
|
|
138
|
+
return invoke(messageId, ['--prepare-reply', messageId, '--task-id', taskId], { taskId });
|
|
139
|
+
},
|
|
140
|
+
};
|
|
141
|
+
} catch { return undefined; }
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export async function deliverAfterDesktopCapture(
|
|
145
|
+
capturePromise: Promise<DesktopTargetOutcome>,
|
|
146
|
+
isCurrent: () => boolean,
|
|
147
|
+
deliver: () => void | Promise<void>,
|
|
148
|
+
record?: (outcome: DesktopTargetOutcome) => void | Promise<void>,
|
|
149
|
+
skipped?: () => void | Promise<void>,
|
|
150
|
+
): Promise<void> {
|
|
151
|
+
let outcome: DesktopTargetOutcome | undefined;
|
|
152
|
+
try { outcome = await capturePromise; } catch { /* Failed observation must not suppress model delivery. */ }
|
|
153
|
+
if (!isCurrent()) { await skipped?.(); return; }
|
|
154
|
+
try { if (outcome) await record?.(outcome); } catch { /* Recording is observational. */ }
|
|
155
|
+
if (!isCurrent()) { await skipped?.(); return; }
|
|
156
|
+
await deliver();
|
|
157
|
+
}
|