@balababa/codex-mesh 0.2.0 → 0.4.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
@@ -31,36 +31,39 @@ see [artifact exports](docs/ARTIFACTS.md).
31
31
 
32
32
  ## npm 安装与普通用户接入
33
33
 
34
- 同一个 **0.2.0** 包包含 Rust Hub/Node/MCP/管理命令、启动器和 Skill。
35
- 普通用户不需要 Rust、源码仓库或本地编译。目前已打包平台为 Linux x86_64、
36
- glibc >=2.35,Node.js >=24.19.0;其他平台会明确报错。
34
+ 当前源码版本为 **0.4.0**,新增浏览器授权机器接入。Rust Hub/Node/MCP/管理命令、
35
+ 启动器和 Skill 使用同一版本。普通用户不需要 Rust、源码仓库或本地编译。
36
+ 支持 Linux x86_64、glibc >=2.35,Node.js >=24.19.0。
37
37
 
38
- npm 包名为 **`@balababa/codex-mesh`**,使用维护者个人 scope。
39
- 正式发布前可安装本地产物;发布后可运行 `npm install -g @balababa/codex-mesh@0.2.0`:
38
+ 包名为 **`@balababa/codex-mesh`**。npm 已发布版本为 **0.3.0**;0.4.0 本轮
39
+ 不发布,请使用匹配的本地产物,并先升级 Hub:
40
40
 
41
41
  ```sh
42
- npm install -g /absolute/path/balababa-codex-mesh-0.2.0.tgz
42
+ npm install -g /absolute/path/balababa-codex-mesh-0.4.0.tgz
43
43
  codex-mesh setup
44
44
  codex-mesh doctor
45
45
  codex
46
46
  ```
47
47
 
48
- 在新的普通 Codex 会话中输入 `$codex-mesh 加入 Mesh`。
49
- `setup` 交互式收集 Hub、节点凭据文件和目录白名单,也提供
50
- `--non-interactive` 模式。它配置稳定路径下的后台 Node、MCP 和 Skill;
51
- 安装/检查不登记会话。服务端用同包的 `credentials issue` 签发独立节点和管理
52
- 凭据。管理端保存配置后,直接 `codex-mesh agents`。
48
+ 首次 setup 填写 Hub 地址后显示授权链接和确认码。在浏览器打开链接,核对机器信息,
49
+ 输入现有管理 Token 并批准,终端自动保存本机独立节点凭据、继续安装 Node、MCP 和 Skill。
50
+ 管理 Token 不会交给接入机器。Hub 管理员须先显式给管理凭据开启节点接入授权权限;
51
+ 已有节点凭据直接复用,脚本仍可使用 `--node-token-file`。
52
+
53
+ 在新的普通 Codex 会话中输入 `$codex-mesh 加入 Mesh`。安装、网页授权和 doctor
54
+ 不登记任何 Codex 会话。管理端保存配置后,直接 `codex-mesh agents`。
53
55
 
54
56
  同一个本地 tarball 可用于 npx 按需启动 MCP:
55
57
 
56
58
  ```sh
57
- npx --yes --package=/absolute/path/balababa-codex-mesh-0.2.0.tgz \
59
+ npx --yes --package=/absolute/path/balababa-codex-mesh-0.4.0.tgz \
58
60
  codex-mesh mcp --socket /absolute/private/mesh/mcp.sock
59
61
  ```
60
62
 
61
- 完整安装、签发、SSH 接入、非交互配置、管理配置、doctor 与升级说明见
62
- [INSTALL.md](docs/INSTALL.md)。默认使用 systemd user 服务;升级 npm 本身不会
63
- 重启 Node 或用户 daemon,改变配置/版本时需要在会话退出 Mesh 后重新 setup。
63
+ 完整安装、管理授权开关、非交互配置、doctor 与升级说明见
64
+ [INSTALL.md](docs/INSTALL.md)。默认使用 systemd user 服务;容器可显式使用
65
+ `--service process`。升级 npm 本身不会重启 Node 或用户 daemon,改变配置/版本时
66
+ 需要在会话退出 Mesh 后重新 setup。
64
67
 
65
68
  ## Build
66
69
 
@@ -140,3 +143,16 @@ $codex-mesh 加入 Mesh,列出在线机器和 Agent。
140
143
 
141
144
  See [ordinary Codex setup and delivery semantics](docs/STOCK_CODEX.md).
142
145
  Building alone does not install the Skill, register MCP or switch a deployment.
