@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.
Files changed (47) hide show
  1. package/README.md +11 -7
  2. package/dist/bin/mcp-stdio.js +124 -56
  3. package/dist/control/mcp/endpoint-discovery.js +60 -0
  4. package/dist/control/mcp/messaging-tools.js +12 -2
  5. package/dist/control/mcp/server.js +10 -2
  6. package/dist/hooks/config.js +106 -0
  7. package/dist/hooks/events.js +19 -0
  8. package/dist/hooks/runner.js +187 -0
  9. package/dist/host/bound-endpoint.js +19 -6
  10. package/dist/host/endpoint-host.js +92 -4
  11. package/dist/host/mcp-binding-config.js +41 -5
  12. package/dist/runtime/native-readiness.js +8 -5
  13. package/dist/storage/creation.js +16 -0
  14. package/dist/storage/ownership.js +45 -1
  15. package/dist/tunnel/background-authorization.js +343 -0
  16. package/dist/tunnel/background-manager.js +104 -8
  17. package/dist/tunnel/background-scope.js +69 -0
  18. package/dist/tunnel/codes.js +1 -1
  19. package/dist/tunnel/hooks-management-ui.js +225 -0
  20. package/dist/tunnel/hooks-management.js +431 -0
  21. package/dist/tunnel/live-adoption-observation.js +136 -0
  22. package/dist/tunnel/live-adoption-probe.js +240 -0
  23. package/dist/tunnel/live-connection-status.js +136 -0
  24. package/dist/tunnel/live-mcp-composition.js +143 -0
  25. package/dist/tunnel/live-process-observation.js +98 -0
  26. package/dist/tunnel/live-session-migration.js +169 -0
  27. package/dist/tunnel/live-session-policy.js +578 -0
  28. package/dist/tunnel/manager-panel.js +4 -2
  29. package/dist/tunnel/manager-ui.js +71 -15
  30. package/dist/tunnel/multi-session-admission.js +1 -1
  31. package/dist/tunnel/multi-session-policy.js +45 -13
  32. package/dist/tunnel/setup-ui.js +2 -4
  33. package/dist/tunnel/status-ui.js +34 -0
  34. package/package.json +4 -1
  35. package/pi-extension/allowlist.example.json +12 -1
  36. package/pi-extension/desktop-target.ts +157 -0
  37. package/pi-extension/index.ts +1128 -132
  38. package/pi-extension/live-session-profile.ts +49 -0
  39. package/pi-extension/live-session-runtime.ts +59 -0
  40. package/pi-extension/multi-session-commands.ts +114 -3
  41. package/pi-extension/multi-session-runtime.ts +63 -11
  42. package/pi-extension/native-inbound.ts +235 -0
  43. package/pi-extension/ownership-feedback.ts +100 -0
  44. package/pi-extension/session-onboarding.ts +154 -0
  45. package/pi-extension/session-recovery.ts +214 -0
  46. package/skills/ce-hook-script/SKILL.md +62 -0
  47. package/skills/ce-hook-script/examples/file-notification.py +79 -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
- // Start/Stop authority follows the measured runtime lifecycle only.
29
- const lifecycle = state === "STOPPED" ? ["start"]
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
- refresh: "Refresh", details: "Details", close: "Close", back: "Back",
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 = "manager";
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
- return this.view === "details" ? DETAIL_ITEMS : tunnelManagerActions(this.projection);
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 = [...renderTunnelPanel(tunnelPanelModel(this.projection, this.view), panelWidth, this.theme)];
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 === "details" ? DETAILS_HINT : MANAGER_HINT, total)));
143
- return lines;
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 in diagnostics returns to the landing panel; only the landing
188
- // panel closes the Manager, so a glance at Details cannot end the session.
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 === undefined)
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"); };
@@ -3,6 +3,7 @@
3
3
  * Runtime composition MUST apply these deny-only intersections before every operation.
4
4
  */
5
5
  import fs from "node:fs";
6
+ import { parseHookRules } from "../hooks/config.js";
6
7
  import { createHash, randomUUID } from "node:crypto";
