@sleep2agi/agent-node 2.2.0-preview.1 → 2.3.1-preview.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.
Files changed (4) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +22 -14
  3. package/dist/cli.js +13 -13
  4. package/package.json +10 -4
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Agent runtime for Agent Network. Connects to a CommHub server, registers under an alias, and processes incoming tasks with one of three runtimes.
4
4
 
5
- **v2.1.1 stable.** The supported entry point is the `anet` CLI from `@sleep2agi/agent-network@2.0.0`, which writes the right `config.json` and environment variables for you.
5
+ The supported entry point is the `anet` CLI from `@sleep2agi/agent-network`, which writes the right `config.json`, network token, and environment variables for you.
6
6
 
7
7
  ## Install
8
8
 
@@ -39,7 +39,7 @@ CLI flags:
39
39
  |---|---|---|
40
40
  | `--alias` | required | unique name in the hub |
41
41
  | `--hub` | `http://127.0.0.1:9200` | CommHub URL |
42
- | `--runtime` | `claude-agent-sdk` | `claude-agent-sdk` / `codex-sdk` / `claude-code-cli` |
42
+ | `--runtime` | `claude-agent-sdk` | `claude-agent-sdk` / `codex-sdk` / `claude-code-cli` / `http-api` |
43
43
  | `--model` | runtime default | passed through to the SDK |
44
44
  | `--tools` | (none) | `all` or comma-separated list |
45
45
  | `--max-turns` | `50` | upper bound per task |
@@ -49,9 +49,10 @@ CLI flags:
49
49
 
50
50
  | Runtime | Backend | Status | Notes |
51
51
  |---|---|---|---|