146
+
147
+ ## 域名和网页管理
148
+
149
+ 0.3.0 Hub 内置网页版只读集群概览,入口为 `/`。网页使用独立管理凭据,
150
+ 列出所有明确登记的 Agent 和节点,不启动推理、不读取私有会话历史。
151
+ 凭据仅保留在页面内存中;支持搜索、分页和刷新。Hub 仍监听回环地址,
152
+ 公网域名由 HTTPS 反向代理承接。配置模板与验收步骤见
153
+ [PUBLIC_HUB.md](docs/PUBLIC_HUB.md)。真实域名、TLS 和公网连通性需分别验证。
154
+
155
+ For an explicitly chosen daemon outside the default verified version range, use
156
+ `codex-mesh setup --skip-daemon-version-check`. The choice persists for setup and
157
+ doctor; `setup --check-daemon-version` restores checking. Socket security and
158
+ runtime checks remain enabled. See [installation options](docs/INSTALL.md).
package/docs/INSTALL.md CHANGED
@@ -1,13 +1,14 @@
1
1
  # npm installation and ordinary Codex setup
2
2
 
3
- Release version: **0.2.0** (npm, Rust binary and Skill metadata).
3
+ Source release version: **0.4.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
- Local tarball installation works before publication; registry installation below
9
- requires a successful publication. The unrelated unscoped `codex-mesh` package
10
- is not this implementation.
8
+ Version 0.3.0 is published (registry metadata checked on 2026-12-05).
9
+ Source 0.4.0 adds browser-authorized node onboarding and is not published in this
10
+ change. Use its matching local tarball and upgrade the Hub deliberately first.
11
+ The unrelated unscoped `codex-mesh` package is not this implementation.
11
12
 
12
13
  ## Supported runtime
13
14
 
@@ -19,21 +20,17 @@ libgcc); consumers need no Rust/compiler/source tree. Ordinary Codex daemon
19
20
  0.173.x/0.174.x is the checked compatibility range; 0.174.0 is the real npm
20
21
  acceptance target. The daemon must already be running and normally authenticated.
21
22
 
22
- After publication under an authorized name, the intended command is:
23
+ For this 0.4.0 build, install the matching local artifact:
23
24
 
24
25
  ```sh
25
- npm install -g @balababa/codex-mesh@0.2.0
26
+ npm install -g /absolute/path/balababa-codex-mesh-0.4.0.tgz
26
27
  codex-mesh setup
27
28
  codex-mesh doctor
28
29
  ```
29
30
 
30
- Until publication, use the tested local artifact instead:
31
-
32
- ```sh
33
- npm install -g /absolute/path/balababa-codex-mesh-0.2.0.tgz
34
- codex-mesh setup
35
- codex-mesh doctor
36
- ```
31
+ After an explicitly authorized publication, the equivalent registry command is
32
+ `npm install -g @balababa/codex-mesh@0.4.0`. This document does not assert that
33
+ version is published.
37
34
 
38
35
  Installation itself has no lifecycle hook, never joins a session and never
39
36
  starts/restarts a daemon. The package contains the original Rust executable,
@@ -41,29 +38,44 @@ stdio launcher, setup/doctor and Skill under one version/checksum manifest.
41
38
 
42
39
  ## Hub and credential provisioning
43
40
 
44
- On the Hub host, install the same tarball/version. Issue an independent node
45
- credential and an independent management credential. Paths, never secret token
46
- values, are passed as arguments:
41
+ On the Hub host, install the same tarball/version. Reuse the existing management
42
+ Token; no second management Token is needed. Enable node-enrollment permission
43
+ explicitly for its credential name (the existing deployment uses `web-manager`):
44
+
45
+ ```sh
46
+ codex-mesh credentials allow-node-enrollment \
47
+ --credentials /home/chh/.local/share/codex-mesh/hub/credentials.json \
48
+ --name web-manager
49
+ ```
50
+
51
+ This preserves the management Token and unrelated grants. Repeated execution is
52
+ safe, and new authentication reads updates without a Hub restart. Existing
53
+ credentials do not gain enrollment rights merely by upgrading.
54
+
55
+ For a new Hub only, first issue its management credential:
47
56
 
