@balababa/codex-mesh 0.3.0 → 0.5.0

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,155 +1,341 @@
1
1
  # Codex Mesh
2
2
 
3
- Codex Mesh 提供三个入口:
3
+ **让分散在不同机器上的原生 Codex 会话互相发现、通信与协作。**
4
4
 
5
- | 组件 | 入口 | 用途 |
6
- | --- | --- | --- |
7
- | Mesh 服务端 | `codex-mesh hub` | 部署在公网服务器,提供认证、成员登记和消息路由 |
8
- | 普通 Codex 接入 | Mesh MCP + `$codex-mesh` Skill | 普通 `codex` 加入集群、查询、收发消息和自动唤醒 |
9
- | 集群管理工具 | `codex-mesh agents`,可选 `codex-mesh tui` | 查看全网明确登记的 Agent 和状态 |
5
+ Codex Mesh 不是一种新的 Agent,而是给原本独立的 Codex Agent 加上网络能力:
6
+ 你继续用普通的 `codex`,只是它现在能看见并调用其他机器上的同伴。
7
+
8
+ ![Codex Mesh 架构总览](docs/assets/architecture.svg)
10
9
 
11
- 日常工作继续用普通 `codex`。每台机器的后台 Node 连接自己的 native daemon;
12
- Hub 不参与推理或任务调度。Agent 使用原生 Thread ID,只有显式加入的会话才会
13
- 对外展示。当前公网服务器通过认证 SSH 隧道提供远程服务,Hub 监听 loopback。
10
+ ## 这是什么
14
11
 
15
- 从 [三个入口的部署与使用说明](docs/PRODUCTS.md) 开始。
12
+ | 组件 | 入口 | 作用 |
13
+ | --- | --- | --- |
14
+ | **Mesh Hub**(服务端) | `codex-mesh hub` | 认证、成员登记、消息路由、持久收件箱。**不做推理、不调度任务** |
15
+ | **Mesh Node**(每台机器) | 后台常驻进程 | 连接本机 Codex daemon,向 Hub 发起出站连接 |
16
+ | **Mesh MCP + Skill** | `$codex-mesh` | 让普通 `codex` 会话加入集群、发现同伴、收发消息 |
17
+ | **集群管理** | `codex-mesh agents` / 网页面板 | 查看全网已登记的 Agent 与状态 |
16
18
 
17
- The core MVP has run on three machines: ali hosts the Hub, and ascend and gpuplct
18
- host Nodes. Real Codex models exchanged an attributed request and result, created
19
- a remote Agent with an idempotency key, and renamed a remote native thread. The
20
- native command center displayed both hosts and opened a live remote conversation.
21
- An existing thread kept its ID, history, permissions, and original tools while
22
- gaining Mesh tools on an opted-in shared App Server.
19
+ ### 三条设计原则
23
20
 
24
- See the [measured test report](docs/TEST_REPORT.md), [requirements audit](docs/REQUIREMENTS_AUDIT.md),
25
- and [progress log](docs/PROGRESS.md) for what was verified and what remains. The
26
- MVP does not yet cover generalized file transfer or all combinations of native
27
- commands and recovery behavior. Stock MCP queue/steer has separate opt-in
28
- semantics and measured coverage described in docs/STOCK_CODEX.md. Small
29
- operator-published artifacts can be downloaded through an opt-in bounded reader;
30
- see [artifact exports](docs/ARTIFACTS.md).
21
+ - **无主(Masterless)**:所有 Agent 地位平等,Hub 只是认证过的基础设施。
22
+ - **会话原生(Session-native)**:Codex 原生 Thread ID 就是 Agent 的唯一身份。重命名不改变它,Fork 后的新会话有独立身份。
23
+ - **本地优先(Local-first)**:Mesh 是可选能力。Hub 不可用时,本地 Codex 照常工作。
31
24
 
32
- ## npm 安装与普通用户接入
25
+ ### 边界(重要)
33
26
 
34
- 当前源码版本为 **0.3.0**,新增 Hub 网页管理界面。Rust Hub/Node/MCP/管理命令、
35
- 启动器和 Skill 使用同一版本。普通用户不需要 Rust、源码仓库或本地编译。
36
- 支持 Linux x86_64、glibc >=2.35,Node.js >=24.19.0。
27
+ - **只有显式加入的会话才会对外展示。** 安装、setup、doctor、打开网页都不会登记任何会话,也不会读取私有历史。
28
+ - **各机器使用自己的 Codex 认证、模型、沙箱与审批策略。** Codex 登录凭据从不上传到 Hub。
29
+ - **Hub 强制只监听 loopback。** 公网访问必须经 SSH 隧道或已验证的 HTTPS 反向代理。
37
30
 
38
- 包名为 **`@balababa/codex-mesh`**。npm 已发布版本为 **0.2.0**;当前 0.3.0
39
- 尚未发布。连接 0.3.0 Hub 时需使用匹配的 0.3.0 本地产物:
31
+ ## 快速开始
40
32
 
41
33
  ```sh
42
- npm install -g /absolute/path/balababa-codex-mesh-0.3.0.tgz
34
+ # 服务端(详见下文"部署服务端")
35
+ docker compose up -d --build
36
+
37
+ # 客户端:每台已装 Codex 的机器
38
+ npm install -g @balababa/codex-mesh@0.5.0
43
39
  codex-mesh setup
44
40
  codex-mesh doctor
45
41
  codex
46
42
  ```
47
43
 
48
- 在新的普通 Codex 会话中输入 `$codex-mesh 加入 Mesh`。
49
- `setup` 交互式收集 Hub、节点凭据文件和目录白名单,也提供
50
- `--non-interactive` 模式。它配置稳定路径下的后台 Node、MCP 和 Skill;
51
- 安装/检查不登记会话。服务端用同包的 `credentials issue` 签发独立节点和管理
52
- 凭据。管理端保存配置后,直接 `codex-mesh agents`。
44
+ ---
45
+
46
+ ## 客户端:安装与使用
47
+
48
+ ![客户端接入流程](docs/assets/client-onboarding.svg)
49
+
50
+ ### 前提
53
51
 
54
- 同一个本地 tarball 可用于 npx 按需启动 MCP:
52
+ - Linux x86_64,glibc ≥ 2.35,Node.js ≥ 24.19.0
53
+ - 机器已安装 Codex 并正常登录,**Codex daemon 正在运行**(daemon 版本 0.173.x / 0.174.x 为已验证范围)
54
+ - 不需要 Rust、编译器或本仓库源码
55
+
56
+ ### 1. 安装
55
57
 
56
58
  ```sh
57
- npx --yes --package=/absolute/path/balababa-codex-mesh-0.3.0.tgz \
58
- codex-mesh mcp --socket /absolute/private/mesh/mcp.sock
59
+ npm install -g @balababa/codex-mesh@0.5.0
59
60
  ```
60
61
 
61
- 完整安装、签发、SSH 接入、非交互配置、管理配置、doctor 与升级说明见
62
- [INSTALL.md](docs/INSTALL.md)。默认使用 systemd user 服务;升级 npm 本身不会
63
- 重启 Node 或用户 daemon,改变配置/版本时需要在会话退出 Mesh 后重新 setup。
62
+ 包内含预编译 Rust 二进制、启动器和 Skill。npm 包名是 `@balababa/codex-mesh`,命令是 `codex-mesh`。
63
+
64
+ > 无关的同名未限定包 `codex-mesh` 不是本项目。Hub 与客户端版本必须一致。
64
65
 
65
- ## Build
66
+ ### 2. 运行 setup,浏览器授权本机
66
67
 
67
68
  ```sh
68
- cargo build --locked
69
- cargo test --workspace --locked
70
- cargo run -- --help
69
+ codex-mesh setup
71
70
  ```
72
71
 
