@zieglar/pi-chat-exchange 0.0.0-stage → 0.2.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 (88) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +137 -2
  3. package/dist/bin/ce-native.js +119 -0
  4. package/dist/bin/mcp-stdio.js +196 -0
  5. package/dist/control/debug-log.js +67 -0
  6. package/dist/control/mcp/debug-transport.js +48 -0
  7. package/dist/control/mcp/messaging-tools.js +278 -0
  8. package/dist/control/mcp/ping.js +43 -0
  9. package/dist/control/mcp/server.js +153 -0
  10. package/dist/core/authorization.js +32 -0
  11. package/dist/core/reference.js +32 -0
  12. package/dist/core/rules.js +468 -0
  13. package/dist/endpoints/pi/contract.js +2 -0
  14. package/dist/endpoints/pi/session-host.js +39 -0
  15. package/dist/host/bound-endpoint.js +176 -0
  16. package/dist/host/endpoint-host.js +839 -0
  17. package/dist/host/mcp-binding-config.js +209 -0
  18. package/dist/host/ownership-recovery.js +257 -0
  19. package/dist/index.js +11 -0
  20. package/dist/protocol/capabilities.js +46 -0
  21. package/dist/protocol/endpoint-capabilities.js +15 -0
  22. package/dist/protocol/entities.js +185 -0
  23. package/dist/protocol/formats.js +13 -0
  24. package/dist/protocol/idempotency.js +93 -0
  25. package/dist/protocol/identity.js +130 -0
  26. package/dist/protocol/index.js +8 -0
  27. package/dist/protocol/lifecycle.js +125 -0
  28. package/dist/protocol/outcomes.js +55 -0
  29. package/dist/runtime/desktop-manifest.js +65 -0
  30. package/dist/runtime/diagnostics.js +34 -0
  31. package/dist/runtime/executables.js +217 -0
  32. package/dist/runtime/native-readiness.js +131 -0
  33. package/dist/storage/capability.js +221 -0
  34. package/dist/storage/connection.js +95 -0
  35. package/dist/storage/creation-request.js +176 -0
  36. package/dist/storage/creation.js +553 -0
  37. package/dist/storage/current-schema.js +397 -0
  38. package/dist/storage/delivery-ack.js +177 -0
  39. package/dist/storage/errors.js +9 -0
  40. package/dist/storage/filesystem.js +171 -0
  41. package/dist/storage/inbox-discovery.js +135 -0
  42. package/dist/storage/messaging.js +156 -0
  43. package/dist/storage/migration.js +258 -0
  44. package/dist/storage/native-artifact.js +234 -0
  45. package/dist/storage/native-compat.js +65 -0
  46. package/dist/storage/ownership.js +789 -0
  47. package/dist/storage/participant-identity.js +127 -0
  48. package/dist/storage/participant.js +700 -0
  49. package/dist/storage/recovery.js +99 -0
  50. package/dist/storage/runtime.js +256 -0
  51. package/dist/storage/schema.js +556 -0
  52. package/dist/storage/session-state.js +75 -0
  53. package/dist/storage/sqlite-driver-node.js +66 -0
  54. package/dist/storage/sqlite-driver-rust.js +121 -0
  55. package/dist/storage/sqlite-driver-selection.js +86 -0
  56. package/dist/storage/sqlite-driver.js +4 -0
  57. package/dist/storage/store.js +450 -0
  58. package/dist/storage/transaction.js +196 -0
  59. package/dist/storage/trust-root.js +164 -0
  60. package/dist/tunnel/background-manager.js +1727 -0
  61. package/dist/tunnel/codes.js +79 -0
  62. package/dist/tunnel/health.js +75 -0
  63. package/dist/tunnel/keychain.js +526 -0
  64. package/dist/tunnel/managed-binding.js +454 -0
  65. package/dist/tunnel/manager-panel.js +249 -0
  66. package/dist/tunnel/manager-ui.js +341 -0
  67. package/dist/tunnel/manager.js +372 -0
  68. package/dist/tunnel/messaging-activation-ui.js +85 -0
  69. package/dist/tunnel/messaging-config.js +246 -0
  70. package/dist/tunnel/multi-session-admission.js +31 -0
  71. package/dist/tunnel/multi-session-policy.js +314 -0
  72. package/dist/tunnel/offline-client.js +104 -0
  73. package/dist/tunnel/profile.js +319 -0
  74. package/dist/tunnel/redact.js +9 -0
  75. package/dist/tunnel/secure-input.js +318 -0
  76. package/dist/tunnel/session-process-mutex.js +338 -0
  77. package/dist/tunnel/setup-ui.js +443 -0
  78. package/dist/tunnel/setup.js +734 -0
  79. package/dist/tunnel/state.js +127 -0
  80. package/native/tunnel-keychain.swift +432 -0
  81. package/package.json +65 -4
  82. package/pi-extension/allowlist.example.json +11 -0
  83. package/pi-extension/index.ts +2346 -0
  84. package/pi-extension/multi-session-commands.ts +93 -0
  85. package/pi-extension/multi-session-runtime.ts +75 -0
  86. package/pi-extension/tui-keys.ts +40 -0
  87. package/scripts/reconcile-session-process-mutex.mjs +262 -0
  88. package/scripts/recover-stale-ownership.mjs +91 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 zieglar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,138 @@