52
- | `claude-agent-sdk` | [@anthropic-ai/claude-agent-sdk](https://www.npmjs.com/package/@anthropic-ai/claude-agent-sdk) | verified | Anthropic Messages API; works with any compatible endpoint |
52
+ | `claude-agent-sdk` | [@anthropic-ai/claude-agent-sdk](https://www.npmjs.com/package/@anthropic-ai/claude-agent-sdk) | verified | Anthropic-compatible API; works with MiniMax, DeepSeek, GLM, Kimi, Anthropic, OpenRouter, or custom endpoints |
53
53
  | `codex-sdk` | [@openai/codex-sdk](https://www.npmjs.com/package/@openai/codex-sdk) | unverified end-to-end | unit tests pass, no full E2E with real codex auth |
54
54
  | `claude-code-cli` | local `claude` CLI | unverified end-to-end | runs locally for Claude Pro subscribers |
55
+ | `http-api` | OpenAI/Anthropic-compatible HTTP | experimental | reads `ANTHROPIC_*`, `OPENAI_*`, or `MINIMAX_CODING_API_KEY` environment variables |
55
56
 
56
57
  Runtimes are loaded lazily — picking one doesn't pull the others' dependencies. `claude-code-cli` adds zero extra SDK weight.
57
58
 
@@ -61,7 +62,7 @@ Runtimes are loaded lazily — picking one doesn't pull the others' dependencies
61
62
 
62
63
  | Provider | Base URL | Default model | Status |
63
64
  |---|---|---|---|
64
- | Anthropic | `https://api.anthropic.com` | `claude-sonnet-4-5` | verified |
65
+ | Anthropic | `https://api.anthropic.com` | configured by `--model` | verified |
65
66
  | MiniMax (国际) | `https://api.minimax.io/anthropic` | `MiniMax-M2.7` | verified |
66
67
  | MiniMax (国内) | `https://api.minimaxi.com/anthropic` | `MiniMax-M2.7` | verified |
67
68
  | DeepSeek | `https://api.deepseek.com/anthropic` | `deepseek-chat` | verified |
@@ -90,16 +91,23 @@ Typical output of `anet node create` at `.anet/nodes/<name>/config.json`:
90
91
 
91
92
  ```json
92
93
  {
93
- "alias": "my-bot",
94
+ "node_id": "n_a1b2c3d4",
95
+ "node_name": "my-bot",
94
96
  "hub": "http://127.0.0.1:9200",
97
+ "token": "ntok_...",
95
98
  "runtime": "claude-agent-sdk",
96
99
  "model": "MiniMax-M2.7",
97
- "anthropic_base_url": "https://api.minimax.io/anthropic",
98
- "anthropic_auth_token": "sk-...",
99
- "tools": "all",
100
- "maxTurns": 50,
101
- "dangerouslySkipPermissions": true,
102
- "teammateMode": true
100
+ "channels": ["server:commhub"],
101
+ "tools": ["Read", "Write", "Edit", "Bash", "Glob", "Grep"],
102
+ "env": {
103
+ "ANTHROPIC_BASE_URL": "https://api.minimax.io/anthropic",
104
+ "ANTHROPIC_AUTH_TOKEN": "sk-..."
105
+ },
106
+ "flags": {
107
+ "dangerouslySkipPermissions": true,
108
+ "teammateMode": "in-process",
109
+ "maxTurns": 50
110
+ }
103
111
  }
104
112
  ```
105
113
 
@@ -140,9 +148,9 @@ When the runtime is `claude-code-cli`, the spawned subprocess gets `settingSourc
140
148
 
141
149
  | Package | Version |
142
150
  |---|---|
143
- | [@sleep2agi/agent-network](https://www.npmjs.com/package/@sleep2agi/agent-network) | 2.0.0 |
144
- | [@sleep2agi/commhub-server](https://www.npmjs.com/package/@sleep2agi/commhub-server) | 0.5.0 |
145
- | [@sleep2agi/agent-network-dashboard](https://www.npmjs.com/package/@sleep2agi/agent-network-dashboard) | 0.1.0 |
151
+ | [@sleep2agi/agent-network](https://www.npmjs.com/package/@sleep2agi/agent-network) | 2.1.0 |
152
+ | [@sleep2agi/commhub-server](https://www.npmjs.com/package/@sleep2agi/commhub-server) | 0.6.0 |
153
+ | [@sleep2agi/agent-network-dashboard](https://www.npmjs.com/package/@sleep2agi/agent-network-dashboard) | 0.3.0 |
146
154
 
147
155
  ## License
148
156
 
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as Rz}from"node:module";var k=Rz(import.meta.url);import{readFileSync as p,existsSync as a,writeFileSync as t,chmodSync as kz}from"fs";import{join as M}from"path";import{hostname as zz,homedir as Pz}from"os";import{mkdirSync as wz,appendFileSync as uz}from"fs";var __dirname="/home/vansin/agent-orchestra/agent-node/src";var qz=Pz(),R=process.argv.slice(2),v={},Wz=[],Gz="2.1.0";try{let z=new URL(".",import.meta.url).pathname;for(let Z of["../package.json","../../package.json"])try{let $=JSON.parse(p(M(z,Z),"utf-8"));if($.version){Gz=$.version;break}}catch{}}catch{}for(let z=0;z<R.length;z++){if(R[z]==="--version"||R[z]==="-v")console.log(`agent-node v${Gz}`),process.exit(0);if(R[z]==="-h"||R[z]==="--help")console.log(`
2
+ import{createRequire as Rz}from"node:module";var x=Rz(import.meta.url);import{readFileSync as f,existsSync as a,writeFileSync as t,chmodSync as xz}from"fs";import{join as M}from"path";import{hostname as zz,homedir as kz}from"os";import{mkdirSync as wz,appendFileSync as Sz}from"fs";var __dirname="/home/vansin/agent-orchestra/agent-node/src";var qz=kz(),R=process.argv.slice(2),v={},Wz=[],Gz="2.1.0";try{let z=new URL(".",import.meta.url).pathname;for(let Z of["../package.json","../../package.json"])try{let $=JSON.parse(f(M(z,Z),"utf-8"));if($.version){Gz=$.version;break}}catch{}}catch{}for(let z=0;z<R.length;z++){if(R[z]==="--version"||R[z]==="-v")console.log(`agent-node v${Gz}`),process.exit(0);if(R[z]==="-h"||R[z]==="--help")console.log(`
3
3
  @sleep2agi/agent-node — AI Agent 节点,一行命令加入 CommHub 网络
4
4
 
5
5
  用法:
@@ -24,23 +24,23 @@ import{createRequire as Rz}from"node:module";var k=Rz(import.meta.url);import{re
24
24
  Runtime:
25
25
  claude-agent-sdk Claude Agent SDK — Claude/MiniMax/Anthropic 兼容 API
26
26
  codex-sdk Codex SDK — GPT-5.4,复用 codex 登录态
27
- `),process.exit(0);if(R[z]==="--new-session"){v["new-session"]="true";continue}if(R[z]==="--channel"&&z+1<R.length){Wz.push(R[++z]);continue}if(R[z].startsWith("--")&&z+1<R.length)v[R[z].slice(2)]=R[++z]}function jz(z){return z.replace(/^~(?=\/|$)/,qz)}function xz(z){let Z=z.indexOf(":");if(Z<0)return{type:z,raw:z};if(Z===0||Z===z.length-1)throw Error(`invalid channel spec "${z}" (expected type or type:path)`);return{type:z.slice(0,Z),path:jz(z.slice(Z+1)),raw:z}}function f(z){if(!a(z))return null;try{return JSON.parse(p(z,"utf-8"))}catch{return null}}var G={},N="";if(v.config){let z=v.config.startsWith("/")?v.config:M(process.cwd(),v.config),Z=f(z);if(Z)G=Z,N=z,console.log(`[agent-node] Config: ${z}`)}var H=v.alias||process.env.COMMHUB_ALIAS||process.env.ALIAS||G.alias;if(!v.config&&H){let z=M(process.cwd(),".anet","nodes",H,"config.json"),Z=M(process.cwd(),".anet","profiles",`${H}.json`),$=a(z)?z:Z,Q=f($);if(Q){if(G={...Q,...G},N=$,console.log(`[agent-node] Config: ${$}`),Q.env&&typeof Q.env==="object"){for(let[Y,X]of Object.entries(Q.env))if(!process.env[Y]&&typeof X==="string")process.env[Y]=jz(X)}}}var T=f(M(qz,".anet","config.json"))||{};if(T.hub&&!G.hub)G.hub=T.hub;if(T.token&&!G.token)G.token=T.token;if(!v.config&&!Object.keys(G).length){let z=f(M(process.cwd(),".agent-node.json"));if(z)G=z,console.log("[agent-node] 配置: .agent-node.json")}if(!H)console.error(`错误: 必须指定 --alias
28
- 用法: npx @sleep2agi/agent-node --alias "我的Agent"`),process.exit(1);var Bz=v.runtime||process.env.RUNTIME||G.runtime||"claude-agent-sdk",yz={"claude-agent-sdk":"claude","claude-sdk":"claude","agent-sdk":"claude",claude:"claude","codex-sdk":"codex",codex:"codex","http-api":"http","openai-api":"http",minimax:"http"},C=yz[Bz]||"claude",Nz=Bz,d=v.url||v.hub||process.env.COMMHUB_URL||G.hub||"http://127.0.0.1:9200",y=v.model||process.env.MODEL||G.model,Lz=["Read","Write","Edit","Bash","Glob","Grep","WebSearch","WebFetch"],Zz=v.tools||(Array.isArray(G.tools)?G.tools.join(","):G.tools)||"",I=Zz==="all"?Lz:Zz.split(",").filter(Boolean),Az=parseInt(v["max-turns"]||G.flags?.maxTurns||G.maxTurns||"50"),$z=parseFloat(v["max-budget"]||G.flags?.maxBudgetUsd||G.maxBudgetUsd||"0"),Cz=v["new-session"]==="true",A=Cz?"":v.session||G.session||G.resume||G.sessionId||"",E=v.prompt||G.systemPrompt||"",L=G.token||T.token||process.env.COMMHUB_TOKEN||"";if(process.env.COMMHUB_TOKEN&&G.token&&process.env.COMMHUB_TOKEN!==G.token)console.warn(`[${H}] ⚠ COMMHUB_TOKEN env override ignored (using node config token). Unset COMMHUB_TOKEN to silence this warning.`);var s=v["log-dir"]||M(process.cwd(),".anet","nodes",H,"logs"),_z={debug:0,info:1,warn:2,error:3},Oz=_z[v["log-level"]||process.env.LOG_LEVEL||G.logLevel||"info"]??1,S=[...(Array.isArray(G.channels)?G.channels:[]).filter((z)=>!z.startsWith("server:")&&!z.startsWith("plugin:")),...Wz],Kz=S.map((z)=>{try{return xz(z)}catch(Z){console.error(`[agent-node] ${Z.message}`),process.exit(1)}});function Fz(z){if(!N||!z)return;try{let Z=JSON.parse(p(N,"utf-8"));if(Z.session===z)return;Z.session=z,t(N,JSON.stringify(Z,null,2)+`
29
- `),P(`session 写回: ${N} → ${z.slice(0,8)}...`)}catch(Z){_(`writebackSession failed: ${Z.message}`)}}function Ez(z){if(!a(z))return;for(let Z of p(z,"utf-8").split(`
30
- `)){let $=Z.trim();if(!$||$.startsWith("#"))continue;let Q=$.indexOf("=");if(Q<=0)continue;let Y=$.slice(0,Q).trim(),X=$.slice(Q+1).trim().replace(/^['"]|['"]$/g,"");if(!process.env[Y])process.env[Y]=X}}function Tz(z){return M(process.cwd(),".anet","nodes",H,"channels",z)}function Iz(z){let Z=z.path||Tz("telegram");Ez(M(Z,".env"));let $=process.env.TELEGRAM_BOT_TOKEN||"";if(!$)console.error(`[agent-node] telegram channel needs TELEGRAM_BOT_TOKEN in ${M(Z,".env")}`),process.exit(1);try{kz(M(Z,".env"),384)}catch{}let Q=f(M(Z,"access.json"))||{},Y=M(Z,"inbox");try{wz(Y,{recursive:!0})}catch{}return{type:"telegram",dir:Z,inboxDir:Y,token:$,allowFrom:Array.isArray(Q.allowFrom)?Q.allowFrom.map(String):[]}}var n=Kz.filter((z)=>z.type==="telegram").map(Iz),Qz=Kz.find((z)=>z.type!=="telegram");if(Qz)console.error(`[agent-node] unsupported channel: ${Qz.raw}`),process.exit(1);if(n.length>0&&C!=="codex"&&!I.includes("Read"))I.push("Read");try{wz(s,{recursive:!0})}catch{}function i(z,Z,$){if(Z<Oz)return;let Q=new Date().toTimeString().slice(0,8),Y=z.toUpperCase().padEnd(5),X=`[${Q}] [${Y}] [${H}] ${$}`;console.log(X);try{let W=new Date().toISOString().slice(0,10);uz(M(s,`${W}.log`),X+`
31
- `)}catch{}}var V=(z)=>i("info",1,z),P=(z)=>i("debug",0,z),_=(z)=>i("warn",2,z),h=(z)=>i("error",3,z);async function c(z,Z,$=3){let Q={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(L)Q.Authorization=`Bearer ${L}`;let Y;for(let X=0;X<=$;X++)try{let W=await fetch(`${d}/mcp`,{method:"POST",headers:Q,body:JSON.stringify({jsonrpc:"2.0",id:Date.now(),method:"tools/call",params:{name:z,arguments:Z}})});if(!W.ok&&X<$){Y=Error(`HTTP ${W.status}`),await new Promise((F)=>setTimeout(F,1000*Math.pow(2,X)));continue}let q=await W.text(),B=q.match(/data: (.+)/),K=B?JSON.parse(B[1]):JSON.parse(q),j=K?.result?.content?.[0]?.text;return j?JSON.parse(j):K}catch(W){if(Y=W,X<$)P(`callCommHub(${z}) attempt ${X+1} failed: ${W.message}, retrying...`),await new Promise((q)=>setTimeout(q,1000*Math.pow(2,X)))}throw Y||Error(`callCommHub(${z}) failed after ${$} retries`)}var l=G.node_id||"",Sz=G.node_name||"",u=G.network_id||process.env.ANET_NETWORK_ID||T.network_id||"",Hz=l?`sdk-${l}`:`sdk-${H}-${Date.now().toString(36)}`,hz=()=>c("report_status",{resume_id:Hz,alias:H,status:"idle",server:zz(),hostname:zz(),agent:`agent-node:${C}`,project_dir:process.cwd(),node_id:l||void 0,node_name:Sz||void 0,session_id:A||void 0,config_path:N||void 0,channels:S.length?JSON.stringify(S):void 0,model:y||void 0,network_id:u||void 0}),r=(z,Z)=>c("report_status",{resume_id:Hz,alias:H,status:z,task:Z,node_id:l||void 0,session_id:m||A||void 0,config_path:N||void 0,channels:S.length?JSON.stringify(S):void 0,network_id:u||void 0}),pz=async()=>(await c("get_inbox",{alias:H,limit:20}))?.messages||[],fz=(z)=>c("ack_inbox",{alias:H,message_id:z}),dz=(z,Z,$,Q=!1)=>c("send_reply",{alias:z,text:Z,from_session:H,in_reply_to:$||void 0,status:Q?"failed":"replied"}),m=A||void 0;async function cz(z,Z){let{existsSync:$}=await import("fs"),Q=!1;try{let J=k.resolve("@anthropic-ai/claude-agent-sdk-linux-x64/claude");if($(J))Q=!0}catch{}if(!Q)try{let{execSync:J}=await import("child_process");J("which claude",{stdio:"pipe"}),Q=!0}catch{}if(!Q&&process.platform==="linux")try{let{execSync:J}=await import("child_process");V("[claude] no Claude binary found — installing @anthropic-ai/claude-agent-sdk-linux-x64 (glibc) ..."),J("npm install --no-save --prefix "+JSON.stringify(__dirname+"/../")+" @anthropic-ai/claude-agent-sdk-linux-x64",{stdio:"pipe",timeout:60000});try{let w=k.resolve("@anthropic-ai/claude-agent-sdk-linux-x64/claude");if($(w))Q=!0,V(`[claude] glibc binary installed: ${w}`)}catch{}}catch(J){V(`[claude] auto-install of glibc binary failed: ${J?.message||J}`)}if(!Q)return["claude 错误: Claude Code 二进制未找到。","agent-node 默认运行 claude-agent-sdk runtime 需要 Claude Code 本地二进制。","解决方案:"," 1. 全局安装 Claude Code: npm i -g @anthropic-ai/claude-code"," 2. 或者切换到 codex-sdk runtime: anet node create <name> --runtime codex-sdk (需 codex auth login)"," 3. 或者在 node config.json 里设 pathToClaudeCodeExecutable 指向已安装的 claude 二进制"].join(`
27
+ `),process.exit(0);if(R[z]==="--new-session"){v["new-session"]="true";continue}if(R[z]==="--channel"&&z+1<R.length){Wz.push(R[++z]);continue}if(R[z].startsWith("--")&&z+1<R.length)v[R[z].slice(2)]=R[++z]}function jz(z){return z.replace(/^~(?=\/|$)/,qz)}function yz(z){let Z=z.indexOf(":");if(Z<0)return{type:z,raw:z};if(Z===0||Z===z.length-1)throw Error(`invalid channel spec "${z}" (expected type or type:path)`);return{type:z.slice(0,Z),path:jz(z.slice(Z+1)),raw:z}}function u(z){if(!a(z))return null;try{return JSON.parse(f(z,"utf-8"))}catch{return null}}var G={},y="";if(v.config){let z=v.config.startsWith("/")?v.config:M(process.cwd(),v.config),Z=u(z);if(Z)G=Z,y=z,console.log(`[agent-node] Config: ${z}`)}var w=v.alias||process.env.COMMHUB_ALIAS||process.env.ALIAS||G.alias;if(!v.config&&w){let z=M(process.cwd(),".anet","nodes",w,"config.json"),Z=M(process.cwd(),".anet","profiles",`${w}.json`),$=a(z)?z:Z,Q=u($);if(Q){if(G={...Q,...G},y=$,console.log(`[agent-node] Config: ${$}`),Q.env&&typeof Q.env==="object"){for(let[Y,X]of Object.entries(Q.env))if(!process.env[Y]&&typeof X==="string")process.env[Y]=jz(X)}}}var I=u(M(qz,".anet","config.json"))||{};if(I.hub&&!G.hub)G.hub=I.hub;if(I.token&&!G.token)G.token=I.token;if(!v.config&&!Object.keys(G).length){let z=u(M(process.cwd(),".agent-node.json"));if(z)G=z,console.log("[agent-node] 配置: .agent-node.json")}if(!w)console.error(`错误: 必须指定 --alias
28
+ 用法: npx @sleep2agi/agent-node --alias "我的Agent"`),process.exit(1);var Bz=v.runtime||process.env.RUNTIME||G.runtime||"claude-agent-sdk",Pz={"claude-agent-sdk":"claude","claude-sdk":"claude","agent-sdk":"claude",claude:"claude","codex-sdk":"codex",codex:"codex","http-api":"http","openai-api":"http",minimax:"http"},_=Pz[Bz]||"claude",Nz=Bz,d=v.url||v.hub||process.env.COMMHUB_URL||G.hub||"http://127.0.0.1:9200",L=v.model||process.env.MODEL||G.model,Lz=["Read","Write","Edit","Bash","Glob","Grep","WebSearch","WebFetch"],Zz=v.tools||(Array.isArray(G.tools)?G.tools.join(","):G.tools)||"",T=Zz==="all"?Lz:Zz.split(",").filter(Boolean),Az=parseInt(v["max-turns"]||G.flags?.maxTurns||G.maxTurns||"50"),$z=parseFloat(v["max-budget"]||G.flags?.maxBudgetUsd||G.maxBudgetUsd||"0"),Cz=v["new-session"]==="true",C=Cz?"":v.session||G.session||G.resume||G.sessionId||"",E=v.prompt||G.systemPrompt||"",P=G.token||I.token||process.env.COMMHUB_TOKEN||"";if(process.env.COMMHUB_TOKEN&&G.token&&process.env.COMMHUB_TOKEN!==G.token)console.warn(`[${w}] ⚠ COMMHUB_TOKEN env override ignored (using node config token). Unset COMMHUB_TOKEN to silence this warning.`);function _z(){if(!y)return!1;let z=u(y),Z=typeof z?.token==="string"?z.token:"";if(!Z||Z===P)return!1;return P=Z,G.token=Z,A(`reloaded node token from ${y}`),!0}var s=v["log-dir"]||M(process.cwd(),".anet","nodes",w,"logs"),Oz={debug:0,info:1,warn:2,error:3},Ez=Oz[v["log-level"]||process.env.LOG_LEVEL||G.logLevel||"info"]??1,h=[...(Array.isArray(G.channels)?G.channels:[]).filter((z)=>!z.startsWith("server:")&&!z.startsWith("plugin:")),...Wz],Kz=h.map((z)=>{try{return yz(z)}catch(Z){console.error(`[agent-node] ${Z.message}`),process.exit(1)}});function Fz(z){if(!y||!z)return;try{let Z=JSON.parse(f(y,"utf-8"));if(Z.session===z)return;Z.session=z,t(y,JSON.stringify(Z,null,2)+`
29
+ `),k(`session 写回: ${y} → ${z.slice(0,8)}...`)}catch(Z){A(`writebackSession failed: ${Z.message}`)}}function Iz(z){if(!a(z))return;for(let Z of f(z,"utf-8").split(`
30
+ `)){let $=Z.trim();if(!$||$.startsWith("#"))continue;let Q=$.indexOf("=");if(Q<=0)continue;let Y=$.slice(0,Q).trim(),X=$.slice(Q+1).trim().replace(/^['"]|['"]$/g,"");if(!process.env[Y])process.env[Y]=X}}function Tz(z){return M(process.cwd(),".anet","nodes",w,"channels",z)}function uz(z){let Z=z.path||Tz("telegram");Iz(M(Z,".env"));let $=process.env.TELEGRAM_BOT_TOKEN||"";if(!$)console.error(`[agent-node] telegram channel needs TELEGRAM_BOT_TOKEN in ${M(Z,".env")}`),process.exit(1);try{xz(M(Z,".env"),384)}catch{}let Q=u(M(Z,"access.json"))||{},Y=M(Z,"inbox");try{wz(Y,{recursive:!0})}catch{}return{type:"telegram",dir:Z,inboxDir:Y,token:$,allowFrom:Array.isArray(Q.allowFrom)?Q.allowFrom.map(String):[]}}var n=Kz.filter((z)=>z.type==="telegram").map(uz),Qz=Kz.find((z)=>z.type!=="telegram");if(Qz)console.error(`[agent-node] unsupported channel: ${Qz.raw}`),process.exit(1);if(n.length>0&&_!=="codex"&&!T.includes("Read"))T.push("Read");try{wz(s,{recursive:!0})}catch{}function i(z,Z,$){if(Z<Ez)return;let Q=new Date().toTimeString().slice(0,8),Y=z.toUpperCase().padEnd(5),X=`[${Q}] [${Y}] [${w}] ${$}`;console.log(X);try{let W=new Date().toISOString().slice(0,10);Sz(M(s,`${W}.log`),X+`
31
+ `)}catch{}}var V=(z)=>i("info",1,z),k=(z)=>i("debug",0,z),A=(z)=>i("warn",2,z),p=(z)=>i("error",3,z);async function c(z,Z,$=3){let Q={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(P)Q.Authorization=`Bearer ${P}`;let Y;for(let X=0;X<=$;X++)try{let W=await fetch(`${d}/mcp`,{method:"POST",headers:Q,body:JSON.stringify({jsonrpc:"2.0",id:Date.now(),method:"tools/call",params:{name:z,arguments:Z}})});if(!W.ok&&X<$){Y=Error(`HTTP ${W.status}`),await new Promise((F)=>setTimeout(F,1000*Math.pow(2,X)));continue}let q=await W.text(),B=q.match(/data: (.+)/),K=B?JSON.parse(B[1]):JSON.parse(q),j=K?.result?.content?.[0]?.text;return j?JSON.parse(j):K}catch(W){if(Y=W,X<$)k(`callCommHub(${z}) attempt ${X+1} failed: ${W.message}, retrying...`),await new Promise((q)=>setTimeout(q,1000*Math.pow(2,X)))}throw Y||Error(`callCommHub(${z}) failed after ${$} retries`)}var l=G.node_id||"",hz=G.node_name||"",S=G.network_id||process.env.ANET_NETWORK_ID||I.network_id||"",Hz=l?`sdk-${l}`:`sdk-${w}-${Date.now().toString(36)}`,pz=()=>c("report_status",{resume_id:Hz,alias:w,status:"idle",server:zz(),hostname:zz(),agent:`agent-node:${_}`,project_dir:process.cwd(),node_id:l||void 0,node_name:hz||void 0,session_id:C||void 0,config_path:y||void 0,channels:h.length?JSON.stringify(h):void 0,model:L||void 0,network_id:S||void 0}),g=(z,Z)=>c("report_status",{resume_id:Hz,alias:w,status:z,task:Z,node_id:l||void 0,session_id:m||C||void 0,config_path:y||void 0,channels:h.length?JSON.stringify(h):void 0,network_id:S||void 0}),fz=async()=>(await c("get_inbox",{alias:w,limit:20}))?.messages||[],dz=(z)=>c("ack_inbox",{alias:w,message_id:z}),cz=(z,Z,$,Q=!1)=>c("send_reply",{alias:z,text:Z,from_session:w,in_reply_to:$||void 0,status:Q?"failed":"replied"}),m=C||void 0;async function mz(z,Z){let{existsSync:$}=await import("fs"),Q=!1;try{let J=x.resolve("@anthropic-ai/claude-agent-sdk-linux-x64/claude");if($(J))Q=!0}catch{}if(!Q)try{let{execSync:J}=await import("child_process");J("which claude",{stdio:"pipe"}),Q=!0}catch{}if(!Q&&process.platform==="linux")try{let{execSync:J}=await import("child_process");V("[claude] no Claude binary found — installing @anthropic-ai/claude-agent-sdk-linux-x64 (glibc) ..."),J("npm install --no-save --prefix "+JSON.stringify(__dirname+"/../")+" @anthropic-ai/claude-agent-sdk-linux-x64",{stdio:"pipe",timeout:60000});try{let H=x.resolve("@anthropic-ai/claude-agent-sdk-linux-x64/claude");if($(H))Q=!0,V(`[claude] glibc binary installed: ${H}`)}catch{}}catch(J){V(`[claude] auto-install of glibc binary failed: ${J?.message||J}`)}if(!Q)return["claude 错误: Claude Code 二进制未找到。","agent-node 默认运行 claude-agent-sdk runtime 需要 Claude Code 本地二进制。","解决方案:"," 1. 全局安装 Claude Code: npm i -g @anthropic-ai/claude-code"," 2. 或者切换到 codex-sdk runtime: anet node create <name> --runtime codex-sdk (需 codex auth login)"," 3. 或者在 node config.json 里设 pathToClaudeCodeExecutable 指向已安装的 claude 二进制"].join(`
32
32
  `);if(typeof process.getuid==="function"&&process.getuid()===0)return["claude 错误: 当前以 root 用户运行,Claude Code 拒绝 --dangerously-skip-permissions。","解决方案 (推荐 1):"," 1. 建非 root 用户后再启动:"," useradd -m anet-agent"," su - anet-agent"," anet login --hub <URL> --username <user> --password <pass>"," anet node start <name>"," 2. 或切换 runtime 为 codex-sdk (root 下可运行,需 codex auth login):"," anet node delete <name> && anet node create <name> --runtime codex-sdk"].join(`
33
- `);let{query:Y}=await import("@anthropic-ai/claude-agent-sdk"),X=process.env.CURRENT_TASK_ID||"",W=[`你是 ${H},一个 AI Agent 节点。收到来自 ${Z} 的任务 (task_id=${X}):`,"",z,"","【若任务需要其他 agent 协助】","1. 先用 mcp_commhub__get_all_status 看哪些 agent 在线。",`2. 用 mcp_commhub__send_task(alias, task, parent_task_id="${X}") 派给合适的 agent。`,` ⚠ 必须把 parent_task_id 设成你当前任务的 ID,这样系统会自动把子任务的最终结果串回给 ${Z}。`,`3. 用 mcp_commhub__get_task(task_id) 轮询子任务状态。允许中途给 ${Z} 发"还在等待"的进度汇报,但你必须继续轮询直到子任务 replied/failed。`,`4. 拿到子任务 reply 后把内容整合到你给 ${Z} 的最终汇报里。`,` 即便你的 session 中途断开,只要 parent_task_id 设了,系统也会自动把子任务结果交付给 ${Z},所以不必焦虑。`,"","【禁止】",`- 不要给自己(${H})发任务(死循环)。`,'- 不要回复"收到""ok""明白了"等无内容确认。',"- 不要在无新任务时主动调用通信工具。",`- send_task 时不要忘记 parent_task_id;忘了就要不回来 ${Z} 的链路。`,"","执行完后简要汇报结果。"].join(`
33
+ `);let{query:Y}=await import("@anthropic-ai/claude-agent-sdk"),X=process.env.CURRENT_TASK_ID||"",W=[`你是 ${w},一个 AI Agent 节点。收到来自 ${Z} 的任务 (task_id=${X}):`,"",z,"","【若任务需要其他 agent 协助】","1. 先用 mcp_commhub__get_all_status 看哪些 agent 在线。",`2. 用 mcp_commhub__send_task(alias, task, parent_task_id="${X}") 派给合适的 agent。`,` ⚠ 必须把 parent_task_id 设成你当前任务的 ID,这样系统会自动把子任务的最终结果串回给 ${Z}。`,`3. 用 mcp_commhub__get_task(task_id) 轮询子任务状态。允许中途给 ${Z} 发"还在等待"的进度汇报,但你必须继续轮询直到子任务 replied/failed。`,`4. 拿到子任务 reply 后把内容整合到你给 ${Z} 的最终汇报里。`,` 即便你的 session 中途断开,只要 parent_task_id 设了,系统也会自动把子任务结果交付给 ${Z},所以不必焦虑。`,"","【禁止】",`- 不要给自己(${w})发任务(死循环)。`,'- 不要回复"收到""ok""明白了"等无内容确认。',"- 不要在无新任务时主动调用通信工具。",`- send_task 时不要忘记 parent_task_id;忘了就要不回来 ${Z} 的链路。`,"","执行完后简要汇报结果。"].join(`
34
34
  `),q=E?`${E}
35
35
 
36
36
  收到来自 ${Z} 的任务:
37
37
 
38
- ${z}`:W,B=process.env.COMMHUB_URL||d,K=process.env.COMMHUB_TOKEN||L,j={};if(B)j.commhub={type:"http",url:`${B}/mcp`,headers:K?{Authorization:`Bearer ${K}`}:void 0};let F=(()=>{try{let{execSync:J}=k("child_process"),w=k("fs");try{let D=k.resolve("@anthropic-ai/claude-agent-sdk-linux-x64/claude");if(w.existsSync(D))return J(`${D} --version`,{stdio:"pipe"}),V(`[claude] using glibc binary: ${D}`),D}catch{}try{let D=J("which claude",{encoding:"utf-8"}).trim();if(D)return V(`[claude] using global binary: ${D}`),D}catch{}V("[claude] no binary resolved, falling back to SDK default");return}catch{return}})(),b={model:y||void 0,tools:I.length?I:void 0,maxTurns:Az,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,settingSources:[],mcpServers:Object.keys(j).length?j:void 0,pathToClaudeCodeExecutable:F,env:process.env,cwd:process.cwd(),stderr:(J)=>{if(J.trim())V(`[stderr] ${J.trim().slice(0,300)}`)},hooks:{PreToolUse:[{hooks:[async(J)=>{return V(`[tool] ${J.tool_name}(${JSON.stringify(J.tool_input).slice(0,80)})`),{continue:!0}}]}]}};if($z>0)b.maxBudgetUsd=$z;if(E)b.systemPrompt=E;if(m)b.resume=m;let O="",U=Date.now();V(`[claude] claudePath=${F||"SDK default"}, mcpServers=${Object.keys(j).join(",")||"none"}`);for await(let J of Y({prompt:q,options:b})){let w=J;if(w.type==="system"&&w.subtype==="init")m=w.session_id,V(`[claude] session=${w.session_id?.slice(0,8)} model=${y||"default"}`),Fz(w.session_id);if(w.type==="result"){let D=Date.now()-U,e=w.usage||{};V(`[claude] ${w.subtype} | ${D}ms | $${w.total_cost_usd?.toFixed(4)||"?"} | in=${e.input_tokens||0} out=${e.output_tokens||0} | turns=${w.num_turns}`),O=w.subtype==="success"?w.result||"任务完成":`执行出错: ${w.error||w.result||"未知错误"}`}}return O}var x=null,mz=E||[`你是 ${H},一个 AI Agent 节点,工作目录:${process.cwd()}。`,"你通过通信网络(CommHub)接收任务并和其他 agent 协作。","","【可用通信工具】","- mcp_commhub__send_task(alias, task):派任务给指定 agent,等其 LLM 处理完返回 reply(同步语义)。","- mcp_commhub__send_message(alias, message):发聊天消息(不要求对方回复)。","- mcp_commhub__get_task(task_id):查询某任务的当前状态/reply。","- mcp_commhub__get_all_status():查看网络上所有在线 agent。","","【协作模式】","当你的任务需要其他 agent 的能力时:","1. 先 get_all_status 看哪些 agent 在线。","2. 用 send_task(alias, task, parent_task_id=<env CURRENT_TASK_ID>) 派给合适的 agent。"," ⚠ 必须把 parent_task_id 设成你当前任务的 ID(环境变量 CURRENT_TASK_ID 里),系统会自动把子任务最终结果串回给你的上游。",'3. 用 get_task 轮询子任务直到 status=replied/failed。允许中途汇报"还在等",但要继续轮询。',"4. 拿到 reply 后整合进你给上游的最终汇报。"," 即使你的 session 中途断开,只要 parent_task_id 设了,结果也会被系统自动 chain 回上游,不必焦虑。","","【禁止】",'- 不要回复"收到""好的""ok""在线""待命"等无内容确认。',"- 不要给自己发任务(会死循环)。","- 收到的若是 reply 类型,不要再 send_task 给原方(会乒乓回复)。","- 没有新任务时保持沉默,不主动发消息。","","你的最终回复会被系统自动 send_reply 给任务发起者。"].join(`
39
- `),Xz={model_auto_compact_token_limit:200000,developer_instructions:mz};async function nz(z,Z,$){try{let{execSync:B}=await import("child_process"),K=B("which codex 2>/dev/null",{encoding:"utf-8"}).trim();if(K){let j=K.replace(/\/codex$/,"");if(!process.env.PATH?.includes(j))process.env.PATH=`${j}:${process.env.PATH}`}}catch{}let Q;try{({Codex:Q}=await import("@openai/codex-sdk"))}catch{throw Error("@openai/codex-sdk not installed. Run: npm install -g @openai/codex-sdk @openai/codex")}if(!x){let B=new Q({config:Xz}),j={skipGitRepoCheck:!0,approvalPolicy:"never",model:y||"gpt-5.4",sandboxMode:"danger-full-access",modelReasoningEffort:"low"};if(A)x=B.resumeThread(A,j),V(`codex resumed thread: ${A}`);else x=B.startThread(j)}V(`[codex] model=${y||"gpt-5.4"} thread=${x?.id||"new"}`);let X=z,W=$?.length?[{type:"text",text:X},...$.map((B)=>({type:"local_image",path:B}))]:X,q=Date.now();try{let{events:B}=await x.runStreamed(W),K="",j=null,F=0;for await(let U of B)if(U.type==="item.started"){let J=U.item;P(`[codex] ${J.type}${J.command?`: ${J.command.slice(0,60)}`:J.tool?`: ${J.server}/${J.tool}`:""}`)}else if(U.type==="item.completed"){F++;let J=U.item;if(J.type==="agent_message")K=J.text||"";if(J.type==="command_execution")P(`[codex] cmd exit=${J.exit_code} | ${J.aggregated_output?.slice(0,80)}`);if(J.type==="reasoning")P(`[codex] thinking: ${J.text?.slice(0,80)}`);if(J.type==="mcp_tool_call")P(`[codex] mcp: ${J.server}/${J.tool} → ${J.status}`)}else if(U.type==="turn.completed")j=U.usage;let b=Date.now()-q,O=j?.input_tokens||0;if(V(`[codex] done | ${b}ms | in=${O} out=${j?.output_tokens||0} | items=${F}`),x?.id)Fz(x.id);return K||"(无回复)"}catch(B){V(`codex thread error: ${B.message}, 重建`),x=new Q({config:Xz}).startThread({skipGitRepoCheck:!0,approvalPolicy:"never",model:y||"gpt-5.4",sandboxMode:"danger-full-access",modelReasoningEffort:"low"});let j=await x.run(W),F=Date.now()-q;return V(`[codex] retry done | ${F}ms`),j.finalResponse||"(无回复)"}}async function lz(z,Z){let $=process.env.ANTHROPIC_API_KEY||process.env.ANTHROPIC_AUTH_TOKEN||process.env.OPENAI_API_KEY||process.env.MINIMAX_CODING_API_KEY||G.apiKey||"",Q=process.env.ANTHROPIC_BASE_URL||G.anthropicBaseUrl||"",Y=process.env.OPENAI_BASE_URL||G.apiBaseUrl||"https://api.openai.com/v1",X=y||"gpt-4o-mini",W=!!Q,B=(Q||Y).replace(/\/v1\/?$/,"");if(!$)return"错误: 需要设置 ANTHROPIC_API_KEY, OPENAI_API_KEY, 或 MINIMAX_CODING_API_KEY";let K=E||`你是 ${H},一个 AI 助手。收到来自 ${Z} 的任务后简要执行并汇报。`,j=Date.now();V(`[http-api] model=${X} format=${W?"anthropic":"openai"} base=${B.replace(/\/v1$/,"")}`);let F="",b=null;if(W){let U=await fetch(`${B}/v1/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":$,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:X,system:K,messages:[{role:"user",content:z}],max_tokens:2000})});if(!U.ok){let D=await U.text();return`Anthropic API 错误 ${U.status}: ${D.slice(0,200)}`}let J=await U.json();F=(Array.isArray(J.content)?J.content:[]).filter((D)=>D.type==="text").map((D)=>D.text).join(`
40
- `)||"",b=J.usage}else{let U=await fetch(`${B}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$}`},body:JSON.stringify({model:X,messages:[{role:"system",content:K},{role:"user",content:z}],max_tokens:2000})});if(!U.ok){let w=await U.text();return`OpenAI API 错误 ${U.status}: ${w.slice(0,200)}`}let J=await U.json();F=J.choices?.[0]?.message?.content||"",b=J.usage}let O=Date.now()-j;return V(`[http-api] done | ${O}ms | in=${b?.input_tokens||b?.prompt_tokens||0} out=${b?.output_tokens||b?.completion_tokens||0}`),F||"(无回复)"}var Yz=Promise.resolve();function vz(z,Z,$,Q){let Y=async()=>{let W=process.env.CURRENT_TASK_ID;if($)process.env.CURRENT_TASK_ID=$;else delete process.env.CURRENT_TASK_ID;try{if(C==="codex")return await nz(z,Z,Q);if(C==="http")return await lz(z,Z);return await cz(z,Z)}finally{if(W!==void 0)process.env.CURRENT_TASK_ID=W;else delete process.env.CURRENT_TASK_ID}},X=Yz.then(Y,Y);return Yz=X.then(()=>{},()=>{}),X}async function rz(z,Z,$=null){V(`→ processing [${C}]: ${z.slice(0,80)}`),await r("working",z.slice(0,200)).catch(()=>{});let Q,Y=!1;try{Q=await vz(z,Z,$)}catch(X){Q=`${C} 错误: ${X.message}`,Y=!0,h(`✗ ${X.message}`)}finally{await r("idle").catch(()=>{})}if(!Y&&/(API 错误|API error|需要设置.*KEY|missing.*key|issue with the selected model|may not have access|may not exist|model.+not.+(found|available))/i.test(Q))Y=!0;return{text:Q,failed:Y}}var o={},gz=5000,iz=new Set(["收到","好的","ok","嗯","是的","了解","明白","确认","done","ack","roger","yes","no","在线","待命","正常","保持在线","通信正常","已收到","收到了","好","行","noted","copy","received","understood","等待任务","等待中","等待指令","无新任务","idle","waiting"]);function Uz(z,Z=!1){if(!z)return!0;let Q=z.trim().replace(/^[\[【].+?[\]】]\s*/,"").trim().toLowerCase().replace(/[\s。!?.!?✅❌👀⏳,,]+$/g,"").trim();if(iz.has(Q))return!0;if(/^[\p{Emoji}\s]+$/u.test(z.trim())&&!/[0-9a-zA-Z#*]/.test(z))return!0;return!1}function oz(z,Z,$){if(z===H)return"self";if(Z.startsWith(`[${H}]`))return"own-prefix";if(z!=="hub"&&z!=="api"){let Q=Date.now();if(o[z]&&Q-o[z]<gz)return"cooldown"}if($!=="task"&&$!=="broadcast"&&Uz(Z))return"low-value-inbound";return null}async function az(){let z=await pz();if(!z.length)return;for(let Z of z){let $=Z.from_session||"hub",Q=Z.content,Y=Z.type||"task";if(V(`← [${$}] (${Y}/${Z.priority||"normal"}) ${Q.slice(0,100)}`),await fz(Z.id),Y!=="task"&&Y!=="broadcast"){P(`skip non-task message: type=${Y}`);continue}let X=oz($,Q,Y);if(X){P(`skip message from ${$}: ${X}`);continue}let{text:W,failed:q}=await rz(Q,$,Z.id);if(V(`processTask returned: "${W.slice(0,80)}" (${W.length} chars, failed=${q})`),!q&&Uz(W,!0)){V(`skip reply: low-value (${W.slice(0,30)})`);continue}try{V(`sending reply to ${$} (task ${Z.id.slice(0,8)}, status=${q?"failed":"replied"})...`),await dz($,`[${H}] ${W.slice(0,2000)}`,Z.id,q),o[$]=Date.now(),V(`→ [${$}] ${W.slice(0,100)}`)}catch(B){_(`reply failed: ${B.message}`)}}}function Dz(z){return String(z.from?.id||z.chat?.id||"")}function Mz(z){return z.from?.username||z.from?.first_name||Dz(z)||"telegram"}function tz(z,Z){if(z.allowFrom.length===0)return!0;let $=Dz(Z),Q=Z.from?.username?String(Z.from.username):"";return z.allowFrom.includes($)||!!Q&&z.allowFrom.includes(Q)}async function g(z,Z,$){let Q=await fetch(`${z.apiBase}/${Z}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify($)}),Y=await Q.json();if(!Y.ok)throw Error(`telegram ${Z} failed: ${Y.description||Q.statusText}`);return Y.result}async function Vz(z,Z,$,Q){let Y=$.match(/[\s\S]{1,4096}/g)||["(无回复)"];for(let X=0;X<Y.length;X++)await g(z,"sendMessage",{chat_id:Z,text:Y[X],...Q&&X===0?{reply_to_message_id:Q}:{}})}async function Jz(z,Z,$){let Q=await g(z,"getFile",{file_id:Z}),Y=String(Q.file_path||""),X=await fetch(`${z.fileBase}/${Y}`);if(!X.ok)throw Error(`telegram file download failed: ${X.status} ${X.statusText}`);let W=Y.split(".").pop(),q=($||Y.split("/").pop()||Z).replace(/[^a-zA-Z0-9._-]/g,"_"),B=q.includes(".")||!W?q:`${q}.${W}`,K=M(z.channel.inboxDir,`${Date.now()}_${B}`);return t(K,Buffer.from(await X.arrayBuffer())),K}async function sz(z,Z){let $=Z.text||Z.caption||"",Q=[];if(Array.isArray(Z.photo)&&Z.photo.length>0){let X=Z.photo[Z.photo.length-1],W=await Jz(z,X.file_id,`photo_${Z.message_id}.jpg`);Q.push(W)}let Y=String(Z.document?.mime_type||"");if(Z.document&&Y.startsWith("image/")){let X=await Jz(z,Z.document.file_id,Z.document.file_name||`image_${Z.message_id}`);Q.push(X)}if(Q.length)$+=`
38
+ ${z}`:W,B=process.env.COMMHUB_URL||d,K=process.env.COMMHUB_TOKEN||P,j={};if(B)j.commhub={type:"http",url:`${B}/mcp`,headers:K?{Authorization:`Bearer ${K}`}:void 0};let F=(()=>{try{let{execSync:J}=x("child_process"),H=x("fs");try{let U=x.resolve("@anthropic-ai/claude-agent-sdk-linux-x64/claude");if(H.existsSync(U))return J(`${U} --version`,{stdio:"pipe"}),V(`[claude] using glibc binary: ${U}`),U}catch{}try{let U=J("which claude",{encoding:"utf-8"}).trim();if(U)return V(`[claude] using global binary: ${U}`),U}catch{}V("[claude] no binary resolved, falling back to SDK default");return}catch{return}})(),b={model:L||void 0,tools:T.length?T:void 0,maxTurns:Az,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,settingSources:[],mcpServers:Object.keys(j).length?j:void 0,pathToClaudeCodeExecutable:F,env:process.env,cwd:process.cwd(),stderr:(J)=>{if(J.trim())V(`[stderr] ${J.trim().slice(0,300)}`)},hooks:{PreToolUse:[{hooks:[async(J)=>{return V(`[tool] ${J.tool_name}(${JSON.stringify(J.tool_input).slice(0,80)})`),{continue:!0}}]}]}};if($z>0)b.maxBudgetUsd=$z;if(E)b.systemPrompt=E;if(m)b.resume=m;let O="",D=Date.now();V(`[claude] claudePath=${F||"SDK default"}, mcpServers=${Object.keys(j).join(",")||"none"}`);for await(let J of Y({prompt:q,options:b})){let H=J;if(H.type==="system"&&H.subtype==="init")m=H.session_id,V(`[claude] session=${H.session_id?.slice(0,8)} model=${L||"default"}`),Fz(H.session_id);if(H.type==="result"){let U=Date.now()-D,e=H.usage||{};V(`[claude] ${H.subtype} | ${U}ms | $${H.total_cost_usd?.toFixed(4)||"?"} | in=${e.input_tokens||0} out=${e.output_tokens||0} | turns=${H.num_turns}`),O=H.subtype==="success"?H.result||"任务完成":`执行出错: ${H.error||H.result||"未知错误"}`}}return O}var N=null,nz=E||[`你是 ${w},一个 AI Agent 节点,工作目录:${process.cwd()}。`,"你通过通信网络(CommHub)接收任务并和其他 agent 协作。","","【可用通信工具】","- mcp_commhub__send_task(alias, task):派任务给指定 agent,等其 LLM 处理完返回 reply(同步语义)。","- mcp_commhub__send_message(alias, message):发聊天消息(不要求对方回复)。","- mcp_commhub__get_task(task_id):查询某任务的当前状态/reply。","- mcp_commhub__get_all_status():查看网络上所有在线 agent。","","【协作模式】","当你的任务需要其他 agent 的能力时:","1. 先 get_all_status 看哪些 agent 在线。","2. 用 send_task(alias, task, parent_task_id=<env CURRENT_TASK_ID>) 派给合适的 agent。"," ⚠ 必须把 parent_task_id 设成你当前任务的 ID(环境变量 CURRENT_TASK_ID 里),系统会自动把子任务最终结果串回给你的上游。",'3. 用 get_task 轮询子任务直到 status=replied/failed。允许中途汇报"还在等",但要继续轮询。',"4. 拿到 reply 后整合进你给上游的最终汇报。"," 即使你的 session 中途断开,只要 parent_task_id 设了,结果也会被系统自动 chain 回上游,不必焦虑。","","【禁止】",'- 不要回复"收到""好的""ok""在线""待命"等无内容确认。',"- 不要给自己发任务(会死循环)。","- 收到的若是 reply 类型,不要再 send_task 给原方(会乒乓回复)。","- 没有新任务时保持沉默,不主动发消息。","","你的最终回复会被系统自动 send_reply 给任务发起者。"].join(`
39
+ `),Xz={model_auto_compact_token_limit:200000,developer_instructions:nz};async function lz(z,Z,$){try{let{execSync:B}=await import("child_process"),K=B("which codex 2>/dev/null",{encoding:"utf-8"}).trim();if(K){let j=K.replace(/\/codex$/,"");if(!process.env.PATH?.includes(j))process.env.PATH=`${j}:${process.env.PATH}`}}catch{}let Q;try{({Codex:Q}=await import("@openai/codex-sdk"))}catch{throw Error("@openai/codex-sdk not installed. Run: npm install -g @openai/codex-sdk @openai/codex")}if(!N){let B=new Q({config:Xz}),j={skipGitRepoCheck:!0,approvalPolicy:"never",model:L||"gpt-5.4",sandboxMode:"danger-full-access",modelReasoningEffort:"low"};if(C)N=B.resumeThread(C,j),V(`codex resumed thread: ${C}`);else N=B.startThread(j)}V(`[codex] model=${L||"gpt-5.4"} thread=${N?.id||"new"}`);let X=z,W=$?.length?[{type:"text",text:X},...$.map((B)=>({type:"local_image",path:B}))]:X,q=Date.now();try{let{events:B}=await N.runStreamed(W),K="",j=null,F=0;for await(let D of B)if(D.type==="item.started"){let J=D.item;k(`[codex] ${J.type}${J.command?`: ${J.command.slice(0,60)}`:J.tool?`: ${J.server}/${J.tool}`:""}`)}else if(D.type==="item.completed"){F++;let J=D.item;if(J.type==="agent_message")K=J.text||"";if(J.type==="command_execution")k(`[codex] cmd exit=${J.exit_code} | ${J.aggregated_output?.slice(0,80)}`);if(J.type==="reasoning")k(`[codex] thinking: ${J.text?.slice(0,80)}`);if(J.type==="mcp_tool_call")k(`[codex] mcp: ${J.server}/${J.tool} → ${J.status}`)}else if(D.type==="turn.completed")j=D.usage;let b=Date.now()-q,O=j?.input_tokens||0;if(V(`[codex] done | ${b}ms | in=${O} out=${j?.output_tokens||0} | items=${F}`),N?.id)Fz(N.id);return K||"(无回复)"}catch(B){V(`codex thread error: ${B.message}, 重建`),N=new Q({config:Xz}).startThread({skipGitRepoCheck:!0,approvalPolicy:"never",model:L||"gpt-5.4",sandboxMode:"danger-full-access",modelReasoningEffort:"low"});let j=await N.run(W),F=Date.now()-q;return V(`[codex] retry done | ${F}ms`),j.finalResponse||"(无回复)"}}async function gz(z,Z){let $=process.env.ANTHROPIC_API_KEY||process.env.ANTHROPIC_AUTH_TOKEN||process.env.OPENAI_API_KEY||process.env.MINIMAX_CODING_API_KEY||G.apiKey||"",Q=process.env.ANTHROPIC_BASE_URL||G.anthropicBaseUrl||"",Y=process.env.OPENAI_BASE_URL||G.apiBaseUrl||"https://api.openai.com/v1",X=L||"gpt-4o-mini",W=!!Q,B=(Q||Y).replace(/\/v1\/?$/,"");if(!$)return"错误: 需要设置 ANTHROPIC_API_KEY, OPENAI_API_KEY, 或 MINIMAX_CODING_API_KEY";let K=E||`你是 ${w},一个 AI 助手。收到来自 ${Z} 的任务后简要执行并汇报。`,j=Date.now();V(`[http-api] model=${X} format=${W?"anthropic":"openai"} base=${B.replace(/\/v1$/,"")}`);let F="",b=null;if(W){let D=await fetch(`${B}/v1/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":$,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:X,system:K,messages:[{role:"user",content:z}],max_tokens:2000})});if(!D.ok){let U=await D.text();return`Anthropic API 错误 ${D.status}: ${U.slice(0,200)}`}let J=await D.json();F=(Array.isArray(J.content)?J.content:[]).filter((U)=>U.type==="text").map((U)=>U.text).join(`
40
+ `)||"",b=J.usage}else{let D=await fetch(`${B}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$}`},body:JSON.stringify({model:X,messages:[{role:"system",content:K},{role:"user",content:z}],max_tokens:2000})});if(!D.ok){let H=await D.text();return`OpenAI API 错误 ${D.status}: ${H.slice(0,200)}`}let J=await D.json();F=J.choices?.[0]?.message?.content||"",b=J.usage}let O=Date.now()-j;return V(`[http-api] done | ${O}ms | in=${b?.input_tokens||b?.prompt_tokens||0} out=${b?.output_tokens||b?.completion_tokens||0}`),F||"(无回复)"}var Yz=Promise.resolve();function vz(z,Z,$,Q){let Y=async()=>{let W=process.env.CURRENT_TASK_ID;if($)process.env.CURRENT_TASK_ID=$;else delete process.env.CURRENT_TASK_ID;try{if(_==="codex")return await lz(z,Z,Q);if(_==="http")return await gz(z,Z);return await mz(z,Z)}finally{if(W!==void 0)process.env.CURRENT_TASK_ID=W;else delete process.env.CURRENT_TASK_ID}},X=Yz.then(Y,Y);return Yz=X.then(()=>{},()=>{}),X}async function rz(z,Z,$=null){V(`→ processing [${_}]: ${z.slice(0,80)}`),await g("working",z.slice(0,200)).catch(()=>{});let Q,Y=!1;try{Q=await vz(z,Z,$)}catch(X){Q=`${_} 错误: ${X.message}`,Y=!0,p(`✗ ${X.message}`)}finally{await g("idle").catch(()=>{})}if(!Y&&/(API 错误|API error|需要设置.*KEY|missing.*key|issue with the selected model|may not have access|may not exist|model.+not.+(found|available))/i.test(Q))Y=!0;return{text:Q,failed:Y}}var o={},iz=5000,oz=new Set(["收到","好的","ok","嗯","是的","了解","明白","确认","done","ack","roger","yes","no","在线","待命","正常","保持在线","通信正常","已收到","收到了","好","行","noted","copy","received","understood","等待任务","等待中","等待指令","无新任务","idle","waiting"]);function Dz(z,Z=!1){if(!z)return!0;let Q=z.trim().replace(/^[\[【].+?[\]】]\s*/,"").trim().toLowerCase().replace(/[\s。!?.!?✅❌👀⏳,,]+$/g,"").trim();if(oz.has(Q))return!0;if(/^[\p{Emoji}\s]+$/u.test(z.trim())&&!/[0-9a-zA-Z#*]/.test(z))return!0;return!1}function az(z,Z,$){if(z===w)return"self";if(Z.startsWith(`[${w}]`))return"own-prefix";if(z!=="hub"&&z!=="api"){let Q=Date.now();if(o[z]&&Q-o[z]<iz)return"cooldown"}if($!=="task"&&$!=="broadcast"&&Dz(Z))return"low-value-inbound";return null}async function tz(){let z=await fz();if(!z.length)return;for(let Z of z){let $=Z.from_session||"hub",Q=Z.content,Y=Z.type||"task";if(V(`← [${$}] (${Y}/${Z.priority||"normal"}) ${Q.slice(0,100)}`),await dz(Z.id),Y!=="task"&&Y!=="broadcast"){k(`skip non-task message: type=${Y}`);continue}let X=az($,Q,Y);if(X){k(`skip message from ${$}: ${X}`);continue}let{text:W,failed:q}=await rz(Q,$,Z.id);if(V(`processTask returned: "${W.slice(0,80)}" (${W.length} chars, failed=${q})`),!q&&Dz(W,!0)){V(`skip reply: low-value (${W.slice(0,30)})`);continue}try{V(`sending reply to ${$} (task ${Z.id.slice(0,8)}, status=${q?"failed":"replied"})...`),await cz($,`[${w}] ${W.slice(0,2000)}`,Z.id,q),o[$]=Date.now(),V(`→ [${$}] ${W.slice(0,100)}`)}catch(B){A(`reply failed: ${B.message}`)}}}function Uz(z){return String(z.from?.id||z.chat?.id||"")}function Mz(z){return z.from?.username||z.from?.first_name||Uz(z)||"telegram"}function sz(z,Z){if(z.allowFrom.length===0)return!0;let $=Uz(Z),Q=Z.from?.username?String(Z.from.username):"";return z.allowFrom.includes($)||!!Q&&z.allowFrom.includes(Q)}async function r(z,Z,$){let Q=await fetch(`${z.apiBase}/${Z}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify($)}),Y=await Q.json();if(!Y.ok)throw Error(`telegram ${Z} failed: ${Y.description||Q.statusText}`);return Y.result}async function Vz(z,Z,$,Q){let Y=$.match(/[\s\S]{1,4096}/g)||["(无回复)"];for(let X=0;X<Y.length;X++)await r(z,"sendMessage",{chat_id:Z,text:Y[X],...Q&&X===0?{reply_to_message_id:Q}:{}})}async function Jz(z,Z,$){let Q=await r(z,"getFile",{file_id:Z}),Y=String(Q.file_path||""),X=await fetch(`${z.fileBase}/${Y}`);if(!X.ok)throw Error(`telegram file download failed: ${X.status} ${X.statusText}`);let W=Y.split(".").pop(),q=($||Y.split("/").pop()||Z).replace(/[^a-zA-Z0-9._-]/g,"_"),B=q.includes(".")||!W?q:`${q}.${W}`,K=M(z.channel.inboxDir,`${Date.now()}_${B}`);return t(K,Buffer.from(await X.arrayBuffer())),K}async function ez(z,Z){let $=Z.text||Z.caption||"",Q=[];if(Array.isArray(Z.photo)&&Z.photo.length>0){let X=Z.photo[Z.photo.length-1],W=await Jz(z,X.file_id,`photo_${Z.message_id}.jpg`);Q.push(W)}let Y=String(Z.document?.mime_type||"");if(Z.document&&Y.startsWith("image/")){let X=await Jz(z,Z.document.file_id,Z.document.file_name||`image_${Z.message_id}`);Q.push(X)}if(Q.length)$+=`
41
41
 
42
42
  [Telegram 附件已下载]
43
43
  ${Q.map((X)=>`- 图片: ${X}`).join(`
44
- `)}`;return{text:$.trim(),images:Q}}async function ez(z,Z){if(!tz(z.channel,Z))return;let $=Z.chat?.id,Q=Z.message_id,Y=`telegram:${Mz(Z)}`,{text:X,images:W}=await sz(z,Z);if(!$||!Q||!X)return;P(`[TG] processing: ${X.slice(0,80)}`);try{let q=await vz(X,Y,W);await Vz(z,$,q,Q),V(`→ [${Y}] ${q.slice(0,100)}`)}catch(q){h(`telegram task failed: ${q.message}`),await Vz(z,$,`处理出错: ${q.message}`,Q).catch(()=>{})}}async function zZ(z){let Z={channel:z,apiBase:`https://api.telegram.org/bot${z.token}`,fileBase:`https://api.telegram.org/file/bot${z.token}`,offset:0};try{let q=await g(Z,"getMe",{});V(`Telegram bot: @${q.username} (${q.first_name})`)}catch(q){h(`Telegram token 无效: ${q.message}`),process.exit(1)}let $=M(z.dir,"state.json");try{let q=JSON.parse(p($,"utf-8"));if(q.offset)Z.offset=q.offset,P(`Telegram offset restored: ${Z.offset}`)}catch{}let Q=()=>{try{t($,JSON.stringify({offset:Z.offset})+`
45
- `)}catch{}},Y=!1,X=[];async function W(){if(Y)return;Y=!0;while(X.length){let{msg:q,updateId:B}=X.shift();try{await ez(Z,q),Z.offset=B+1,Q()}catch(K){h(`TG handle: ${K.message}`)}}Y=!1}V(`Telegram polling: ${z.dir}`);while(!0)try{let B=await(await fetch(`${Z.apiBase}/getUpdates?offset=${Z.offset}&timeout=30`)).json();if(!B.ok)throw Error(B.description||"getUpdates failed");for(let K of B.result||[])if(Z.offset=K.update_id+1,K.message){let j=K.message,F=Mz(j),b=j.text||j.caption||"";if(V(`← TG [${F}] ${b.slice(0,80)}${j.photo?" +img":""}${j.document?" +file":""}`),j.chat?.id&&j.message_id)g(Z,"setMessageReaction",{chat_id:j.chat.id,message_id:j.message_id,reaction:[{type:"emoji",emoji:X.length>0?"⏳":"\uD83D\uDC40"}]}).catch(()=>{});X.push({msg:j,updateId:K.update_id}),W()}}catch(q){_(`Telegram polling error: ${q.message}`),await new Promise((B)=>setTimeout(B,3000))}}async function ZZ(){let z=`${d}/events/${encodeURIComponent(H)}`,Z=3000;while(!0){P(`SSE connecting: ${z}`);try{let $={Accept:"text/event-stream","Cache-Control":"no-cache"};if(L)$.Authorization=`Bearer ${L}`;let Q=await fetch(z,{headers:$});if(!Q.ok||!Q.body){if(Q.status===401)h("SSE 401: token 无效或未配置。检查 ~/.anet/config.json token 字段");else _(`SSE failed: ${Q.status}`);await new Promise((q)=>setTimeout(q,Z)),Z=Math.min(Z*1.5,60000);continue}Z=3000;let Y=Q.body.getReader(),X=new TextDecoder,W="";while(!0){let{done:q,value:B}=await Y.read();if(q)break;W+=X.decode(B,{stream:!0});let K=W.split(`
46
- `);W=K.pop()||"";for(let j of K){if(!j.startsWith("data: "))continue;try{let F=JSON.parse(j.slice(6));if(F.type==="connected"){V("SSE connected");continue}if(["new_task","broadcast"].includes(F.type))V(`← SSE ${F.type}`),await az();if(F.type==="new_reply")V(`← SSE reply from ${F.from||"?"}${F.in_reply_to?` (task ${F.in_reply_to.slice(0,8)})`:""}`)}catch{}}}}catch($){_(`SSE error: ${$.message}`)}P(`SSE reconnecting (${Z/1000}s)...`),await new Promise(($)=>setTimeout($,Z)),Z=Math.min(Z*1.5,60000)}}V("启动");V(` runtime: ${Nz}`);V(` model: ${y||(C==="codex"?"gpt-5.4":"claude-sonnet-4-6")} ${y?"":"(default)"}`);V(` hub: ${d}${L?" (auth)":" (no auth!)"}`);if(L)try{let z=await fetch(`${d}/api/auth/me`,{headers:{Authorization:`Bearer ${L}`}}).then((Z)=>Z.json()).catch(()=>null);if(z?.ok&&z.user)if(V(` user: ${z.user.username} (${z.user.role})`),z.current_network){let Z=z.networks?.find(($)=>$.network_id===z.current_network)?.network_name;V(` network: ${Z||z.current_network}`)}else V(` network: ${u||"(global)"}`);else if(z?.ok===!1)V(` network: ${u||"(global)"}`);else _(" token 验证失败 — 检查 token 是否有效。运行: anet login")}catch{V(` network: ${u||"(global)"}`)}else _(" 未配置 token — agent 数据不隔离。运行: anet login");V(` tools: ${I.length?`[${I.join(",")}]`:"(none)"}`);V(` channels:${n.length?` telegram(${n.map((z)=>z.dir).join(",")})`:" (none)"}`);V(` session: ${A||"(new)"}`);V(` log-dir: ${s}`);await hz();V("已注册到 CommHub");setInterval(()=>r("idle").catch(()=>{}),180000);var bz=async()=>{V("shutting down..."),await r("offline").catch(()=>{}),process.exit(0)};process.on("SIGINT",bz);process.on("SIGTERM",bz);for(let z of n)zZ(z);ZZ();
44
+ `)}`;return{text:$.trim(),images:Q}}async function zZ(z,Z){if(!sz(z.channel,Z))return;let $=Z.chat?.id,Q=Z.message_id,Y=`telegram:${Mz(Z)}`,{text:X,images:W}=await ez(z,Z);if(!$||!Q||!X)return;k(`[TG] processing: ${X.slice(0,80)}`);try{let q=await vz(X,Y,W);await Vz(z,$,q,Q),V(`→ [${Y}] ${q.slice(0,100)}`)}catch(q){p(`telegram task failed: ${q.message}`),await Vz(z,$,`处理出错: ${q.message}`,Q).catch(()=>{})}}async function ZZ(z){let Z={channel:z,apiBase:`https://api.telegram.org/bot${z.token}`,fileBase:`https://api.telegram.org/file/bot${z.token}`,offset:0};try{let q=await r(Z,"getMe",{});V(`Telegram bot: @${q.username} (${q.first_name})`)}catch(q){p(`Telegram token 无效: ${q.message}`),process.exit(1)}let $=M(z.dir,"state.json");try{let q=JSON.parse(f($,"utf-8"));if(q.offset)Z.offset=q.offset,k(`Telegram offset restored: ${Z.offset}`)}catch{}let Q=()=>{try{t($,JSON.stringify({offset:Z.offset})+`
45
+ `)}catch{}},Y=!1,X=[];async function W(){if(Y)return;Y=!0;while(X.length){let{msg:q,updateId:B}=X.shift();try{await zZ(Z,q),Z.offset=B+1,Q()}catch(K){p(`TG handle: ${K.message}`)}}Y=!1}V(`Telegram polling: ${z.dir}`);while(!0)try{let B=await(await fetch(`${Z.apiBase}/getUpdates?offset=${Z.offset}&timeout=30`)).json();if(!B.ok)throw Error(B.description||"getUpdates failed");for(let K of B.result||[])if(Z.offset=K.update_id+1,K.message){let j=K.message,F=Mz(j),b=j.text||j.caption||"";if(V(`← TG [${F}] ${b.slice(0,80)}${j.photo?" +img":""}${j.document?" +file":""}`),j.chat?.id&&j.message_id)r(Z,"setMessageReaction",{chat_id:j.chat.id,message_id:j.message_id,reaction:[{type:"emoji",emoji:X.length>0?"⏳":"\uD83D\uDC40"}]}).catch(()=>{});X.push({msg:j,updateId:K.update_id}),W()}}catch(q){A(`Telegram polling error: ${q.message}`),await new Promise((B)=>setTimeout(B,3000))}}async function $Z(){let z=`${d}/events/${encodeURIComponent(w)}`,Z=3000;while(!0){k(`SSE connecting: ${z}`);try{let $={Accept:"text/event-stream","Cache-Control":"no-cache"};if(P)$.Authorization=`Bearer ${P}`;let Q=await fetch(z,{headers:$});if(!Q.ok||!Q.body){if(Q.status===401){if(_z()){A(`SSE 401: ntok_ 已刷新,正在用 .anet/nodes/${w}/config.json 里的新 token 重试`),await new Promise((q)=>setTimeout(q,500));continue}p("SSE 401: ntok_ 已失效(hub DB 可能被重置或 token 被撤销)。试 `anet doctor --fix`")}else A(`SSE failed: ${Q.status}`);await new Promise((q)=>setTimeout(q,Z)),Z=Math.min(Z*1.5,60000);continue}Z=3000;let Y=Q.body.getReader(),X=new TextDecoder,W="";while(!0){let{done:q,value:B}=await Y.read();if(q)break;W+=X.decode(B,{stream:!0});let K=W.split(`
46
+ `);W=K.pop()||"";for(let j of K){if(!j.startsWith("data: "))continue;try{let F=JSON.parse(j.slice(6));if(F.type==="connected"){V("SSE connected");continue}if(["new_task","broadcast"].includes(F.type))V(`← SSE ${F.type}`),await tz();if(F.type==="new_reply")V(`← SSE reply from ${F.from||"?"}${F.in_reply_to?` (task ${F.in_reply_to.slice(0,8)})`:""}`)}catch{}}}}catch($){A(`SSE error: ${$.message}`)}k(`SSE reconnecting (${Z/1000}s)...`),await new Promise(($)=>setTimeout($,Z)),Z=Math.min(Z*1.5,60000)}}V("启动");V(` runtime: ${Nz}`);V(` model: ${L||(_==="codex"?"gpt-5.4":"claude-sonnet-4-6")} ${L?"":"(default)"}`);V(` hub: ${d}${P?" (auth)":" (no auth!)"}`);if(P)try{let z=await fetch(`${d}/api/auth/me`,{headers:{Authorization:`Bearer ${P}`}}).then((Z)=>Z.json()).catch(()=>null);if(z?.ok&&z.user)if(V(` user: ${z.user.username} (${z.user.role})`),z.current_network){let Z=z.networks?.find(($)=>$.network_id===z.current_network)?.network_name;V(` network: ${Z||z.current_network}`)}else V(` network: ${S||"(global)"}`);else if(z?.ok===!1)V(` network: ${S||"(global)"}`);else A(" token 验证失败 — 检查 token 是否有效。运行: anet login")}catch{V(` network: ${S||"(global)"}`)}else A(" 未配置 token — agent 数据不隔离。运行: anet login");V(` tools: ${T.length?`[${T.join(",")}]`:"(none)"}`);V(` channels:${n.length?` telegram(${n.map((z)=>z.dir).join(",")})`:" (none)"}`);V(` session: ${C||"(new)"}`);V(` log-dir: ${s}`);await pz();V("已注册到 CommHub");setInterval(()=>g("idle").catch(()=>{}),180000);var bz=async()=>{V("shutting down..."),await g("offline").catch(()=>{}),process.exit(0)};process.on("SIGINT",bz);process.on("SIGTERM",bz);for(let z of n)ZZ(z);$Z();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sleep2agi/agent-node",
3
- "version": "2.2.0-preview.1",
3
+ "version": "2.3.1-preview.0",
4
4
  "description": "AI Agent runtime for CommHub networks. Supports Claude Agent SDK, Codex SDK, and OpenAI/Anthropic-compatible HTTP API.",
5
5
  "bin": {
6
6
  "agent-node": "./dist/cli.js"
@@ -11,7 +11,7 @@
11
11
  "README.md"
12
12
  ],
13
13
  "scripts": {
14
- "build": "bun build src/cli.ts --outfile dist/cli.js --target node --minify --external @anthropic-ai/claude-agent-sdk --external @openai/codex-sdk",
14
+ "build": "bun build src/cli.ts --outdir dist --entry-naming cli.js --target node --minify --external @anthropic-ai/claude-agent-sdk --external @openai/codex-sdk",
15
15
  "prepublishOnly": "npm run build"
16
16
  },
17
17
  "keywords": [
@@ -28,13 +28,19 @@
28
28
  "anthropic"
29
29
  ],
30
30
  "author": "sleep2agi",
31
- "license": "MIT",
32
- "homepage": "https://anet.vansin.me",
31
+ "license": "Apache-2.0",
32
+ "homepage": "https://anet.sh",
33
33
  "repository": {
34
34
  "type": "git",
35
35
  "url": "https://github.com/sleep2agi/agent-network",
36
36
  "directory": "agent-node"
37
37
  },
38
+ "publishConfig": {
39
+ "access": "public"
40
+ },
41
+ "bugs": {
42
+ "url": "https://github.com/sleep2agi/agent-network/issues"
43
+ },
38
44
  "engines": {
39
45
  "node": ">=18.0.0"
40
46
  },