73
- Mesh services require Rust 1.95 or newer. Building the separate native TUI patch
74
- uses the upstream pinned Rust 1.99.1 toolchain without changing your default:
72
+ 交互式 setup 会依次:
73
+
74
+ 1. 询问 Hub 地址和本机显示名称(默认主机名)
75
+ 2. 打印一个短时效授权链接和确认码
76
+ 3. 你在**任意设备**的浏览器打开链接,核对机器信息与确认码,输入管理 Token 并批准
77
+ 4. 终端自动保存本机独立节点凭据,继续安装后台 Node、MCP 和 Skill
78
+
79
+ 管理 Token **不会**保存到本机,浏览器授权只是签发本机自己的节点凭据。授权链接 10 分钟有效;中断后重跑 setup 可续接。
80
+
81
+ ### 3. 自检
75
82
 
76
83
  ```sh
77
- ./scripts/prepare-upstream.sh
78
- ./scripts/build-native.sh
84
+ codex-mesh doctor
85
+ ```
86
+
87
+ 检查版本、凭据、Hub 连通、Codex daemon、Node 服务、MCP 注册与 Skill。**不登记会话、不触发推理。**
88
+
89
+ ### 4. 在普通 codex 里显式加入
90
+
91
+ 在允许的项目目录打开普通 `codex`,输入:
92
+
93
+ ```text
94
+ $codex-mesh 加入 Mesh
95
+ ```
96
+
97
+ 只有这一步才会登记当前会话。日常对话仍然是原生 Codex 体验。
98
+
99
+ ### 5. 使用
100
+
101
+ ```text
102
+ $codex-mesh 列出在线机器和 Agent。
103
+ 给 <名字或原生 session_id> 发消息:帮我检查这个问题……
104
+ 查看 Mesh 收件箱。
105
+ 退出 Mesh。
79
106
  ```
80
107
 
81
- Mesh uses an independent `codex-mesh` executable and never replaces installed
82
- `codex`. A Node needs its machine's normally authenticated Codex CLI; the Hub does
83
- not. The pinned official source is described in docs/UPSTREAM_BASELINE.json.
84
- Upstream Apache-2.0 LICENSE and NOTICE are retained.
108
+ 底层是 8 个 Mesh MCP 工具:
109
+
110
+ | 工具 | 用途 |
111
+ | --- | --- |
112
+ | `mesh_join` / `mesh_leave` | 显式加入 / 退出(退出保留原生会话) |
113
+ | `mesh_whoami` | 读取本会话的原生身份 |
114
+ | `mesh_list_nodes` / `mesh_list_agents` / `mesh_get_status` | 发现机器、同伴与集群状态 |
115
+ | `mesh_send_message` | 发消息给同伴 |
116
+ | `mesh_get_messages` | 读取本会话的持久收件箱 |
85
117
 
86
- ## Development safety
118
+ 消息投递语义:
87
119
 
88
- Use independent runtime directories, allowlisted test workspaces and per-Node
89
- credentials. The initial Hub binds to loopback and must be reached via an SSH
90
- tunnel or certificate-verified TLS. Codex login credentials are never uploaded to
91
- the Hub. Do not enable unrestricted execution for tests or enroll private threads.
120
+ - `request` + `enqueue`(默认):空闲同伴会被唤醒,忙的排队等当前轮次结束
121
+ - `request` + `steer`:立即补充到正在进行的轮次(需要接收方已选择加入)
122
+ - `notify`:只进收件箱,不唤醒
123
+ - 回复用 `reply` / `result` + `notify`,避免自动回信循环
92
124
 
93
- The authorized test-fleet deployment and status commands are:
125
+ ### 脚本化与非交互安装
94
126
 
95
127
  ```sh
96
- cargo build --release --locked
97
- python3 scripts/deploy-test-cluster.py --apply --native-package artifacts/native/package
98
- python3 scripts/deploy-test-cluster.py --status
99
- target/release/codex-mesh rpc --hub http://127.0.0.1:19010 \
100
- --token-file .mesh/cluster/client.token mesh.list_nodes
128
+ codex-mesh setup --non-interactive \
129
+ --hub https://mesh.example.com \
130
+ --node-token-file /private/received/laptop.token \
131
+ --node-name laptop \
132
+ --allow-dir /absolute/project/one --allow-dir /absolute/project/two
101
133
  ```
102
134
 
103
- The script provisions only project-owned user services, credentials and allowlisted
104
- test workspaces on `ali`, `gpuplct`, and the local machine. Read
105
- [deployment instructions](docs/DEPLOYMENT.md) before running it on another setup.
106
- The native UI launcher is:
135
+ Token 走私有文件,**不要**把 Token 值作为命令行参数。首次 setup 的允许目录默认是用户主目录;用 `--allow-dir` 收窄范围。
136
+
137
+ ### 容器或无 systemd 环境
107
138
 
108
139
  ```sh
109
- target/release/codex-mesh tui --hub http://127.0.0.1:19010 \
110
- --token-file .mesh/cluster/client.token --node ascend \
111
- --codex artifacts/native/package/bin/codex-mesh-native -- agents
140
+ codex-mesh setup --service process
112
141
  ```
113
142
 
114
- Press F6 to switch between the global and local roster. Select a session and
115
- press Enter to use its ordinary Codex conversation. Within a connected session,
116
- `/mesh nodes`, `/mesh agents`, `/mesh inbox` and `/status` show cluster state.
117
- `/send <session-id-or-name> <message>` sends an ordinary message;
118
- `/spawn <node> <absolute-directory> <name> [initial task]` creates a real native
119
- Agent in an allowed destination directory. Quote names or directories with spaces.
120
- Existing sessions are published only after explicit enrollment; the
121
- [protocol guide](docs/PROTOCOL.md)
122
- explains shared App Server attachment and the opt-in for attaching model tools.
123
- `codex-mesh local` launches ordinary local Codex without contacting the Hub.
124
- Read [AGENTS.md](AGENTS.md) before contributing.
143
+ 默认使用 systemd user 服务。`--service process` 是显式的脱离进程后端,重启后需要重新 setup。
125
144
 
126
- ## Ordinary Codex through MCP
145
+ ### 集群管理(不需要 Codex)
127
146
 
128
- An additional opt-in path lets an unmodified Codex session use Mesh through a
129
- private local MCP adapter while its Node attaches to the same native daemon.
130
- Explicit joins preserve the native thread ID; request messages can wake the
131
- original thread through the native queue, with generated source headers.
132
- Use `codex-mesh setup` to install the included
133
- [codex-mesh Skill](skills/codex-mesh/SKILL.md), provision the local Node connection
134
- and register MCP. The older `scripts/install-stock-skill.py` remains a source-tree
135
- operator helper, not the npm user flow. In a new ordinary `codex` session, ask:
147
+ 只做管理、不跑 Agent 的机器:
136
148
 