48
57
  ```sh
49
58
  codex-mesh credentials issue --credentials /private/mesh-hub/credentials.json \
50
- --token-file /private/mesh-hub/laptop.token --name laptop --role node
51
- codex-mesh credentials issue --credentials /private/mesh-hub/credentials.json \
52
- --token-file /private/mesh-hub/manager.token --name manager --role client
59
+ --token-file /private/mesh-hub/manager.token --name web-manager --role client
60
+ codex-mesh credentials allow-node-enrollment \
61
+ --credentials /private/mesh-hub/credentials.json --name web-manager
53
62
  codex-mesh hub --bind 127.0.0.1:9010 \
63
+ --public-url https://codex-mesh.wcisman.cc \
54
64
  --database /private/mesh-hub/hub.sqlite \
55
65
  --credentials /private/mesh-hub/credentials.json
56
66
  ```
57
67
 
58
- The issuer creates private directories/files, reports the node UUID and token
59
- file path without printing tokens, and preserves other grants. Transfer the node
60
- token file only to its node through an authenticated private channel. Transfer the
61
- management token only to the administrator. Hub reads atomic credential-file
62
- updates on new authentication; new nodes require no Hub restart. Existing
63
- connections retain their authenticated grant: hot revocation is not implemented.
64
- Reusing the same name/token file is idempotent; conflicting grants are refused.
65
- An interrupted issuance may leave a private token file; rerun the same command to
66
- complete it. Hub remains infrastructure and never schedules inference.
68
+ `--public-url` is the trusted origin used for browser authorization links. It must
69
+ be verified HTTPS, or loopback HTTP for local/tunnel use. Behind Caddy use the
70
+ external HTTPS origin while Hub continues listening on loopback. No forwarded
71
+ host header determines authorization links.
72
+
73
+ For automation, the existing `credentials issue --role node` and
74
+ `setup --node-token-file /private/node.token` remain supported. Transfer that
75
+ file only to its intended machine through an authenticated private channel.
76
+ Do not pass secret Token values as arguments. Hub remains infrastructure and
77
+ never schedules inference. Existing authenticated connections retain their
78
+ grant: immediate live revocation is not implemented.
67
79
 
68
80
  Keep Hub on loopback and provide an authenticated SSH tunnel:
69
81
 
@@ -77,11 +89,28 @@ existing secure tunnel/service to survive your desired session lifecycle.
77
89
 
78
90
  ## Node setup
79
91
 
80
- Interactive `codex-mesh setup` asks for Hub URL, node token **file**, node UUID
81
- (optional, verified from Hub admission), and allowed project directories. It uses
82
- the existing ordinary Codex and discovers its owning daemon. It does not start,
83
- replace or restart Codex. If another independently owned server is used, pass
84
- `--daemon-socket` explicitly; ownership/mode checks still apply.
92
+ First-time interactive `codex-mesh setup` asks for the Hub URL, then prints a
93
+ short-lived authorization URL and confirmation code. Open it on any device,
94
+ verify the self-reported machine name/hostname and matching code, enter the
95
+ existing authorized management Token, and approve. The CLI automatically saves
96
+ its independent Node Token and resumes configuration. The management Token is
97
+ never saved on the new machine. This works on headless servers and containers;
98
+ a browser is only needed on the device used for approval.
99
+
100
+ A request lasts 10 minutes. The CLI keeps a private pending record so rerunning
101
+ setup can resume after interruption. Approved credentials are retained if a later
102
+ local setup check fails. Timeout, denial or missing permission produces an error,
103
+ not a successful installation. Doctor points to incomplete onboarding. For a hard
104
+ process termination, follow the stale setup-lock instructions below before retry.
105
+
106
+ Existing saved node credentials are reused. Explicit `--node-token-file` uses the
107
+ file workflow. Non-interactive setup without saved/file credentials fails with
108
+ instructions rather than waiting for browser input. A Hub without browser
109
+ authorization support must be upgraded, or use the file workflow.
110
+
111
+ Setup uses the existing ordinary Codex and discovers its owning daemon; it does
112
+ not start, replace or restart Codex. If another independently owned server is
113
+ used, pass `--daemon-socket` explicitly; ownership/mode checks still apply.
85
114
 
86
115
  For scripts:
87
116
 
@@ -129,7 +158,7 @@ replies use notify to avoid wake loops.
129
158
  The same package provides every Rust subcommand, including stdio MCP:
130
159
 
131
160
  ```sh
132
- npx --yes --package=/absolute/path/balababa-codex-mesh-0.2.0.tgz \
161
+ npx --yes --package=/absolute/path/balababa-codex-mesh-0.4.0.tgz \
133
162
  codex-mesh mcp --socket /absolute/private/mesh-runtime/mcp.sock
134
163
  ```
