@sleep2agi/agent-node 2.1.0 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +12 -8
  2. package/dist/cli.js +18 -16
  3. package/package.json +11 -6
package/README.md CHANGED
@@ -21,8 +21,11 @@ agent-node
21
21
  ├── runtime: claude ──→ @anthropic-ai/claude-agent-sdk
22
22
  │ └── query() → spawn claude CLI → AI 处理 + 工具调用
23
23
 
24
- └── runtime: codex ───→ @openai/codex-sdk
25
- └── exec() → spawn codex CLI → AI 处理 + 工具调用
24
+ ├── runtime: codex ───→ @openai/codex-sdk
25
+ └── exec() → spawn codex CLI → AI 处理 + 工具调用
26
+
27
+ └── runtime: http-api ─→ 直接 HTTP 调用 (V2 新增)
28
+ └── OpenAI/Anthropic 兼容 API → MiniMax/DeepSeek 等
26
29
  ```
27
30
 
28
31
  ### Claude Agent SDK(`--runtime claude`,默认)
@@ -121,9 +124,9 @@ SSE 长连接 /events/:alias
121
124
  │ ↓
122
125
  │ report_status: working
123
126
  │ ↓
124
- │ AI 处理(claude query() 或 codex exec()
127
+ │ AI 处理(claude/codex/http-api
125
128
  │ ↓
126
- send_task回报结果给发送者
129
+ send_reply回报结果(V2: 关联 task_id)
127
130
  │ ↓
128
131
  │ report_status: idle
129
132
  │ ↓
@@ -213,8 +216,8 @@ npx @sleep2agi/agent-node --alias Claude马 --hub http://IP:9200 --tools all
213
216
  |------|--------|------|
214
217
  | `--alias` | 必填 | Agent 名称 |
215
218
  | `--hub` | `http://127.0.0.1:9200` | CommHub URL |
216
- | `--runtime` | `claude` | `claude` `codex` |
217
- | `--model` | claude: `claude-sonnet-4-6` / codex: `gpt-5.4` | 模型名 |
219
+ | `--runtime` | `claude` | `claude` / `codex` / `http-api` / `minimax` |
220
+ | `--model` | runtime | codex: `gpt-5.4`, http-api: `claude-3-5-haiku-20241022` |
218
221
  | `--tools` | 无 | `all` 或逗号分隔 |
219
222
  | `--max-turns` | `5` | 每任务最大轮次 |
220
223
  | `--max-budget` | 无 | 每任务预算(美元) |
@@ -229,8 +232,9 @@ npx @sleep2agi/agent-node --alias Claude马 --hub http://IP:9200 --tools all
229
232
  |---|------------|
230
233
  | `@anthropic-ai/claude-agent-sdk` | `--runtime claude` 时(动态 import) |
231
234
  | `@openai/codex-sdk` | `--runtime codex` 时(动态 import) |
235
+ | 无外部依赖 | `--runtime http-api` 时(内置 fetch) |
232
236
 
233
- 未使用的 runtime 不会加载依赖。
237
+ 未使用的 runtime 不会加载依赖。`http-api` runtime 零依赖。
234
238
 
235
239
  ---
236
240
 