137
- ```text
138
- $codex-mesh 加入 Mesh,列出在线机器和 Agent。
149
+ ```sh
150
+ codex-mesh setup --manager --non-interactive \
151
+ --hub https://mesh.example.com --admin-token-file /private/manager.token
152
+ codex-mesh agents
153
+ codex-mesh agents --json
139
154
  ```
140
155
 
141
- See [ordinary Codex setup and delivery semantics](docs/STOCK_CODEX.md).
142
- Building alone does not install the Skill, register MCP or switch a deployment.
156
+ ---
157
+
158
+ ## 部署服务端(Hub)
159
+
160
+ ![服务端容器部署](docs/assets/server-docker.svg)
161
+
162
+ Hub 是**纯基础设施**:不需要安装 Codex、不需要登录模型、不做推理。
163
+
164
+ ### 方式一:Docker Compose(推荐)
165
+
166
+ Docker 配置随 GitHub 源码 Release 分发,不包含在 npm 运行包内。先下载或克隆与客户端相同的 `v0.5.0` 源码标签,再执行以下命令。
167
+
168
+ Hub 强制只监听 loopback。容器方案让 Hub 监听容器内 `127.0.0.1:9010`,由共享网络命名空间的 Caddy 终止 TLS 并对外提供 80/443。**Hub 的 9010 端口不发布到宿主机。**
169
+
170
+ ```sh
171
+ cd deploy/docker
172
+ cp .env.example .env
173
+ # 编辑 .env:填入真实域名和 ACME 邮箱
174
+ ```
175
+
176
+ ```sh
177
+ docker compose up -d --build
178
+ docker compose ps
179
+ ```
180
+
181
+ 首次启动时 entrypoint 会自动签发一个管理凭据(名为 `web-manager`),并开启它的节点接入授权权限。取出这个私有 Token 文件:
182
+
183
+ ```sh
184
+ docker compose exec hub cat /var/lib/codex-mesh/manager.token > manager.token
185
+ chmod 600 manager.token
186
+ ```
187
+
188
+ 用它登录 `https://你的域名/` 的网页管理面板,或在浏览器授权新机器时输入。
189
+
190
+ 域名与网络前置条件:
191
+
192
+ - 域名 A 记录指向本服务器公网 IP
193
+ - 云安全组与主机防火墙放行 TCP 80 / 443
194
+ - **保持 9010 端口私有**
195
+
196
+ ### 已有宿主机反向代理(多网站服务器)
197
+
198
+ 如果宿主机 Caddy 已经占用 80/443 并托管其他网站,不要停止或替换它。让现有 Mesh 站点继续 `reverse_proxy 127.0.0.1:9010`,然后只容器化 Hub:
199
+
200
+ ```sh
201
+ cd deploy/docker
202
+ cp .env.example .env
203
+ # 在 .env 中设置 MESH_PUBLIC_URL=https://你的域名
204
+
205
+ docker compose -f docker-compose.host-caddy.yml up -d --build
206
+ docker compose -f docker-compose.host-caddy.yml exec hub \
207
+ cat /var/lib/codex-mesh/manager.token > manager.token
208
+ chmod 600 manager.token
209
+ ```
210
+
211
+ `docker-compose.host-caddy.yml` 不启动容器 Caddy,也不发布任何端口;Hub 通过 `network_mode: host` 与宿主机共享回环地址。它保留非 root 用户、文件系统隔离和数据卷,但网络命名空间隔离弱于默认方案。宿主机反代配置可参考 `deploy/public/Caddyfile.example`,其他站点无需修改或重载。
212
+
213
+ ### 签发更多凭据
214
+
215
+ ```sh
216
+ # 管理凭据(网页面板 / 集群管理用)
217
+ docker compose exec hub codex-mesh credentials issue \
218
+ --credentials /var/lib/codex-mesh/credentials.json \
219
+ --token-file /var/lib/codex-mesh/another-manager.token \
220
+ --name another-manager --role client
221
+
222
+ # 节点凭据(脚本化接入用;浏览器授权流程不需要)
223
+ docker compose exec hub codex-mesh credentials issue \
224
+ --credentials /var/lib/codex-mesh/credentials.json \
225
+ --token-file /var/lib/codex-mesh/laptop.token \
226
+ --name laptop --role node
227
+ ```
228
+
229
+ Hub 每次认证都重新读取凭据文件,**新增授权无需重启**。Token 通过私有通道传到目标机器。
230
+
231
+ ### 升级与备份
232
+
233
+ ```sh
234
+ # 使用宿主机反代模式时,以下 docker compose 命令都要加上
235
+ # -f docker-compose.host-caddy.yml。
236
+ backup="$HOME/.local/share/codex-mesh-backups/$(date +%Y%m%d-%H%M%S)"
237
+ install -d -m 700 "$backup"
238
+
239
+ # SQLite 使用 WAL;停止 Hub 后再复制,不能依赖运行中直接 tar 数据目录。
240
+ docker compose stop hub
241
+ docker compose cp hub:/var/lib/codex-mesh/. "$backup/"
242
+ docker compose up -d --build
243
+ ```
244
+
245
+ SQLite 与凭据都在 `hub-state` 卷里,重建镜像不会丢失,**升级不要运行 `down -v`**。重启 Hub 前确认没有进行中的任务;Node 会自动重连,网页内存会话需要重新登录。保留备份和旧镜像以便回滚。
246
+
247
+ ### 方式二:裸机部署
248
+
249
+ ```sh
250
+ codex-mesh hub --bind 127.0.0.1:9010 \
251
+ --public-url https://mesh.example.com \
252
+ --database /private/mesh-hub/hub.sqlite \
253
+ --credentials /private/mesh-hub/credentials.json
254
+ ```
255
+
256
+ `--public-url` 是浏览器授权链接使用的可信来源,必须是已验证的 HTTPS 源(本地可用 loopback HTTP)。私有目录 0700、凭据文件 0600。
257
+
258
+ 全新 Hub 先签发管理凭据:
259
+
260
+ ```sh
261
+ codex-mesh credentials issue --credentials /private/mesh-hub/credentials.json \
262
+ --token-file /private/mesh-hub/manager.token --name web-manager --role client
263
+ codex-mesh credentials allow-node-enrollment \
264
+ --credentials /private/mesh-hub/credentials.json --name web-manager
265
+ ```
266
+
267
+ ### 方式三:SSH 隧道(无公网 TLS 时)
268
+
269
+ ```sh
270
+ ssh -N -o ExitOnForwardFailure=yes \
271
+ -L 127.0.0.1:19010:127.0.0.1:9010 your-hub-host
272
+ ```
273
+
274
+ 客户端 `setup` 时 Hub 地址填 `http://127.0.0.1:19010`。此方式下浏览器授权不可用,需用 `--node-token-file`。
275
+
276
+ ### 验证
277
+
278
+ ```sh
279
+ # 应返回 Hub 健康信息
280
+ curl --fail --show-error https://mesh.example.com/health
281
+ # 应返回 401
282
+ curl -s -o /dev/null -w '%{http_code}\n' https://mesh.example.com/v1/node/check
283
+ ```
284
+
285
+ 不要用 `curl -k` 当作验收。健康检查通过不代表 WebSocket 路由或唤醒机制可用,完整验收见 [PUBLIC_HUB.md](docs/PUBLIC_HUB.md)。
286
+
287
+ ---
288
+
289
+ ## 网页管理面板
290
+
291
+ Hub 根路径 `/` 内置管理面板:
292
+
293
+ - 使用**管理凭据**登录(不是节点凭据),成功后设置 7 天 HttpOnly 会话 Cookie
294
+ - 节点与 Agent 按所属关系分组,可展开、搜索
295
+ - 删除 Agent 只是让它退出 Mesh;删除 Node 会撤销服务端凭据并断开连接
296
+ - **两者都不删除原生 Codex 会话与历史**
297
+ - 网页不启动推理、不读取私有会话历史
298
+
299
+ ---
300
+
301
+ ## 已验证状态与限制
302
+
303
+ 核心 MVP 已在三台机器上真实运行:ali 部署 Hub,ascend 与 gpuplct 运行 Node。真实 Codex 模型完成过带来源标注的请求与结果交换、带幂等键的远程 Agent 创建、远程原生线程重命名。已有线程在加入后保留原有 ID、历史、权限与工具。
304
+
305
+ **尚未覆盖**:通用文件传输、原生命令与恢复行为的全部组合。Stock MCP 的 queue/steer 是独立的可选语义,覆盖范围见 [STOCK_CODEX.md](docs/STOCK_CODEX.md)。小型操作者发布产物可通过可选的受限读取器下载,见 [ARTIFACTS.md](docs/ARTIFACTS.md)。
306
+
307
+ 容器部署方案(`deploy/docker/`)已实测:镜像构建、首启自动签发凭据、Hub 仅回环监听、Caddy TLS 反代、未认证请求返回 401、宿主机无法直连 9010、Node 经 TLS 的 WebSocket 握手。**尚未实测**:真实公网域名上的 ACME 证书签发、多日运行、生产流量。
308
+
309
+ 详见 [测试报告](docs/TEST_REPORT.md)、[需求审计](docs/REQUIREMENTS_AUDIT.md)、[进度日志](docs/PROGRESS.md)。
310
+
311
+ ## 从源码构建
312
+
313
+ ```sh
314
+ cargo build --locked
315
+ cargo test --workspace --locked
316
+ cargo run -- --help
317
+ ```
318
+
319
+ 需要 Rust 1.95 或更新版本。保留的原生 App Server 补丁及其可复现构建见 [upstream analysis](docs/UPSTREAM_ANALYSIS.md)。
320
+
321
+ `codex-mesh` 是独立可执行文件,**从不替换已安装的 `codex`**。Node 需要本机正常认证的 Codex CLI;Hub 不需要。上游基线见 [UPSTREAM_BASELINE.json](docs/UPSTREAM_BASELINE.json),Apache-2.0 LICENSE 与 NOTICE 已保留。
322
+
323
+ ## 文档索引
324
+
325
+ | 文档 | 内容 |
326
+ | --- | --- |
327
+ | [INSTALL.md](docs/INSTALL.md) | npm 安装完整选项、doctor、升级与排错 |
328
+ | [PRODUCTS.md](docs/PRODUCTS.md) | 三个入口的底层命令与配置结构 |
329
+ | [PUBLIC_HUB.md](docs/PUBLIC_HUB.md) | 公网域名、Caddy、浏览器授权与验收 |
330
+ | [DEPLOYMENT.md](docs/DEPLOYMENT.md) | 已授权的三机测试集群部署脚本 |
331
+ | [ARCHITECTURE.md](docs/ARCHITECTURE.md) | 系统架构与安全边界 |
332
+ | [PROTOCOL.md](docs/PROTOCOL.md) | 网络与消息协议 |
333
+ | [SECURITY.md](docs/SECURITY.md) | 安全模型 |
334
+ | [STOCK_CODEX.md](docs/STOCK_CODEX.md) | 普通 Codex MCP 接入与投递语义 |
335
+ | [TEST_REPORT.md](docs/TEST_REPORT.md) | 真实测试结果与未覆盖范围 |
143
336
 