135
164
 
@@ -168,7 +197,10 @@ Upgrade npm to the desired exact version, upgrade Hub deliberately, then rerun
168
197
  `setup` and `doctor`. No npm install hook restarts running services. If a Node has
169
198
  any enrolled sessions, a changed setup is deferred before stopping it. Ask those
170
199
  sessions to leave Mesh, then rerun. Unchanged setup is safe to repeat while joined.
171
- User Codex daemon is never restarted. Keep the existing secure Hub tunnel running.
200
+ User Codex daemon is never restarted. Keep the existing verified TLS endpoint or secure Hub tunnel running.
201
+ The current setup requires exact Hub/package release versions; it does not
202
+ silently relax that gate for older clients. Plan the Hub and node upgrades
203
+ together, and rerun setup to refresh stable services, MCP and Skill.
172
204
 
173
205
  Setup records `pending` before side effects and `ready` only after actual checks.
174
206
  Interrupted/pending setup is not reported healthy; fix the reported cause and
@@ -191,3 +223,34 @@ Artifacts appear under ignored `artifacts/npm/`. The pack script verifies Rust,
191
223
  npm, binary and Skill versions and writes the binary SHA-256 manifest. It never
192
224
  publishes. Tests install this tarball into an isolated npm global prefix and use
193
225
  npx against the same local artifact. See the repository docs/TEST_REPORT.md for measured scope.
