@zieglar/pi-chat-exchange 0.2.0 → 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.
package/README.md CHANGED
@@ -1,44 +1,59 @@
1
1
  # Pi Chat Exchange
2
2
 
3
- 让 ChatGPT 与 Pi 通过显式工具交换持久化消息:发送、发现收件箱、授权读取,以及独立授权的接收回执(ACK)。它不是自动任务调度器,也不把 ACK 或对话回复当作任务完成。
3
+ English | [简体中文](https://github.com/zieglar/pi-packages/blob/main/packages/pi-chat-exchange/README.zh-CN.md)
4
4
 
5
- 本包版本为 **0.2.0**。CE 自有代码已获所有者授权采用 **MIT**(见 [LICENSE](LICENSE));第三方许可证证据已按三层证据闭合(逐版本审计记录为 `docs/license-audit.md`,仅仓库保留、不随 tarball 分发)。0.2.0 的认证范围仅 **Node 24.21.0 / Pi 1.3.0 / macOS arm64**;cloud transport 为 NOT_VERIFIED,Linux 未验证。
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
6
 
7
- ## 当前能力与典型用法
7
+ <a id="当前能力与典型用法"></a>
8
8
 
9
- - **持久化消息**:ChatGPT 发来计划或问题,Pi 显式查看 inbox、授权读取,再以新 Message 回复检查结果。
10
- - **独立接收回执**:按需授权 payload read 与 ACK;接收回执不等于任务完成,也不触发正文执行。
11
- - **多 Session**:多个项目中的真实 Pi Session 使用独立 Endpoint,共享 Tunnel;ChatGPT inbox 仍不隔离对话。
9
+ ## Features
12
10
 
13
- 当前不提供自动任务调度、自动执行或 exactly-once delivery/execution。只需自动远端执行而不逐次授权时,本项目不适用。
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.
14
16
 
15
- ## 选择连接方式
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.
16
18
 
17
- - **推荐:Secure MCP Tunnel。** `/ce-tunnel` 提供设置向导、显式激活、后台 Start/Stop 和健康状态;无需 Desktop stdio 插件。按 [Tunnel 快速开始](docs/tunnel-setup.md)操作。
18
- - **Desktop 本地 stdio 插件。** 由支持本地插件的 ChatGPT Desktop 启动 bundled MCP server;需配置本机 Node 与外置 binding。见 [ChatGPT 安装](docs/chatgpt-installation.md)。不要与 Tunnel 同时争用同一 Endpoint。
19
+ ## Requirements and support
19
20
 
20
- ## 安装 Pi 扩展
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.
21
22
 
22
- **信任提示:Pi 扩展以你的完整用户权限运行。安装前审查源码与制品来源;消息授权门槛不等于操作系统沙箱。**
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.
23
24
 
24
- 正式日常使用请用**独立安装路径**:作者交付预构建私有 tarball,消费者物理安装后 `pi install` 注册,无需仓库/build,见 [独立安装指南](docs/independent-install.md)。下面是开发者源码路径。
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.
25
26
 
26
- 先安装 Pi **1.3.0**、pnpm **12.9.1** 和批准的 Node **24.21.0 或 24.22.1**。Node 还必须通过完整 SQLite 身份、编译选项与 API 门槛,不是任意 `24.x`。Pi host 与 MCP child 分别校验;mise 或其他版本管理器均不是必需品。
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 |
27
33
 
28
- 从仓库根目录,在已选中批准 Node 的 shell 中执行:
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:
29
41
 
30
42
  ```sh
31
43
  node --version
32
- pnpm install --frozen-lockfile
33
- pnpm --dir packages/pi-chat-exchange run build
34
- pi -e ./packages/pi-chat-exchange/pi-extension/index.ts
44
+ pi install npm:@zieglar/pi-chat-exchange@0.2.1
45
+ pi list
35
46
  ```
36
47
 
37
- 扩展入口会导入包内 `dist/`;修改源码后须重新运行上述 build,再在已加载的 Session 中 `/reload`。`/reload` 不会编译源码,旧 `dist/` 会继续运行旧逻辑。
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.
38
49
 
39
- 这是临时加载。若要长期从不同项目使用,在 build 后执行 `pi install /absolute/path/to/packages/pi-chat-exchange` 注册本地包,再正常启动 Pi。本地安装引用该目录,不复制源码;不要同时安装和 `-e` 加载第二份。本包不提供独立的 `ce` 安装 CLI;安装只经 Pi 的 managed npm / tarball / 本地目录三条路径。
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.
40
51
 
41
- 进入交互 TUI 后:
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:
42
57
 
43
58
  ```text
44
59
  /ce-tunnel doctor
@@ -48,43 +63,76 @@ pi -e ./packages/pi-chat-exchange/pi-extension/index.ts
48
63
  /ce-status
49
64
  ```
50
65
 
51
- Setup 的 Advanced · Messaging 必须显式授权当前 Session;只保存基本 transport 设置时默认不能通信。首次 reload 缺少 mapping 时可能拒绝,随后显式 activate,不清理数据库。启动真实 Tunnel 还需父 Pi 环境的 `CE_TUNNEL_BACKGROUND_ALLOW=1` 和单独 `/ce-tunnel start`;完整步骤、可信绝对路径启动方式和 ChatGPT 自定义 MCP 配置见 [Tunnel 指南](docs/tunnel-setup.md)。
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).
52
69
 
