@zieglar/pi-chat-exchange 0.2.2 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -7
- package/dist/bin/mcp-stdio.js +124 -56
- package/dist/control/mcp/endpoint-discovery.js +60 -0
- package/dist/control/mcp/messaging-tools.js +12 -2
- package/dist/control/mcp/server.js +10 -2
- package/dist/hooks/config.js +106 -0
- package/dist/hooks/events.js +19 -0
- package/dist/hooks/runner.js +187 -0
- package/dist/host/bound-endpoint.js +19 -6
- package/dist/host/endpoint-host.js +92 -4
- package/dist/host/mcp-binding-config.js +41 -5
- package/dist/runtime/native-readiness.js +8 -5
- package/dist/storage/creation.js +16 -0
- package/dist/storage/ownership.js +45 -1
- package/dist/tunnel/background-authorization.js +343 -0
- package/dist/tunnel/background-manager.js +104 -8
- package/dist/tunnel/background-scope.js +69 -0
- package/dist/tunnel/codes.js +1 -1
- package/dist/tunnel/hooks-management-ui.js +225 -0
- package/dist/tunnel/hooks-management.js +431 -0
- package/dist/tunnel/live-adoption-observation.js +136 -0
- package/dist/tunnel/live-adoption-probe.js +240 -0
- package/dist/tunnel/live-connection-status.js +136 -0
- package/dist/tunnel/live-mcp-composition.js +143 -0
- package/dist/tunnel/live-process-observation.js +98 -0
- package/dist/tunnel/live-session-migration.js +169 -0
- package/dist/tunnel/live-session-policy.js +578 -0
- package/dist/tunnel/manager-panel.js +4 -2
- package/dist/tunnel/manager-ui.js +71 -15
- package/dist/tunnel/multi-session-admission.js +1 -1
- package/dist/tunnel/multi-session-policy.js +45 -13
- package/dist/tunnel/setup-ui.js +2 -4
- package/dist/tunnel/status-ui.js +34 -0
- package/package.json +4 -1
- package/pi-extension/allowlist.example.json +12 -1
- package/pi-extension/desktop-target.ts +157 -0
- package/pi-extension/index.ts +1128 -132
- package/pi-extension/live-session-profile.ts +49 -0
- package/pi-extension/live-session-runtime.ts +59 -0
- package/pi-extension/multi-session-commands.ts +114 -3
- package/pi-extension/multi-session-runtime.ts +63 -11
- package/pi-extension/native-inbound.ts +235 -0
- package/pi-extension/ownership-feedback.ts +100 -0
- package/pi-extension/session-onboarding.ts +154 -0
- package/pi-extension/session-recovery.ts +214 -0
- package/skills/ce-hook-script/SKILL.md +62 -0
- package/skills/ce-hook-script/examples/file-notification.py +79 -0
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
|
-
|
|
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
|
|
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.
|
|
33
|
+
pi install npm:@zieglar/pi-chat-exchange@0.3.0
|
|
36
34
|
pi list
|
|
37
35
|
pi
|
|
38
36
|
```
|
|
@@ -48,19 +46,25 @@ 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
|
|
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
|
|
60
64
|
|
|
61
65
|
- [Native management](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/native-management.md) and [Native SQLite](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/native-sqlite.md).
|
|
62
66
|
- [Tunnel setup and troubleshooting](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/tunnel-setup.md).
|
|
63
|
-
- [Multiple Sessions](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/multi-session-usage.md), [Pi tools](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/pi-extension/README.md) and [ACK contract](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/delivery-ack-contract.md).
|
|
67
|
+
- [Multiple Sessions](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/multi-session-usage.md), [Pi tools](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/pi-extension/README.md), [local Hooks](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/hooks.md) and [ACK contract](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/delivery-ack-contract.md).
|
|
64
68
|
- [Operations / source development](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/operations.md). The prebuilt npm install needs no repository or compiler.
|
|
65
69
|
- [Independent Host / tarball installation](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/independent-install.md), with current0.2.1 alternatives and a separate historical0.2.0 record.
|
|
66
70
|
- [Architecture](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/architecture.md), [storage security](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/storage-security.md) and [bilingual documentation index](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/documentation.md).
|
package/dist/bin/mcp-stdio.js
CHANGED
|
@@ -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";
|
|
@@ -33,6 +36,10 @@ import { debugEvent, errorSummary } from "../control/debug-log.js";
|
|
|
33
36
|
import { observeTransport } from "../control/mcp/debug-transport.js";
|
|
34
37
|
import { initializeStore, openStore } from "../storage/store.js";
|
|
35
38
|
import { createMcpPolicyAdmission } from "../tunnel/multi-session-admission.js";
|
|
39
|
+
import { CeHookRunner } from "../hooks/runner.js";
|
|
40
|
+
import { isDeepStrictEqual } from "node:util";
|
|
41
|
+
import { effectiveMcpHookRules, readLoadedMultiSessionPolicy, readSelectedMultiSessionPolicy } from "../tunnel/multi-session-policy.js";
|
|
42
|
+
import { createLiveMcpComposition, projectEndpointDiscovery, observeLiveMcpRuntime } from "../tunnel/live-mcp-composition.js";
|
|
36
43
|
debugEvent("server", "SERVER_ENTRY", { version: process.version });
|
|
37
44
|
// Monitor rather than handle exceptions: preserve Node's fatal exit behavior.
|
|
38
45
|
process.on("uncaughtExceptionMonitor", (error, origin) => {
|
|
@@ -71,7 +78,7 @@ function loadBindingConfig(path) {
|
|
|
71
78
|
return fail("CE_MCP_CONFIG_INVALID", "config.not_json");
|
|
72
79
|
}
|
|
73
80
|
try {
|
|
74
|
-
return parseMcpBindingConfig(parsed);
|
|
81
|
+
return { config: parseMcpBindingConfig(parsed), launchDigest: createHash("sha256").update(raw).digest("hex") };
|
|
75
82
|
}
|
|
76
83
|
catch (error) {
|
|
77
84
|
if (error instanceof McpBindingConfigError)
|
|
@@ -97,19 +104,38 @@ async function main() {
|
|
|
97
104
|
if (argv.length !== 2 || flag !== "--config" || configPath === undefined || !configPath.startsWith("/")) {
|
|
98
105
|
fail("CE_MCP_LAUNCH_INVALID", "usage: mcp-stdio.js [--config /absolute/path.json]");
|
|
99
106
|
}
|
|
100
|
-
const config = loadBindingConfig(configPath);
|
|
107
|
+
const { config, launchDigest } = loadBindingConfig(configPath);
|
|
101
108
|
// Verify actual launch bytes before Store creation; managed provenance grants nothing.
|
|
102
|
-
const
|
|
103
|
-
|
|
104
|
-
const
|
|
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);
|
|
115
|
+
const hookRunner = new CeHookRunner({
|
|
116
|
+
directory: config.store.directory, rules: config.hooks ?? [],
|
|
117
|
+
...(loadedHookPolicy === undefined && live === undefined ? {} : { admit: (rule, event) => {
|
|
118
|
+
if (event !== undefined && (!isDeepStrictEqual(event.sender, config.endpoint) || !isDeepStrictEqual(event.recipient, rule.recipient)))
|
|
119
|
+
return false;
|
|
120
|
+
if (live !== undefined)
|
|
121
|
+
return live.hookAllowed(rule);
|
|
122
|
+
return loadedHookPolicy !== undefined && effectiveMcpHookRules(loadedHookPolicy, readSelectedMultiSessionPolicy(loadedHookPolicy.profilePath)).some(candidate => isDeepStrictEqual(candidate, rule));
|
|
123
|
+
} }),
|
|
124
|
+
});
|
|
125
|
+
const hookAudit = hookRunner.snapshot();
|
|
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"}`);
|
|
127
|
+
const store = openBindingStore(config);
|
|
128
|
+
const host = new CeEndpointHost(store, {
|
|
105
129
|
adapter: config.endpoint.adapter,
|
|
106
130
|
allowlist: [{ endpointId: config.endpoint.endpointId }],
|
|
107
131
|
recipients: config.recipients,
|
|
132
|
+
...(live === undefined ? {} : { liveRecipients: live.recipients }),
|
|
108
133
|
exchangeNamespace: config.exchange.namespace,
|
|
109
134
|
exchangeIdempotencyKey: config.exchange.idempotencyKey,
|
|
110
135
|
leaseTtlSeconds: config.lease.ttlSeconds,
|
|
111
136
|
payloadRead: { enabled: config.payloadRead.enabled },
|
|
112
137
|
ack: { enabled: config.ack.enabled },
|
|
138
|
+
onMessageCommitted: event => hookRunner.publish(event),
|
|
113
139
|
});
|
|
114
140
|
debugEvent("authority", "AUTHORITY_CHECK_STARTED", { stage: "requireUnowned" });
|
|
115
141
|
const bound = CeBoundEndpoint.start(host, config.endpoint.endpointId, {
|
|
@@ -127,61 +153,103 @@ async function main() {
|
|
|
127
153
|
},
|
|
128
154
|
});
|
|
129
155
|
debugEvent("authority", "OWNERSHIP_ACQUIRED", { owned: true });
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
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();
|
|
138
237
|
}
|
|
139
|
-
|
|
140
|
-
debugEvent("server", "TRANSPORT_CREATED");
|
|
141
|
-
let initiated = false;
|
|
142
|
-
const initiateShutdown = async () => {
|
|
143
|
-
if (initiated)
|
|
144
|
-
return;
|
|
145
|
-
initiated = true;
|
|
238
|
+
finally {
|
|
146
239
|
try {
|
|
147
|
-
await
|
|
240
|
+
await probe?.close();
|
|
148
241
|
}
|
|
149
|
-
|
|
150
|
-
|
|
242
|
+
finally {
|
|
243
|
+
const hooks = hookRunner.close();
|
|
244
|
+
try {
|
|
245
|
+
await bound.shutdown();
|
|
246
|
+
}
|
|
247
|
+
finally {
|
|
248
|
+
await hooks;
|
|
249
|
+
store.close();
|
|
250
|
+
}
|
|
151
251
|
}
|
|
152
|
-
|
|
153
|
-
debugEvent("authority", "OWNERSHIP_RELEASED", { released: shutdown.released, detached: shutdown.detached });
|
|
154
|
-
console.error(shutdown.released
|
|
155
|
-
? `CE_MCP_STOPPED released=true detached=${shutdown.detached}`
|
|
156
|
-
: `CE_MCP_STOPPED released=false code=${shutdown.code ?? "CE_HOST_UNAVAILABLE"}`);
|
|
157
|
-
};
|
|
158
|
-
let resolveShutdown;
|
|
159
|
-
const shutdownRequested = new Promise((resolvePromise) => {
|
|
160
|
-
resolveShutdown = resolvePromise;
|
|
161
|
-
});
|
|
162
|
-
const requestShutdown = () => resolveShutdown();
|
|
163
|
-
// `on`, not `once`: a repeat SIGTERM/SIGINT during the drain window must be
|
|
164
|
-
// absorbed by this idempotent request instead of hitting Node's default
|
|
165
|
-
// disposition and killing the process before the lease is released.
|
|
166
|
-
process.on("SIGTERM", () => { debugEvent("process", "PROCESS_SIGNAL", { signal: "SIGTERM" }); requestShutdown(); });
|
|
167
|
-
process.on("SIGINT", () => { debugEvent("process", "PROCESS_SIGNAL", { signal: "SIGINT" }); requestShutdown(); });
|
|
168
|
-
process.stdin.once("end", requestShutdown);
|
|
169
|
-
process.stdin.once("close", requestShutdown);
|
|
170
|
-
server.onclose = requestShutdown;
|
|
171
|
-
await server.connect(transport);
|
|
172
|
-
debugEvent("server", "TRANSPORT_CONNECTED");
|
|
173
|
-
debugEvent("server", "SERVER_READY", { mode: "bound" });
|
|
174
|
-
// HANDOFF-CE-E2B-01: the diagnostic mirrors exactly what the server above
|
|
175
|
-
// advertises for this binding (same construction, same order) — ce_ack
|
|
176
|
-
// appears only when the operator ack opt-in is enabled.
|
|
177
|
-
const advertisedTools = [
|
|
178
|
-
PING_TOOL_NAME,
|
|
179
|
-
...MESSAGING_TOOL_NAMES,
|
|
180
|
-
...(config.ack.enabled ? [CE_ACK_TOOL.name] : []),
|
|
181
|
-
];
|
|
182
|
-
console.error(`CE_MCP_STARTED tools=${advertisedTools.join(",")}`);
|
|
183
|
-
await shutdownRequested;
|
|
184
|
-
await initiateShutdown();
|
|
252
|
+
}
|
|
185
253
|
}
|
|
186
254
|
main().catch((error) => {
|
|
187
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: "
|
|
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
|
-
"
|
|
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.
|
|
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
|
|
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.
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { isAbsolute, normalize } from "node:path";
|
|
2
|
+
import { CE_MESSAGE_COMMITTED_EVENT } from "./events.js";
|
|
3
|
+
export const CE_HOOK_DEFAULT_TIMEOUT_MS = 30_000;
|
|
4
|
+
export const CE_HOOK_MIN_TIMEOUT_MS = 1_000;
|
|
5
|
+
export const CE_HOOK_MAX_TIMEOUT_MS = 60_000;
|
|
6
|
+
export class CeHookConfigError extends Error {
|
|
7
|
+
field;
|
|
8
|
+
code = "CE_HOOK_CONFIG_INVALID";
|
|
9
|
+
constructor(field) {
|
|
10
|
+
super(`CE_HOOK_CONFIG_INVALID at ${field}`);
|
|
11
|
+
this.field = field;
|
|
12
|
+
this.name = "CeHookConfigError";
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function refuse(field) {
|
|
16
|
+
throw new CeHookConfigError(field);
|
|
17
|
+
}
|
|
18
|
+
function fields(value, field, allowed, required) {
|
|
19
|
+
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
20
|
+
refuse(field);
|
|
21
|
+
const prototype = Object.getPrototypeOf(value);
|
|
22
|
+
if (prototype !== Object.prototype && prototype !== null)
|
|
23
|
+
refuse(field);
|
|
24
|
+
const result = {};
|
|
25
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
26
|
+
if (typeof key !== "string" || !allowed.includes(key))
|
|
27
|
+
refuse(field);
|
|
28
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
29
|
+
if (descriptor === undefined || !("value" in descriptor) || descriptor.enumerable !== true)
|
|
30
|
+
refuse(`${field}.${key}`);
|
|
31
|
+
result[key] = descriptor.value;
|
|
32
|
+
}
|
|
33
|
+
for (const key of required)
|
|
34
|
+
if (!Object.hasOwn(result, key))
|
|
35
|
+
refuse(`${field}.${key}`);
|
|
36
|
+
return result;
|
|
37
|
+
}
|
|
38
|
+
function text(value, field, maximum) {
|
|
39
|
+
if (typeof value !== "string" || value.length === 0 || value.length > maximum || /[\u0000-\u001f\u007f]/.test(value))
|
|
40
|
+
refuse(field);
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
function recipient(value, field) {
|
|
44
|
+
const input = fields(value, field, ["adapter", "endpointId"], ["adapter", "endpointId"]);
|
|
45
|
+
return Object.freeze({
|
|
46
|
+
adapter: text(input.adapter, `${field}.adapter`, 64),
|
|
47
|
+
endpointId: text(input.endpointId, `${field}.endpointId`, 256),
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
function command(value, field) {
|
|
51
|
+
const parsed = text(value, field, 4096);
|
|
52
|
+
if (!isAbsolute(parsed) || normalize(parsed) !== parsed || parsed === "/")
|
|
53
|
+
refuse(field);
|
|
54
|
+
return parsed;
|
|
55
|
+
}
|
|
56
|
+
function timeout(value, field) {
|
|
57
|
+
if (value === undefined)
|
|
58
|
+
return CE_HOOK_DEFAULT_TIMEOUT_MS;
|
|
59
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < CE_HOOK_MIN_TIMEOUT_MS || value > CE_HOOK_MAX_TIMEOUT_MS)
|
|
60
|
+
refuse(field);
|
|
61
|
+
return value;
|
|
62
|
+
}
|
|
63
|
+
/** Parse already-loaded local JSON. No file, environment, message or process input
|
|
64
|
+
* can supply a command; only this static configuration becomes execution authority. */
|
|
65
|
+
export function parseHookRules(raw) {
|
|
66
|
+
if (raw === undefined)
|
|
67
|
+
return Object.freeze([]);
|
|
68
|
+
if (!Array.isArray(raw) || raw.length > 64)
|
|
69
|
+
refuse("hooks");
|
|
70
|
+
const rules = [];
|
|
71
|
+
const ids = new Set();
|
|
72
|
+
for (const [index, value] of raw.entries()) {
|
|
73
|
+
const field = `hooks[${index}]`;
|
|
74
|
+
const input = fields(value, field, ["id", "event", "recipient", "command", "args", "timeoutMs", "enabled"], ["id", "event", "recipient", "command"]);
|
|
75
|
+
const id = text(input.id, `${field}.id`, 64);
|
|
76
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(id) || ids.has(id))
|
|
77
|
+
refuse(`${field}.id`);
|
|
78
|
+
ids.add(id);
|
|
79
|
+
if (input.event !== CE_MESSAGE_COMMITTED_EVENT)
|
|
80
|
+
refuse(`${field}.event`);
|
|
81
|
+
if (input.enabled !== undefined && typeof input.enabled !== "boolean")
|
|
82
|
+
refuse(`${field}.enabled`);
|
|
83
|
+
let args = Object.freeze([]);
|
|
84
|
+
if (input.args !== undefined) {
|
|
85
|
+
if (!Array.isArray(input.args) || input.args.length > 32)
|
|
86
|
+
refuse(`${field}.args`);
|
|
87
|
+
args = Object.freeze(input.args.map((arg, argIndex) => text(arg, `${field}.args[${argIndex}]`, 4096)));
|
|
88
|
+
}
|
|
89
|
+
rules.push(Object.freeze({
|
|
90
|
+
id,
|
|
91
|
+
event: CE_MESSAGE_COMMITTED_EVENT,
|
|
92
|
+
recipient: recipient(input.recipient, `${field}.recipient`),
|
|
93
|
+
command: command(input.command, `${field}.command`),
|
|
94
|
+
args,
|
|
95
|
+
timeoutMs: timeout(input.timeoutMs, `${field}.timeoutMs`),
|
|
96
|
+
enabled: input.enabled ?? true,
|
|
97
|
+
}));
|
|
98
|
+
}
|
|
99
|
+
return Object.freeze(rules);
|
|
100
|
+
}
|
|
101
|
+
export function matchesHookRule(rule, event) {
|
|
102
|
+
return rule.enabled && rule.event === event.event &&
|
|
103
|
+
rule.recipient.adapter === event.recipient.adapter &&
|
|
104
|
+
rule.recipient.endpointId === event.recipient.endpointId;
|
|
105
|
+
}
|
|
106
|
+
//# sourceMappingURL=config.js.map
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { generateEntityId } from "../protocol/identity.js";
|
|
2
|
+
export const CE_MESSAGE_COMMITTED_EVENT = "ce.message.committed.v1";
|
|
3
|
+
export function createCommittedMessageEvent(creation) {
|
|
4
|
+
const message = creation.message;
|
|
5
|
+
return Object.freeze({
|
|
6
|
+
schemaVersion: 1,
|
|
7
|
+
event: CE_MESSAGE_COMMITTED_EVENT,
|
|
8
|
+
eventId: generateEntityId("evt_", Date.parse(message.createdAt)),
|
|
9
|
+
eventKey: `${message.exchangeId}/${creation.auditSequence}`,
|
|
10
|
+
messageId: message.messageId,
|
|
11
|
+
exchangeId: message.exchangeId,
|
|
12
|
+
sender: Object.freeze({ ...message.from }),
|
|
13
|
+
recipient: Object.freeze({ ...message.to }),
|
|
14
|
+
createdAt: message.createdAt,
|
|
15
|
+
payloadDigest: message.payloadDigest,
|
|
16
|
+
payloadLength: message.payloadLength,
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
//# sourceMappingURL=events.js.map
|