226
+
227
+ ## Public domain and web management
228
+
229
+ The Hub serves its read-only dashboard at the Hub root. Use a management/client
230
+ credential, separate from per-node setup credentials. For verified HTTPS domain
231
+ access, Caddy reverse proxy, external checks and current privilege prerequisites,
232
+ see [PUBLIC_HUB.md](PUBLIC_HUB.md). HTTP remains loopback-only.
233
+
234
+ ## Optional daemon version gate
235
+
236
+ Default setup accepts measured daemon versions 0.173.x/0.174.x. To explicitly try
237
+ another daemon version without upgrading/restarting it, run:
238
+
239
+ ```sh
240
+ codex-mesh setup --skip-daemon-version-check
241
+ codex-mesh doctor
242
+ ```
243
+
244
+ The boolean policy is saved as `skipDaemonVersionCheck` in the private
245
+ `installation.json`; subsequent setup and doctor reuse it. Doctor labels the
246
+ skipped version check explicitly. Re-enable the default with
247
+ `codex-mesh setup --check-daemon-version`. Both flags work with non-interactive
248
+ setup; they are mutually exclusive. Only the version gate is bypassed: running
249
+ daemon discovery, private owned socket checks, actual Node startup/connectivity,
250
+ MCP and all sandbox/approval rules still apply. This does not certify 0.172.0
251
+ native queue/steer compatibility.
252
+
253
+ First-time setup defaults the allowed directory to the current user home (`~`),
254
+ in both interactive and non-interactive modes. Saved allowlists remain unchanged
255
+ on repeat setup; explicit `--allow-dir` values override them. This includes home
256
+ subdirectories. Use explicit project directories when a narrower scope is wanted.
@@ -0,0 +1,104 @@
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) {
55
+ state={hub,version,node_name:nodeName||os.hostname(),hostname:os.hostname(),token:crypto.randomBytes(32).toString('hex'),claim:crypto.randomBytes(32).toString('hex')};
56
+ write(file,state);
57
+ }
58
+ if(!state.request_id) {
59
+ let started;
60
+ 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)});}
61
+ catch(error) {
62
+ 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.');
63
+ if(error.status===503)throw new Error('Browser authorization is unavailable. Configure the Hub --public-url, or use setup --node-token-file FILE.');
64
+ throw error;
65
+ }
66
+ const verification=verificationUrl(started.verification_uri,hub,started.request_id);
67
+ 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.');
68
+ 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}};
69
+ write(file,state);
70
+ }
71
+ verificationUrl(state.verification_uri,hub,state.request_id);
72
+ 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…`);
73
+ openBrowser(state.verification_uri);
74
+ const endpoint='/v1/enrollment/'+state.request_id;
75
+ for(;;) {
76
+ if(signal?.aborted)throw new Error('Authorization interrupted; rerun setup to resume.');
77
+ let result;
78
+ try{result=await request(hub,endpoint+'/poll',state.claim,{});}
79
+ catch(error){
80
+ 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.');}
81
+ throw new Error(`Authorization status unavailable; rerun setup to resume. ${error.message}`);
82
+ }
83
+ if(['denied','cancelled','expired'].includes(result.status)){fs.rmSync(file);terminalState(result.status);}
84
+ if(['approved','completed'].includes(result.status)) {
85
+ const grant=await request(hub,'/v1/node/check',state.token);
86
+ if(grant.node_id!==state.node_id)throw new Error('Authorized node identity does not match this authorization request.');
87
+ if(validateGrant)validateGrant(grant);
88
+ const tokenFile=path.join(root,'node.token');
89
+ if(fs.existsSync(tokenFile))checkFile(tokenFile);
90
+ const temporary=tokenFile+'.new-'+crypto.randomUUID();
91
+ const fd=fs.openSync(temporary,'wx',0o600);
92
+ try{fs.writeFileSync(fd,state.token+'\n');fs.fsyncSync(fd);}finally{fs.closeSync(fd);}
93
+ fs.renameSync(temporary,tokenFile);
94
+ await request(hub,endpoint+'/complete',state.claim,{});
95
+ fs.rmSync(file);
96
+ log('Machine authorized. Node credential saved privately; no Codex session enrolled.');
97
+ return {token:state.token,grant};
98
+ }
99
+ if(result.status!=='pending')throw new Error('Hub returned an invalid authorization status.');
100
+ if(result.expires_at!==undefined&&result.expires_at*1000<=now()){fs.rmSync(file);terminalState('expired');}
101
+ if(state.expires_at*1000<=now()){fs.rmSync(file);terminalState('expired');}
102
+ await sleep(3000,signal);
103
+ }
104
+ }
@@ -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={}) {
@@ -66,17 +67,19 @@ function absoluteProgram(program) {
66
67
  const p=path.join(dir,program);try{fs.accessSync(p,fs.constants.X_OK);return fs.realpathSync(p);}catch{}
67
68
  }throw new Error(`Cannot find ${program}; install ordinary Codex and place it on PATH`);
68
69
  }
69
- function daemon(codex,socketOverride) {
70
+ export function daemonVersionPolicy(options,previous={}) {
71
+ return options.skipDaemonVersionCheck ?? previous.skipDaemonVersionCheck ?? false;
72
+ }
73
+ export function daemon(codex,socketOverride,skipVersionCheck=false) {
70
74
  const d=JSON.parse(command(codex,['app-server','daemon','version']));
71
75
  if(!socketOverride && (d.status!=='running' || !d.socketPath)) throw new Error('Codex owning daemon is not running; start it with your normal Codex workflow, then rerun setup');
72
76
  const socket=path.resolve(socketOverride||d.socketPath);
73
77
  const advertised=fs.lstatSync(socket),resolved=fs.realpathSync(socket),s=fs.statSync(resolved);
74
78
  const parents=[path.dirname(socket),path.dirname(resolved)].map(p=>fs.statSync(p));
75
79
  if(advertised.uid!==process.getuid() || !s.isSocket() || s.uid!==process.getuid() || (s.mode&0o077) || parents.some(p=>!p.isDirectory()||p.uid!==process.getuid()||(p.mode&0o077))) throw new Error('Owning daemon socket/rendezvous directories must be private and owned by this user');
76
- // Stock compatibility was measured on 0.173/0.174; reject older/mismatched APIs
77
- // rather than pretending any app-server supports the required native queue.
80
+ // Version opt-out does not bypass native socket ownership or runtime checks.
78
81
  const v=d.appServerVersion||d.managedCodexVersion||'';
79
- if(!/^0\.(173|174)\./.test(v)) throw new Error(`Unverified Codex daemon ${v}; supported daemon versions are 0.173.x/0.174.x`);
82
+ if(!skipVersionCheck&&!/^0\.(173|174)\./.test(v)) throw new Error(`Unverified Codex daemon ${v}; supported daemon versions are 0.173.x/0.174.x. To try this daemon explicitly, rerun setup --skip-daemon-version-check`);
80
83
  return {socket,version:v,cli:command(codex,['--version'])};
81
84
  }
82
85
  export function localHealth(socket) {
@@ -139,7 +142,7 @@ function options(args) {
139
142
  const o={allowDirs:[]};
140
143
  const names={'--hub':'hub','--token-file':'tokenFile','--node-token-file':'tokenFile','--admin-token-file':'adminTokenFile','--node-id':'nodeId','--node-name':'nodeName','--allow-dir':'allowDirs','--codex':'codex','--daemon-socket':'daemonSocket','--service':'service','--skills-dir':'skillsDir'};
141
144
  for(let i=0;i<args.length;i++){
142
- const a=args[i];if(['--non-interactive','--manager','--help','--json'].includes(a)){o[a.slice(2).replace(/-([a-z])/g,(_,c)=>c.toUpperCase())]=true;continue;}
145
+ const a=args[i];if(a==='--skip-daemon-version-check'||a==='--check-daemon-version'){if(o.skipDaemonVersionCheck!==undefined)throw new Error('Choose only one daemon version policy flag');o.skipDaemonVersionCheck=a==='--skip-daemon-version-check';continue;}if(['--non-interactive','--manager','--help','--json'].includes(a)){o[a.slice(2).replace(/-([a-z])/g,(_,c)=>c.toUpperCase())]=true;continue;}
143
146
  if(!names[a]||!args[i+1]||args[i+1].startsWith('--'))throw new Error(`Unknown or missing option ${a}; see codex-mesh setup --help`);
144
147
  const v=args[++i];if(names[a]==='allowDirs')o.allowDirs.push(v);else o[names[a]]=v;
145
148
  }return o;
@@ -173,12 +176,6 @@ async function setup(o,context) {
173
176
  try{
174
177
  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';
175
178
  if(o.manager)o.adminTokenFile=o.adminTokenFile||await rl.question('Management token FILE path (not the token): ');
176
- else {
177
- o.tokenFile=o.tokenFile||await rl.question('Node token FILE path (leave empty to reuse saved credential): ')||undefined;
178
- o.nodeId=o.nodeId||await rl.question(`Node UUID [${old?.nodeId||'from Hub credential'}]: `)||old?.nodeId;
179
- const dir=await rl.question(`Allowed project directory [${old?.allowed?.join(', ')||process.cwd()}]: `);
180
- if(!o.allowDirs.length)o.allowDirs=dir?[dir]:(old?.allowed||[process.cwd()]);
181
- }
182
179
  }finally{rl.close();}
183
180
  }
184
181
  const hub=hubUrl(o.hub||old?.hub||managerSaved?.hub||'');
@@ -189,14 +186,26 @@ async function setup(o,context) {
189
186
  write(path.join(root,'admin.token'),token+'\n');write(path.join(root,'management.json'),{version:context.version,hub,tokenFile:path.join(root,'admin.token')});
190
187
  console.log('Management configuration saved. Run codex-mesh agents. No session enrolled.');return;
191
188
  }
192
- const token=readToken(path.resolve(o.tokenFile||path.join(root,'node.token')));
193
- const grant=await request(hub,'/v1/node/check',token);
194
- 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`);
189
+ const tokenFile=path.resolve(o.tokenFile||path.join(root,'node.token'));
190
+ 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`);};
191
+ let token,grant;
192
+ if(!o.tokenFile&&((!o.nonInteractive&&pendingEnrollment(root))||!fs.existsSync(tokenFile))) {
193
+ 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.');
194
+ const controller=new AbortController();const interrupt=()=>controller.abort();process.on('SIGINT',interrupt);
195
+ try {({token,grant}=await browserEnrollment({root,hub,nodeName:o.nodeName,version:context.version,request,validateGrant,signal:controller.signal}));}
196
+ finally {process.removeListener('SIGINT',interrupt);}
197
+ } else {token=readToken(tokenFile);grant=await request(hub,'/v1/node/check',token);validateGrant(grant);}
198
+ if(!o.nonInteractive&&!o.allowDirs.length) {
199
+ const rl=createInterface({input:process.stdin,output:process.stdout});
200
+ 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();}
201
+ }
195
202
  const nodeId=o.nodeId||old?.nodeId||grant.node_id;
196
203
  if(nodeId!==grant.node_id)throw new Error('Node UUID does not match this node credential (management tokens cannot join)');
197
204
  const codex=absoluteProgram(o.codex||old?.codex||'codex');
198
- const d=daemon(codex,o.daemonSocket);
199
- const allowed=(o.allowDirs.length?o.allowDirs:old?.allowed||[]).map(p=>fs.realpathSync(path.resolve(p)));
205
+ const skipDaemonVersionCheck=daemonVersionPolicy(o,old||{});
206
+ const d=daemon(codex,o.daemonSocket,skipDaemonVersionCheck);
207
+ if(skipDaemonVersionCheck)console.error(`Daemon version check skipped by saved/explicit policy (${d.version||"unknown"}); runtime compatibility is not guaranteed.`);
208
+ const allowed=(o.allowDirs.length?o.allowDirs:old?.allowed||[os.homedir()]).map(p=>fs.realpathSync(path.resolve(p)));
200
209
  if(!allowed.length || allowed.some(p=>!fs.statSync(p).isDirectory()))throw new Error('At least one --allow-dir DIRECTORY is required');
201
210
  const service=o.service||old?.service||'systemd';if(!['systemd','process'].includes(service))throw new Error('--service must be systemd or process');
202
211
  if(service==='systemd')command('systemctl',['--user','show-environment']);
@@ -205,7 +214,7 @@ async function setup(o,context) {
205
214
  if(!fs.existsSync(binary)){fs.copyFileSync(context.binary,binary,fs.constants.COPYFILE_EXCL);fs.chmodSync(binary,0o700);}
206
215
  if(hash(binary)!==hash(context.binary))throw new Error('Stable binary checksum mismatch');
207
216
  const skillsDir=path.resolve(o.skillsDir||old?.skillsDir||process.env.CODEX_MESH_SKILLS_DIR||path.join(os.homedir(),'.agents/skills'));
208
- const state={root,version:context.version,packageName:JSON.parse(fs.readFileSync(path.join(context.packageRoot,'package.json'))).name,status:'pending',hub,nodeId,nodeName:o.nodeName||old?.nodeName||os.hostname(),codex,daemonSocket:d.socket,allowed,service,skillsDir,binary,socket:path.join(root,'mcp.sock'),nodeConfig:path.join(root,'node.json'),unit:'codex-mesh-'+crypto.createHash('sha256').update(root).digest('hex').slice(0,12)+'.service'};
217
+ const state={root,version:context.version,packageName:JSON.parse(fs.readFileSync(path.join(context.packageRoot,'package.json'))).name,status:'pending',hub,nodeId,nodeName:o.nodeName||old?.nodeName||os.hostname(),codex,daemonSocket:d.socket,skipDaemonVersionCheck,allowed,service,skillsDir,binary,socket:path.join(root,'mcp.sock'),nodeConfig:path.join(root,'node.json'),unit:'codex-mesh-'+crypto.createHash('sha256').update(root).digest('hex').slice(0,12)+'.service'};
209
218
  const current=mcp(codex);
210
219
  if(current&&!matchesMcp(current,old||state))throw new Error('Existing mesh MCP registration is unmanaged; preserve it or explicitly remove it before setup');
211
220
  const target=path.join(skillsDir,'codex-mesh');
@@ -222,6 +231,7 @@ async function setup(o,context) {
222
231
  if(running&&old.process)state.process=old.process;
223
232
  write(file,state); // Pending until actual Node/MCP/Skill checks pass.
224
233
  write(path.join(root,'node.token'),token+'\n');write(state.nodeConfig,node);
234
+ if(o.tokenFile||o.nonInteractive)fs.rmSync(path.join(root,'enrollment.json'),{force:true});
225
235
  if(!running)await startService(state);
226
236
  safeManagedSkill(state,path.join(context.packageRoot,'skills/codex-mesh'));
227
237
  command(codex,['mcp','add','mesh','--',state.binary,'mcp','--socket',state.socket]);
@@ -241,7 +251,7 @@ async function inspect(state,context,requireReady=true) {
241
251
  await check('configuration',()=>{privateDir(state.root);privateFile(path.join(state.root,'installation.json'));privateFile(state.nodeConfig);const node=json(state.nodeConfig);if(node.node_id!==state.nodeId||node.local_mcp_socket!==state.socket||JSON.stringify(node.allowed_directories)!==JSON.stringify(state.allowed)||state.allowed.some(p=>fs.realpathSync(p)!==p))throw Error();if(requireReady&&state.status!=='ready')throw Error();if(state.version!==context.version)throw Error();},'Run codex-mesh setup again with this version; incomplete setup is not ready.');
242
252
  await check('binary/Skill version',()=>{if(command(state.binary,['--version'])!==`codex-mesh ${context.version}`||hash(state.binary)!==hash(context.binary))throw Error();const text=fs.readFileSync(path.join(state.skillsDir,'codex-mesh/SKILL.md'),'utf8');if(!text.includes(`version: "${context.version}"`)||text!==fs.readFileSync(path.join(context.packageRoot,'skills/codex-mesh/SKILL.md'),'utf8'))throw Error();},'Run setup to refresh stable binary and managed Skill; leave enrolled sessions before upgrading.');
243
253
  await check('node credential/Hub',async()=>{const grant=await request(hubUrl(state.hub),'/v1/node/check',readToken(path.join(state.root,'node.token')));if(grant.node_id!==state.nodeId||grant.version!==context.version)throw Error();},'Check private node token (chmod 600), SSH tunnel/Hub URL, node UUID and matching Hub version.');
244
- await check('owning Codex daemon',()=>{const d=daemon(state.codex,state.daemonSocket);if(d.socket!==state.daemonSocket)throw Error();},'Start the owning ordinary Codex daemon; rerun setup if its socket changed.');
254
+ await check(state.skipDaemonVersionCheck?'owning Codex daemon (version check skipped by saved policy)':'owning Codex daemon',()=>{const d=daemon(state.codex,state.daemonSocket,state.skipDaemonVersionCheck===true);if(d.socket!==state.daemonSocket)throw Error();},'Start the owning ordinary Codex daemon; rerun setup if its socket changed.');
245
255
  await check('Node service',async()=>{if(!serviceAlive(state))throw Error();const h=await localHealth(state.socket);if(h.node_id!==state.nodeId||h.version!==context.version||!h.hub_connected)throw Error();},'Inspect private node.log and rerun setup. Never restart the user Codex daemon for a Mesh upgrade.');
246
256
  await check('MCP registration',()=>{if(!matchesMcp(mcp(state.codex),state))throw Error();},'Run setup in the same CODEX_HOME used by your ordinary Codex.');
247
257
  await check('MCP initialize/tools',()=>{const messages=[{jsonrpc:'2.0',id:1,method:'initialize',params:{protocolVersion:'2024-11-05',capabilities:{},clientInfo:{name:'mesh-doctor',version:context.version}}},{jsonrpc:'2.0',id:2,method:'tools/list',params:{}}];const output=command(state.binary,['mcp','--socket',state.socket],{input:messages.map(m=>JSON.stringify(m)+'\n').join('')});const replies=output.split('\n').map(JSON.parse);if(!replies.find(r=>r.id===1&&r.result)||replies.find(r=>r.id===2)?.result?.tools?.length!==8)throw Error();},'Repair the managed Node/socket and rerun setup; doctor never calls mesh_join.');
@@ -260,12 +270,15 @@ export function savedAgentArgs(args) {
260
270
  }
261
271
  export async function main(args,context) {
262
272
  const [action,...rest]=args;const o=options(rest);
263
- 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]\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.\nUpgrade: install new npm version, leave Mesh sessions, rerun setup; no install hooks restart services.`);return;}
273
+ 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 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; 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;}
264
274
  if(action==='setup')return setup(o,context);