144
- ## 域名和网页管理
337
+ ## 开发安全
145
338
 
146
- 0.3.0 Hub 内置网页版只读集群概览,入口为 `/`。网页使用独立管理凭据,
147
- 列出所有明确登记的 Agent 和节点,不启动推理、不读取私有会话历史。
148
- 凭据仅保留在页面内存中;支持搜索、分页和刷新。Hub 仍监听回环地址,
149
- 公网域名由 HTTPS 反向代理承接。配置模板与验收步骤见
150
- [PUBLIC_HUB.md](docs/PUBLIC_HUB.md)。真实域名、TLS 和公网连通性需分别验证。
339
+ 使用独立运行目录、白名单测试工作区和每节点独立凭据。Hub 绑定 loopback,经 SSH 隧道或证书验证的 TLS 访问。Codex 登录凭据从不上传。不要为测试开启无限制执行,也不要登记私有线程。
151
340
 
152
- For an explicitly chosen daemon outside the default verified version range, use
153
- `codex-mesh setup --skip-daemon-version-check`. The choice persists for setup and
154
- doctor; `setup --check-daemon-version` restores checking. Socket security and
155
- runtime checks remain enabled. See [installation options](docs/INSTALL.md).
341
+ 贡献前请阅读 [AGENTS.md](AGENTS.md)。
package/docs/INSTALL.md CHANGED
@@ -1,14 +1,14 @@
1
1
  # npm installation and ordinary Codex setup
2
2
 
3
- Source release version: **0.3.0** (npm, Rust binary and Skill metadata).
3
+ Source release version: **0.5.0** (npm, Rust binary and Skill metadata).
4
4
 
5
5
  The npm package name is **`@balababa/codex-mesh`**, using the maintainer's
6
6
  personal scope. The operator selected this name after the prior organization
7
7
  scope failed publication with `Scope not found`. The command remains `codex-mesh`.
8
- Version 0.2.0 is published and its registry global/npx installation was verified.
9
- Source version 0.3.0 adds the Hub dashboard and is not yet published; use its
10
- matching local tarball with a 0.3.0 Hub. The unrelated unscoped `codex-mesh` package
11
- is not this implementation.
8
+ Version 0.5.0 is published to npm and the matching Linux x86_64 GNU Hub binary
9
+ is attached to GitHub Release v0.5.0 (verified on 2026-12-05). Upgrade the Hub
10
+ deliberately before connecting 0.5.0 nodes.
11
+ The unrelated unscoped `codex-mesh` package is not this implementation.
12
12
 
13
13
  ## Supported runtime
14
14
 
@@ -20,21 +20,16 @@ libgcc); consumers need no Rust/compiler/source tree. Ordinary Codex daemon
20
20
  0.173.x/0.174.x is the checked compatibility range; 0.174.0 is the real npm
21
21
  acceptance target. The daemon must already be running and normally authenticated.
22
22
 
23
- Install the published 0.2.0 release only when connecting to a matching 0.2.0 Hub:
23
+ Install the published release:
24
24
 
25
25
  ```sh
26
- npm install -g @balababa/codex-mesh@0.2.0
26
+ npm install -g @balababa/codex-mesh@0.5.0
27
27
  codex-mesh setup
28
28
  codex-mesh doctor
29
29
  ```
30
30
 
31
- For the 0.3.0 Hub/dashboard build, use the matching local artifact:
32
-
33
- ```sh
34
- npm install -g /absolute/path/balababa-codex-mesh-0.3.0.tgz
35
- codex-mesh setup
36
- codex-mesh doctor
37
- ```
31
+ The x86_64 Hub binary is available from GitHub Release `v0.5.0`; verify it with
32
+ the attached `.sha256` file before installing it on the server.
38
33
 
39
34
  Installation itself has no lifecycle hook, never joins a session and never
40
35
  starts/restarts a daemon. The package contains the original Rust executable,
@@ -42,29 +37,46 @@ stdio launcher, setup/doctor and Skill under one version/checksum manifest.
42
37
 
43
38
  ## Hub and credential provisioning
44
39
 
45
- On the Hub host, install the same tarball/version. Issue an independent node
46
- credential and an independent management credential. Paths, never secret token
47
- values, are passed as arguments:
40
+ On the Hub host, install the same tarball/version. Reuse the existing management
41
+ Token; no second management Token is needed. Enable node-enrollment permission
42
+ explicitly for its credential name (the existing deployment uses `web-manager`):
43
+
44
+ ```sh
45
+ codex-mesh credentials allow-node-enrollment \
46
+ --credentials /home/chh/.local/share/codex-mesh/hub/credentials.json \
47
+ --name web-manager
48
+ ```
49
+
50
+ This preserves the management Token and unrelated grants. Repeated execution is
51
+ safe, and new authentication reads updates without a Hub restart. Existing
52
+ credentials do not gain enrollment rights merely by upgrading.
53
+
54
+ For a new Hub only, first issue its management credential:
48
55
 
49
56
  ```sh
50
57
  codex-mesh credentials issue --credentials /private/mesh-hub/credentials.json \
51
- --token-file /private/mesh-hub/laptop.token --name laptop --role node
52
- codex-mesh credentials issue --credentials /private/mesh-hub/credentials.json \
53
- --token-file /private/mesh-hub/manager.token --name manager --role client
58
+ --token-file /private/mesh-hub/manager.token --name web-manager --role client
59
+ codex-mesh credentials allow-node-enrollment \
60
+ --credentials /private/mesh-hub/credentials.json --name web-manager
54
61
  codex-mesh hub --bind 127.0.0.1:9010 \
62
+ --public-url https://codex-mesh.wcisman.cc \
55
63
  --database /private/mesh-hub/hub.sqlite \
56
64
  --credentials /private/mesh-hub/credentials.json
57
65
  ```
58
66
 