53
- ## 多项目、多 Session
70
+ ## Configuration
54
71
 
55
- 每个真实 Pi Session 注册不同的稳定 Endpoint;项目目录本身不是身份。共享的 `chatgpt/main` inbox **不是 ChatGPT 对话隔离**。
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.
56
73
 
57
- - `/ce-status`:当前 Pi / CE 身份与 Ownership 状态。
58
- - `/ce-tunnel sessions`:经当前运行时授权的、所选配置中 active Endpoint 列表,不证明 MCP 已加载。
59
- - `/ce-tunnel deactivate`:确认后正常解绑当前本地 CE binding,不删注册/历史,也不停止 Tunnel。
60
- - `/ce-tunnel revoke <exact-endpoint>`:撤销注册的后续权限;需先核实 transport STOPPED,不等于正常解绑。
61
- - `/reload`:有效 binding 重新校验并恢复;已正常释放或未绑定的 Session 需要显式 activate。
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).
62
75
 
63
- 转换、注册、权限和生效顺序见 [多 Session 使用指南](docs/multi-session-usage.md)。不要直接修改生成文件或删除 Store/Owner 作为排障。
76
+ <a id="多项目多-session"></a>
64
77
 
65
- ## 阅读导航
78
+ ## Commands and message workflow
66
79
 
67
- | 目标 | 文档 |
80
+ | Command/tool | Purpose |
68
81
  |---|---|
69
- | **独立安装(正式日常使用,预构建 tarball)** | [独立安装指南](docs/independent-install.md) |
70
- | 首次设置、可信安装诊断、ChatGPT 连接、启动与排障 | [Tunnel 用户指南](docs/tunnel-setup.md) |
71
- | Desktop stdio 打包与本机配置 | [ChatGPT 安装](docs/chatgpt-installation.md) |
72
- | 工具参数、Inbox、payload/ACK、生命周期 | [Pi 扩展指南](pi-extension/README.md) |
73
- | 多项目/Session 注册、解绑、撤销 | [多 Session 使用](docs/multi-session-usage.md) |
74
- | 分层、身份、授权、验证与扩展点 | [架构指南](docs/architecture.md) |
75
- | 后台进程所有权与停止约束 | [后台 Manager](docs/tunnel-manager-background.md) |
76
- | 精确安全契约 | [协议 v2](docs/protocol-v2.md) · [Ownership](docs/ownership-contract.md) · [Storage](docs/storage-contract.md) · [ACK](docs/delivery-ack-contract.md) · [Store 安全边界](docs/storage-security.md) |
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.
77
101
 
78
- 独立安装包(tarball)随包分发上表所有文档、CHANGELOG 与本版本 release notes,消费者无需访问仓库即可取得操作与安全契约。仅作者侧的治理与证据记录(如 `docs/license-audit.md`、`docs/runtime-qualification.md` 及各阶段审计记录)仅仓库保留,不进入消费者制品。
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.
79
103
 
80
- ## 边界与验证
104
+ ## Native readiness and management (0.2.1)
81
105
 
