@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.
Files changed (40) hide show
  1. package/README.md +10 -6
  2. package/dist/bin/mcp-stdio.js +113 -62
  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/host/bound-endpoint.js +19 -6
  7. package/dist/host/endpoint-host.js +78 -4
  8. package/dist/host/mcp-binding-config.js +27 -4
  9. package/dist/runtime/native-readiness.js +8 -5
  10. package/dist/storage/creation.js +16 -0
  11. package/dist/storage/ownership.js +45 -1
  12. package/dist/tunnel/background-authorization.js +343 -0
  13. package/dist/tunnel/background-manager.js +104 -8
  14. package/dist/tunnel/background-scope.js +69 -0
  15. package/dist/tunnel/codes.js +1 -1
  16. package/dist/tunnel/hooks-management-ui.js +225 -0
  17. package/dist/tunnel/hooks-management.js +431 -0
  18. package/dist/tunnel/live-adoption-observation.js +136 -0
  19. package/dist/tunnel/live-adoption-probe.js +240 -0
  20. package/dist/tunnel/live-connection-status.js +136 -0
  21. package/dist/tunnel/live-mcp-composition.js +143 -0
  22. package/dist/tunnel/live-process-observation.js +98 -0
  23. package/dist/tunnel/live-session-migration.js +169 -0
  24. package/dist/tunnel/live-session-policy.js +578 -0
  25. package/dist/tunnel/manager-panel.js +4 -2
  26. package/dist/tunnel/manager-ui.js +71 -15
  27. package/dist/tunnel/multi-session-admission.js +1 -1
  28. package/dist/tunnel/setup-ui.js +2 -4
  29. package/dist/tunnel/status-ui.js +34 -0
  30. package/package.json +1 -1
  31. package/pi-extension/desktop-target.ts +157 -0
  32. package/pi-extension/index.ts +1053 -135
  33. package/pi-extension/live-session-profile.ts +49 -0
  34. package/pi-extension/live-session-runtime.ts +59 -0
  35. package/pi-extension/multi-session-commands.ts +114 -3
  36. package/pi-extension/multi-session-runtime.ts +63 -11
  37. package/pi-extension/native-inbound.ts +235 -0
  38. package/pi-extension/ownership-feedback.ts +100 -0
  39. package/pi-extension/session-onboarding.ts +154 -0
  40. package/pi-extension/session-recovery.ts +214 -0
package/README.md CHANGED
@@ -18,11 +18,9 @@ Pi Chat Exchange (CE) lets ChatGPT and Pi exchange durable messages through expl
18
18
 
19
19
  Use **Pi 1.3.0**, **Node >=22.19.0** and a Store-supported platform: **macOS arm64 or Linux x64 GNU**. Filesystem, ownership and runtime admission checks still apply. Other Native artifacts do not establish Store support; Windows Native is unsupported and WSL2 integration remains unverified.
20
20
 
21
- Version **0.2.1** is published on npm. An actual Registry installation passed isolated Pi 1.3.0 / Node 22.19.0 loading and persistence checks on macOS arm64. Linux x64 Native checks passed 227/227 on Node 22.19.0 and 24.22.2. **Real Cloud transport and the complete ChatGPT ↔ Pi exchange remain unverified.** See [runtime support](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/runtime-support.md) for the tested matrix and limits; the engine range is not exhaustive qualification.
21
+ The published stable package is **0.3.0**. Historical 0.2.1 Registry installation checks passed isolated Pi 1.3.0 / Node 22.19.0 loading and persistence on macOS arm64; Linux x64 Native checks passed 227/227 on Node 22.19.0 and 24.22.2. Those version-specific results do not certify the current candidate. See [runtime support](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/runtime-support.md) for the tested matrix and limits; the engine range is not exhaustive qualification.
22
22
 
23
- This working tree prepares local candidate **0.2.2**. Explicit `CE_TUNNEL_CLIENT_PATH` delegates trust to a user-managed client installation, including group-writable Homebrew ancestors; automatic discovery stays strict. Installation writers may replace a program that can run as you and read Tunnel credentials. Install the candidate tarball with npm into a dedicated prefix, then register the installed package directory with Pi; see Getting started. This is not a Registry installation. The npm command below still selects published 0.2.1 and its old admission rules.
24
-
25
- Candidate evidence: [compatibility matrix](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/compatibility/README.md). Client 0.0.19 has source-matched macOS arm64 legacy-identity manual bidirectional Cloud E2E; Linux x64 CI covers synthetic local lifecycle. Historical 0.0.16 evidence is runtime-scoped; 0.0.18 and real namespaced Cloud remain NOT_VERIFIED. Independent latest monitoring and actual same-run publication integration remain NOT_VERIFIED. Managed profiles explicitly set `MCP_STDIO_FAILURE_POLICY=exit`: on 0.0.19 child failure the client exits, with no automatic respawn or recovery; inspect ownership and recover explicitly before restarting.
23
+ This working tree prepares formal **0.3.1** as a candidate, retaining published CE 0.3.0 Hooks and integrating the reviewed local changes. It is not yet a Registry release. See [0.3.1 scope and validation limits](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/releases/0.3.1.md). Explicit `CE_TUNNEL_CLIENT_PATH` delegates trust to a user-managed client installation, including group-writable Homebrew ancestors; automatic discovery stays strict. Test a reviewed local tarball in a new dedicated prefix before registering its physical package directory with Pi. Historical Cloud evidence does not qualify this changed runtime.
26
24
 
27
25
  <a id="安装-pi-扩展"></a>
28
26
  <a id="选择连接方式"></a>