265
275
  const root=home();const file=path.join(root,'installation.json');let checks;
266
276
  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.'}];}}
267
277
  else if(fs.existsSync(path.join(root,'management.json'))){
268
278
  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.'}];}
279
+ }else if(fs.existsSync(path.join(root,'enrollment.json'))) {
280
+ 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.`}];}
281
+ catch {checks=[{name:'browser authorization',ok:false,fix:'Saved authorization is invalid or has unsafe permissions; inspect private enrollment.json and rerun setup.'}];}
269
282
  }else checks=[{name:'configuration',ok:false,fix:'Run codex-mesh setup (or setup --manager for management-only use).'}];
270
283
  if(o.json)console.log(JSON.stringify({version:context.version,ok:checks.every(c=>c.ok),checks},null,2));
271
284
  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.2.0",
3
+ "version": "0.4.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.2.0",
2
+ "version": "0.4.0",
3
3
  "protocolVersion": 1,
4
4
  "platforms": {
5
5
  "linux-x64-gnu": {
6
6
  "path": "platforms/linux-x64-gnu/codex-mesh",
7
- "sha256": "531429c37563df5f487b5813db4981c29151d94e030347e2b6051bb84cc442c9",
7
+ "sha256": "3cf6a2c17d6aff3824ce2f8ccc9f3fd3837b91ce565b47c2bc1dc35708d38b8a",
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.2.0"
5
+ version: "0.4.0"
6
6
  ---
7
7
 
8
8
  # Codex Mesh
@@ -1,4 +1,4 @@
1
- # Host setup for packaged Mesh 0.2.0
1
+ # Host setup for packaged Mesh 0.4.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.2.0 codex-mesh mcp --socket
33
+ package version with `npx --yes --package=<package>@0.4.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.