82
- **Configured ≠ Pi-bound ≠ Connected ≠ 消息实证。** `CONNECTED` 只证明测得的传输健康;ACK 仅为 reception receipt,不证明 delivery、read、processing 或 task completion。
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
+ ```
83
131
 
84
- 不自动启动/重连、接管过期 Owner、排空 Inbox、执行 payload、合并 Store 或重试未知结果。`DELIVERY_UNKNOWN != CANCELLED`。凭据文件不是加密保险箱;不要把 key、capability、正文或完整日志贴入诊断。
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).
85
133
 
86
- Store 平台 allowlist 为 macOS arm64 / Linux x64;两种批准 Node 的实测为 macOS arm64,不等于 Linux 或每种 Desktop UI 均已验收。已有本地人工双向消息与 Tunnel 启停验收不替代本次变更的隔离测试,也不证明机器冷启动或所有终端交互。
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/`.
87
135
 
88
- 开发检查:从包目录执行 `pnpm run verify`(check → typecheck → build → test → plugin-package test);扩展测试前须 build。证据层次见[架构指南](docs/architecture.md#验证层次)。
136
+ ## License
89
137
 
90
- 许可证:**MIT**,Copyright (c) 2026 zieglar。第三方依赖保留各自许可,不由 CE 的 MIT 重新授权;`@earendil-works/pi-tui@1.3.0` 与 Host peer 的制品未随包附带 LICENSE 文本(上游打包省略;经 registry 制品与上游 v1.3.0 标签根 LICENSE 三层核实为 MIT)。完整逐版本审计记录为 `docs/license-audit.md`(仅仓库保留,不随 tarball 分发)。0.2.0 的认证范围仅 Node 24.21.0 / Pi 1.3.0 / macOS arm64;cloud NOT_VERIFIED,Linux 未验证。见 [0.2.0 release notes](docs/releases/0.2.0.md) 与 [安全卸载/升级/回滚](docs/independent-install.md#5-安全卸载升级与回滚)。
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
@@ -23,7 +23,7 @@ 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
25
  export const SERVER_NAME = "pi-chat-exchange";
26
- export const SERVER_VERSION = "0.2.0";
26
+ export const SERVER_VERSION = "0.2.1";
27
27
  const PING_TOOL = {
28
28
  name: PING_TOOL_NAME,
29
29
  description: "Read-only liveness probe for the pi-chat-exchange service. " +
@@ -1,4 +1,4 @@
1
- import { APPROVED_RUNTIME_TUPLES, assertHostRuntimeEligibility } from "../storage/runtime.js";
1
+ import { CANDIDATE_NODE_RANGE, MINIMUM_SQLITE_VERSION, PI_HOST_MINIMUM_NODE_VERSION, assertHostRuntimeEligibility } from "../storage/runtime.js";
2
2
  import { ExecutableRefusal, diagnoseTunnelClient, resolveApprovedNode } from "./executables.js";
3
3
  /** No profile, credential, Store or transport access. Host uses the actual
4
4
  * in-memory SQLite/API battery; only an admitted Node child is executed. */
@@ -29,6 +29,6 @@ export function installationDiagnosticMessage(result) {
29
29
  /** No raw subprocess output, paths, configuration values or exception causes. */
30
30
  export function hostRuntimeRepairMessage(nodeVersion = process.version) {
31
31
  const current = /^v\d+\.\d+\.\d+$/.test(nodeVersion) ? nodeVersion : "unrecognized";
32
- return `current Pi Node ${current}; requires approved Node ${APPROVED_RUNTIME_TUPLES.map(({ nodeVersion: version }) => version).join(" or ")} with approved SQLite; restart Pi using a trusted absolute approved Node executable. CE_NODE_PATH selects the MCP child only, not the running Pi host; each qualifies independently and need not use the same executable; mise is not required`;
32
+ return `current Pi Node ${current}; Native requires Pi Host Node >=${PI_HOST_MINIMUM_NODE_VERSION}, Node-API >=8 and a verified Native cache with SQLite >=${MINIMUM_SQLITE_VERSION} and proven capabilities. Native trust/load failure is closed, with no fallback; prepare requires separately verified pins. Explicit non-production node-sqlite retains candidate Node >=${CANDIDATE_NODE_RANGE.minimum} within majors 24/25/26 and its known-defect refusals; restart Pi using a trusted absolute approved Node executable. CE_NODE_PATH selects the MCP child only, not the running Pi host; each qualifies independently and need not use the same executable; mise is not required`;
33
33
  }
34
34
  //# sourceMappingURL=diagnostics.js.map
@@ -2,7 +2,10 @@ import { execFileSync } from "node:child_process";
2
2
  import { accessSync, constants, existsSync, lstatSync, realpathSync, statSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
4
  import { dirname, isAbsolute, join, normalize, relative, sep } from "node:path";
5
- import { APPROVED_RUNTIME_TUPLES, REQUIRED_SQLITE_CAPABILITIES, assertRuntimeEligibility } from "../storage/runtime.js";
5
+ import { MISE_DISCOVERY_NODE_VERSIONS, probeSqliteCapabilities, assertRuntimeEligibility } from "../storage/runtime.js";
6
+ import { resolveSqliteDriver } from "../storage/sqlite-driver-selection.js";
7
+ import { createNodeSqliteDriver } from "../storage/sqlite-driver-node.js";
8
+ import { createRustNativeDriver } from "../storage/sqlite-driver-rust.js";
6
9
  /** These are locations, not PATH search. Every discovered file still needs admission. */
7
10
  const SYSTEM_DIRECTORIES = ["/usr/local/bin", "/usr/bin", "/bin", "/opt/homebrew/bin"];
8
11
  export class ExecutableRefusal extends Error {
@@ -107,35 +110,26 @@ export function admitExecutable(path, options = {}) {
107
110
  export function admitInstallationDirectory(path, options = {}) {
108
111
  return admitPath(path, options, "directory");
109
112
  }
110
- // Inline probe imports builtins only; no project loader, package resolution,
111
- // configuration, Store, credentials, network or inherited Node options.
112
- const NODE_PROBE = `
113
- const { DatabaseSync } = require('node:sqlite');
114
- const db = new DatabaseSync(':memory:');
113
+ // Inline probe uses only the selected factory and verified Native path. No project
114
+ // loader, configuration, Store, credentials, network or inherited Node options.
115
+ function buildNodeProbe(driver) {
116
+ const factory = driver.kind === "node-sqlite"
117
+ ? `const driver = (${createNodeSqliteDriver.toString()})();`
118
+ : `const driver = (${createRustNativeDriver.toString()})(require, ${JSON.stringify(driver.nativePath)});`;
119
+ return `
120
+ ${factory}
121
+ const db = driver.open(':memory:');
115
122
  try {
116
- const row = db.prepare('SELECT sqlite_source_id() AS sourceId').get();
117
- const compileOptions = db.prepare('PRAGMA compile_options').all().map(option => {
118
- const value = Object.values(option)[0];
119
- if (typeof value !== 'string') throw new Error('invalid compile option');
120
- return value;
121
- }).sort();
122
- db.enableDefensive(true);
123
- db.exec('PRAGMA writable_schema=ON');
124
- if (db.prepare('PRAGMA writable_schema').get()?.writable_schema !== 0) throw new Error('defensive mode unavailable');
125
- db.exec('CREATE TABLE runtime_probe (value INTEGER); BEGIN');
126
- if (db.isTransaction !== true) throw new Error('transaction state unavailable');
127
- if (db.prepare('INSERT INTO runtime_probe VALUES (?)').run(1).changes !== 1
128
- || db.prepare('SELECT value FROM runtime_probe').get()?.value !== 1
129
- || db.prepare('SELECT value FROM runtime_probe').all().length !== 1) throw new Error('statement APIs unavailable');
130
- db.exec('ROLLBACK');
131
- if (db.isTransaction !== false) throw new Error('transaction state unavailable');
132
- process.stdout.write(JSON.stringify({nodeVersion:process.version,sqliteVersion:process.versions.sqlite,sqliteSourceId:row.sourceId,platform:process.platform,arch:process.arch,compileOptions,sqliteCapabilities:${JSON.stringify(REQUIRED_SQLITE_CAPABILITIES)}}));
123
+ const evidence = (${probeSqliteCapabilities.toString()})(db);
124
+ process.stdout.write(JSON.stringify({...evidence,driver:driver.kind,nodeVersion:process.version,napiVersion:process.versions.napi,sqliteVersion:driver.kind==='node-sqlite'?process.versions.sqlite:driver.nativeInfo.sqliteVersion,platform:process.platform,arch:process.arch,...(driver.nativeInfo?{native:driver.nativeInfo}:{})}));
133
125
  } finally { db.close(); }
134
126
  `;
127
+ }
135
128
  export function qualifyNodeExecutable(path, options = {}) {
136
129
  const canonical = admitExecutable(path, options);
137
130
  try {
138
- const text = execFileSync(canonical, ["--input-type=commonjs", "-e", NODE_PROBE], {
131
+ const selected = options.driver ?? resolveSqliteDriver();
132
+ const text = execFileSync(canonical, ["--input-type=commonjs", "-e", buildNodeProbe(selected)], {
139
133
  cwd: "/", env: { PATH: "/usr/bin:/bin", LANG: "C", LC_ALL: "C" },
140
134
  shell: false, timeout: 5_000, killSignal: "SIGKILL", maxBuffer: 16_384,
141
135
  encoding: "utf8", stdio: ["ignore", "pipe", "pipe"],
@@ -150,9 +144,10 @@ export function qualifyNodeExecutable(path, options = {}) {
150
144
  }
151
145
  export function resolveApprovedNode(options = {}) {
152
146
  const env = options.env ?? {};
147
+ const selected = options.driver ?? resolveSqliteDriver();
153
148
  const qualify = (path) => {
154
149
  const canonical = admitExecutable(path, options);
155
- qualifyNodeExecutable(canonical, options);
150
+ qualifyNodeExecutable(canonical, { ...options, driver: selected });
156
151
  return canonical;
157
152
  };
158
153
  if (env.CE_NODE_PATH !== undefined)
@@ -161,7 +156,7 @@ export function resolveApprovedNode(options = {}) {
161
156
  const candidates = [
162
157
  options.execPath ?? process.execPath,
163
158
  ...(options.systemDirectories ?? SYSTEM_DIRECTORIES).map((directory) => join(directory, "node")),
164
- ...(isAbsolute(legacyRoot) ? APPROVED_RUNTIME_TUPLES.map(({ nodeVersion }) => join(legacyRoot, "installs/node", nodeVersion.slice(1), "bin/node")) : []),
159
+ ...(isAbsolute(legacyRoot) ? MISE_DISCOVERY_NODE_VERSIONS.map((nodeVersion) => join(legacyRoot, "installs/node", nodeVersion.slice(1), "bin/node")) : []),
165
160
  ];
166
161
  for (const path of new Set(candidates)) {
167
162
  try {
@@ -0,0 +1,131 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { loadVerifiedNativeArtifact, nativeCacheRoot, nativeTarget, prepareNativeArtifact } from "../storage/native-artifact.js";
3
+ import { NATIVE_COMPAT, parseNativeCompat } from "../storage/native-compat.js";
4
+ import { readDriverSelection, writeDriverSelection } from "../storage/sqlite-driver-selection.js";
5
+ import { assertHostRuntimeEligibility } from "../storage/runtime.js";
6
+ export const NATIVE_STARTUP_WARNING = "Chat Exchange: Native Driver is not ready. Messaging is disabled. Run /ce-native to inspect or install the trusted driver.";
7
+ const reasons = {
8
+ READY: "Verified Native driver is ready.",
9
+ MISSING: "Trusted Native driver is not cached. Run /ce-native install.",
10
+ UNTRUSTED: "Native artifact or cache failed trust verification.",
11
+ INCOMPATIBLE: "Selected driver or Native identity is incompatible with CE.",
12
+ INITIALIZATION_FAILED: "Native driver initialization failed.",
13
+ UNSUPPORTED_PLATFORM: "Native driver does not support this platform or architecture.",
14
+ };
15
+ function errorCode(error) {
16
+ const code = error instanceof Error && "code" in error ? error.code : undefined;
17
+ // Never echo arbitrary loader messages, payloads, or unknown error codes.
18
+ return typeof code === "string" && /^CE_(?:NATIVE_[A-Z_]+|SQLITE_DRIVER_SELECTION_INVALID)$/.test(code)
19
+ ? code : "CE_NATIVE_INITIALIZATION_FAILED";
20
+ }
21
+ function failureState(code) {
22
+ if (code === "CE_NATIVE_CACHE_MISSING")
23
+ return "MISSING";
24
+ if (code === "CE_NATIVE_TARGET_UNSUPPORTED")
25
+ return "UNSUPPORTED_PLATFORM";
26
+ if (/HASH|UNPINNED|CACHE_UNSAFE|ASSET_INVALID|MANIFEST_INVALID/.test(code))
27
+ return "UNTRUSTED";
28
+ if (/ABI|IDENTITY|VERSION|SELECTION|DRIVER_INCOMPATIBLE/.test(code))
29
+ return "INCOMPATIBLE";
30
+ return "INITIALIZATION_FAILED";
31
+ }
32
+ /** Release asset target for a platform pair. Windows has no published Native asset. */
33
+ export function nativeTargetName(platform, arch) {
34
+ if (platform === "darwin" && arch === "arm64")
35
+ return "aarch64-apple-darwin";
36
+ if (platform === "darwin" && arch === "x64")
37
+ return "x86_64-apple-darwin";
38
+ if (platform === "linux" && arch === "x64")
39
+ return "x86_64-unknown-linux-gnu";
40
+ if (platform === "linux" && arch === "arm64")
41
+ return "aarch64-unknown-linux-gnu";
42
+ return null;
43
+ }
44
+ function supported(options) {
45
+ return ["darwin", "linux"].includes(options.platform ?? process.platform)
46
+ && ["arm64", "x64"].includes(options.arch ?? process.arch);
47
+ }
48
+ export function inspectNativeReadiness(options = {}) {
49
+ let manifest = options.manifest ?? NATIVE_COMPAT;
50
+ let driver = "rust-native";
51
+ let version = manifest.defaultVersion;
52
+ let target = null;
53
+ try {
54
+ if (!supported(options))
55
+ throw Object.assign(new Error(), { code: "CE_NATIVE_TARGET_UNSUPPORTED" });
56
+ // The loader targets this process; injected foreign platforms are diagnostic only.
57
+ const platform = options.platform ?? process.platform;
58
+ const arch = options.arch ?? process.arch;
59
+ target = nativeTargetName(platform, arch);
60
+ const selection = readDriverSelection(options.selectionFile);
61
+ driver = selection.driver;
62
+ version = selection.nativeVersion ?? manifest.defaultVersion;
63
+ if (driver !== "rust-native")
64
+ throw Object.assign(new Error(), { code: "CE_NATIVE_DRIVER_INCOMPATIBLE" });
65
+ if (selection.manifestFile !== undefined) {
66
+ try {
67
+ manifest = parseNativeCompat(JSON.parse(readFileSync(selection.manifestFile, "utf8")));
68
+ }
69
+ catch {
70
+ throw Object.assign(new Error(), { code: "CE_NATIVE_MANIFEST_INVALID" });
71
+ }
72
+ }
73
+ if (platform !== process.platform || arch !== process.arch)
74
+ throw Object.assign(new Error(), { code: "CE_NATIVE_TARGET_UNSUPPORTED" });
75
+ const verified = loadVerifiedNativeArtifact({ root: options.root ?? nativeCacheRoot(), version, manifest });
76
+ return { state: "READY", code: "CE_NATIVE_READY", reason: reasons.READY, driver, version,
77
+ abiVersion: verified.info.abiVersion, sqliteVersion: verified.info.sqliteVersion, target };
78
+ }
79
+ catch (error) {
80
+ const code = errorCode(error);
81
+ const state = failureState(code);
82
+ return { state, code, reason: reasons[state], driver, version, abiVersion: manifest.abiVersion, sqliteVersion: null, target };
83
+ }
84
+ }
85
+ /** Revalidate immediately before Tunnel side effects. Artifact presence alone is
86
+ * insufficient: the selected Native module must also pass the production Store admission battery. */
87
+ export function assertNativeReadyForTunnel() {
88
+ const readiness = inspectNativeReadiness();
89
+ if (readiness.state !== "READY")
90
+ throw Object.assign(new Error("Native is not ready; run /ce-native before starting Tunnel"), { code: readiness.code });
91
+ assertHostRuntimeEligibility();
92
+ return readiness;
93
+ }
94
+ export async function runNativeCommand(args, options = {}) {
95
+ const command = args.trim();
96
+ if (command === "" || command === "status" || command === "verify")
97
+ return JSON.stringify(inspectNativeReadiness(options), null, 2);
98
+ if (command !== "install" && command !== "repair confirm" && command !== "check-updates") {
99
+ return "Usage: /ce-native [status|install|verify|repair confirm|check-updates]. Repair requires explicit repair confirm.";
100
+ }
101
+ const manifest = options.manifest ?? NATIVE_COMPAT;
102
+ try {
103
+ if (command === "check-updates") {
104
+ // Release metadata is discovery, never an artifact trust anchor or selection input.
105
+ const response = await (options.fetchImpl ?? fetch)(`https://api.github.com/repos/${NATIVE_COMPAT.repository}/releases/latest`, {
106
+ redirect: "error", headers: { Accept: "application/vnd.github+json" }, signal: AbortSignal.timeout(10_000),
107
+ });
108
+ if (!response.ok)
109
+ throw Object.assign(new Error(), { code: "CE_NATIVE_DISCOVERY_FAILED" });
110
+ const metadata = await response.json();
111
+ if (typeof metadata !== "object" || metadata === null || !("tag_name" in metadata) || typeof metadata.tag_name !== "string") {
112
+ throw Object.assign(new Error(), { code: "CE_NATIVE_DISCOVERY_FAILED" });
113
+ }
114
+ const differs = metadata.tag_name !== `ce-sqlite-v${manifest.defaultVersion}`;
115
+ return `Current trusted Native version: ${manifest.defaultVersion}. Release discovery ${differs ? "differs; wait for a CE compatibility update" : "matches the trusted version"}. No driver was installed or selected.`;
116
+ }
117
+ if (!supported(options) || (options.platform !== undefined && options.platform !== process.platform)
118
+ || (options.arch !== undefined && options.arch !== process.arch))
119
+ throw Object.assign(new Error(), { code: "CE_NATIVE_TARGET_UNSUPPORTED" });
120
+ await prepareNativeArtifact({ root: options.root ?? nativeCacheRoot(), manifest, version: manifest.defaultVersion,
121
+ repairCorrupt: command === "repair confirm",
122
+ ...(options.fetchImpl === undefined ? {} : { fetchImpl: options.fetchImpl }) });
123
+ // Selection changes only after the fixed default artifact has been verified.
124
+ writeDriverSelection({ driver: "rust-native", nativeVersion: manifest.defaultVersion }, options.selectionFile);
125
+ return `Trusted Native ${manifest.defaultVersion} installed and selected. Restart Pi to initialize messaging with the installed driver.`;
126
+ }
127
+ catch (error) {
128
+ return `Native command failed (${errorCode(error)}). Current selection was not changed.`;
129
+ }
130
+ }
131
+ //# sourceMappingURL=native-readiness.js.map
@@ -1,6 +1,6 @@
1
- import { DatabaseSync } from "node:sqlite";
2
1
  import { assertSecureDatabaseArtifacts, prepareDatabasePath, exclusivelyCreateDatabase, pathStat, withRestrictiveUmask, } from "./filesystem.js";
3
2
  import { assertRuntimeEligibility, readRuntimeIdentity, } from "./runtime.js";
3
+ import { resolveSqliteDriver } from "./sqlite-driver-selection.js";
4
4
  export const DEFAULT_BUSY_TIMEOUT_MS = 1_000;
5
5
  export const MAX_BUSY_TIMEOUT_MS = 5_000;
6
6
  export const WAL_AUTOCHECKPOINT_PAGES = 1_000;
@@ -12,7 +12,7 @@ export class ConnectionPolicyError extends Error {
12
12
  }
13
13
  }
14
14
  export function assertStorageRuntimeEligibility(options) {
15
- assertRuntimeEligibility((options.runtimeIdentity ?? readRuntimeIdentity)());
15
+ assertRuntimeEligibility((options.runtimeIdentity ?? (() => readRuntimeIdentity(options.driver)))());
16
16
  }
17
17
  function readPragma(db, name) {
18
18
  const row = db.prepare(`PRAGMA ${name}`).get();
@@ -65,7 +65,8 @@ export function openStorageConnection(options, validateExisting, createExclusive
65
65
  }
66
66
  let db;
67
67
  try {
68
- db = withRestrictiveUmask(() => new DatabaseSync(databasePath, { defensive: true, timeout: busyTimeoutMs }));
68
+ const driver = options.driver ?? resolveSqliteDriver();
69
+ db = withRestrictiveUmask(() => driver.open(databasePath, { defensive: true, timeout: busyTimeoutMs }));
69
70
  // Revalidate identity/compatibility before persistent writer PRAGMAs.
70
71
  // A read transaction gives these checks one consistent schema/data snapshot.
71
72
  if (validateExisting !== undefined) {