@@ -32,7 +30,7 @@ Candidate evidence: [compatibility matrix](https://github.com/zieglar/pi-package
32
30
  With Pi already installed, run in your **system terminal**:
33
31
 
34
32
  ```sh
35
- pi install npm:@zieglar/pi-chat-exchange@0.2.1
33
+ pi install npm:@zieglar/pi-chat-exchange@0.3.0
36
34
  pi list
37
35
  pi
38
36
  ```
@@ -48,12 +46,18 @@ Before upgrading an existing installation, stop the owned Tunnel and verify `STO
48
46
 
49
47
  ## Limits and safe operation
50
48
 
51
- CE does not automatically schedule tasks or drain inboxes. A shared ChatGPT endpoint does not isolate conversations. Payload reads and ACKs require their own grants; payload text is untrusted data and may enter model history.
49
+ CE does not schedule tasks or drain inboxes by default. Optional native intake requires an explicitly enabled, Session-bound policy. A shared ChatGPT endpoint does not isolate conversations. Payload reads and ACKs require their own grants; payload text is untrusted data and may enter model history.
52
50
 
53
51
  ACK records reception only, not delivery, reading, processing or task completion. CE provides no exactly-once delivery/execution guarantee. `DELIVERY_UNKNOWN != CANCELLED`; missing ACK or timeout does not authorize blind retry or a new-key resend. Keep the original Message ID/key and inspect evidence first.
54
52
 
55
53
  Closing Manager or exiting Pi does not stop the detached Tunnel client. Use `/ce-tunnel stop`, then `/ce-tunnel status` to verify `STOPPED`. Keep credentials and capabilities out of messages, screenshots and reports.
56
54
 
55
+ ## Optional desktop test integrations
56
+
57
+ The repository also contains [CE → Ovis](https://github.com/zieglar/pi-packages-dev/blob/main/tools/ce-ovis-desktop/README.md) and [Pi → ChatGPT wake](https://github.com/zieglar/pi-packages-dev/blob/main/tools/ce-chatgpt-wake/README.md). These operator-run macOS tools are outside the npm payload. The local 0.3.1 candidate integration retains CE 0.3.0 Hooks and adds the accepted Daily UX changes; this identity is distinct from the published 0.3.0 artifact.
58
+
59
+ The wake notice carries fixed instructions and message identifiers only; the actual task stays in CE. Each integration requires explicit window authorization and its own isolated run. They refuse an already running Tunnel Client, so plan a separate test window after a normal Stop and confirmed STOPPED. See the tools' READMEs for setup, stop/cleanup and the limits of the recorded E2E evidence.
60
+
57
61
  <a id="阅读导航"></a>
58
62
 
59
63
  ## Documentation
@@ -22,6 +22,9 @@
22
22
  */
23
23
  import { readFileSync, statSync, existsSync } from "node:fs";
24
24
  import { join } from "node:path";
25
+ import { createHash } from "node:crypto";
26
+ import { execFileSync } from "node:child_process";
27
+ import { startLiveAdoptionProbe } from "../tunnel/live-adoption-probe.js";
25
28
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
26
29
  import { runStdioServer, createExchangeMcpServer } from "../control/mcp/server.js";
27
30
  import { CE_ACK_TOOL, MESSAGING_TOOL_NAMES } from "../control/mcp/messaging-tools.js";
@@ -36,6 +39,7 @@ import { createMcpPolicyAdmission } from "../tunnel/multi-session-admission.js";
36
39
  import { CeHookRunner } from "../hooks/runner.js";
37
40
  import { isDeepStrictEqual } from "node:util";
38
41
  import { effectiveMcpHookRules, readLoadedMultiSessionPolicy, readSelectedMultiSessionPolicy } from "../tunnel/multi-session-policy.js";
42
+ import { createLiveMcpComposition, projectEndpointDiscovery, observeLiveMcpRuntime } from "../tunnel/live-mcp-composition.js";
39
43
  debugEvent("server", "SERVER_ENTRY", { version: process.version });
40
44
  // Monitor rather than handle exceptions: preserve Node's fatal exit behavior.
41
45
  process.on("uncaughtExceptionMonitor", (error, origin) => {
@@ -74,7 +78,7 @@ function loadBindingConfig(path) {
74
78
  return fail("CE_MCP_CONFIG_INVALID", "config.not_json");
75
79
  }
76
80
  try {
77
- return parseMcpBindingConfig(parsed);
81
+ return { config: parseMcpBindingConfig(parsed), launchDigest: createHash("sha256").update(raw).digest("hex") };
78
82
  }
79
83
  catch (error) {
80
84
  if (error instanceof McpBindingConfigError)
@@ -100,25 +104,32 @@ async function main() {
100
104
  if (argv.length !== 2 || flag !== "--config" || configPath === undefined || !configPath.startsWith("/")) {
101
105
  fail("CE_MCP_LAUNCH_INVALID", "usage: mcp-stdio.js [--config /absolute/path.json]");
102
106
  }
103
- const config = loadBindingConfig(configPath);
107
+ const { config, launchDigest } = loadBindingConfig(configPath);
104
108
  // Verify actual launch bytes before Store creation; managed provenance grants nothing.
105
- const admission = createMcpPolicyAdmission(config, configPath);
106
- admission?.({ kind: "begin" });
107
- const loadedHookPolicy = config.admissionPolicy === undefined ? undefined : readLoadedMultiSessionPolicy(config.admissionPolicy.profilePath, configPath);
109
+ const live = config.admissionPolicy?.kind === "ce-live-session-v1" || config.admissionPolicy?.kind === "ce-live-session-v2"
110
+ ? createLiveMcpComposition(config, undefined, { bindingPath: configPath }) : undefined;
111
+ const admission = live?.admission ?? createMcpPolicyAdmission(config, configPath);
112
+ if (live === undefined)
113
+ admission?.({ kind: "begin" });
114
+ const loadedHookPolicy = config.admissionPolicy?.kind !== "ce-multi-session-v1" ? undefined : readLoadedMultiSessionPolicy(config.admissionPolicy.profilePath, configPath);
108
115
  const hookRunner = new CeHookRunner({
109
116
  directory: config.store.directory, rules: config.hooks ?? [],
110
- ...(loadedHookPolicy === undefined ? {} : { admit: (rule, event) => {
111
- if (event !== undefined && !isDeepStrictEqual(event.sender, config.endpoint))
117
+ ...(loadedHookPolicy === undefined && live === undefined ? {} : { admit: (rule, event) => {
118
+ if (event !== undefined && (!isDeepStrictEqual(event.sender, config.endpoint) || !isDeepStrictEqual(event.recipient, rule.recipient)))
112
119
  return false;
113
- return effectiveMcpHookRules(loadedHookPolicy, readSelectedMultiSessionPolicy(loadedHookPolicy.profilePath)).some(candidate => isDeepStrictEqual(candidate, rule));
120
+ if (live !== undefined)
121
+ return live.hookAllowed(rule);
122
+ return loadedHookPolicy !== undefined && effectiveMcpHookRules(loadedHookPolicy, readSelectedMultiSessionPolicy(loadedHookPolicy.profilePath)).some(candidate => isDeepStrictEqual(candidate, rule));
114
123
  } }),
115
124
  });
116
125
  const hookAudit = hookRunner.snapshot();
117
126
  console.error(`CE_HOOKS_ACTIVE active=${hookAudit.active} configured=${hookAudit.configured} rules=${hookAudit.rules.filter(rule => rule.enabled).map(rule => rule.id).join(",") || "none"}`);
118
- const host = new CeEndpointHost(openBindingStore(config), {
127
+ const store = openBindingStore(config);
128
+ const host = new CeEndpointHost(store, {
119
129
  adapter: config.endpoint.adapter,
120
130
  allowlist: [{ endpointId: config.endpoint.endpointId }],
121
131
  recipients: config.recipients,
132
+ ...(live === undefined ? {} : { liveRecipients: live.recipients }),
122
133
  exchangeNamespace: config.exchange.namespace,
123
134
  exchangeIdempotencyKey: config.exchange.idempotencyKey,
124
135
  leaseTtlSeconds: config.lease.ttlSeconds,
@@ -142,63 +153,103 @@ async function main() {
142
153
  },
143
154
  });
144
155
  debugEvent("authority", "OWNERSHIP_ACQUIRED", { owned: true });
145
- // HANDOFF-CE-E2B-01: advertise `ce_ack` only when the validated binding
146
- // declares the ack opt-in; the default surface stays exactly four tools.
147
- const server = createExchangeMcpServer(undefined, {
148
- port: bound, ackEnabled: config.ack.enabled, executionGuard: config.debugExecutionGuard,
149
- ...(admission === undefined ? {} : { admission: () => admission({ kind: "inbox" }) }),
150
- });
151
- if (config.debugExecutionGuard.enabled) {
152
- debugEvent("server", "EXECUTION_GUARD_ARMED", { scope: "tools/call", stage: "unified-dispatch-entry" });
156
+ let probe;
157
+ try {
158
+ if (live !== undefined) {
159
+ try {
160
+ const output = execFileSync("/bin/ps", ["-p", String(process.pid), "-o", "lstart="], {
161
+ env: { PATH: "/usr/bin:/bin", LC_ALL: "C" }, timeout: 5000, maxBuffer: 4096, encoding: "utf8",
162
+ });
163
+ const match = /^\s*([A-Za-z]{3}\s+[A-Za-z]{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s*$/.exec(output);
164
+ if (match === null)
165
+ throw new Error("process identity unavailable");
166
+ probe = await startLiveAdoptionProbe({ ref: live.ref, launchDigest,
167
+ identity: { pid: process.pid, startedKey: match[1] },
168
+ observe: () => observeLiveMcpRuntime(live, host, bound, store, config.endpoint.endpointId), });
169
+ }
170
+ catch {
171
+ // Local observation is advisory. Unsupported socket paths/identity cannot
172
+ // attest readiness, but do not revoke an otherwise valid messaging port.
173
+ console.error("CE_MCP_ADOPTION_UNVERIFIED");
174
+ }
175
+ }
176
+ // HANDOFF-CE-E2B-01: advertise `ce_ack` only when the validated binding
177
+ // declares the ack opt-in; the default surface stays exactly four tools.
178
+ const server = createExchangeMcpServer(undefined, {
179
+ port: bound, ackEnabled: config.ack.enabled, executionGuard: config.debugExecutionGuard,
180
+ ...(live === undefined
181
+ ? admission === undefined ? {} : { admission: () => admission({ kind: "inbox" }) }
182
+ : { discovery: { discover: () => projectEndpointDiscovery(bound.discover()) } }),
183
+ });
184
+ if (config.debugExecutionGuard.enabled) {
185
+ debugEvent("server", "EXECUTION_GUARD_ARMED", { scope: "tools/call", stage: "unified-dispatch-entry" });
186
+ }
187
+ const transport = observeTransport(new StdioServerTransport());
188
+ debugEvent("server", "TRANSPORT_CREATED");
189
+ let initiated = false;
190
+ const initiateShutdown = async () => {
191
+ if (initiated)
192
+ return;
193
+ initiated = true;
194
+ await probe?.close();
195
+ try {
196
+ await server.close();
197
+ }
198
+ catch {
199
+ // Transport already gone; the lease release below is what matters.
200
+ }
201
+ const hookCleanup = hookRunner.close();
202
+ const shutdown = await bound.shutdown();
203
+ debugEvent("authority", "OWNERSHIP_RELEASED", { released: shutdown.released, detached: shutdown.detached });
204
+ console.error(shutdown.released
205
+ ? `CE_MCP_STOPPED released=true detached=${shutdown.detached}`
206
+ : `CE_MCP_STOPPED released=false code=${shutdown.code ?? "CE_HOST_UNAVAILABLE"}`);
207
+ await hookCleanup;
208
+ };
209
+ let resolveShutdown;
210
+ const shutdownRequested = new Promise((resolvePromise) => {
211
+ resolveShutdown = resolvePromise;
212
+ });
213
+ const requestShutdown = () => resolveShutdown();
214
+ // `on`, not `once`: a repeat SIGTERM/SIGINT during the drain window must be
215
+ // absorbed by this idempotent request instead of hitting Node's default
216
+ // disposition and killing the process before the lease is released.
217
+ process.on("SIGTERM", () => { debugEvent("process", "PROCESS_SIGNAL", { signal: "SIGTERM" }); requestShutdown(); });
218
+ process.on("SIGINT", () => { debugEvent("process", "PROCESS_SIGNAL", { signal: "SIGINT" }); requestShutdown(); });
219
+ process.stdin.once("end", requestShutdown);
220
+ process.stdin.once("close", requestShutdown);
221
+ server.onclose = requestShutdown;
222
+ await server.connect(transport);
223
+ debugEvent("server", "TRANSPORT_CONNECTED");
224
+ debugEvent("server", "SERVER_READY", { mode: "bound" });
225
+ // HANDOFF-CE-E2B-01: the diagnostic mirrors exactly what the server above
226
+ // advertises for this binding (same construction, same order) — ce_ack
227
+ // appears only when the operator ack opt-in is enabled.
228
+ const advertisedTools = [
229
+ PING_TOOL_NAME,
230
+ ...MESSAGING_TOOL_NAMES,
231
+ ...(config.ack.enabled ? [CE_ACK_TOOL.name] : []),
232
+ ...(live === undefined ? [] : ["ce_endpoints"]),
233
+ ];
234
+ console.error(`CE_MCP_STARTED tools=${advertisedTools.join(",")}`);
235
+ await shutdownRequested;
236
+ await initiateShutdown();
153
237
  }
154
- const transport = observeTransport(new StdioServerTransport());
155
- debugEvent("server", "TRANSPORT_CREATED");
156
- let initiated = false;
157
- const initiateShutdown = async () => {
158
- if (initiated)
159
- return;
160
- initiated = true;
238
+ finally {
161
239
  try {
162
- await server.close();
240
+ await probe?.close();
163
241
  }
164
- catch {
165
- // Transport already gone; the lease release below is what matters.
242
+ finally {
243
+ const hooks = hookRunner.close();
244
+ try {
245
+ await bound.shutdown();
246
+ }
247
+ finally {
248
+ await hooks;
249
+ store.close();
250
+ }
166
251
  }
167
- const hookCleanup = hookRunner.close();
168
- const shutdown = await bound.shutdown();
169
- debugEvent("authority", "OWNERSHIP_RELEASED", { released: shutdown.released, detached: shutdown.detached });
170
- console.error(shutdown.released
171
- ? `CE_MCP_STOPPED released=true detached=${shutdown.detached}`
172
- : `CE_MCP_STOPPED released=false code=${shutdown.code ?? "CE_HOST_UNAVAILABLE"}`);
173
- await hookCleanup;
174
- };
175
- let resolveShutdown;
176
- const shutdownRequested = new Promise((resolvePromise) => {
177
- resolveShutdown = resolvePromise;
178
- });
179
- const requestShutdown = () => resolveShutdown();
180
- // `on`, not `once`: a repeat SIGTERM/SIGINT during the drain window must be
181
- // absorbed by this idempotent request instead of hitting Node's default
182
- // disposition and killing the process before the lease is released.
183
- process.on("SIGTERM", () => { debugEvent("process", "PROCESS_SIGNAL", { signal: "SIGTERM" }); requestShutdown(); });
184
- process.on("SIGINT", () => { debugEvent("process", "PROCESS_SIGNAL", { signal: "SIGINT" }); requestShutdown(); });
185
- process.stdin.once("end", requestShutdown);
186
- process.stdin.once("close", requestShutdown);
187
- server.onclose = requestShutdown;
188
- await server.connect(transport);
189
- debugEvent("server", "TRANSPORT_CONNECTED");
190
- debugEvent("server", "SERVER_READY", { mode: "bound" });
191
- // HANDOFF-CE-E2B-01: the diagnostic mirrors exactly what the server above
192
- // advertises for this binding (same construction, same order) — ce_ack
193
- // appears only when the operator ack opt-in is enabled.
194
- const advertisedTools = [
195
- PING_TOOL_NAME,
196
- ...MESSAGING_TOOL_NAMES,
197
- ...(config.ack.enabled ? [CE_ACK_TOOL.name] : []),
198
- ];
199
- console.error(`CE_MCP_STARTED tools=${advertisedTools.join(",")}`);
200
- await shutdownRequested;
201
- await initiateShutdown();
252
+ }
202
253
  }
203
254
  main().catch((error) => {
204
255
  debugEvent("server", "MCP_ERROR", { stage: "startup", ...errorSummary(error) });
@@ -0,0 +1,60 @@
1
+ /** Optional caller-bound, read-only discovery. Composition owns visibility filtering
2
+ * before observation and computes the digest from only this visible projection. */
3
+ import { Type } from "@sinclair/typebox";
4
+ import { Value } from "@sinclair/typebox/value";
5
+ import { ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
6
+ export const CE_ENDPOINTS_TOOL_NAME = "ce_endpoints";
7
+ const closed = { additionalProperties: false };
8
+ const identity = {
9
+ adapter: Type.String({ minLength: 1, maxLength: 64 }),
10
+ endpointId: Type.String({ minLength: 1, maxLength: 256 }),
11
+ };
12
+ const state = Type.Union([Type.Literal("true"), Type.Literal("false"), Type.Literal("unknown")]);
13
+ export const EndpointDiscoveryResultSchema = Type.Object({
14
+ self: Type.Object({
15
+ ...identity,
16
+ ownCapabilities: Type.Object({ send: Type.Boolean(), inbox: Type.Boolean(), payloadRead: Type.Boolean(), ack: Type.Boolean() }, closed),
17
+ }, closed),
18
+ targets: Type.Array(Type.Object({
19
+ ...identity,
20
+ registered: Type.Literal(true),
21
+ authorized: Type.Object({ send: Type.Literal(true) }, closed),
22
+ active: state,
23
+ reachable: state,
24
+ reason: Type.Union([
25
+ Type.Literal("AVAILABLE"), Type.Literal("NOT_JOINED"), Type.Literal("INACTIVE"),
26
+ Type.Literal("PRESENCE_WITHHELD"), Type.Literal("OBSERVATION_UNKNOWN"),
27
+ Type.Literal("MCP_OPERATION_BLOCKED"),
28
+ ]),
29
+ }, closed), { maxItems: 128 }),
30
+ observedAt: Type.String({ pattern: "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}Z$" }),
31
+ viewDigest: Type.String({ pattern: "^[0-9a-f]{64}$" }),
32
+ }, closed);
33
+ const argsSchema = Type.Object({}, closed);
34
+ export const CE_ENDPOINTS_TOOL = {
35
+ name: CE_ENDPOINTS_TOOL_NAME,
36
+ description: "Read this caller's own identity and authorized exact targets. Advisory observations only; sends recheck authority. Ambiguous targets require explicit user selection.",
37
+ inputSchema: { ...argsSchema },
38
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
39
+ };
40
+ export function callEndpointDiscovery(port, args) {
41
+ if (!Value.Check(argsSchema, args)) {
42
+ throw new McpError(ErrorCode.InvalidParams, "endpoint discovery takes no arguments");
43
+ }
44
+ try {
45
+ // Snapshot once into plain JSON, then validate the exact bytes to be exposed.
46
+ // This also prevents custom serialization from bypassing the closed schema.
47
+ const text = JSON.stringify(port.discover());
48
+ const result = JSON.parse(text);
49
+ if (!Value.Check(EndpointDiscoveryResultSchema, result))
50
+ throw new Error();
51
+ const time = new Date(result.observedAt);
52
+ if (!Number.isFinite(time.getTime()) || time.toISOString() !== result.observedAt)
53
+ throw new Error();
54
+ return { content: [{ type: "text", text }], structuredContent: result, isError: false };
55
+ }
56
+ catch {
57
+ throw new McpError(ErrorCode.InternalError, "endpoint discovery unavailable");
58
+ }
59
+ }
60
+ //# sourceMappingURL=endpoint-discovery.js.map
@@ -26,7 +26,7 @@ export const MESSAGING_TOOL_NAMES = [CE_SEND_TOOL_NAME, CE_INBOX_LIST_TOOL_NAME,
26
26
  export const CE_ACK_TOOL_NAME = "ce_ack";
27
27
  const closed = { additionalProperties: false };
28
28
  export const SendArgsSchema = Type.Object({
29
- to: Type.String({ minLength: 1, maxLength: 256, description: "Recipient label authorized by the local operator configuration" }),
29
+ to: Type.String({ minLength: 1, maxLength: 256, description: "Exact recipient label selected from a fresh ce_endpoints result in live mode; do not infer the latest Session" }),
30
30
  text: Type.String({ minLength: 1, description: "Text to deliver; stored as the private payload" }),
31
31
  idempotencyKey: Type.String({ minLength: 1, maxLength: 256, description: "Stable key; a replay returns the original record" }),
32
32
  }, closed);
@@ -57,7 +57,10 @@ export const MESSAGING_TOOLS = [
57
57
  name: CE_SEND_TOOL_NAME,
58
58
  description: "Send one durable chat-exchange item from this server's fixed, operator-configured endpoint to an " +
59
59
  "operator-authorized recipient label. Idempotent by idempotencyKey. The sender is never a parameter. " +
60
- "If the result is CE_HOST_UNCERTAIN the outcome is unknown: do not retry; ask the operator to inspect.",
60
+ "In live mode, call ce_endpoints before choosing a recipient. Do not reuse a recipient label from an " +
61
+ "earlier conversation; ambiguous targets require explicit user selection. CREATED/REPLAYED does not prove " +
62
+ "receiver reading or task completion. If the result is CE_HOST_UNCERTAIN the outcome is unknown: do not " +
63
+ "retry; ask the operator to inspect.",
61
64
  inputSchema: { ...SendArgsSchema },
62
65
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
63
66
  },
@@ -109,6 +112,13 @@ function refusalOf(error) {
109
112
  }
110
113
  function refusalResult(error) {
111
114
  const refusal = refusalOf(error);
115
+ if (refusal.reason === "MESSAGE_READ_REJECTED") {
116
+ return {
117
+ content: [{ type: "text", text: "chat-exchange message read rejected (MESSAGE_READ_REJECTED): this endpoint is not eligible for the message" }],
118
+ structuredContent: { code: refusal.code, reason: refusal.reason, retryable: refusal.retryable },
119
+ isError: true,
120
+ };
121
+ }
112
122
  const guidance = refusal.code === "CE_HOST_UNCERTAIN"
113
123
  ? "; outcome unknown \u2014 do not retry, the operator must inspect durable state"
114
124
  : refusal.retryable ? "; rolled back, safe to retry the whole request" : "";
@@ -22,8 +22,9 @@ import { argumentShape, debugEvent, errorSummary } from "../debug-log.js";
22
22
  import { observeTransport } from "./debug-transport.js";
23
23
  import { PING_TOOL_NAME, PingArgsSchema, PingResultSchema, defaultHostLabel, ping } from "./ping.js";
24
24
  import { callMessagingTool, CE_ACK_TOOL, isAckToolName, isMessagingToolName, MESSAGING_TOOLS, } from "./messaging-tools.js";
25
+ import { callEndpointDiscovery, CE_ENDPOINTS_TOOL, CE_ENDPOINTS_TOOL_NAME } from "./endpoint-discovery.js";
25
26
  export const SERVER_NAME = "pi-chat-exchange";
26
- export const SERVER_VERSION = "0.3.0";
27
+ export const SERVER_VERSION = "0.3.1";
27
28
  const PING_TOOL = {
28
29
  name: PING_TOOL_NAME,
29
30
  description: "Read-only liveness probe for the pi-chat-exchange service. " +
@@ -46,7 +47,8 @@ export function createExchangeMcpServer(hostLabel = defaultHostLabel(), messagin
46
47
  const tools = messaging === undefined ? [PING_TOOL] : [PING_TOOL, ...MESSAGING_TOOLS];
47
48
  // HANDOFF-CE-E2B-01: `ce_ack` is advertised last, and only on the explicit
48
49
  // operator ack opt-in carried by the binding.
49
- const advertised = messaging?.ackEnabled === true ? [...tools, CE_ACK_TOOL] : tools;
50
+ const withAck = messaging?.ackEnabled === true ? [...tools, CE_ACK_TOOL] : tools;
51
+ const advertised = messaging?.discovery === undefined ? withAck : [...withAck, CE_ENDPOINTS_TOOL];
50
52
  for (const tool of advertised)
51
53
  debugEvent("tool", "TOOL_REGISTERED", { tool: tool.name });
52
54
  const admit = () => {
@@ -87,6 +89,12 @@ export function createExchangeMcpServer(hostLabel = defaultHostLabel(), messagin
87
89
  try {
88
90
  // HANDOFF-CE-E2B-01: `ce_ack` exists only behind the explicit opt-in; a
89
91
  // call without it fails closed exactly like an unadvertised tool.
92
+ if (name === CE_ENDPOINTS_TOOL_NAME) {
93
+ if (messaging?.discovery === undefined) {
94
+ throw new McpError(ErrorCode.MethodNotFound, `unknown tool: ${String(name)}`);
95
+ }
96
+ return callEndpointDiscovery(messaging.discovery, args ?? {});
97
+ }
90
98
  if (isAckToolName(name)) {
91
99
  if (messaging === undefined || messaging.ackEnabled !== true) {
92
100
  // Never advertised in this mode, but fail closed all the same.
@@ -19,6 +19,7 @@
19
19
  * heartbeat, then `host.end` (release, then detach) exactly once. An unknown
20
20
  * outcome is reported, never retried.
21
21
  */
22
+ import { createHash } from "node:crypto";
22
23
  import { CeHostRefusal, } from "./endpoint-host.js";
23
24
  const defaultTimers = {
24
25
  setInterval: (callback, ms) => {
@@ -53,8 +54,7 @@ export class CeBoundEndpoint {
53
54
  if (!Number.isSafeInteger(options.renewIntervalMs) || options.renewIntervalMs < 1) {
54
55
  throw new CeHostRefusal("CE_HOST_INVALID_REQUEST");
55
56
  }
56
- options.admission?.({ kind: "begin" });
57
- host.beginSession(endpointId, { requireUnowned: true });
57
+ host.runWithRecipientSnapshot(snapshot => options.admission?.({ kind: "begin" }, snapshot), () => host.beginSession(endpointId, { requireUnowned: true }));
58
58
  const bound = new CeBoundEndpoint(host, endpointId, options);
59
59
  bound.#heartbeat = bound.#timers.setInterval(() => bound.#renew(), options.renewIntervalMs);
60
60
  return bound;
@@ -62,6 +62,21 @@ export class CeBoundEndpoint {
62
62
  get state() {
63
63
  return this.#state;
64
64
  }
65
+ operationalStatus() {
66
+ return Object.freeze({ state: this.#state, renewal: this.#heartbeat === undefined ? "STOPPED" : "RUNNING" });
67
+ }
68
+ discover() {
69
+ return this.#run(false, { kind: "discover" }, () => {
70
+ const discovery = this.#host.discover(this.#endpointId);
71
+ if (this.#state !== "WRITE_BLOCKED")
72
+ return discovery;
73
+ const targets = Object.freeze(discovery.targets.map(target => target.reason === "PRESENCE_WITHHELD"
74
+ ? target
75
+ : Object.freeze({ ...target, reachable: "FALSE", reason: "PORT_BLOCKED" })));
76
+ const projection = { self: { ...discovery.self, effective: { ...discovery.self.effective, send: false, ack: false } }, targets };
77
+ return Object.freeze({ ...discovery, ...projection, viewDigest: createHash("sha256").update(JSON.stringify(projection)).digest("hex") });
78
+ });
79
+ }
65
80
  #emit(event) {
66
81
  try {
67
82
  this.#onEvent?.(event);
@@ -80,8 +95,7 @@ export class CeBoundEndpoint {
80
95
  if (this.#state !== "ACTIVE")
81
96
  return;
82
97
  try {
83
- this.#admission?.({ kind: "renew" });
84
- this.#host.renew(this.#endpointId);
98
+ this.#host.runWithRecipientSnapshot(snapshot => this.#admission?.({ kind: "renew" }, snapshot), () => this.#host.renew(this.#endpointId));
85
99
  this.#emit({ kind: "renewed" });
86
100
  }
87
101
  catch (error) {
@@ -108,10 +122,9 @@ export class CeBoundEndpoint {
108
122
  }
109
123
  #run(write, request, operation) {
110
124
  this.#admit(write);
111
- this.#admission?.(request);
112
125
  this.#inFlight += 1;
113
126
  try {
114
- return operation();
127
+ return this.#host.runWithRecipientSnapshot(snapshot => this.#admission?.(request, snapshot), operation);
115
128
  }
116
129
  finally {
117
130
  this.#inFlight -= 1;
@@ -33,6 +33,7 @@
33
33
  * for CE-TAKEOVER-RECOVERY-CALLER-001 is not reachable through this adapter.
34
34
  * Restart never implies ownership recovery.
35
35
  */
36
+ import { createHash } from "node:crypto";
36
37
  import { EXCHANGE_ID_PATTERN, MESSAGE_ID_PATTERN } from "../protocol/identity.js";
37
38
  import { SHA256_HEX_PATTERN } from "../protocol/entities.js";
38
39
  import { createCommittedMessageEvent } from "../hooks/events.js";
@@ -45,7 +46,7 @@ import { readMessageMetadata, readMessagePayload, sendMessage, } from "../storag
45
46
  import { discoverInboxMessages } from "../storage/inbox-discovery.js";
46
47
  import { captureFields, isParticipantId, isSessionId, ParticipantRequestError, } from "../storage/participant-identity.js";
47
48
  import { createParticipant, ParticipantDomainError, issueCapability, joinExchange, readParticipantByEndpoint, } from "../storage/participant.js";
48
- import { acquireOwnership, bindSession, detachSession, generateSessionId, LEASE_DEFAULT_TTL_SECONDS, LEASE_MAX_TTL_SECONDS, LEASE_MIN_TTL_SECONDS, readCurrentOwnership, readLeaseStatus, readSessionLifecycle, releaseOwnership, renewLease, } from "../storage/ownership.js";
49
+ import { acquireOwnership, bindSession, detachSession, generateSessionId, LEASE_DEFAULT_TTL_SECONDS, LEASE_MAX_TTL_SECONDS, LEASE_MIN_TTL_SECONDS, readCurrentOwnership, readEndpointObservations, readLeaseStatus, readSessionLifecycle, releaseOwnership, renewLease, } from "../storage/ownership.js";
49
50
  import { StorageTransactionError } from "../storage/transaction.js";
50
51
  const REFUSAL_DETAIL = {
51
52
  CE_HOST_ENDPOINT_NOT_ALLOWED: "endpoint is not in the host allowlist",
@@ -233,9 +234,12 @@ export class CeEndpointHost {
233
234
  #ackEnabled;
234
235
  /** Explicit cross-adapter recipients, validated and frozen at construction. */
235
236
  #recipients;
237
+ #liveRecipients;
236
238
  #seams;
237
239
  #onMessageCommitted;
238
240
  #authorities = new Map();
241
+ #prepared;
242
+ #preparing = false;
239
243
  constructor(store, policy) {
240
244
  if (!isEndpointLabel(policy.adapter, ADAPTER_MAX_LENGTH))
241
245
  throw new CeHostRefusal("CE_HOST_INVALID_REQUEST");
@@ -251,6 +255,10 @@ export class CeEndpointHost {
251
255
  seen.add(entry.endpointId);
252
256
  }
253
257
  this.#recipients = validatedRecipients(policy, seen);
258
+ if (policy.liveRecipients !== undefined && typeof policy.liveRecipients.snapshot !== "function") {
259
+ throw new CeHostRefusal("CE_HOST_INVALID_REQUEST");
260
+ }
261
+ this.#liveRecipients = policy.liveRecipients;
254
262
  this.#store = store;
255
263
  this.#policy = policy;
256
264
  this.#leaseTtlSeconds = clampLeaseTtl(policy);
@@ -276,11 +284,46 @@ export class CeEndpointHost {
276
284
  /** Resolve a recipient label: an allowlisted same-adapter Endpoint first,
277
285
  * otherwise an explicitly configured cross-adapter recipient. Any other
278
286
  * label is refused exactly like before (`CE_HOST_ENDPOINT_NOT_ALLOWED`). */
279
- #recipient(label) {
287
+ /** One synchronous policy selection shared by outer admission and the Host
288
+ * operation. No async or reentrant operation may retain this authority. */
289
+ runWithRecipientSnapshot(admit, operation) {
290
+ if (this.#preparing)
291
+ throw new CeHostRefusal("CE_HOST_UNAVAILABLE", false, "RECIPIENT_SNAPSHOT_REENTRANT");
292
+ this.#preparing = true;
293
+ try {
294
+ this.#prepared = this.#readSnapshot();
295
+ admit(this.#prepared);
296
+ return operation();
297
+ }
298
+ finally {
299
+ this.#prepared = undefined;
300
+ this.#preparing = false;
301
+ }
302
+ }
303
+ #snapshot() {
304
+ if (this.#preparing)
305
+ return this.#prepared;
306
+ return this.#readSnapshot();
307
+ }
308
+ #readSnapshot() {
309
+ if (this.#liveRecipients === undefined)
310
+ return undefined;
311
+ try {
312
+ const snapshot = this.#liveRecipients.snapshot();
313
+ const recipients = validatedRecipients({ ...this.#policy, recipients: snapshot.recipients }, new Set(this.#policy.allowlist.map(entry => entry.endpointId)));
314
+ if (recipients.length > 128)
315
+ throw new CeHostRefusal("CE_HOST_UNAVAILABLE");
316
+ return { ...snapshot, recipients };
317
+ }
318
+ catch (error) {
319
+ throw toRefusal(error);
320
+ }
321
+ }
322
+ #recipient(label, snapshot) {
280
323
  if (this.#policy.allowlist.some((candidate) => candidate.endpointId === label)) {
281
324
  return { adapter: this.#policy.adapter, endpointId: label };
282
325
  }
283
- const external = this.#recipients.find((candidate) => candidate.endpointId === label);
326
+ const external = (snapshot?.recipients ?? this.#recipients).find((candidate) => candidate.endpointId === label);
284
327
  if (external === undefined)
285
328
  throw new CeHostRefusal("CE_HOST_ENDPOINT_NOT_ALLOWED");
286
329
  return external;
@@ -556,7 +599,8 @@ export class CeEndpointHost {
556
599
  if (typeof to !== "string" || to.length === 0 || to.length > 256) {
557
600
  throw new CeHostRefusal("CE_HOST_INVALID_REQUEST");
558
601
  }
559
- const recipient = this.#recipient(to);
602
+ const snapshot = this.#snapshot();
603
+ const recipient = this.#recipient(to, snapshot);
560
604
  if (typeof text !== "string" || text.length === 0)
561
605
  throw new CeHostRefusal("CE_HOST_INVALID_REQUEST");
562
606
  if (typeof idempotencyKey !== "string" || idempotencyKey.length === 0 || idempotencyKey.length > 256) {
@@ -568,6 +612,12 @@ export class CeEndpointHost {
568
612
  let creation;
569
613
  try {
570
614
  const fencingToken = this.#currentFencing(authority);
615
+ if (snapshot !== undefined) {
616
+ // Check the caller before exposing a target's membership state.
617
+ const observation = readEndpointObservations(this.#store, authority.exchangeId, [recipient], this.#seams);
618
+ if (!observation.targets[0]?.joined)
619
+ throw new CeHostRefusal("CE_HOST_UNAVAILABLE", false, "PARTICIPANT_NOT_MEMBER");
620
+ }
571
621
  creation = sendMessage(this.#store, {
572
622
  participantId: authority.participantId,
573
623
  sessionId: authority.sessionId,
@@ -804,6 +854,30 @@ export class CeEndpointHost {
804
854
  throw toRefusal(error);
805
855
  }
806
856
  }
857
+ /** Caller-bound advisory projection. Filter before any durable observation. */
858
+ discover(endpointId) {
859
+ this.#allowlisted(endpointId);
860
+ const authority = this.#authority(endpointId);
861
+ this.#currentFencing(authority);
862
+ const snapshot = this.#snapshot();
863
+ if (snapshot === undefined)
864
+ throw new CeHostRefusal("CE_HOST_UNAVAILABLE");
865
+ const visible = snapshot.recipients.filter(recipient => recipient.endpointId !== endpointId);
866
+ const disclosed = visible.filter(recipient => snapshot.presence.some(entry => entry.endpointId === recipient.endpointId && entry.disclose));
867
+ let observation;
868
+ try {
869
+ observation = readEndpointObservations(this.#store, authority.exchangeId, disclosed, this.#seams);
870
+ }
871
+ catch { /* Advisory uncertainty grants nothing. */ }
872
+ const targets = visible.map(recipient => {
873
+ const disclose = disclosed.some(entry => entry.endpointId === recipient.endpointId);
874
+ const observed = observation?.targets.find(entry => entry.adapter === recipient.adapter && entry.endpointId === recipient.endpointId);
875
+ return Object.freeze({ ...recipient, registered: true, authorized: Object.freeze({ send: true }), active: observed?.active ?? "UNKNOWN", reachable: observed === undefined ? "UNKNOWN" : observed.joined ? "TRUE" : "FALSE", reason: !disclose ? "PRESENCE_WITHHELD" : observed === undefined ? "OBSERVATION_UNKNOWN" : "OBSERVED" });
876
+ });
877
+ const self = Object.freeze({ adapter: this.#policy.adapter, endpointId, effective: Object.freeze({ send: true, readPayload: this.#payloadReadEnabled && (snapshot.ownPolicy?.payloadRead ?? true), ack: this.#ackEnabled && (snapshot.ownPolicy?.ack ?? true) }) });
878
+ const projection = { self, targets: Object.freeze(targets) };
879
+ return Object.freeze({ ...projection, observedAt: observation?.observedAt ?? "UNKNOWN", viewDigest: createHash("sha256").update(JSON.stringify(projection)).digest("hex") });
880
+ }
807
881
  /** Advisory status for the operator command. Authorizes nothing. */
808
882
  status(endpointId) {
809
883
  const authority = this.#authorities.get(endpointId);