59
- The issuer creates private directories/files, reports the node UUID and token
60
- file path without printing tokens, and preserves other grants. Transfer the node
61
- token file only to its node through an authenticated private channel. Transfer the
62
- management token only to the administrator. Hub reads atomic credential-file
63
- updates on new authentication; new nodes require no Hub restart. Existing
64
- connections retain their authenticated grant: hot revocation is not implemented.
65
- Reusing the same name/token file is idempotent; conflicting grants are refused.
66
- An interrupted issuance may leave a private token file; rerun the same command to
67
- complete it. Hub remains infrastructure and never schedules inference.
67
+ `--public-url` is the trusted origin used for browser authorization links. It must
68
+ be verified HTTPS, or loopback HTTP for local/tunnel use. Behind Caddy use the
69
+ external HTTPS origin while Hub continues listening on loopback. No forwarded
70
+ host header determines authorization links.
71
+
72
+ For automation, the existing `credentials issue --role node` and
73
+ `setup --node-token-file /private/node.token` remain supported. Transfer that
74
+ file only to its intended machine through an authenticated private channel.
75
+ Do not pass secret Token values as arguments. Hub remains infrastructure and
76
+ never schedules inference. Manually removing a grant blocks new authentication,
77
+ but an already authenticated connection retains its grant until disconnected.
78
+ The dashboard's **delete Node** action additionally closes that connection and
79
+ provides immediate revocation.
68
80
 
69
81
  Keep Hub on loopback and provide an authenticated SSH tunnel:
70
82
 
@@ -78,11 +90,29 @@ existing secure tunnel/service to survive your desired session lifecycle.
78
90
 
79
91
  ## Node setup
80
92
 
81
- Interactive `codex-mesh setup` asks for Hub URL, node token **file**, node UUID
82
- (optional, verified from Hub admission), and allowed project directories. It uses
83
- the existing ordinary Codex and discovers its owning daemon. It does not start,
84
- replace or restart Codex. If another independently owned server is used, pass
85
- `--daemon-socket` explicitly; ownership/mode checks still apply.
93
+ First-time interactive `codex-mesh setup` asks for the Hub URL and a node display
94
+ name (blank uses the machine hostname), then prints a short-lived authorization
95
+ URL and confirmation code. Open it on any device,
96
+ verify the self-reported machine name/hostname and matching code, enter the
97
+ existing authorized management Token, and approve. The CLI automatically saves
98
+ its independent Node Token and resumes configuration. The management Token is
99
+ never saved on the new machine. This works on headless servers and containers;
100
+ a browser is only needed on the device used for approval.
101
+
102
+ A request lasts 10 minutes. The CLI keeps a private pending record so rerunning
103
+ setup can resume after interruption. Approved credentials are retained if a later
104
+ local setup check fails. Timeout, denial or missing permission produces an error,
105
+ not a successful installation. Doctor points to incomplete onboarding. For a hard
106
+ process termination, follow the stale setup-lock instructions below before retry.
107
+
108
+ Existing saved node credentials are reused. Explicit `--node-token-file` uses the
109
+ file workflow. Non-interactive setup without saved/file credentials fails with
110
+ instructions rather than waiting for browser input. A Hub without browser
111
+ authorization support must be upgraded, or use the file workflow.
112
+
113
+ Setup uses the existing ordinary Codex and discovers its owning daemon; it does
114
+ not start, replace or restart Codex. If another independently owned server is
115
+ used, pass `--daemon-socket` explicitly; ownership/mode checks still apply.
86
116
 
87
117
  For scripts:
88
118
 
@@ -130,7 +160,7 @@ replies use notify to avoid wake loops.
130
160
  The same package provides every Rust subcommand, including stdio MCP:
131
161
 
132
162
  ```sh
133
- npx --yes --package=/absolute/path/balababa-codex-mesh-0.3.0.tgz \
163
+ npx --yes --package=/absolute/path/balababa-codex-mesh-0.5.0.tgz \
134
164
  codex-mesh mcp --socket /absolute/private/mesh-runtime/mcp.sock
135
165
  ```
136
166
 
@@ -169,7 +199,10 @@ Upgrade npm to the desired exact version, upgrade Hub deliberately, then rerun
169
199
  `setup` and `doctor`. No npm install hook restarts running services. If a Node has
170
200
  any enrolled sessions, a changed setup is deferred before stopping it. Ask those
171
201
  sessions to leave Mesh, then rerun. Unchanged setup is safe to repeat while joined.
172
- User Codex daemon is never restarted. Keep the existing secure Hub tunnel running.
202
+ User Codex daemon is never restarted. Keep the existing verified TLS endpoint or secure Hub tunnel running.
203
+ The current setup requires exact Hub/package release versions; it does not
204
+ silently relax that gate for older clients. Plan the Hub and node upgrades
205
+ together, and rerun setup to refresh stable services, MCP and Skill.
173
206
 
174
207
  Setup records `pending` before side effects and `ready` only after actual checks.
175
208
  Interrupted/pending setup is not reported healthy; fix the reported cause and
@@ -195,8 +228,18 @@ npx against the same local artifact. See the repository docs/TEST_REPORT.md for
195
228
 
196
229
  ## Public domain and web management
197
230
 
198
- 0.3.0 serves its read-only dashboard at the Hub root. Use a management/client
199
- credential, separate from per-node setup credentials. For verified HTTPS domain
231
+ The Hub serves its management dashboard at the Hub root. Docker deployment uses
232
+ the Compose files from the matching GitHub source tag; they are not included in
233
+ the npm runtime package. Docker users can choose the default self-contained TLS stack or `docker-compose.host-caddy.yml`, which
234
+ keeps an existing multi-site host Caddy unchanged and containerizes only the
235
+ Hub. Both options preserve state in the Compose `hub-state` volume; never use
236
+ `down -v` during an upgrade. See the README deployment section for commands.
237
+ Use a management/client
238
+ credential, separate from per-node setup credentials. A successful login sets a
239
+ seven-day HttpOnly session cookie; the original Token is not persisted by the
240
+ browser. Agents are grouped under Nodes, with expand/collapse and confirmed
241
+ Agent/Node removal. Agent removal requires an online Node; Node removal revokes
242
+ its credential and Hub records. Neither removes native Codex history. For verified HTTPS domain
200
243
  access, Caddy reverse proxy, external checks and current privilege prerequisites,
201
244
  see [PUBLIC_HUB.md](PUBLIC_HUB.md). HTTP remains loopback-only.
202
245
 
@@ -217,5 +260,9 @@ skipped version check explicitly. Re-enable the default with
217
260
  setup; they are mutually exclusive. Only the version gate is bypassed: running
218
261
  daemon discovery, private owned socket checks, actual Node startup/connectivity,
219
262
  MCP and all sandbox/approval rules still apply. This does not certify 0.172.0