@@ -241,7 +245,7 @@ npx @sleep2agi/agent-node --alias Claude马 --hub http://IP:9200 --tools all
241
245
  | **npm** | [@sleep2agi/agent-node](https://www.npmjs.com/package/@sleep2agi/agent-node) |
242
246
  | **CLI 管理工具** | [@sleep2agi/agent-network](https://www.npmjs.com/package/@sleep2agi/agent-network) |
243
247
  | **通信服务器** | [@sleep2agi/commhub-server](https://www.npmjs.com/package/@sleep2agi/commhub-server) |
244
- | **Dashboard** | [agent-network-dashboard.vercel.app](https://agent-network-dashboard.vercel.app) |
248
+ | **Dashboard** | [agent-net.vansin.me](https://agent-net.vansin.me) |
245
249
 
246
250
  ## License
247
251
 
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as Uz}from"node:module";var i=Uz(import.meta.url);import{readFileSync as L,existsSync as r,writeFileSync as n,chmodSync as vz}from"fs";import{join as b}from"path";import{hostname as a,homedir as Dz}from"os";import{mkdirSync as qz,appendFileSync as Lz}from"fs";var Qz=Dz(),U=process.argv.slice(2),j={},Yz=[],Wz="2.1.0";try{let z=new URL(".",import.meta.url).pathname;for(let Z of["../package.json","../../package.json"])try{let $=JSON.parse(L(b(z,Z),"utf-8"));if($.version){Wz=$.version;break}}catch{}}catch{}for(let z=0;z<U.length;z++){if(U[z]==="--version"||U[z]==="-v")console.log(`agent-node v${Wz}`),process.exit(0);if(U[z]==="-h"||U[z]==="--help")console.log(`
2
+ import{createRequire as bz}from"node:module";var N=bz(import.meta.url);import{readFileSync as f,existsSync as a,writeFileSync as t,chmodSync as Mz}from"fs";import{join as U}from"path";import{hostname as e,homedir as yz}from"os";import{mkdirSync as Fz,appendFileSync as Iz}from"fs";var qz=yz(),k=process.argv.slice(2),v={},Jz=[],Wz="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(U(z,Z),"utf-8"));if($.version){Wz=$.version;break}}catch{}}catch{}for(let z=0;z<k.length;z++){if(k[z]==="--version"||k[z]==="-v")console.log(`agent-node v${Wz}`),process.exit(0);if(k[z]==="-h"||k[z]==="--help")console.log(`
3
3
  @sleep2agi/agent-node — AI Agent 节点,一行命令加入 CommHub 网络
4
4
 
5
5
  用法:
@@ -8,11 +8,11 @@ import{createRequire as Uz}from"node:module";var i=Uz(import.meta.url);import{re
8
8
  选项:
9
9
  --config <path> 配置文件 (.anet/nodes/<name>/config.json)
10
10
  --alias <name> Agent 别名 / CommHub alias (必需)
11
- --runtime <type> claude-agent-sdk (default) | codex-sdk
12
- --model <name> AI 模型 (claude-agent-sdk: claude-sonnet-4-6, codex-sdk: gpt-5.4)
11
+ --runtime <type> claude-agent-sdk (default) | codex-sdk | http-api | minimax
12
+ --model <name> AI 模型 (codex: gpt-5.4, http-api: gpt-4o-mini, minimax: MiniMax-M1)
13
13
  --hub <url> CommHub URL
14
14
  --tools <list> 工具列表,逗号分隔 ("all" = 全部)
15
- --max-turns <n> 每任务最大轮次 (default: 5)
15
+ --max-turns <n> 每任务最大轮次 (default: 50)
16
16
  --max-budget <usd> 每任务预算上限
17
17
  --session <id> 恢复 session / thread ID
18
18
  --channel <spec> Channel (telegram 或 telegram:/path)
@@ -24,19 +24,21 @@ import{createRequire as Uz}from"node:module";var i=Uz(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(U[z]==="--new-session"){j["new-session"]="true";continue}if(U[z]==="--channel"&&z+1<U.length){Yz.push(U[++z]);continue}if(U[z].startsWith("--")&&z+1<U.length)j[U[z].slice(2)]=U[++z]}function Xz(z){return z.replace(/^~(?=\/|$)/,Qz)}function Mz(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:Xz(z.slice(Z+1)),raw:z}}function T(z){if(!r(z))return null;try{return JSON.parse(L(z,"utf-8"))}catch{return null}}var q={},M="";if(j.config){let z=j.config.startsWith("/")?j.config:b(process.cwd(),j.config),Z=T(z);if(Z)q=Z,M=z,console.log(`[agent-node] Config: ${z}`)}var F=j.alias||process.env.COMMHUB_ALIAS||process.env.ALIAS||q.alias;if(!j.config&&F){let z=b(process.cwd(),".anet","nodes",F,"config.json"),Z=b(process.cwd(),".anet","profiles",`${F}.json`),$=r(z)?z:Z,Q=T($);if(Q){if(q={...Q,...q},M=$,console.log(`[agent-node] Config: ${$}`),Q.env&&typeof Q.env==="object"){for(let[Y,W]of Object.entries(Q.env))if(!process.env[Y]&&typeof W==="string")process.env[Y]=Xz(W)}}}var _=T(b(Qz,".anet","config.json"))||{};if(_.hub&&!q.hub)q.hub=_.hub;if(_.token&&!q.token)q.token=_.token;if(!j.config&&!Object.keys(q).length){let z=T(b(process.cwd(),".agent-node.json"));if(z)q=z,console.log("[agent-node] 配置: .agent-node.json")}if(!F)console.error(`错误: 必须指定 --alias
28
- 用法: npx @sleep2agi/agent-node --alias "我的Agent"`),process.exit(1);var Bz=j.runtime||process.env.RUNTIME||q.runtime||"claude-agent-sdk",Pz={"claude-agent-sdk":"claude","claude-sdk":"claude","agent-sdk":"claude",claude:"claude","codex-sdk":"codex",codex:"codex"},y=Pz[Bz]||"claude",Rz=Bz,l=j.url||j.hub||process.env.COMMHUB_URL||q.hub||"http://127.0.0.1:9200",P=j.model||process.env.MODEL||q.model,kz=["Read","Write","Edit","Bash","Glob","Grep","WebSearch","WebFetch"],o=j.tools||(Array.isArray(q.tools)?q.tools.join(","):q.tools)||"",x=o==="all"?kz:o.split(",").filter(Boolean),yz=parseInt(j["max-turns"]||q.flags?.maxTurns||q.maxTurns||"5"),t=parseFloat(j["max-budget"]||q.flags?.maxBudgetUsd||q.maxBudgetUsd||"0"),xz=j["new-session"]==="true",R=xz?"":j.session||q.session||q.resume||q.sessionId||"",d=j.prompt||q.systemPrompt||"",N=process.env.COMMHUB_TOKEN||q.token||_.token||"",g=j["log-dir"]||b(process.cwd(),".anet","nodes",F,"logs"),_z={debug:0,info:1,warn:2,error:3},Nz=_z[j["log-level"]||process.env.LOG_LEVEL||q.logLevel||"info"]??1,A=[...(Array.isArray(q.channels)?q.channels:[]).filter((z)=>!z.startsWith("server:")&&!z.startsWith("plugin:")),...Yz],Kz=A.map((z)=>{try{return Mz(z)}catch(Z){console.error(`[agent-node] ${Z.message}`),process.exit(1)}});function Vz(z){if(!M||!z)return;try{let Z=JSON.parse(L(M,"utf-8"));if(Z.session===z)return;Z.session=z,n(M,JSON.stringify(Z,null,2)+`
29
- `),v(`session 写回: ${M} → ${z.slice(0,8)}...`)}catch(Z){O(`writebackSession failed: ${Z.message}`)}}function Az(z){if(!r(z))return;for(let Z of L(z,"utf-8").split(`
30
- `)){let $=Z.trim();if(!$||$.startsWith("#"))continue;let Q=$.indexOf("=");if(Q<=0)continue;let Y=$.slice(0,Q).trim(),W=$.slice(Q+1).trim().replace(/^['"]|['"]$/g,"");if(!process.env[Y])process.env[Y]=W}}function Oz(z){return b(process.cwd(),".anet","nodes",F,"channels",z)}function Cz(z){let Z=z.path||Oz("telegram");Az(b(Z,".env"));let $=process.env.TELEGRAM_BOT_TOKEN||"";if(!$)console.error(`[agent-node] telegram channel needs TELEGRAM_BOT_TOKEN in ${b(Z,".env")}`),process.exit(1);try{vz(b(Z,".env"),384)}catch{}let Q=T(b(Z,"access.json"))||{},Y=b(Z,"inbox");try{qz(Y,{recursive:!0})}catch{}return{type:"telegram",dir:Z,inboxDir:Y,token:$,allowFrom:Array.isArray(Q.allowFrom)?Q.allowFrom.map(String):[]}}var u=Kz.filter((z)=>z.type==="telegram").map(Cz),s=Kz.find((z)=>z.type!=="telegram");if(s)console.error(`[agent-node] unsupported channel: ${s.raw}`),process.exit(1);if(u.length>0&&y!=="codex"&&!x.includes("Read"))x.push("Read");try{qz(g,{recursive:!0})}catch{}function c(z,Z,$){if(Z<Nz)return;let Q=new Date().toTimeString().slice(0,8),Y=z.toUpperCase().padEnd(5),W=`[${Q}] [${Y}] [${F}] ${$}`;console.log(W);try{let K=new Date().toISOString().slice(0,10);Lz(b(g,`${K}.log`),W+`
31
- `)}catch{}}var V=(z)=>c("info",1,z),v=(z)=>c("debug",0,z),O=(z)=>c("warn",2,z),C=(z)=>c("error",3,z);async function E(z,Z,$=3){let Q={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(N)Q.Authorization=`Bearer ${N}`;let Y;for(let W=0;W<=$;W++)try{let K=await fetch(`${l}/mcp`,{method:"POST",headers:Q,body:JSON.stringify({jsonrpc:"2.0",id:Date.now(),method:"tools/call",params:{name:z,arguments:Z}})});if(!K.ok&&W<$){Y=Error(`HTTP ${K.status}`),await new Promise((H)=>setTimeout(H,1000*Math.pow(2,W)));continue}let X=await K.text(),B=X.match(/data: (.+)/),G=B?JSON.parse(B[1]):JSON.parse(X),J=G?.result?.content?.[0]?.text;return J?JSON.parse(J):G}catch(K){if(Y=K,W<$)v(`callCommHub(${z}) attempt ${W+1} failed: ${K.message}, retrying...`),await new Promise((X)=>setTimeout(X,1000*Math.pow(2,W)))}throw Y||Error(`callCommHub(${z}) failed after ${$} retries`)}var S=q.node_id||"",Jz=S?`sdk-${S}`:`sdk-${F}-${Date.now().toString(36)}`,Tz=()=>E("report_status",{resume_id:Jz,alias:F,status:"idle",server:a(),hostname:a(),agent:`agent-node:${y}`,project_dir:process.cwd(),node_id:S||void 0,session_id:R||void 0,config_path:M||void 0,channels:A.length?JSON.stringify(A):void 0}),h=(z,Z)=>E("report_status",{resume_id:Jz,alias:F,status:z,task:Z,node_id:S||void 0,session_id:I||R||void 0,config_path:M||void 0,channels:A.length?JSON.stringify(A):void 0}),Ez=async()=>(await E("get_inbox",{alias:F,limit:20}))?.messages||[],Iz=(z)=>E("ack_inbox",{alias:F,message_id:z}),uz=(z,Z,$)=>E("send_reply",{alias:z,text:Z,from_session:F,in_reply_to:$||void 0,status:"replied"}),I=R||void 0;async function Sz(z,Z){let{query:$}=await import("@anthropic-ai/claude-agent-sdk"),Q=`你是 ${F},收到来自 ${Z} 的任务:
27
+ `),process.exit(0);if(k[z]==="--new-session"){v["new-session"]="true";continue}if(k[z]==="--channel"&&z+1<k.length){Jz.push(k[++z]);continue}if(k[z].startsWith("--")&&z+1<k.length)v[k[z].slice(2)]=k[++z]}function Bz(z){return z.replace(/^~(?=\/|$)/,qz)}function Rz(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:Bz(z.slice(Z+1)),raw:z}}function p(z){if(!a(z))return null;try{return JSON.parse(f(z,"utf-8"))}catch{return null}}var B={},x="";if(v.config){let z=v.config.startsWith("/")?v.config:U(process.cwd(),v.config),Z=p(z);if(Z)B=Z,x=z,console.log(`[agent-node] Config: ${z}`)}var H=v.alias||process.env.COMMHUB_ALIAS||process.env.ALIAS||B.alias;if(!v.config&&H){let z=U(process.cwd(),".anet","nodes",H,"config.json"),Z=U(process.cwd(),".anet","profiles",`${H}.json`),$=a(z)?z:Z,Q=p($);if(Q){if(B={...Q,...B},x=$,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]=Bz(X)}}}var O=p(U(qz,".anet","config.json"))||{};if(O.hub&&!B.hub)B.hub=O.hub;if(O.token&&!B.token)B.token=O.token;if(!v.config&&!Object.keys(B).length){let z=p(U(process.cwd(),".agent-node.json"));if(z)B=z,console.log("[agent-node] 配置: .agent-node.json")}if(!H)console.error(`错误: 必须指定 --alias
28
+ 用法: npx @sleep2agi/agent-node --alias "我的Agent"`),process.exit(1);var Gz=v.runtime||process.env.RUNTIME||B.runtime||"claude-agent-sdk",xz={"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"},L=xz[Gz]||"claude",Pz=Gz,d=v.url||v.hub||process.env.COMMHUB_URL||B.hub||"http://127.0.0.1:9200",R=v.model||process.env.MODEL||B.model,Nz=["Read","Write","Edit","Bash","Glob","Grep","WebSearch","WebFetch"],zz=v.tools||(Array.isArray(B.tools)?B.tools.join(","):B.tools)||"",E=zz==="all"?Nz:zz.split(",").filter(Boolean),_z=parseInt(v["max-turns"]||B.flags?.maxTurns||B.maxTurns||"50"),Zz=parseFloat(v["max-budget"]||B.flags?.maxBudgetUsd||B.maxBudgetUsd||"0"),Lz=v["new-session"]==="true",_=Lz?"":v.session||B.session||B.resume||B.sessionId||"",C=v.prompt||B.systemPrompt||"",P=B.token||O.token||process.env.COMMHUB_TOKEN||"";if(process.env.COMMHUB_TOKEN&&B.token&&process.env.COMMHUB_TOKEN!==B.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"]||U(process.cwd(),".anet","nodes",H,"logs"),Az={debug:0,info:1,warn:2,error:3},Cz=Az[v["log-level"]||process.env.LOG_LEVEL||B.logLevel||"info"]??1,S=[...(Array.isArray(B.channels)?B.channels:[]).filter((z)=>!z.startsWith("server:")&&!z.startsWith("plugin:")),...Jz],jz=S.map((z)=>{try{return Rz(z)}catch(Z){console.error(`[agent-node] ${Z.message}`),process.exit(1)}});function Kz(z){if(!x||!z)return;try{let Z=JSON.parse(f(x,"utf-8"));if(Z.session===z)return;Z.session=z,t(x,JSON.stringify(Z,null,2)+`
29
+ `),M(`session 写回: ${x} → ${z.slice(0,8)}...`)}catch(Z){A(`writebackSession failed: ${Z.message}`)}}function Oz(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 Ez(z){return U(process.cwd(),".anet","nodes",H,"channels",z)}function Tz(z){let Z=z.path||Ez("telegram");Oz(U(Z,".env"));let $=process.env.TELEGRAM_BOT_TOKEN||"";if(!$)console.error(`[agent-node] telegram channel needs TELEGRAM_BOT_TOKEN in ${U(Z,".env")}`),process.exit(1);try{Mz(U(Z,".env"),384)}catch{}let Q=p(U(Z,"access.json"))||{},Y=U(Z,"inbox");try{Fz(Y,{recursive:!0})}catch{}return{type:"telegram",dir:Z,inboxDir:Y,token:$,allowFrom:Array.isArray(Q.allowFrom)?Q.allowFrom.map(String):[]}}var n=jz.filter((z)=>z.type==="telegram").map(Tz),$z=jz.find((z)=>z.type!=="telegram");if($z)console.error(`[agent-node] unsupported channel: ${$z.raw}`),process.exit(1);if(n.length>0&&L!=="codex"&&!E.includes("Read"))E.push("Read");try{Fz(s,{recursive:!0})}catch{}function i(z,Z,$){if(Z<Cz)return;let Q=new Date().toTimeString().slice(0,8),Y=z.toUpperCase().padEnd(5),X=`[${Q}] [${Y}] [${H}] ${$}`;console.log(X);try{let J=new Date().toISOString().slice(0,10);Iz(U(s,`${J}.log`),X+`
31
+ `)}catch{}}var q=(z)=>i("info",1,z),M=(z)=>i("debug",0,z),A=(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(P)Q.Authorization=`Bearer ${P}`;let Y;for(let X=0;X<=$;X++)try{let J=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(!J.ok&&X<$){Y=Error(`HTTP ${J.status}`),await new Promise((w)=>setTimeout(w,1000*Math.pow(2,X)));continue}let V=await J.text(),K=V.match(/data: (.+)/),F=K?JSON.parse(K[1]):JSON.parse(V),G=F?.result?.content?.[0]?.text;return G?JSON.parse(G):F}catch(J){if(Y=J,X<$)M(`callCommHub(${z}) attempt ${X+1} failed: ${J.message}, retrying...`),await new Promise((V)=>setTimeout(V,1000*Math.pow(2,X)))}throw Y||Error(`callCommHub(${z}) failed after ${$} retries`)}var r=B.node_id||"",uz=B.node_name||"",u=B.network_id||process.env.ANET_NETWORK_ID||O.network_id||"",wz=r?`sdk-${r}`:`sdk-${H}-${Date.now().toString(36)}`,Sz=()=>c("report_status",{resume_id:wz,alias:H,status:"idle",server:e(),hostname:e(),agent:`agent-node:${L}`,project_dir:process.cwd(),node_id:r||void 0,node_name:uz||void 0,session_id:_||void 0,config_path:x||void 0,channels:S.length?JSON.stringify(S):void 0,model:R||void 0,network_id:u||void 0}),l=(z,Z)=>c("report_status",{resume_id:wz,alias:H,status:z,task:Z,node_id:r||void 0,session_id:m||_||void 0,config_path:x||void 0,channels:S.length?JSON.stringify(S):void 0,network_id:u||void 0}),hz=async()=>(await c("get_inbox",{alias:H,limit:20}))?.messages||[],fz=(z)=>c("ack_inbox",{alias:H,message_id:z}),pz=(z,Z,$,Q=!1)=>c("send_reply",{alias:z,text:Z,from_session:H,in_reply_to:$||void 0,status:Q?"failed":"replied"}),m=_||void 0;async function dz(z,Z){let{query:$}=await import("@anthropic-ai/claude-agent-sdk"),Q=[`你是 ${H},一个 AI Agent 节点。收到来自 ${Z} 的任务:`,"",z,"","【若任务需要其他 agent 协助】","1. 先用 mcp_commhub__get_all_status 看哪些 agent 在线。","2. 用 mcp_commhub__send_task(alias, task) 派给合适的 agent,记下 task_id。","3. 用 mcp_commhub__get_task(task_id) 轮询直到 status 是 replied 或 failed,拿到 reply 内容。",`4. 把对方的 reply 整合到你给 ${Z} 的最终汇报里。`,"","【禁止】",`- 不要给自己(${H})发任务(死循环)。`,'- 不要回复"收到""ok""明白了"等无内容确认。',"- 不要在无新任务时主动调用通信工具。","","执行完后简要汇报结果。"].join(`
32
+ `),Y=C?`${C}
32
33
 
33
- ${z}
34
+ 收到来自 ${Z} 的任务:
34
35
 
35
- 执行完后简要汇报结果。`,Y={model:P||void 0,tools:x.length?x:void 0,maxTurns:yz,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,settingSources:[],env:process.env,cwd:process.cwd(),stderr:(X)=>{if(X.trim())v(`[stderr] ${X.trim().slice(0,200)}`)},hooks:{PreToolUse:[{hooks:[async(X)=>{return V(`[tool] ${X.tool_name}(${JSON.stringify(X.tool_input).slice(0,80)})`),{continue:!0}}]}]}};if(t>0)Y.maxBudgetUsd=t;if(d)Y.systemPrompt=d;if(I)Y.resume=I;let W="",K=Date.now();for await(let X of $({prompt:Q,options:Y})){let B=X;if(B.type==="system"&&B.subtype==="init")I=B.session_id,V(`[claude] session=${B.session_id?.slice(0,8)} model=${P||"default"}`),Vz(B.session_id);if(B.type==="result"){let G=Date.now()-K,J=B.usage||{};V(`[claude] ${B.subtype} | ${G}ms | $${B.total_cost_usd?.toFixed(4)||"?"} | in=${J.input_tokens||0} out=${J.output_tokens||0} | turns=${B.num_turns}`),W=B.subtype==="success"?B.result||"任务完成":`执行出错: ${B.error||B.result||"未知错误"}`}}return W}var D=null,hz=d||[`你是 ${F},一个 AI Agent 节点,工作目录:${process.cwd()}。`,"你通过通信网络接收任务。收到任务后执行并返回结果。","规则:","1. 只回复有实质内容的结果。",'2. 绝对不要回复"收到""好的""ok""在线""待命""等待任务"等确认消息。',"3. 没有新任务时保持完全沉默,不要主动发任何消息。","4. 不要调用任何通信工具(send_task/send_message 等)。","5. 你的回复会被系统自动发送给任务发送者。"].join(`
36
- `),e={model_auto_compact_token_limit:200000,developer_instructions:hz};async function fz(z,Z,$){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(!D){let B=new Q({config:e}),J={skipGitRepoCheck:!0,approvalPolicy:"never",model:P||"gpt-5.4",sandboxMode:"danger-full-access",modelReasoningEffort:"low"};if(R)D=B.resumeThread(R,J),V(`codex resumed thread: ${R}`);else D=B.startThread(J)}V(`[codex] model=${P||"gpt-5.4"} thread=${D?.id||"new"}`);let W=z,K=$?.length?[{type:"text",text:W},...$.map((B)=>({type:"local_image",path:B}))]:W,X=Date.now();try{let{events:B}=await D.runStreamed(K),G="",J=null,H=0;for await(let k of B)if(k.type==="item.started"){let w=k.item;v(`[codex] ${w.type}${w.command?`: ${w.command.slice(0,60)}`:w.tool?`: ${w.server}/${w.tool}`:""}`)}else if(k.type==="item.completed"){H++;let w=k.item;if(w.type==="agent_message")G=w.text||"";if(w.type==="command_execution")v(`[codex] cmd exit=${w.exit_code} | ${w.aggregated_output?.slice(0,80)}`);if(w.type==="reasoning")v(`[codex] thinking: ${w.text?.slice(0,80)}`);if(w.type==="mcp_tool_call")v(`[codex] mcp: ${w.server}/${w.tool} → ${w.status}`)}else if(k.type==="turn.completed")J=k.usage;let p=Date.now()-X,bz=J?.input_tokens||0;if(V(`[codex] done | ${p}ms | in=${bz} out=${J?.output_tokens||0} | items=${H}`),D?.id)Vz(D.id);return G||"(无回复)"}catch(B){V(`codex thread error: ${B.message}, 重建`),D=new Q({config:e}).startThread({skipGitRepoCheck:!0,approvalPolicy:"never",model:P||"gpt-5.4",sandboxMode:"danger-full-access",modelReasoningEffort:"low"});let J=await D.run(K),H=Date.now()-X;return V(`[codex] retry done | ${H}ms`),J.finalResponse||"(无回复)"}}var zz=Promise.resolve();function Gz(z,Z,$){let Q=async()=>{if(y==="codex")return fz(z,Z,$);return Sz(z,Z)},Y=zz.then(Q,Q);return zz=Y.then(()=>{},()=>{}),Y}async function cz(z,Z){V(`→ processing [${y}]: ${z.slice(0,80)}`),await h("working",z.slice(0,200));let $;try{$=await Gz(z,Z)}catch(Q){$=`${y} 错误: ${Q.message}`,C(`✗ ${Q.message}`)}return await h("idle"),$}var m={},pz=5000,dz=new Set(["收到","好的","ok","嗯","是的","了解","明白","确认","done","ack","roger","yes","no","在线","待命","正常","保持在线","通信正常","已收到","收到了","好","行","noted","copy","received","understood","等待任务","等待中","等待指令","无新任务","idle","waiting"]);function jz(z,Z=!1){if(!z)return!0;if(!Z){if(z.replace(/[\s\p{P}\p{S}\p{Emoji}]/gu,"").length<3)return!0}let Q=z.trim().replace(/^[\[【].+?[\]】]\s*/,"").trim().toLowerCase().replace(/[\s。!?.!?✅❌👀⏳,,]+$/g,"").trim();if(dz.has(Q))return!0;if(/^[\p{Emoji}\s]+$/u.test(z.trim())&&!/[0-9a-zA-Z#*]/.test(z))return!0;return!1}function mz(z,Z){if(z===F)return"self";if(Z.startsWith(`[${F}]`))return"own-prefix";let $=Date.now();if(m[z]&&$-m[z]<pz)return"cooldown";if(jz(Z))return"low-value-inbound";return null}async function rz(){let z=await Ez();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 Iz(Z.id),Y!=="task"&&Y!=="broadcast"){v(`skip non-task message: type=${Y}`);continue}let W=mz($,Q);if(W){v(`skip message from ${$}: ${W}`);continue}let K=await cz(Q,$);if(V(`processTask returned: "${K.slice(0,80)}" (${K.length} chars)`),jz(K,!0)){V(`skip reply: low-value (${K.slice(0,30)})`);continue}try{V(`sending reply to ${$} (task ${Z.id.slice(0,8)})...`),await uz($,`[${F}] ${K.slice(0,2000)}`,Z.id),m[$]=Date.now(),V(`→ [${$}] ${K.slice(0,100)}`)}catch(X){O(`reply failed: ${X.message}`)}}}function Fz(z){return String(z.from?.id||z.chat?.id||"")}function wz(z){return z.from?.username||z.from?.first_name||Fz(z)||"telegram"}function nz(z,Z){if(z.allowFrom.length===0)return!0;let $=Fz(Z),Q=Z.from?.username?String(Z.from.username):"";return z.allowFrom.includes($)||!!Q&&z.allowFrom.includes(Q)}async function f(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 Zz(z,Z,$,Q){let Y=$.match(/[\s\S]{1,4096}/g)||["(无回复)"];for(let W=0;W<Y.length;W++)await f(z,"sendMessage",{chat_id:Z,text:Y[W],...Q&&W===0?{reply_to_message_id:Q}:{}})}async function $z(z,Z,$){let Q=await f(z,"getFile",{file_id:Z}),Y=String(Q.file_path||""),W=await fetch(`${z.fileBase}/${Y}`);if(!W.ok)throw Error(`telegram file download failed: ${W.status} ${W.statusText}`);let K=Y.split(".").pop(),X=($||Y.split("/").pop()||Z).replace(/[^a-zA-Z0-9._-]/g,"_"),B=X.includes(".")||!K?X:`${X}.${K}`,G=b(z.channel.inboxDir,`${Date.now()}_${B}`);return n(G,Buffer.from(await W.arrayBuffer())),G}async function lz(z,Z){let $=Z.text||Z.caption||"",Q=[];if(Array.isArray(Z.photo)&&Z.photo.length>0){let W=Z.photo[Z.photo.length-1],K=await $z(z,W.file_id,`photo_${Z.message_id}.jpg`);Q.push(K)}let Y=String(Z.document?.mime_type||"");if(Z.document&&Y.startsWith("image/")){let W=await $z(z,Z.document.file_id,Z.document.file_name||`image_${Z.message_id}`);Q.push(W)}if(Q.length)$+=`
36
+ ${z}`:Q,X=process.env.COMMHUB_URL||d,J=process.env.COMMHUB_TOKEN||P,V={};if(X)V.commhub={type:"http",url:`${X}/mcp`,headers:J?{Authorization:`Bearer ${J}`}:void 0};let F=Object.keys(V).length>0?void 0:(()=>{try{let{execSync:D}=N("child_process"),j=N("fs");try{let W=N.resolve("@anthropic-ai/claude-agent-sdk-linux-x64/claude");if(j.existsSync(W))return D(`${W} --version`,{stdio:"pipe"}),q(`[claude] using glibc binary: ${W}`),W}catch{}try{let W=D("which claude",{encoding:"utf-8"}).trim();if(W)return q(`[claude] using global binary: ${W}`),W}catch{}return}catch{return}})(),G={model:R||void 0,tools:E.length?E:void 0,maxTurns:_z,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,settingSources:[],mcpServers:Object.keys(V).length?V:void 0,pathToClaudeCodeExecutable:F,env:process.env,cwd:process.cwd(),stderr:(D)=>{if(D.trim())q(`[stderr] ${D.trim().slice(0,300)}`)},hooks:{PreToolUse:[{hooks:[async(D)=>{return q(`[tool] ${D.tool_name}(${JSON.stringify(D.tool_input).slice(0,80)})`),{continue:!0}}]}]}};if(Zz>0)G.maxBudgetUsd=Zz;if(C)G.systemPrompt=C;if(m)G.resume=m;let w="",b=Date.now();q(`[claude] claudePath=${F||"SDK default"}, mcpServers=${Object.keys(V).join(",")||"none"}`);for await(let D of $({prompt:Y,options:G})){let j=D;if(j.type==="system"&&j.subtype==="init")m=j.session_id,q(`[claude] session=${j.session_id?.slice(0,8)} model=${R||"default"}`),Kz(j.session_id);if(j.type==="result"){let W=Date.now()-b,T=j.usage||{};q(`[claude] ${j.subtype} | ${W}ms | $${j.total_cost_usd?.toFixed(4)||"?"} | in=${T.input_tokens||0} out=${T.output_tokens||0} | turns=${j.num_turns}`),w=j.subtype==="success"?j.result||"任务完成":`执行出错: ${j.error||j.result||"未知错误"}`}}return w}var y=null,cz=C||[`你是 ${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 派给合适的 agent。","3. **必须** 用 get_task 轮询那个 task_id 直到 status=replied,拿到对方的 reply 内容。","4. 把 reply 整合进你给原始任务发起者的最终汇报。","","【禁止】",'- 不要回复"收到""好的""ok""在线""待命"等无内容确认。',"- 不要给自己发任务(会死循环)。","- 收到的若是 reply 类型,不要再 send_task 给原方(会乒乓回复)。","- 没有新任务时保持沉默,不主动发消息。","","你的最终回复会被系统自动 send_reply 给任务发起者。"].join(`
37
+ `),Qz={model_auto_compact_token_limit:200000,developer_instructions:cz};async function mz(z,Z,$){try{let{execSync:K}=await import("child_process"),F=K("which codex 2>/dev/null",{encoding:"utf-8"}).trim();if(F){let G=F.replace(/\/codex$/,"");if(!process.env.PATH?.includes(G))process.env.PATH=`${G}:${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(!y){let K=new Q({config:Qz}),G={skipGitRepoCheck:!0,approvalPolicy:"never",model:R||"gpt-5.4",sandboxMode:"danger-full-access",modelReasoningEffort:"low"};if(_)y=K.resumeThread(_,G),q(`codex resumed thread: ${_}`);else y=K.startThread(G)}q(`[codex] model=${R||"gpt-5.4"} thread=${y?.id||"new"}`);let X=z,J=$?.length?[{type:"text",text:X},...$.map((K)=>({type:"local_image",path:K}))]:X,V=Date.now();try{let{events:K}=await y.runStreamed(J),F="",G=null,w=0;for await(let j of K)if(j.type==="item.started"){let W=j.item;M(`[codex] ${W.type}${W.command?`: ${W.command.slice(0,60)}`:W.tool?`: ${W.server}/${W.tool}`:""}`)}else if(j.type==="item.completed"){w++;let W=j.item;if(W.type==="agent_message")F=W.text||"";if(W.type==="command_execution")M(`[codex] cmd exit=${W.exit_code} | ${W.aggregated_output?.slice(0,80)}`);if(W.type==="reasoning")M(`[codex] thinking: ${W.text?.slice(0,80)}`);if(W.type==="mcp_tool_call")M(`[codex] mcp: ${W.server}/${W.tool} → ${W.status}`)}else if(j.type==="turn.completed")G=j.usage;let b=Date.now()-V,D=G?.input_tokens||0;if(q(`[codex] done | ${b}ms | in=${D} out=${G?.output_tokens||0} | items=${w}`),y?.id)Kz(y.id);return F||"(无回复)"}catch(K){q(`codex thread error: ${K.message}, 重建`),y=new Q({config:Qz}).startThread({skipGitRepoCheck:!0,approvalPolicy:"never",model:R||"gpt-5.4",sandboxMode:"danger-full-access",modelReasoningEffort:"low"});let G=await y.run(J),w=Date.now()-V;return q(`[codex] retry done | ${w}ms`),G.finalResponse||"(无回复)"}}async function nz(z,Z){let $=process.env.ANTHROPIC_API_KEY||process.env.OPENAI_API_KEY||process.env.MINIMAX_CODING_API_KEY||B.apiKey||"",Q=process.env.ANTHROPIC_BASE_URL||B.anthropicBaseUrl||"",Y=process.env.OPENAI_BASE_URL||B.apiBaseUrl||"https://api.openai.com/v1",X=R||"gpt-4o-mini",J=!!Q,K=(Q||Y).replace(/\/v1\/?$/,"");if(!$)return"错误: 需要设置 ANTHROPIC_API_KEY, OPENAI_API_KEY, 或 MINIMAX_CODING_API_KEY";let F=C||`你是 ${H},一个 AI 助手。收到来自 ${Z} 的任务后简要执行并汇报。`,G=Date.now();q(`[http-api] model=${X} format=${J?"anthropic":"openai"} base=${K.replace(/\/v1$/,"")}`);let w="",b=null;if(J){let j=await fetch(`${K}/v1/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":$,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:X,system:F,messages:[{role:"user",content:z}],max_tokens:2000})});if(!j.ok){let I=await j.text();return`Anthropic API 错误 ${j.status}: ${I.slice(0,200)}`}let W=await j.json();w=(Array.isArray(W.content)?W.content:[]).filter((I)=>I.type==="text").map((I)=>I.text).join(`
38
+ `)||"",b=W.usage}else{let j=await fetch(`${K}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$}`},body:JSON.stringify({model:X,messages:[{role:"system",content:F},{role:"user",content:z}],max_tokens:2000})});if(!j.ok){let T=await j.text();return`OpenAI API 错误 ${j.status}: ${T.slice(0,200)}`}let W=await j.json();w=W.choices?.[0]?.message?.content||"",b=W.usage}let D=Date.now()-G;return q(`[http-api] done | ${D}ms | in=${b?.input_tokens||b?.prompt_tokens||0} out=${b?.output_tokens||b?.completion_tokens||0}`),w||"(无回复)"}var Xz=Promise.resolve();function Hz(z,Z,$){let Q=async()=>{if(L==="codex")return mz(z,Z,$);if(L==="http")return nz(z,Z);return dz(z,Z)},Y=Xz.then(Q,Q);return Xz=Y.then(()=>{},()=>{}),Y}async function rz(z,Z){q(`→ processing [${L}]: ${z.slice(0,80)}`),await l("working",z.slice(0,200)).catch(()=>{});let $,Q=!1;try{$=await Hz(z,Z)}catch(Y){$=`${L} 错误: ${Y.message}`,Q=!0,h(`✗ ${Y.message}`)}finally{await l("idle").catch(()=>{})}if(!Q&&/(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=!0;return{text:$,failed:Q}}var o={},lz=5000,gz=new Set(["收到","好的","ok","嗯","是的","了解","明白","确认","done","ack","roger","yes","no","在线","待命","正常","保持在线","通信正常","已收到","收到了","好","行","noted","copy","received","understood","等待任务","等待中","等待指令","无新任务","idle","waiting"]);function vz(z,Z=!1){if(!z)return!0;let Q=z.trim().replace(/^[\[【].+?[\]】]\s*/,"").trim().toLowerCase().replace(/[\s。!?.!?✅❌👀⏳,,]+$/g,"").trim();if(gz.has(Q))return!0;if(/^[\p{Emoji}\s]+$/u.test(z.trim())&&!/[0-9a-zA-Z#*]/.test(z))return!0;return!1}function iz(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]<lz)return"cooldown"}if($!=="task"&&$!=="broadcast"&&vz(Z))return"low-value-inbound";return null}async function oz(){let z=await hz();if(!z.length)return;for(let Z of z){let $=Z.from_session||"hub",Q=Z.content,Y=Z.type||"task";if(q(`← [${$}] (${Y}/${Z.priority||"normal"}) ${Q.slice(0,100)}`),await fz(Z.id),Y!=="task"&&Y!=="broadcast"){M(`skip non-task message: type=${Y}`);continue}let X=iz($,Q,Y);if(X){M(`skip message from ${$}: ${X}`);continue}let{text:J,failed:V}=await rz(Q,$);if(q(`processTask returned: "${J.slice(0,80)}" (${J.length} chars, failed=${V})`),!V&&vz(J,!0)){q(`skip reply: low-value (${J.slice(0,30)})`);continue}try{q(`sending reply to ${$} (task ${Z.id.slice(0,8)}, status=${V?"failed":"replied"})...`),await pz($,`[${H}] ${J.slice(0,2000)}`,Z.id,V),o[$]=Date.now(),q(`→ [${$}] ${J.slice(0,100)}`)}catch(K){A(`reply failed: ${K.message}`)}}}function Uz(z){return String(z.from?.id||z.chat?.id||"")}function Dz(z){return z.from?.username||z.from?.first_name||Uz(z)||"telegram"}function az(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 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 Yz(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 Vz(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 J=Y.split(".").pop(),V=($||Y.split("/").pop()||Z).replace(/[^a-zA-Z0-9._-]/g,"_"),K=V.includes(".")||!J?V:`${V}.${J}`,F=U(z.channel.inboxDir,`${Date.now()}_${K}`);return t(F,Buffer.from(await X.arrayBuffer())),F}async function tz(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],J=await Vz(z,X.file_id,`photo_${Z.message_id}.jpg`);Q.push(J)}let Y=String(Z.document?.mime_type||"");if(Z.document&&Y.startsWith("image/")){let X=await Vz(z,Z.document.file_id,Z.document.file_name||`image_${Z.message_id}`);Q.push(X)}if(Q.length)$+=`
37
39
 
38
40
  [Telegram 附件已下载]
39
- ${Q.map((W)=>`- 图片: ${W}`).join(`
40
- `)}`;return{text:$.trim(),images:Q}}async function gz(z,Z){if(!nz(z.channel,Z))return;let $=Z.chat?.id,Q=Z.message_id,Y=`telegram:${wz(Z)}`,{text:W,images:K}=await lz(z,Z);if(!$||!Q||!W)return;v(`[TG] processing: ${W.slice(0,80)}`);try{let X=await Gz(W,Y,K);await Zz(z,$,X,Q),V(`→ [${Y}] ${X.slice(0,100)}`)}catch(X){C(`telegram task failed: ${X.message}`),await Zz(z,$,`处理出错: ${X.message}`,Q).catch(()=>{})}}async function iz(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 X=await f(Z,"getMe",{});V(`Telegram bot: @${X.username} (${X.first_name})`)}catch(X){C(`Telegram token 无效: ${X.message}`),process.exit(1)}let $=b(z.dir,"state.json");try{let X=JSON.parse(L($,"utf-8"));if(X.offset)Z.offset=X.offset,v(`Telegram offset restored: ${Z.offset}`)}catch{}let Q=()=>{try{n($,JSON.stringify({offset:Z.offset})+`
41
- `)}catch{}},Y=!1,W=[];async function K(){if(Y)return;Y=!0;while(W.length){let{msg:X,updateId:B}=W.shift();try{await gz(Z,X),Z.offset=B+1,Q()}catch(G){C(`TG handle: ${G.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 G of B.result||[])if(Z.offset=G.update_id+1,G.message){let J=G.message,H=wz(J),p=J.text||J.caption||"";if(V(`← TG [${H}] ${p.slice(0,80)}${J.photo?" +img":""}${J.document?" +file":""}`),J.chat?.id&&J.message_id)f(Z,"setMessageReaction",{chat_id:J.chat.id,message_id:J.message_id,reaction:[{type:"emoji",emoji:W.length>0?"⏳":"\uD83D\uDC40"}]}).catch(()=>{});W.push({msg:J,updateId:G.update_id}),K()}}catch(X){O(`Telegram polling error: ${X.message}`),await new Promise((B)=>setTimeout(B,3000))}}async function az(){let z=`${l}/events/${encodeURIComponent(F)}`,Z=3000;while(!0){v(`SSE connecting: ${z}`);try{let $={Accept:"text/event-stream","Cache-Control":"no-cache"};if(N)$.Authorization=`Bearer ${N}`;let Q=await fetch(z,{headers:$});if(!Q.ok||!Q.body){if(Q.status===401)C("SSE 401: token 无效或未配置。检查 ~/.anet/config.json 的 token 字段");else O(`SSE failed: ${Q.status}`);await new Promise((X)=>setTimeout(X,Z)),Z=Math.min(Z*1.5,60000);continue}Z=3000;let Y=Q.body.getReader(),W=new TextDecoder,K="";while(!0){let{done:X,value:B}=await Y.read();if(X)break;K+=W.decode(B,{stream:!0});let G=K.split(`
42
- `);K=G.pop()||"";for(let J of G){if(!J.startsWith("data: "))continue;try{let H=JSON.parse(J.slice(6));if(H.type==="connected"){V("SSE connected");continue}if(["new_task","broadcast"].includes(H.type))V(`← SSE ${H.type}`),await rz();if(H.type==="new_reply")V(`← SSE reply from ${H.from||"?"}${H.in_reply_to?` (task ${H.in_reply_to.slice(0,8)})`:""}`)}catch{}}}}catch($){O(`SSE error: ${$.message}`)}v(`SSE reconnecting (${Z/1000}s)...`),await new Promise(($)=>setTimeout($,Z)),Z=Math.min(Z*1.5,60000)}}V("启动");V(` runtime: ${Rz}`);V(` model: ${P||(y==="codex"?"gpt-5.4":"claude-sonnet-4-6")} ${P?"":"(default)"}`);V(` hub: ${l}${N?" (auth)":" (no auth!)"}`);V(` tools: ${x.length?`[${x.join(",")}]`:"(none)"}`);V(` channels:${u.length?` telegram(${u.map((z)=>z.dir).join(",")})`:" (none)"}`);V(` session: ${R||"(new)"}`);V(` log-dir: ${g}`);await Tz();V("已注册到 CommHub");setInterval(()=>h("idle").catch(()=>{}),180000);var Hz=async()=>{V("shutting down..."),await h("offline").catch(()=>{}),process.exit(0)};process.on("SIGINT",Hz);process.on("SIGTERM",Hz);for(let z of u)iz(z);az();
41
+ ${Q.map((X)=>`- 图片: ${X}`).join(`
42
+ `)}`;return{text:$.trim(),images:Q}}async function sz(z,Z){if(!az(z.channel,Z))return;let $=Z.chat?.id,Q=Z.message_id,Y=`telegram:${Dz(Z)}`,{text:X,images:J}=await tz(z,Z);if(!$||!Q||!X)return;M(`[TG] processing: ${X.slice(0,80)}`);try{let V=await Hz(X,Y,J);await Yz(z,$,V,Q),q(`→ [${Y}] ${V.slice(0,100)}`)}catch(V){h(`telegram task failed: ${V.message}`),await Yz(z,$,`处理出错: ${V.message}`,Q).catch(()=>{})}}async function ez(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 V=await g(Z,"getMe",{});q(`Telegram bot: @${V.username} (${V.first_name})`)}catch(V){h(`Telegram token 无效: ${V.message}`),process.exit(1)}let $=U(z.dir,"state.json");try{let V=JSON.parse(f($,"utf-8"));if(V.offset)Z.offset=V.offset,M(`Telegram offset restored: ${Z.offset}`)}catch{}let Q=()=>{try{t($,JSON.stringify({offset:Z.offset})+`
43
+ `)}catch{}},Y=!1,X=[];async function J(){if(Y)return;Y=!0;while(X.length){let{msg:V,updateId:K}=X.shift();try{await sz(Z,V),Z.offset=K+1,Q()}catch(F){h(`TG handle: ${F.message}`)}}Y=!1}q(`Telegram polling: ${z.dir}`);while(!0)try{let K=await(await fetch(`${Z.apiBase}/getUpdates?offset=${Z.offset}&timeout=30`)).json();if(!K.ok)throw Error(K.description||"getUpdates failed");for(let F of K.result||[])if(Z.offset=F.update_id+1,F.message){let G=F.message,w=Dz(G),b=G.text||G.caption||"";if(q(`← TG [${w}] ${b.slice(0,80)}${G.photo?" +img":""}${G.document?" +file":""}`),G.chat?.id&&G.message_id)g(Z,"setMessageReaction",{chat_id:G.chat.id,message_id:G.message_id,reaction:[{type:"emoji",emoji:X.length>0?"⏳":"\uD83D\uDC40"}]}).catch(()=>{});X.push({msg:G,updateId:F.update_id}),J()}}catch(V){A(`Telegram polling error: ${V.message}`),await new Promise((K)=>setTimeout(K,3000))}}async function zZ(){let z=`${d}/events/${encodeURIComponent(H)}`,Z=3000;while(!0){M(`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)h("SSE 401: token 无效或未配置。检查 ~/.anet/config.json 的 token 字段");else A(`SSE failed: ${Q.status}`);await new Promise((V)=>setTimeout(V,Z)),Z=Math.min(Z*1.5,60000);continue}Z=3000;let Y=Q.body.getReader(),X=new TextDecoder,J="";while(!0){let{done:V,value:K}=await Y.read();if(V)break;J+=X.decode(K,{stream:!0});let F=J.split(`
44
+ `);J=F.pop()||"";for(let G of F){if(!G.startsWith("data: "))continue;try{let w=JSON.parse(G.slice(6));if(w.type==="connected"){q("SSE connected");continue}if(["new_task","broadcast"].includes(w.type))q(`← SSE ${w.type}`),await oz();if(w.type==="new_reply")q(`← SSE reply from ${w.from||"?"}${w.in_reply_to?` (task ${w.in_reply_to.slice(0,8)})`:""}`)}catch{}}}}catch($){A(`SSE error: ${$.message}`)}M(`SSE reconnecting (${Z/1000}s)...`),await new Promise(($)=>setTimeout($,Z)),Z=Math.min(Z*1.5,60000)}}q("启动");q(` runtime: ${Pz}`);q(` model: ${R||(L==="codex"?"gpt-5.4":"claude-sonnet-4-6")} ${R?"":"(default)"}`);q(` 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(q(` user: ${z.user.username} (${z.user.role})`),z.current_network){let Z=z.networks?.find(($)=>$.network_id===z.current_network)?.network_name;q(` network: ${Z||z.current_network}`)}else q(` network: ${u||"(global)"}`);else if(z?.ok===!1)q(` network: ${u||"(global)"}`);else A(" token 验证失败 — 检查 token 是否有效。运行: anet login")}catch{q(` network: ${u||"(global)"}`)}else A(" 未配置 token — agent 数据不隔离。运行: anet login");q(` tools: ${E.length?`[${E.join(",")}]`:"(none)"}`);q(` channels:${n.length?` telegram(${n.map((z)=>z.dir).join(",")})`:" (none)"}`);q(` session: ${_||"(new)"}`);q(` log-dir: ${s}`);await Sz();q("已注册到 CommHub");setInterval(()=>l("idle").catch(()=>{}),180000);var kz=async()=>{q("shutting down..."),await l("offline").catch(()=>{}),process.exit(0)};process.on("SIGINT",kz);process.on("SIGTERM",kz);for(let z of n)ez(z);zZ();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@sleep2agi/agent-node",
3
- "version": "2.1.0",
4
- "description": "One-command AI Agent node for CommHub networks. Claude + Codex dual runtime.",
3
+ "version": "2.1.1",
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"
7
7
  },
@@ -23,13 +23,16 @@
23
23
  "gpt5",
24
24
  "sdk",
25
25
  "minimax",
26
- "swarm"
26
+ "runtime",
27
+ "node",
28
+ "anthropic"
27
29
  ],
28
30
  "author": "sleep2agi",
29
31
  "license": "MIT",
32
+ "homepage": "https://anet.vansin.me",
30
33
  "repository": {
31
34
  "type": "git",
32
- "url": "https://github.com/sleep2agi/agent-comm-hub",
35
+ "url": "https://github.com/sleep2agi/agent-network",
33
36
  "directory": "agent-node"
34
37
  },
35
38
  "engines": {
@@ -42,6 +45,8 @@
42
45
  "@openai/codex-sdk": ">=0.118.0"
43
46
  },
44
47
  "peerDependenciesMeta": {
45
- "@openai/codex-sdk": { "optional": true }
48
+ "@openai/codex-sdk": {
49
+ "optional": true
50
+ }
46
51
  }
47
- }
52
+ }