1
- # Temporary Holding Version
1
+ # Pi Chat Exchange
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ English | [简体中文](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/README.zh-CN.md)
4
+
5
+ Pi Chat Exchange (CE) lets ChatGPT and Pi exchange durable messages through explicit tools. It stores messages, provides an authorized inbox, separates metadata from payload access, and records reception receipts (ACKs). Sending a message does not authorize its execution or prove task completion.
6
+
7
+ <a id="当前能力与典型用法"></a>
8
+
9
+ ## Features
10
+
11
+ - SQLite-backed messages with scoped idempotency keys and audit evidence.
12
+ - Independent permissions for sending, discovering messages, reading payloads and recording ACKs.
13
+ - Stable endpoints for individual Pi sessions, with explicit registration, activation, deactivation and revocation.
14
+ - Secure MCP Tunnel management, plus a separate Desktop stdio plugin path.
15
+ - Rust Native SQLite is the only default persistence driver; `node:sqlite` remains only as an explicitly selected, non-production compatibility driver.
16
+
17
+ CE does not provide automatic task scheduling, inbox draining or exactly-once delivery/execution. `DELIVERY_UNKNOWN != CANCELLED`; a missing ACK does not justify retrying an operation.
18
+
19
+ ## Requirements and support
20
+
21
+ Version **0.2.1** includes Native as the default persistence driver, readiness checks and explicit driver management. It requires Node **`>=22.19.0`**, matching Pi 1.3.0's `engines.node`. Local Node 22 / Pi 1.3.0 first-run and persistence checks passed. Linux x64 hosted checks passed **227/227** on both Node **22.19.0** and **24.22.2**; these results do not qualify cloud transport.
22
+
23
+ The historical npm **0.2.0** distribution qualification covers **Node 24.21.0 / Pi 1.3.0 / macOS arm64**, with cloud transport **NOT_VERIFIED**. The 0.2.1 results do not change that historical scope.
24
+
25
+ Pi 1.3.0's installed manifest declares **Node >=22.19.0**. Native uses its bundled SQLite and requires Node-API >=8, rather than the built-in SQLite version. Tested versions are not a compatibility promise for every subsequent release. The explicit compatibility `node:sqlite` path retains its own candidate-version and known-defect restrictions. See [runtime evidence](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/runtime-support.md) for the matrix and limits.
26
+
27
+ | Platform | Current Native evidence | Scope |
28
+ |---|---|---|
29
+ | macOS arm64 | Artifact/conformance and Store integration | Does not certify every client or cloud workflow |
30
+ | Linux x64 GNU | Artifact/conformance, Store integration and hosted checks | 227/227 on Node 22.19.0 and 24.22.2; cloud unverified |
31
+ | macOS x64 | Artifact/conformance only | Store integration not established |
32
+ | Linux arm64 GNU | Artifact/conformance only | Store integration not established |
33
+
34
+ The Store allowlist remains macOS arm64 / Linux x64. Runtime admission also checks SQLite behavior, filesystem safety and ownership. See [Native SQLite](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/native-sqlite.md) and [runtime qualification](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/runtime-support.md).
35
+
36
+ <a id="安装-pi-扩展"></a>
37
+
38
+ ## Installation and upgrades
39
+
40
+ Use an approved Node executable to run Pi **1.3.0**, then install the exact version:
41
+
42
+ ```sh
43
+ node --version
44
+ pi install npm:@zieglar/pi-chat-exchange@0.2.1
45
+ pi list
46
+ ```
47
+
48
+ This is Pi's managed npm source syntax; it is not a standalone `ce` command. Extensions run with your user permissions. Review the package and its source before installation. Registry publication proves availability, not successful cloud setup on your machine.
49
+
50
+ For a prebuilt tarball or a dedicated host prefix, follow [independent installation](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/independent-install.md). Before upgrading, stop the owned Tunnel, confirm `STOPPED`, deactivate affected bindings, and exit affected Pi hosts. Preserve the Store and credentials; check schema compatibility before rollback. Never delete ownership or lock files to force an upgrade.
51
+
52
+ <a id="选择连接方式"></a>
53
+
54
+ ## Quick start
55
+
56
+ Start Pi under the approved Node runtime. Run `/ce-native status`; if the trusted driver is missing, run `/ce-native install`, then exit and restart Pi before setup or messaging. CE does not download Native automatically. In the restarted interactive session:
57
+
58
+ ```text
59
+ /ce-tunnel doctor
60
+ /ce-tunnel setup
61
+ /reload
62
+ /ce-tunnel activate
63
+ /ce-status
64
+ ```
65
+
66
+ Setup must explicitly grant messaging to the current session under Advanced · Messaging. Saving transport settings alone does not authorize messaging. A first reload can refuse a missing mapping; explicitly activate after setup. Activation does not start transport.
67
+
68
+ A real Tunnel needs a separately trusted client, a configured ChatGPT connection, the parent process opt-in `CE_TUNNEL_BACKGROUND_ALLOW=1`, and an explicit `/ce-tunnel start`. Follow [getting started](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/getting-started.md) and [Tunnel setup](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/tunnel-setup.md). The Desktop stdio route has separate [installation steps](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/chatgpt-installation.md).
69
+
70
+ ## Configuration
71
+
72
+ Use the setup UI to write private configuration. `CE_TUNNEL_PROFILE` selects an absolute profile **file** path, `CE_NODE_PATH` selects the MCP child's qualified Node executable, and `CE_TUNNEL_CLIENT_PATH` selects a trusted absolute client executable. Neither child selection nor a version label qualifies the already running Pi host.
73
+
74
+ Payload reads and ACKs require separate grants. Keep credentials in the operator-owned credential files; do not place them in messages, screenshots or issue reports. See [configuration and commands](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/getting-started.md) and the [Pi extension reference](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/pi-extension/README.md).
75
+
76
+ <a id="多项目多-session"></a>
77
+
78
+ ## Commands and message workflow
79
+
80
+ | Command/tool | Purpose |
81
+ |---|---|
82
+ | `/ce-status` | Inspect the current Pi/CE identity and ownership state |
83
+ | `/ce-tunnel doctor` | Inspect installation/runtime qualification without starting transport |
84
+ | `/ce-tunnel start`, `/ce-tunnel stop`, `/ce-tunnel status` | Explicitly manage and inspect the owned transport |
85
+ | `/ce-tunnel sessions`, `register`, `convert`, `revoke` | Manage session registration under the documented policy |
86
+ | `/ce-tunnel activate`, `/ce-tunnel deactivate` | Bind or normally release the current session |
87
+ | `ce_send`, `ce_inbox_list`, `ce_read` | Send, discover and inspect message metadata |
88
+ | `ce_read_payload`, `ce_ack` | Separately authorized payload access and reception receipt |
89
+
90
+ For a received message, discover its ID, read metadata, request payload access only when needed, and record an ACK only under its separate grant. A reply is a new Message. ACK means reception receipt; it does not establish delivery, read, processing or completion. See [multi-session usage](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/multi-session-usage.md) and the [ACK contract](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/delivery-ack-contract.md).
91
+
92
+ ## Architecture and responsibilities
93
+
94
+ Task governance, policy, recovery and completion decisions stay with the external workflow or operator that uses CE. CE owns message delivery/lifecycle rules, durable evidence and reconciliation. Pi owns sessions, runtime and provider transport. CE's adapters use the same Host/Storage authority; tool labels and model claims cannot grant permissions.
95
+
96
+ Recovery markers are not locks or fencing tokens. Changing models must not replay a task that has already produced effects. See [architecture](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/architecture.md) for component responsibilities and the distinction between implemented messaging tools and the broader protocol model.
97
+
98
+ ## SQLite Native driver
99
+
100
+ The independent immutable Native Release is [**`ce-sqlite-v0.1.0`**](https://github.com/zieglar/pi-packages/releases/tag/ce-sqlite-v0.1.0), with ABI **1**, bundled SQLite **3.54.1**, and source SHA **`a8386aafd657c84825b2905847f34a43d5b91e1e`**. Version 0.2.1 uses this same independent Native release; its binaries are not bundled in npm.
101
+
102
+ In 0.2.1, the default is Native, including when no selection file exists. `node:sqlite` is loaded lazily only after an explicit selection; Native trust, load or initialization failure is closed and never falls back. Production `NATIVE_COMPAT` pins now trust immutable Release `427441708`: four platform SHA-256 values verified against `SHA256SUMS`, with seven attestation subjects bound to that source. Version 0.2.1 includes these fixed trust pins.
103
+
104
+ ## Native readiness and management (0.2.1)
105
+
106
+ Run `/ce-native status` or `/ce-native verify` to inspect Native without downloads or selection changes. Explicit `/ce-native install` installs only the trusted default version and verifies it before changing selection; restart Pi afterward. `/ce-native repair confirm` is explicit repair. `/ce-native check-updates` reads GitHub Release metadata only: `latest` never becomes trusted or changes selection. CE never automatically downloads, repairs or upgrades Native.
107
+
108
+ Extension load is read-only: it never downloads, creates a Store or starts Tunnel. Pi and management commands remain available when Native is not ready; Store, Tunnel start and messaging fail closed. `/ce-tunnel start` revalidates Native and Store admission before manager/profile/process effects; refusal includes a `CE_NATIVE_*` code and `/ce-native` hint. Status reports `native=<STATE> (code)` separately from transport and never infers `STOPPED`; stop remains available for cleanup.
109
+
110
+ Windows Native is unsupported (`CE_NATIVE_TARGET_UNSUPPORTED`); no Windows binary exists and CE never tries a Linux binary there. Run Linux Node.js, Pi and CE inside WSL2 to select the real Linux x64/arm64 asset. Keep an active SQLite Store on the Linux filesystem rather than `/mnt/c` or other Windows mounts. WSL2 is recommended but integration testing here has not verified it; platform tests cover target mapping and Windows refusal only. Existing Store filesystem rules still apply. See [Native management](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/native-management.md) for the warning, commands and recovery limits.
111
+
112
+ <a id="边界与验证"></a>
113
+
114
+ ## Security and troubleshooting
115
+
116
+ Configured, Pi-bound, connected and demonstrated message exchange are different states. Transport health does not prove message authority. Unknown outcomes remain unknown until evidence resolves them; do not retry blindly, take over an owner or delete the Store.
117
+
118
+ Start with [operations and troubleshooting](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/operations.md). Share error codes and redacted metadata, never payloads, credentials, capabilities or full raw logs. Detailed boundaries are in [protocol v2](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/protocol-v2.md), [ownership](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/ownership-contract.md), [storage](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/storage-contract.md) and [storage security](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/storage-security.md).
119
+
120
+ <a id="阅读导航"></a>
121
+
122
+ ## Development and contribution
123
+
124
+ From the repository root, with the qualified Node runtime and pnpm **12.9.1**:
125
+
126
+ ```sh
127
+ pnpm install --frozen-lockfile --ignore-scripts
128
+ pnpm --dir packages/pi-chat-exchange run verify
129
+ pi -e ./packages/pi-chat-exchange/pi-extension/index.ts
130
+ ```
131
+
132
+ The extension imports `dist/`. Rebuild after source edits; `/reload` does not compile TypeScript. Optional client and real-host tests need their documented prerequisites and are separate from default tests. Follow [development and release operations](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/operations.md) and the [bilingual documentation guide](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/documentation.md).
133
+
134
+ The npm package contains the prebuilt extension and runtime files. Detailed operating guides are linked on GitHub; the npm tarball does not include `docs/`.
135
+
136
+ ## License
137
+
138
+ [MIT](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/LICENSE), Copyright (c) 2026 zieglar. Dependencies retain their own licenses; see the [license audit](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/docs/licenses.md).
@@ -0,0 +1,119 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { loadVerifiedNativeArtifact, nativeCacheRoot, nativeTarget, prepareNativeArtifact } from "../storage/native-artifact.js";
4
+ import { NATIVE_COMPAT, parseNativeCompat } from "../storage/native-compat.js";
5
+ import { resolve } from "node:path";
6
+ import { defaultDriverSelectionFile, readDriverSelection, writeDriverSelection } from "../storage/sqlite-driver-selection.js";
7
+ function usage() {
8
+ console.error("Usage: ce-native status | prepare [--version X] | select --driver node-sqlite|rust-native [--version X] [--root DIR] [--manifest FILE] [--selection FILE]");
9
+ process.exit(2);
10
+ }
11
+ function readManifest(path) {
12
+ try {
13
+ return parseNativeCompat(JSON.parse(readFileSync(path, "utf8")));
14
+ }
15
+ catch {
16
+ throw Object.assign(new Error(`invalid Native compatibility manifest: ${path}`), { code: "CE_NATIVE_MANIFEST_INVALID" });
17
+ }
18
+ }
19
+ function parse(argv) {
20
+ const [command, ...rest] = argv;
21
+ if (command === undefined)
22
+ usage();
23
+ const args = { command };
24
+ for (let i = 0; i < rest.length; i += 1) {
25
+ const flag = rest[i];
26
+ const value = rest[i + 1];
27
+ if (value === undefined)
28
+ usage();
29
+ if (flag === "--version")
30
+ args.version = value;
31
+ else if (flag === "--root")
32
+ args.root = value;
33
+ else if (flag === "--manifest") {
34
+ args.manifest = readManifest(value);
35
+ args.manifestFile = resolve(value);
36
+ }
37
+ else if (flag === "--selection")
38
+ args.selectionFile = value;
39
+ else if (flag === "--driver")
40
+ args.command = `${command}:${value}`;
41
+ else
42
+ usage();
43
+ i += 1;
44
+ }
45
+ return args;
46
+ }
47
+ function manifestOptions(args, selectionManifestFile) {
48
+ const manifest = args.manifest ?? (selectionManifestFile === undefined ? undefined : readManifest(selectionManifestFile));
49
+ return {
50
+ ...(args.version === undefined ? {} : { version: args.version }),
51
+ ...(args.root === undefined ? {} : { root: args.root }),
52
+ ...(manifest === undefined ? {} : { manifest }),
53
+ };
54
+ }
55
+ function status(args) {
56
+ const selection = readDriverSelection(args.selectionFile);
57
+ const result = {
58
+ selectionFile: args.selectionFile ?? defaultDriverSelectionFile(),
59
+ driver: selection.driver,
60
+ nativeVersion: selection.nativeVersion ?? null,
61
+ target: nativeTarget(),
62
+ cacheRoot: args.root ?? nativeCacheRoot(),
63
+ };
64
+ if (selection.driver === "rust-native") {
65
+ try {
66
+ const verified = loadVerifiedNativeArtifact({ ...(selection.nativeVersion === undefined ? {} : { version: selection.nativeVersion }), ...manifestOptions(args, selection.manifestFile) });
67
+ result.ready = true;
68
+ result.native = verified.info;
69
+ }
70
+ catch (error) {
71
+ result.ready = false;
72
+ result.error = error instanceof Error && "code" in error ? error.code : "CE_NATIVE_LOAD_FAILED";
73
+ }
74
+ }
75
+ else {
76
+ result.ready = true;
77
+ }
78
+ console.log(JSON.stringify(result, null, 2));
79
+ }
80
+ async function main() {
81
+ const args = parse(process.argv.slice(2));
82
+ if (args.command === "status")
83
+ return status(args);
84
+ if (args.command === "prepare") {
85
+ const prepared = await prepareNativeArtifact(manifestOptions(args));
86
+ console.log(JSON.stringify({ prepared: true, path: prepared.path, info: prepared.info }, null, 2));
87
+ return;
88
+ }
89
+ if (args.command.startsWith("select:")) {
90
+ const driver = args.command.slice("select:".length);
91
+ if (driver !== "node-sqlite" && driver !== "rust-native")
92
+ usage();
93
+ const selection = driver === "node-sqlite"
94
+ ? { driver }
95
+ : { driver, nativeVersion: args.version ?? (args.manifest ?? NATIVE_COMPAT).defaultVersion };
96
+ if (driver === "rust-native") {
97
+ if (args.root !== undefined && resolve(args.root) !== nativeCacheRoot()) {
98
+ throw Object.assign(new Error("select requires the default runtime cache root; use --root only for prepare/status qualification"), { code: "CE_NATIVE_SELECTION_ROOT_INVALID" });
99
+ }
100
+ const verified = loadVerifiedNativeArtifact(manifestOptions(args));
101
+ writeDriverSelection({ ...selection, ...(args.manifestFile === undefined ? {} : { manifestFile: args.manifestFile }) }, args.selectionFile);
102
+ console.log(JSON.stringify({ selected: selection, native: verified.info }, null, 2));
103
+ }
104
+ else {
105
+ writeDriverSelection(selection, args.selectionFile);
106
+ console.log(JSON.stringify({ selected: selection }, null, 2));
107
+ }
108
+ return;
109
+ }
110
+ usage();
111
+ }
112
+ try {
113
+ await main();
114
+ }
115
+ catch (error) {
116
+ console.error(error instanceof Error && "code" in error ? `${error.code}: ${error.message}` : String(error));
117
+ process.exitCode = 1;
118
+ }
119
+ //# sourceMappingURL=ce-native.js.map
@@ -0,0 +1,196 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * stdio entrypoint for the pi-chat-exchange MCP server (composition only).
4
+ *
5
+ * Intended launch forms:
6
+ * node dist/bin/mcp-stdio.js
7
+ * Phase 1 smoke surface: exactly the `ping` tool, no durable state.
8
+ *
9
+ * node dist/bin/mcp-stdio.js --config /abs/path/binding.json
10
+ * CE-0002 B3-P3B messaging surface: binds ONE Endpoint from trusted,
11
+ * operator-controlled launch configuration (never from tool arguments,
12
+ * never from the environment), acquires its ownership lease with
13
+ * `requireUnowned`, renews it on a heartbeat, and releases it on clean
14
+ * shutdown. A prior crashed instance leaves an ownership row that refuses
15
+ * startup — fail closed, no takeover.
16
+ *
17
+ * tunnel-client run --profile pi-chat-exchange (with --mcp-command "node .../mcp-stdio.js")
18
+ *
19
+ * stdout is reserved for MCP protocol frames; diagnostics go to stderr and
20
+ * carry status codes only — never configuration values, identifiers from
21
+ * tool arguments, payloads, or capability secrets.
22
+ */
23
+ import { readFileSync, statSync, existsSync } from "node:fs";
24
+ import { join } from "node:path";
25
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
26
+ import { runStdioServer, createExchangeMcpServer } from "../control/mcp/server.js";
27
+ import { CE_ACK_TOOL, MESSAGING_TOOL_NAMES } from "../control/mcp/messaging-tools.js";
28
+ import { PING_TOOL_NAME } from "../control/mcp/ping.js";
29
+ import { CeEndpointHost } from "../host/endpoint-host.js";
30
+ import { CeBoundEndpoint } from "../host/bound-endpoint.js";
31
+ import { McpBindingConfigError, MCP_BINDING_CONFIG_MAX_BYTES, parseMcpBindingConfig, } from "../host/mcp-binding-config.js";
32
+ import { debugEvent, errorSummary } from "../control/debug-log.js";
33
+ import { observeTransport } from "../control/mcp/debug-transport.js";
34
+ import { initializeStore, openStore } from "../storage/store.js";
35
+ import { createMcpPolicyAdmission } from "../tunnel/multi-session-admission.js";
36
+ debugEvent("server", "SERVER_ENTRY", { version: process.version });
37
+ // Monitor rather than handle exceptions: preserve Node's fatal exit behavior.
38
+ process.on("uncaughtExceptionMonitor", (error, origin) => {
39
+ debugEvent("process", origin === "unhandledRejection" ? "UNHANDLED_REJECTION" : "UNCAUGHT_EXCEPTION", { ...errorSummary(error), origin });
40
+ });
41
+ process.on("exit", (exitCode) => debugEvent("process", "PROCESS_EXIT", { exitCode }));
42
+ function fail(code, detail) {
43
+ debugEvent("server", "MCP_ERROR", { code, stage: "startup" });
44
+ console.error(detail === undefined ? code : `${code} ${detail}`);
45
+ process.exit(1);
46
+ }
47
+ /** Read the binding configuration from an absolute path, refusing anything
48
+ * oversized or unreadable before a single durable write can happen. */
49
+ function loadBindingConfig(path) {
50
+ let size;
51
+ try {
52
+ size = statSync(path).size;
53
+ }
54
+ catch {
55
+ return fail("CE_MCP_CONFIG_INVALID", "config.unreadable");
56
+ }
57
+ if (size > MCP_BINDING_CONFIG_MAX_BYTES)
58
+ return fail("CE_MCP_CONFIG_INVALID", "config.too_large");
59
+ let raw;
60
+ try {
61
+ raw = readFileSync(path, "utf8");
62
+ }
63
+ catch {
64
+ return fail("CE_MCP_CONFIG_INVALID", "config.unreadable");
65
+ }
66
+ let parsed;
67
+ try {
68
+ parsed = JSON.parse(raw);
69
+ }
70
+ catch {
71
+ return fail("CE_MCP_CONFIG_INVALID", "config.not_json");
72
+ }
73
+ try {
74
+ return parseMcpBindingConfig(parsed);
75
+ }
76
+ catch (error) {
77
+ if (error instanceof McpBindingConfigError)
78
+ return fail(error.code, error.field);
79
+ return fail("CE_MCP_CONFIG_INVALID", "config.unexpected");
80
+ }
81
+ }
82
+ /** Open (or initialize on first use) the shared durable store. */
83
+ function openBindingStore(config) {
84
+ const options = { directory: config.store.directory, filename: config.store.file, busyTimeoutMs: 5_000 };
85
+ debugEvent("store", "STORE_OPEN_STARTED");
86
+ const store = existsSync(join(options.directory, options.filename)) ? openStore(options) : initializeStore(options);
87
+ debugEvent("store", "STORE_OPEN_COMPLETED");
88
+ return store;
89
+ }
90
+ async function main() {
91
+ const argv = process.argv.slice(2);
92
+ if (argv.length === 0) {
93
+ await runStdioServer();
94
+ return;
95
+ }
96
+ const [flag, configPath] = argv;
97
+ if (argv.length !== 2 || flag !== "--config" || configPath === undefined || !configPath.startsWith("/")) {
98
+ fail("CE_MCP_LAUNCH_INVALID", "usage: mcp-stdio.js [--config /absolute/path.json]");
99
+ }
100
+ const config = loadBindingConfig(configPath);
101
+ // Verify actual launch bytes before Store creation; managed provenance grants nothing.
102
+ const admission = createMcpPolicyAdmission(config, configPath);
103
+ admission?.({ kind: "begin" });
104
+ const host = new CeEndpointHost(openBindingStore(config), {
105
+ adapter: config.endpoint.adapter,
106
+ allowlist: [{ endpointId: config.endpoint.endpointId }],
107
+ recipients: config.recipients,
108
+ exchangeNamespace: config.exchange.namespace,
109
+ exchangeIdempotencyKey: config.exchange.idempotencyKey,
110
+ leaseTtlSeconds: config.lease.ttlSeconds,
111
+ payloadRead: { enabled: config.payloadRead.enabled },
112
+ ack: { enabled: config.ack.enabled },
113
+ });
114
+ debugEvent("authority", "AUTHORITY_CHECK_STARTED", { stage: "requireUnowned" });
115
+ const bound = CeBoundEndpoint.start(host, config.endpoint.endpointId, {
116
+ renewIntervalMs: config.lease.renewIntervalSeconds * 1_000,
117
+ ...(admission === undefined ? {} : { admission }),
118
+ onEvent: (event) => {
119
+ debugEvent("authority", "AUTHORITY_CHECK_RESULT", { stage: event.kind });
120
+ if (event.kind === "renewed")
121
+ return;
122
+ // Codes only; renewal_deferred is retryable at the next tick,
123
+ // renewal_stopped has already blocked new sends.
124
+ console.error(event.kind === "renewal_deferred"
125
+ ? `CE_MCP_RENEWAL_DEFERRED code=${event.code}`
126
+ : `CE_MCP_RENEWAL_STOPPED code=${event.code}`);
127
+ },
128
+ });
129
+ debugEvent("authority", "OWNERSHIP_ACQUIRED", { owned: true });
130
+ // HANDOFF-CE-E2B-01: advertise `ce_ack` only when the validated binding
131
+ // declares the ack opt-in; the default surface stays exactly four tools.
132
+ const server = createExchangeMcpServer(undefined, {
133
+ port: bound, ackEnabled: config.ack.enabled, executionGuard: config.debugExecutionGuard,
134
+ ...(admission === undefined ? {} : { admission: () => admission({ kind: "inbox" }) }),
135
+ });
136
+ if (config.debugExecutionGuard.enabled) {
137
+ debugEvent("server", "EXECUTION_GUARD_ARMED", { scope: "tools/call", stage: "unified-dispatch-entry" });
138
+ }
139
+ const transport = observeTransport(new StdioServerTransport());
140
+ debugEvent("server", "TRANSPORT_CREATED");
141
+ let initiated = false;
142
+ const initiateShutdown = async () => {
143
+ if (initiated)
144
+ return;
145
+ initiated = true;
146
+ try {
147
+ await server.close();
148
+ }
149
+ catch {
150
+ // Transport already gone; the lease release below is what matters.
151
+ }
152
+ const shutdown = await bound.shutdown();
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();
185
+ }
186
+ main().catch((error) => {
187
+ debugEvent("server", "MCP_ERROR", { stage: "startup", ...errorSummary(error) });
188
+ // Sanitized: host refusals carry fixed codes; anything else collapses
189
+ // without echoing message text (which could contain operator paths).
190
+ const code = typeof error.code === "string"
191
+ ? String(error.code)
192
+ : "CE_MCP_START_FAILED";
193
+ console.error(code.startsWith("CE_") ? code : "CE_MCP_START_FAILED");
194
+ process.exitCode = 1;
195
+ });
196
+ //# sourceMappingURL=mcp-stdio.js.map
@@ -0,0 +1,67 @@
1
+ /** DIAG-01 development diagnostics: always on, best effort, never stdout.
2
+ * Only explicitly projected metadata is accepted; never pass raw args/results/errors.
3
+ * The built module's ../../.debug-logs is inside the independent debug artifact.
4
+ */
5
+ import { appendFileSync, closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, writeSync } from "node:fs";
6
+ import { join, resolve } from "node:path";
7
+ const FIELDS = new Set(["stage", "method", "requestId", "requestIdType", "requestIdLength", "tool", "args", "errorType", "stackFrames", "code", "isError", "durationMs", "count", "released", "detached", "signal", "exitCode", "version", "fencing", "owned", "mode", "origin", "reason", "scope"]);
8
+ export function createDebugLog(directory) {
9
+ return (component, event, metadata = {}) => {
10
+ // Include serialization in the guard: even hostile getters/cycles cannot
11
+ // turn diagnostics into a business/protocol failure.
12
+ try {
13
+ const context = Object.fromEntries(Object.entries(metadata).filter(([key]) => FIELDS.has(key)));
14
+ const line = `${JSON.stringify({ ts: new Date().toISOString(), pid: process.pid, component, event, ...context })}\n`;
15
+ try {
16
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
17
+ if (!lstatSync(directory).isDirectory() || lstatSync(directory).isSymbolicLink())
18
+ throw new Error("unsafe log directory");
19
+ const fd = openSync(join(directory, `ce-debug-${process.pid}.jsonl`), constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW, 0o600);
20
+ try {
21
+ const stat = fstatSync(fd);
22
+ if (!stat.isFile() || (process.getuid !== undefined && stat.uid !== process.getuid()))
23
+ throw new Error("unsafe log file");
24
+ appendFileSync(fd, line);
25
+ }
26
+ finally {
27
+ closeSync(fd);
28
+ }
29
+ }
30
+ catch { /* diagnostics file unavailable: stderr mirror remains best effort */ }
31
+ try {
32
+ writeSync(2, line);
33
+ }
34
+ catch { /* closed stderr must not alter behavior */ }
35
+ }
36
+ catch { /* diagnostics must never escape */ }
37
+ };
38
+ }
39
+ export const debugEvent = createDebugLog(resolve(import.meta.dirname, "../../.debug-logs"));
40
+ const ARG_FIELDS = new Set(["to", "text", "idempotencyKey", "afterAuditSequence", "pageSize", "rawScanLimit", "messageId", "payloadDigest", "payloadLength", "messageCreatedAuditSequence"]);
41
+ export function argumentShape(args) {
42
+ try {
43
+ if (args === null || typeof args !== "object")
44
+ return [];
45
+ return Object.entries(args).slice(0, 32).map(([key, value]) => ({
46
+ field: ARG_FIELDS.has(key) ? key : "unknown-field",
47
+ type: value === null ? "null" : Array.isArray(value) ? "array" : typeof value,
48
+ ...(typeof value === "string" ? { length: value.length } : {}),
49
+ }));
50
+ }
51
+ catch {
52
+ return [];
53
+ }
54
+ }
55
+ export function errorSummary(error) {
56
+ try {
57
+ // Error messages and first stack line can contain payloads/credentials.
58
+ // Retain source basenames/line:column only, never function names or paths.
59
+ const stackFrames = error instanceof Error ? (error.stack ?? "").split("\n").slice(1, 9)
60
+ .flatMap((line) => line.match(/[/\\]([A-Za-z0-9_.-]+\.[cm]?[jt]s:\d+:\d+)\)?$/)?.[1] ?? []) : [];
61
+ return { errorType: error instanceof TypeError ? "TypeError" : error instanceof Error ? "Error" : typeof error, stackFrames };
62
+ }
63
+ catch {
64
+ return { errorType: "unknown" };
65
+ }
66
+ }
67
+ //# sourceMappingURL=debug-log.js.map
@@ -0,0 +1,48 @@
1
+ import { debugEvent, errorSummary } from "../debug-log.js";
2
+ const METHODS = new Set(["initialize", "notifications/initialized", "tools/list", "tools/call", "ping", "notifications/cancelled"]);
3
+ function frameMetadata(frame) {
4
+ const id = "id" in frame ? frame.id : undefined;
5
+ return {
6
+ ...("method" in frame ? { method: METHODS.has(frame.method) ? frame.method : "other" } : {}),
7
+ ...(typeof id === "number" ? { requestId: id } : typeof id === "string" ? { requestIdType: "string", requestIdLength: id.length } : {}),
8
+ ...("error" in frame ? { code: frame.error.code } : {}),
9
+ };
10
+ }
11
+ /** Observe the existing stdio transport without parsing/rewriting wire data.
12
+ * SDK connect installs callbacks before start. Preserve frame/extra/options,
13
+ * this binding, return/rejection semantics, and existing close/error callbacks.
14
+ */
15
+ export function observeTransport(transport, log = debugEvent) {
16
+ const start = transport.start.bind(transport);
17
+ const send = transport.send.bind(transport);
18
+ transport.start = async () => {
19
+ const receive = transport.onmessage;
20
+ const close = transport.onclose;
21
+ const error = transport.onerror;
22
+ transport.onmessage = (frame, extra) => {
23
+ log("mcp", "MCP_REQUEST_RECEIVED", frameMetadata(frame));
24
+ if ("method" in frame) {
25
+ const aliases = new Map([["initialize", "MCP_INITIALIZE"], ["notifications/initialized", "MCP_INITIALIZED"], ["tools/list", "MCP_TOOLS_LIST"], ["tools/call", "MCP_TOOLS_CALL"]]);
26
+ const event = aliases.get(frame.method);
27
+ if (event !== undefined)
28
+ log("mcp", event, frameMetadata(frame));
29
+ }
30
+ receive?.call(transport, frame, extra);
31
+ };
32
+ transport.onclose = () => { log("mcp", "SERVER_STOPPED"); close?.call(transport); };
33
+ transport.onerror = (e) => { log("mcp", "MCP_ERROR", errorSummary(e)); error?.call(transport, e); };
34
+ return start();
35
+ };
36
+ transport.send = async (frame, options) => {
37
+ try {
38
+ await send(frame, options);
39
+ log("mcp", "error" in frame ? "MCP_ERROR" : "MCP_RESPONSE_SENT", frameMetadata(frame));
40
+ }
41
+ catch (error) {
42
+ log("mcp", "MCP_ERROR", errorSummary(error));
43
+ throw error;
44
+ }
45
+ };
46
+ return transport;
47
+ }
48
+ //# sourceMappingURL=debug-transport.js.map