220
- native queue/steer compatibility. Use an actual project allowlist rather than
221
- accepting Downloads unless that is the intended workspace.
263
+ native queue/steer compatibility.
264
+
265
+ First-time setup defaults the allowed directory to the current user home (`~`),
266
+ in both interactive and non-interactive modes. Saved allowlists remain unchanged
267
+ on repeat setup; explicit `--allow-dir` values override them. This includes home
268
+ subdirectories. Use explicit project directories when a narrower scope is wanted.
@@ -0,0 +1,105 @@
1
+ // Browser approval only provisions a node credential. It never enrolls a Codex thread.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import os from 'node:os';
5
+ import crypto from 'node:crypto';
6
+ import {spawn} from 'node:child_process';
7
+
8
+ const pendingName='enrollment.json';
9
+ const digest=value=>crypto.createHash('sha256').update(value).digest('hex');
10
+ function checkFile(file) {
11
+ const stat=fs.lstatSync(file);
12
+ if(!stat.isFile()||stat.isSymbolicLink()||stat.uid!==process.getuid()||(stat.mode&0o077))throw new Error(`Private owned regular file required (chmod 600): ${file}`);
13
+ }
14
+ function write(file,value) {
15
+ if(fs.existsSync(file))checkFile(file);
16
+ const temporary=file+'.new-'+crypto.randomUUID();
17
+ const fd=fs.openSync(temporary,'wx',0o600);
18
+ try{fs.writeFileSync(fd,JSON.stringify(value,null,2)+'\n');fs.fsyncSync(fd);}finally{fs.closeSync(fd);}
19
+ fs.renameSync(temporary,file);
20
+ }
21
+ export function pendingEnrollment(root) {
22
+ const file=path.join(root,pendingName);
23
+ if(!fs.existsSync(file))return null;
24
+ checkFile(file);
25
+ const state=JSON.parse(fs.readFileSync(file,'utf8'));
26
+ if(typeof state.hub!=='string'||typeof state.token!=='string'||! /^[a-f0-9]{64}$/.test(state.token)||! /^[a-f0-9]{64}$/.test(state.claim))throw new Error('Invalid saved browser authorization; preserve private state and rerun setup with a token file');
27
+ return state;
28
+ }
29
+ function verificationUrl(value,hub,id) {
30
+ const url=new URL(value);
31
+ if(!['https:','http:'].includes(url.protocol)||url.username||url.password||url.search||url.hash||url.origin!==new URL(hub.replace(/^ws:/,'http:').replace(/^wss:/,'https:')).origin||url.pathname!=='/activate/'+id)throw new Error('Hub returned an unsafe authorization URL; check its --public-url configuration.');
32
+ return url.href;
33
+ }
34
+ function browser(url) {
35
+ if(!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY)return;
36
+ try {
37
+ const child=spawn('xdg-open',[url],{detached:true,stdio:'ignore'});
38
+ child.on('error',()=>{});child.unref();
39
+ } catch {}
40
+ }
41
+ const pause=(ms,signal)=>new Promise((resolve,reject)=>{
42
+ if(signal?.aborted){reject(new Error('Authorization interrupted; rerun setup to resume.'));return;}
43
+ const aborted=()=>{clearTimeout(timer);reject(new Error('Authorization interrupted; rerun setup to resume.'));};
44
+ const timer=setTimeout(()=>{signal?.removeEventListener('abort',aborted);resolve();},ms);
45
+ signal?.addEventListener('abort',aborted,{once:true});
46
+ });
47
+ function terminalState(state) {
48
+ if(['denied','cancelled','expired'].includes(state))throw new Error(`Browser authorization ${state}; rerun setup to request authorization again.`);
49
+ }
50
+ export async function browserEnrollment({root,hub,nodeName,version,request,validateGrant,signal,log=console.log,openBrowser=browser,sleep=pause,now=()=>Date.now()}) {
51
+ const file=path.join(root,pendingName);
52
+ let state=pendingEnrollment(root);
53
+ if(state&&state.hub!==hub)throw new Error('Pending browser authorization belongs to a different Hub; resume it with that Hub or explicitly use --node-token-file.');
54
+ if(state&&nodeName&&nodeName!==state.node_name)throw new Error(`Pending browser authorization uses node name "${state.node_name}"; resume it with that name.`);
55
+ if(!state) {
56
+ state={hub,version,node_name:nodeName||os.hostname(),hostname:os.hostname(),token:crypto.randomBytes(32).toString('hex'),claim:crypto.randomBytes(32).toString('hex')};
57
+ write(file,state);
58
+ }
59
+ if(!state.request_id) {
60
+ let started;
61
+ try {started=await request(hub,'/v1/enrollment/start',null,{node_name:state.node_name,hostname:state.hostname,token_sha256:digest(state.token),claim_sha256:digest(state.claim)});}
62
+ catch(error) {
63
+ if([404,405].includes(error.status))throw new Error('This Hub does not support browser authorization. Upgrade the Hub to 0.4.0 or use setup --node-token-file FILE.');
64
+ if(error.status===503)throw new Error('Browser authorization is unavailable. Configure the Hub --public-url, or use setup --node-token-file FILE.');
65
+ throw error;
66
+ }
67
+ const verification=verificationUrl(started.verification_uri,hub,started.request_id);
68
+ if(!/^[0-9a-f-]{36}$/.test(started.request_id)||!/^[0-9a-f-]{36}$/.test(started.node_id)||typeof started.user_code!=='string'||!/^[A-Z0-9-]{4,32}$/.test(started.user_code)||!Number.isFinite(started.expires_at))throw new Error('Hub returned an invalid browser authorization response.');
69
+ state={...state,...{request_id:started.request_id,node_id:started.node_id,user_code:started.user_code,verification_uri:verification,expires_at:started.expires_at,interval:3}};
70
+ write(file,state);
71
+ }
72
+ verificationUrl(state.verification_uri,hub,state.request_id);
73
+ log(`Open this link to authorize this machine:\n${state.verification_uri}\nConfirmation code: ${state.user_code}\nEnter your management token in the browser only. Waiting for authorization…`);
74
+ openBrowser(state.verification_uri);
75
+ const endpoint='/v1/enrollment/'+state.request_id;
76
+ for(;;) {
77
+ if(signal?.aborted)throw new Error('Authorization interrupted; rerun setup to resume.');
78
+ let result;
79
+ try{result=await request(hub,endpoint+'/poll',state.claim,{});}
80
+ catch(error){
81
+ if([401,404,410].includes(error.status)&&state.expires_at*1000<=now()){fs.rmSync(file);throw new Error('Browser authorization expired or unavailable; rerun setup to request a new link.');}
82
+ throw new Error(`Authorization status unavailable; rerun setup to resume. ${error.message}`);
83
+ }
84
+ if(['denied','cancelled','expired'].includes(result.status)){fs.rmSync(file);terminalState(result.status);}
85
+ if(['approved','completed'].includes(result.status)) {
86
+ const grant=await request(hub,'/v1/node/check',state.token);
87
+ if(grant.node_id!==state.node_id)throw new Error('Authorized node identity does not match this authorization request.');
88
+ if(validateGrant)validateGrant(grant);
89
+ const tokenFile=path.join(root,'node.token');
90
+ if(fs.existsSync(tokenFile))checkFile(tokenFile);
91
+ const temporary=tokenFile+'.new-'+crypto.randomUUID();
92
+ const fd=fs.openSync(temporary,'wx',0o600);
93
+ try{fs.writeFileSync(fd,state.token+'\n');fs.fsyncSync(fd);}finally{fs.closeSync(fd);}
94
+ fs.renameSync(temporary,tokenFile);
95
+ await request(hub,endpoint+'/complete',state.claim,{});
96
+ fs.rmSync(file);
97
+ log('Machine authorized. Node credential saved privately; no Codex session enrolled.');
98
+ return {token:state.token,grant};
99
+ }
100
+ if(result.status!=='pending')throw new Error('Hub returned an invalid authorization status.');
101
+ if(result.expires_at!==undefined&&result.expires_at*1000<=now()){fs.rmSync(file);terminalState('expired');}
102
+ if(state.expires_at*1000<=now()){fs.rmSync(file);terminalState('expired');}
103
+ await sleep(3000,signal);
104
+ }
105
+ }
@@ -7,6 +7,7 @@ import https from 'node:https';
7
7
  import crypto from 'node:crypto';
8
8
  import {spawn, spawnSync, execFileSync} from 'node:child_process';
9
9
  import {createInterface} from 'node:readline/promises';
10
+ import {browserEnrollment, pendingEnrollment} from './enrollment.mjs';
10
11
 
11
12
  const marker='Managed by codex-mesh npm setup';
12
13
  const home=()=>path.resolve(process.env.CODEX_MESH_HOME || path.join(os.homedir(),'.local/share/codex-mesh/npm'));