7
8
  import { dirname, isAbsolute, join, normalize } from "node:path";
8
9
  import { isDeepStrictEqual } from "node:util";
@@ -14,14 +15,15 @@ import { buildPiAllowlistDocument, publishMessagingGeneration, readMessagingGene
14
15
  const KIND = "ce-multi-session-v1";
15
16
  const invalid = () => new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "messaging.multiSession");
16
17
  const conflict = () => new TunnelRefusal("CE_TUNNEL_CONFIG_CONFLICT", "profile");
17
- function object(value, keys) {
18
+ function object(value, keys, optional = []) {
18
19
  if (typeof value !== "object" || value === null || Array.isArray(value))
19
20
  throw invalid();
20
21
  if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)
21
22
  throw invalid();
22
- if (Reflect.ownKeys(value).length !== keys.length)
23
+ const present = Reflect.ownKeys(value);
24
+ if (present.some((key) => typeof key !== "string" || !keys.includes(key) && !optional.includes(key)))
23
25
  throw invalid();
24
- for (const key of keys) {
26
+ for (const key of [...keys, ...optional.filter((key) => present.includes(key))]) {
25
27
  const d = Object.getOwnPropertyDescriptor(value, key);
26
28
  if (d === undefined || !("value" in d) || !d.enumerable)
27
29
  throw invalid();
@@ -36,8 +38,18 @@ function label(value) {
36
38
  function bool(value) { if (typeof value !== "boolean")
37
39
  throw invalid(); return value; }
38
40
  function inputRegistration(raw) {
39
- const r = object(raw, ["endpointId", "runtimeSessionId", "payloadRead", "ack"]);
40
- return Object.freeze({ endpointId: label(r.endpointId), runtimeSessionId: label(r.runtimeSessionId), payloadRead: bool(r.payloadRead), ack: bool(r.ack) });
41
+ const r = object(raw, ["endpointId", "runtimeSessionId", "payloadRead", "ack"], ["hooks"]);
42
+ let hooks;
43
+ if (r.hooks !== undefined) {
44
+ try {
45
+ hooks = parseHookRules(r.hooks);
46
+ }
47
+ catch {
48
+ throw invalid();
49
+ }
50
+ }
51
+ return Object.freeze({ endpointId: label(r.endpointId), runtimeSessionId: label(r.runtimeSessionId), payloadRead: bool(r.payloadRead), ack: bool(r.ack),
52
+ ...(hooks === undefined ? {} : { hooks }) });
41
53
  }
42
54
  /** Closed schema, including tombstones. Runtime IDs and stable endpoints are globally unique. */
43
55
  export function parseMultiSessionManifest(raw) {
@@ -62,8 +74,10 @@ export function parseMultiSessionManifest(raw) {
62
74
  const endpoints = new Set([endpointId]);
63
75
  const sessions = new Set();
64
76
  const registrations = r.registrations.map((value) => {
65
- const entry = object(value, ["endpointId", "runtimeSessionId", "epoch", "status", "payloadRead", "ack"]);
66
- const registration = inputRegistration({ endpointId: entry.endpointId, runtimeSessionId: entry.runtimeSessionId, payloadRead: entry.payloadRead, ack: entry.ack });
77
+ const entry = object(value, ["endpointId", "runtimeSessionId", "epoch", "status", "payloadRead", "ack"], ["hooks"]);
78
+ const registration = inputRegistration({ endpointId: entry.endpointId, runtimeSessionId: entry.runtimeSessionId, payloadRead: entry.payloadRead, ack: entry.ack, ...(entry.hooks === undefined ? {} : { hooks: entry.hooks }) });
79
+ if (registration.hooks?.some((rule) => rule.recipient.adapter !== "chatgpt" || rule.recipient.endpointId !== endpointId))
80
+ throw invalid();
67
81
  if (typeof entry.epoch !== "number" || !Number.isSafeInteger(entry.epoch) || entry.epoch < 1 ||
68
82
  (entry.status !== "active" && entry.status !== "revoked") || endpoints.has(registration.endpointId) || sessions.has(registration.runtimeSessionId))
69
83
  throw invalid();
@@ -103,7 +117,8 @@ function checkPair(profilePath, pair, manifest) {
103
117
  if (c.admissionPolicy?.kind !== KIND || c.admissionPolicy.profilePath !== profilePath ||
104
118
  !isDeepStrictEqual(c.store, manifest.store) || !isDeepStrictEqual(c.exchange, manifest.exchange) ||
105
119
  !isDeepStrictEqual(c.endpoint, manifest.chatgptEndpoint) || !isDeepStrictEqual(c.recipients, recipients) ||
106
- c.payloadRead.enabled !== manifest.mcp.payloadRead || c.ack.enabled !== manifest.mcp.ack)
120
+ c.payloadRead.enabled !== manifest.mcp.payloadRead || c.ack.enabled !== manifest.mcp.ack ||
121
+ c.hooks?.some((rule) => rule.recipient.adapter !== "pi" || !recipients.some((ref) => ref.endpointId === rule.recipient.endpointId)))
107
122
  throw invalid();
108
123
  }
109
124
  /** READ is the linearization point, conditional on successful verification of
@@ -171,6 +186,18 @@ export function intersectMcpRecipients(loaded, current) {
171
186
  }
172
187
  }));
173
188
  }
189
+ /** Only unchanged, enabled loaded rules survive current policy. Rules confer no messaging grants. */
190
+ export function effectivePiHookRules(loaded, current, runtimeSessionId) {
191
+ const registration = intersectRegistration(loaded, current, runtimeSessionId);
192
+ const currentRules = current.manifest.registrations.find((r) => r.runtimeSessionId === runtimeSessionId).hooks ?? [];
193
+ return Object.freeze((registration.hooks ?? []).filter((rule) => rule.enabled && currentRules.some((candidate) => candidate.enabled && isDeepStrictEqual(rule, candidate))));
194
+ }
195
+ export function effectiveMcpHookRules(loaded, current) {
196
+ const recipients = intersectMcpRecipients(loaded, current);
197
+ return Object.freeze((loaded.config.hooks ?? []).filter((rule) => rule.enabled &&
198
+ recipients.some((ref) => isDeepStrictEqual(ref, rule.recipient)) &&
199
+ (current.config.hooks ?? []).some((candidate) => candidate.enabled && isDeepStrictEqual(rule, candidate))));
200
+ }
174
201
  /** Complete MCP global grant intersection, still not CE authority. */
175
202
  export function intersectMcpPolicy(loaded, current) {
176
203
  return Object.freeze({ recipients: intersectMcpRecipients(loaded, current),
@@ -180,9 +207,9 @@ export function intersectMcpPolicy(loaded, current) {
180
207
  /** New-mode per-Pi projection: NEVER feed the complete registration set to one Host. */
181
208
  export function projectPiRegistration(snapshot, runtimeSessionId) {
182
209
  const r = intersectRegistration(snapshot, snapshot, runtimeSessionId);
183
- return buildPiAllowlistDocument({ chatgptEndpoint: snapshot.manifest.chatgptEndpoint, piEndpoint: { adapter: "pi", endpointId: r.endpointId },
184
- piSessionId: r.runtimeSessionId, exchangeNamespace: snapshot.manifest.exchange.namespace, exchangeIdempotencyKey: snapshot.manifest.exchange.idempotencyKey,
185
- store: snapshot.manifest.store, payloadRead: r.payloadRead, ack: r.ack });
210
+ return { ...buildPiAllowlistDocument({ chatgptEndpoint: snapshot.manifest.chatgptEndpoint, piEndpoint: { adapter: "pi", endpointId: r.endpointId },
211
+ piSessionId: r.runtimeSessionId, exchangeNamespace: snapshot.manifest.exchange.namespace, exchangeIdempotencyKey: snapshot.manifest.exchange.idempotencyKey,
212
+ store: snapshot.manifest.store, payloadRead: r.payloadRead, ack: r.ack }), ...(r.hooks === undefined ? {} : { hooks: r.hooks }) };
186
213
  }
187
214
  /** Every conversion/register/revoke publication uses the existing STOPPED-only
188
215
  * transport lock. It never starts/stops transport and never reads credentials. */
@@ -298,7 +325,8 @@ export function createMultiSessionRegistration(options) {
298
325
  const old = current.manifest.registrations.find((entry) => entry.endpointId === r.endpointId);
299
326
  if (current.manifest.registrations.some((entry) => entry.runtimeSessionId === r.runtimeSessionId && entry.endpointId !== r.endpointId) || (old !== undefined && old.runtimeSessionId !== r.runtimeSessionId))
300
327
  throw invalid();
301
- const registration = { ...r, epoch: old === undefined ? 1 : old.status === "revoked" ? old.epoch + 1 : old.epoch, status: "active" };
328
+ // Omission preserves operator rules; an explicit empty array clears them.
329
+ const registration = { ...r, ...(r.hooks === undefined && old?.hooks !== undefined ? { hooks: old.hooks } : {}), epoch: old === undefined ? 1 : old.status === "revoked" ? old.epoch + 1 : old.epoch, status: "active" };
302
330
  const registrations = old === undefined ? [...current.manifest.registrations, registration] : current.manifest.registrations.map((entry) => entry === old ? registration : entry);
303
331
  return { config: current.config, manifest: { ...current.manifest, registrations } };
304
332
  }),
@@ -307,7 +335,11 @@ export function createMultiSessionRegistration(options) {
307
335
  const old = current.manifest.registrations.find((r) => r.endpointId === input.endpointId);
308
336
  if (old === undefined || old.status !== "active")
309
337
  throw invalid();
310
- return { config: current.config, manifest: { ...current.manifest, registrations: current.manifest.registrations.map((r) => r === old ? { ...r, status: "revoked" } : r) } };
338
+ const registrations = current.manifest.registrations.map((r) => r === old ? { ...r, status: "revoked" } : r);
339
+ // Revocation removes execution rules for its recipient in the same publication.
340
+ const config = current.config.hooks === undefined ? current.config : { ...current.config,
341
+ hooks: current.config.hooks.filter((rule) => registrations.some((r) => r.status === "active" && rule.recipient.adapter === "pi" && rule.recipient.endpointId === r.endpointId)) };
342
+ return { config, manifest: { ...current.manifest, registrations } };
311
343
  }),
312
344
  };
313
345
  }
@@ -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
- if (ctx.mode === "tui" && ctx.hasUI && typeof ctx.ui.custom === "function") {
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zieglar/pi-chat-exchange",
3
- "version": "0.2.2",
3
+ "version": "0.3.1",
4
4
  "license": "MIT",
5
5
  "publishConfig": {
6
6
  "access": "public",
@@ -49,6 +49,8 @@
49
49
  "vitest": "4.1.11"
50
50
  },
51
51
  "files": [
52
+ "skills/ce-hook-script/SKILL.md",
53
+ "skills/ce-hook-script/examples/file-notification.py",
52
54
  "pi-extension/*.ts",
53
55
  "pi-extension/allowlist.example.json",
54
56
  "dist/**/*.js",
@@ -60,6 +62,7 @@
60
62
  "@earendil-works/pi-coding-agent": "1.3.0"
61
63
  },
62
64
  "pi": {
65
+ "skills": ["./skills"],
63
66
  "extensions": [
64
67
  "./pi-extension/index.ts"
65
68
  ]
@@ -7,5 +7,16 @@
7
7
  "recipients": [{ "adapter": "mcp", "endpointId": "chatgpt-desktop" }],
8
8
  "sessions": {
9
9
  "pi-main": { "endpointId": "pi-main" }
10
- }
10
+ },
11
+ "hooks": [
12
+ {
13
+ "id": "pi-notify-example",
14
+ "event": "ce.message.committed.v1",
15
+ "recipient": { "adapter": "mcp", "endpointId": "chatgpt-desktop" },
16
+ "command": "/absolute/path/to/node",
17
+ "args": ["/absolute/path/to/local-hook.mjs"],
18
+ "timeoutMs": 30000,
19
+ "enabled": false
20
+ }
21
+ ]
11
22
  }
@@ -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
+ }