@@ -46,13 +47,13 @@ async function request(hub,endpoint,token,body) {
46
47
  const response=await new Promise((resolve,reject)=>{
47
48
  const transport=url.protocol==='https:'?https:http;
48
49
  const directAgent=new transport.Agent({keepAlive:false,proxyEnv:{}});
49
- const req=transport.request(url,{agent:directAgent,method:body?'POST':'GET',headers:{authorization:'Bearer '+token,...(body?{'content-type':'application/json'}:{})}},res=>{
50
+ const req=transport.request(url,{agent:directAgent,method:body?'POST':'GET',headers:{...(token?{authorization:'Bearer '+token}:{}),...(body?{'content-type':'application/json'}:{})}},res=>{
50
51
  let bytes=0,text='';res.setEncoding('utf8');res.on('data',chunk=>{bytes+=Buffer.byteLength(chunk);if(bytes>1024*1024){req.destroy(new Error('Hub response exceeds limit'));return;}text+=chunk;});res.on('end',()=>resolve({status:res.statusCode,text}));res.on('error',reject);
51
52
  });
52
53
  req.setTimeout(10000,()=>req.destroy(new Error('Hub request timed out')));req.on('error',()=>reject(new Error('Hub connection failed; check URL, tunnel and certificate')));
53
54
  req.end(body?JSON.stringify(body):undefined);
54
55
  });
55
- if(response.status<200||response.status>=300) throw new Error(`Hub authentication/connectivity failed (HTTP ${response.status}); check tunnel, Hub and credential role`);
56
+ if(response.status<200||response.status>=300) {const error=new Error(`Hub authentication/connectivity failed (HTTP ${response.status}); check tunnel, Hub and credential role`);error.status=response.status;throw error;}
56
57
  const result=JSON.parse(response.text);if(result.error) throw new Error('Hub rejected operation; check credential role/grants');return result;
57
58
  }
58
59
  function command(program,args,options={}) {
@@ -169,20 +170,18 @@ async function setup(o,context) {
169
170
  try {
170
171
  const file=path.join(root,'installation.json');const old=fs.existsSync(file)?json(file):null;
171
172
  const managerFile=path.join(root,'management.json');const managerSaved=fs.existsSync(managerFile)?json(managerFile):null;
173
+ const pending=o.nonInteractive||o.manager?null:pendingEnrollment(root);
174
+ if(pending&&o.nodeName&&o.nodeName!==pending.node_name)throw new Error(`Saved browser authorization uses node name "${pending.node_name}"; resume it with that name or explicitly use --node-token-file`);
172
175
  if(!o.nonInteractive && !process.stdin.isTTY)throw new Error('No interactive terminal; use setup --non-interactive with explicit options');
173
176
  if(!o.nonInteractive) {
174
177
  const rl=createInterface({input:process.stdin,output:process.stdout});
175
178
  try{
176
179
  o.hub=o.hub||await rl.question(`Hub URL [${old?.hub||'http://127.0.0.1:19010'}]: `)||old?.hub||'http://127.0.0.1:19010';
177
180
  if(o.manager)o.adminTokenFile=o.adminTokenFile||await rl.question('Management token FILE path (not the token): ');
178
- else {
179
- o.tokenFile=o.tokenFile||await rl.question('Node token FILE path (leave empty to reuse saved credential): ')||undefined;
180
- o.nodeId=o.nodeId||await rl.question(`Node UUID [${old?.nodeId||'from Hub credential'}]: `)||old?.nodeId;
181
- const dir=await rl.question(`Allowed project directory [${old?.allowed?.join(', ')||process.cwd()}]: `);
182
- if(!o.allowDirs.length)o.allowDirs=dir?[dir]:(old?.allowed||[process.cwd()]);
183
- }
181
+ else if(!o.nodeName){const defaultName=pending?.node_name||old?.nodeName||os.hostname();o.nodeName=await rl.question(`Node display name [${defaultName}]: `)||defaultName;}
184
182
  }finally{rl.close();}
185
183
  }
184
+ if(!o.manager&&(o.nodeName!==undefined)&&(typeof o.nodeName!=='string'||!o.nodeName.length||o.nodeName.length>128||/[\p{Cc}]/u.test(o.nodeName)))throw new Error('Node display name must be 1-128 characters without control characters');
186
185
  const hub=hubUrl(o.hub||old?.hub||managerSaved?.hub||'');
187
186
  if(o.manager) {
188
187
  if(!o.adminTokenFile && !managerSaved?.tokenFile)throw new Error('Manager setup requires --admin-token-file');
@@ -191,16 +190,26 @@ async function setup(o,context) {
191
190
  write(path.join(root,'admin.token'),token+'\n');write(path.join(root,'management.json'),{version:context.version,hub,tokenFile:path.join(root,'admin.token')});
192
191
  console.log('Management configuration saved. Run codex-mesh agents. No session enrolled.');return;
193
192
  }
194
- const token=readToken(path.resolve(o.tokenFile||path.join(root,'node.token')));
195
- const grant=await request(hub,'/v1/node/check',token);
196
- if(grant.protocol_version!==1 || grant.version!==context.version)throw new Error(`Hub ${grant.version} is not compatible with package ${context.version}; upgrade the Hub deliberately first`);
193
+ const tokenFile=path.resolve(o.tokenFile||path.join(root,'node.token'));
194
+ const validateGrant=grant=>{if(grant.protocol_version!==1 || grant.version!==context.version)throw new Error(`Hub ${grant.version} is not compatible with package ${context.version}; upgrade the Hub deliberately first`);};
195
+ let token,grant;
196
+ if(!o.tokenFile&&((!o.nonInteractive&&pendingEnrollment(root))||!fs.existsSync(tokenFile))) {
197
+ if(o.nonInteractive)throw new Error('Non-interactive setup requires --node-token-file FILE or a saved credential. Run interactive setup to authorize this machine in a browser.');
198
+ const controller=new AbortController();const interrupt=()=>controller.abort();process.on('SIGINT',interrupt);
199
+ try {({token,grant}=await browserEnrollment({root,hub,nodeName:o.nodeName,version:context.version,request,validateGrant,signal:controller.signal}));}
200
+ finally {process.removeListener('SIGINT',interrupt);}
201
+ } else {token=readToken(tokenFile);grant=await request(hub,'/v1/node/check',token);validateGrant(grant);}
202
+ if(!o.nonInteractive&&!o.allowDirs.length) {
203
+ const rl=createInterface({input:process.stdin,output:process.stdout});
204
+ try {const dir=await rl.question(`Allowed project directory [${old?.allowed?.join(', ')||os.homedir()}]: `);o.allowDirs=dir?[dir]:(old?.allowed||[os.homedir()]);}finally{rl.close();}
205
+ }
197
206
  const nodeId=o.nodeId||old?.nodeId||grant.node_id;
198
207
  if(nodeId!==grant.node_id)throw new Error('Node UUID does not match this node credential (management tokens cannot join)');
199
208
  const codex=absoluteProgram(o.codex||old?.codex||'codex');
200
209
  const skipDaemonVersionCheck=daemonVersionPolicy(o,old||{});
201
210
  const d=daemon(codex,o.daemonSocket,skipDaemonVersionCheck);
202
211
  if(skipDaemonVersionCheck)console.error(`Daemon version check skipped by saved/explicit policy (${d.version||"unknown"}); runtime compatibility is not guaranteed.`);
203
- const allowed=(o.allowDirs.length?o.allowDirs:old?.allowed||[]).map(p=>fs.realpathSync(path.resolve(p)));
212
+ const allowed=(o.allowDirs.length?o.allowDirs:old?.allowed||[os.homedir()]).map(p=>fs.realpathSync(path.resolve(p)));
204
213
  if(!allowed.length || allowed.some(p=>!fs.statSync(p).isDirectory()))throw new Error('At least one --allow-dir DIRECTORY is required');
205
214
  const service=o.service||old?.service||'systemd';if(!['systemd','process'].includes(service))throw new Error('--service must be systemd or process');
206
215
  if(service==='systemd')command('systemctl',['--user','show-environment']);
@@ -226,6 +235,7 @@ async function setup(o,context) {
226
235
  if(running&&old.process)state.process=old.process;
227
236
  write(file,state); // Pending until actual Node/MCP/Skill checks pass.
228
237
  write(path.join(root,'node.token'),token+'\n');write(state.nodeConfig,node);
238
+ if(o.tokenFile||o.nonInteractive)fs.rmSync(path.join(root,'enrollment.json'),{force:true});
229
239
  if(!running)await startService(state);
230
240
  safeManagedSkill(state,path.join(context.packageRoot,'skills/codex-mesh'));
231
241
  command(codex,['mcp','add','mesh','--',state.binary,'mcp','--socket',state.socket]);
@@ -264,12 +274,15 @@ export function savedAgentArgs(args) {
264
274
  }
265
275
  export async function main(args,context) {
266
276
  const [action,...rest]=args;const o=options(rest);
267
- if(o.help){console.log(`codex-mesh ${action}\nsetup [--non-interactive] --hub URL --token-file FILE [--node-id UUID] --allow-dir DIR...\n [--node-name NAME] [--codex PATH] [--daemon-socket PATH] [--service systemd|process]\n [--skills-dir DIR] [--admin-token-file FILE]\n [--skip-daemon-version-check | --check-daemon-version]\nsetup --manager [--non-interactive] --hub URL --admin-token-file FILE\ndoctor [--json]\nCredentials are FILE paths only; never pass token values. CODEX_MESH_HOME isolates Mesh state.\nDefault systemd user service survives terminals; process backend is explicitly opt-in and needs setup after reboot.\nDaemon version policy is saved; skip only bypasses version gating, never socket security or runtime checks.\nUpgrade: install new npm version, leave Mesh sessions, rerun setup; no install hooks restart services.`);return;}
277
+ if(o.help){console.log(`codex-mesh ${action}\nsetup [--non-interactive] --hub URL [--node-token-file FILE] [--node-id UUID] [--allow-dir DIR...]\n [--node-name NAME] [--codex PATH] [--daemon-socket PATH] [--service systemd|process]\n [--skills-dir DIR] [--admin-token-file FILE]\n [--skip-daemon-version-check | --check-daemon-version]\nsetup --manager [--non-interactive] --hub URL --admin-token-file FILE\ndoctor [--json]\nFirst interactive setup asks for a node display name (default: hostname), then prints a browser authorization link; use your existing authorized management token in the browser.\nScripted setup requires a saved credential or --node-token-file FILE; --node-name defaults to the hostname; never pass token values. CODEX_MESH_HOME isolates Mesh state.\nAllowed directories default to your home directory on first setup; saved directories and explicit --allow-dir take precedence.\nDefault systemd user service survives terminals; process backend is explicitly opt-in and needs setup after reboot.\nDaemon version policy is saved; skip only bypasses version gating, never socket security or runtime checks.\nUpgrade: install new npm version, leave Mesh sessions, rerun setup; no install hooks restart services.`);return;}
268
278
  if(action==='setup')return setup(o,context);
269
279
  const root=home();const file=path.join(root,'installation.json');let checks;
270
280
  if(fs.existsSync(file)){try{checks=await inspect(json(file),context);}catch{checks=[{name:'configuration',ok:false,fix:'Saved installation configuration is incomplete/invalid; rerun setup with explicit options after preserving its private runtime state.'}];}}
271
281
  else if(fs.existsSync(path.join(root,'management.json'))){
272
282
  try{const s=json(path.join(root,'management.json'));if(s.version!==context.version)throw Error();privateDir(root);privateFile(path.join(root,'management.json'));await request(hubUrl(s.hub),'/v1/rpc',readToken(s.tokenFile),{id:'doctor',method:'mesh.list_agents',params:{limit:1}});checks=[{name:'management config/Hub',ok:true}];}catch{checks=[{name:'management config/Hub',ok:false,fix:'Run setup --manager with a private management token and reachable Hub.'}];}
283
+ }else if(fs.existsSync(path.join(root,'enrollment.json'))) {
284
+ try {const enrollment=pendingEnrollment(root);checks=[{name:'browser authorization',ok:false,fix:`Authorization is incomplete${enrollment.expires_at&&enrollment.expires_at*1000<Date.now()?' (approval deadline passed)':''}; rerun interactive codex-mesh setup --hub ${hubUrl(enrollment.hub)} to resume or request approval again.`}];}
285
+ catch {checks=[{name:'browser authorization',ok:false,fix:'Saved authorization is invalid or has unsafe permissions; inspect private enrollment.json and rerun setup.'}];}
273
286
  }else checks=[{name:'configuration',ok:false,fix:'Run codex-mesh setup (or setup --manager for management-only use).'}];
274
287
  if(o.json)console.log(JSON.stringify({version:context.version,ok:checks.every(c=>c.ok),checks},null,2));
275
288
  else for(const c of checks)console.log(`${c.ok?'OK':'FAIL'} ${c.name}${c.fix?' — '+c.fix:''}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@balababa/codex-mesh",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "Session-native Mesh Hub, ordinary Codex MCP/Skill and Agent management",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
Binary file
package/release.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
- "version": "0.3.0",
2
+ "version": "0.5.0",
3
3
  "protocolVersion": 1,
4
4
  "platforms": {
5
5
  "linux-x64-gnu": {
6
6
  "path": "platforms/linux-x64-gnu/codex-mesh",
7
- "sha256": "83ff1768379f66447f45e933613a94d89c649ee0bca9adf13caea69714179eda",
7
+ "sha256": "0489134f5f8f9b21875a35c635564a303ca5c70c1a84077d14a856febdde0431",
8
8
  "nodeMinimum": "24.19.0",
9
9
  "glibcMinimum": "2.35"
10
10
  }
@@ -2,7 +2,7 @@
2
2
  name: codex-mesh
3
3
  description: Connect ordinary Codex to Codex Mesh (集群/机器/Agent 通信). Use when the user wants to join or leave Mesh, discover enrolled agents or machines, send a peer message, or read Mesh replies. Mesh MCP supplies the actions; this skill explains the workflow.
4
4
  metadata:
5
- version: "0.3.0"
5
+ version: "0.5.0"
6
6
  ---
7
7
 
8
8
  # Codex Mesh
@@ -1,4 +1,4 @@
1
- # Host setup for packaged Mesh 0.3.0
1
+ # Host setup for packaged Mesh 0.5.0
2
2
 
3
3
  The Skill supplies instructions; MCP performs actions; a persistent local Node
4
4
  receives messages and wakes explicitly enrolled native sessions. Installing or
@@ -6,8 +6,12 @@ loading this Skill does not enroll anything.
6
6
 
7
7
  A host operator installs the authorized npm package (or its local release tarball),
8
8
  then runs `codex-mesh setup` and `codex-mesh doctor`. Setup needs a running owning
9
- ordinary Codex daemon, a reachable authenticated Hub, a per-node token **file**
10
- issued by the Hub operator, and explicit allowed project directories.
9
+ ordinary Codex daemon, a reachable authenticated Hub, browser approval with the existing authorized management Token (or an explicitly
10
+ provided per-node token file for scripts), and allowed project directories.
11
+ The CLI prints a link and confirmation code; the human approves on a trusted
12
+ browser and the CLI saves independent node credentials automatically. Never ask
13
+ for a management Token through model tools or store it in a project.
14
+ Machine authorization does not enroll this Codex session.
11
15
 
12
16
  ```sh
13
17
  codex-mesh setup --non-interactive --hub http://127.0.0.1:19010 \
@@ -26,7 +30,7 @@ supported reload or a new session. Do not call mesh_join merely to diagnose an
26
30
  installation. Doctor checks readiness without inference or enrollment.
27
31
 
28
32
  For an npm/npx MCP entry, first complete host setup, then use the exact authorized
29
- package version with `npx --yes --package=<package>@0.3.0 codex-mesh mcp --socket
33
+ package version with `npx --yes --package=<package>@0.5.0 codex-mesh mcp --socket
30
34
  /private/mesh/mcp.sock`. The Node remains in stable managed storage. The package
31
35
  name is `@balababa/codex-mesh` under the maintainer personal scope; registry
32
36
  installation requires publication of that version. Do not install the unrelated unscoped `codex-mesh` package.