@sleep2agi/agent-node 2.0.0 → 2.1.0-preview.10

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 +15 -15
  3. package/package.json +28 -7
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 wz}from"node:module";var l=wz(import.meta.url);import{readFileSync as S,existsSync as d,writeFileSync as m,chmodSync as Dz}from"fs";import{join as D}from"path";import{hostname as i,homedir as vz}from"os";import{mkdirSync as Kz,appendFileSync as Az}from"fs";var Zz=vz(),H=process.argv.slice(2),j={},$z=[],Hz="2.0.0";for(let z=0;z<H.length;z++){if(H[z]==="--version"||H[z]==="-v")console.log(`agent-node v${Hz}`),process.exit(0);if(H[z]==="-h"||H[z]==="--help")console.log(`
2
+ import{createRequire as kz}from"node:module";var p=kz(import.meta.url);import{readFileSync as u,existsSync as a,writeFileSync as o,chmodSync as Dz}from"fs";import{join as P}from"path";import{hostname as e,homedir as Mz}from"os";import{mkdirSync as Fz,appendFileSync as Iz}from"fs";var qz=Mz(),U=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(u(P(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(`
3
3
  @sleep2agi/agent-node — AI Agent 节点,一行命令加入 CommHub 网络
4
4
 
5
5
  用法:
@@ -8,8 +8,8 @@ import{createRequire as wz}from"node:module";var l=wz(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
15
  --max-turns <n> 每任务最大轮次 (default: 5)
@@ -24,20 +24,20 @@ import{createRequire as wz}from"node:module";var l=wz(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(H[z]==="--new-session"){j["new-session"]="true";continue}if(H[z]==="--channel"&&z+1<H.length){$z.push(H[++z]);continue}if(H[z].startsWith("--")&&z+1<H.length)j[H[z].slice(2)]=H[++z]}function Qz(z){return z.replace(/^~(?=\/|$)/,Zz)}function bz(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:Qz(z.slice(Z+1)),raw:z}}function C(z){if(!d(z))return null;try{return JSON.parse(S(z,"utf-8"))}catch{return null}}var V={},k="";if(j.config){let z=j.config.startsWith("/")?j.config:D(process.cwd(),j.config),Z=C(z);if(Z)V=Z,k=z,console.log(`[agent-node] Config: ${z}`)}var F=j.alias||process.env.COMMHUB_ALIAS||process.env.ALIAS||V.alias;if(!j.config&&F){let z=D(process.cwd(),".anet","nodes",F,"config.json"),Z=D(process.cwd(),".anet","profiles",`${F}.json`),$=d(z)?z:Z,Q=C($);if(Q){if(V={...Q,...V},k=$,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]=Qz(X)}}}var _=C(D(Zz,".anet","config.json"))||{};if(_.hub&&!V.hub)V.hub=_.hub;if(_.token&&!V.token)V.token=_.token;if(!j.config&&!Object.keys(V).length){let z=C(D(process.cwd(),".agent-node.json"));if(z)V=z,console.log("[agent-node] 配置: .agent-node.json")}if(!F)console.error(`错误: 必须指定 --alias
28
- 用法: npx @sleep2agi/agent-node --alias "我的Agent"`),process.exit(1);var Xz=j.runtime||process.env.RUNTIME||V.runtime||"claude-agent-sdk",Uz={"claude-agent-sdk":"claude","claude-sdk":"claude","agent-sdk":"claude",claude:"claude","codex-sdk":"codex",codex:"codex"},P=Uz[Xz]||"claude",yz=Xz,r=j.url||j.hub||process.env.COMMHUB_URL||V.hub||"http://127.0.0.1:9200",y=j.model||process.env.MODEL||V.model,Rz=["Read","Write","Edit","Bash","Glob","Grep","WebSearch","WebFetch"],g=j.tools||(Array.isArray(V.tools)?V.tools.join(","):V.tools)||"",M=g==="all"?Rz:g.split(",").filter(Boolean),kz=parseInt(j["max-turns"]||V.flags?.maxTurns||V.maxTurns||"5"),a=parseFloat(j["max-budget"]||V.flags?.maxBudgetUsd||V.maxBudgetUsd||"0"),Pz=j["new-session"]==="true",N=Pz?"":j.session||V.session||V.resume||V.sessionId||"",E=j.prompt||V.systemPrompt||"",x=process.env.COMMHUB_TOKEN||V.token||_.token||"",n=j["log-dir"]||D(process.cwd(),".anet","nodes",F,"logs"),Mz={debug:0,info:1,warn:2,error:3},Nz=Mz[j["log-level"]||process.env.LOG_LEVEL||V.logLevel||"info"]??1,_z=[...(Array.isArray(V.channels)?V.channels:[]).filter((z)=>!z.startsWith("server:")&&!z.startsWith("plugin:")),...$z],Yz=_z.map((z)=>{try{return bz(z)}catch(Z){console.error(`[agent-node] ${Z.message}`),process.exit(1)}});function Wz(z){if(!k||!z)return;try{let Z=JSON.parse(S(k,"utf-8"));if(Z.session===z)return;Z.session=z,m(k,JSON.stringify(Z,null,2)+`
29
- `),b(`session 写回: ${k} → ${z.slice(0,8)}...`)}catch{}}function xz(z){if(!d(z))return;for(let Z of S(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 Oz(z){return D(process.cwd(),".anet","nodes",F,"channels",z)}function Cz(z){let Z=z.path||Oz("telegram");xz(D(Z,".env"));let $=process.env.TELEGRAM_BOT_TOKEN||"";if(!$)console.error(`[agent-node] telegram channel needs TELEGRAM_BOT_TOKEN in ${D(Z,".env")}`),process.exit(1);try{Dz(D(Z,".env"),384)}catch{}let Q=C(D(Z,"access.json"))||{},Y=D(Z,"inbox");try{Kz(Y,{recursive:!0})}catch{}return{type:"telegram",dir:Z,inboxDir:Y,token:$,allowFrom:Array.isArray(Q.allowFrom)?Q.allowFrom.map(String):[]}}var T=Yz.filter((z)=>z.type==="telegram").map(Cz),o=Yz.find((z)=>z.type!=="telegram");if(o)console.error(`[agent-node] unsupported channel: ${o.raw}`),process.exit(1);if(T.length>0&&P!=="codex"&&!M.includes("Read"))M.push("Read");try{Kz(n,{recursive:!0})}catch{}function h(z,Z,$){if(Z<Nz)return;let Q=new Date().toTimeString().slice(0,8),Y=z.toUpperCase().padEnd(5),X=`[${Q}] [${Y}] [${F}] ${$}`;console.log(X);try{let q=new Date().toISOString().slice(0,10);Az(D(n,`${q}.log`),X+`
31
- `)}catch{}}var B=(z)=>h("info",1,z),b=(z)=>h("debug",0,z),L=(z)=>h("warn",2,z),O=(z)=>h("error",3,z);async function A(z,Z){let $={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(x)$.Authorization=`Bearer ${x}`;let Y=await(await fetch(`${r}/mcp`,{method:"POST",headers:$,body:JSON.stringify({jsonrpc:"2.0",id:Date.now(),method:"tools/call",params:{name:z,arguments:Z}})})).text(),X=Y.match(/data: (.+)/),q=X?JSON.parse(X[1]):JSON.parse(Y),W=q?.result?.content?.[0]?.text;return W?JSON.parse(W):q}var t=V.node_id||"",Vz=t?`sdk-${t}`:`sdk-${F}-${Date.now().toString(36)}`,Ez=()=>A("report_status",{resume_id:Vz,alias:F,status:"idle",server:i(),hostname:i(),agent:`agent-node:${P}`,project_dir:process.cwd()}),I=(z,Z)=>A("report_status",{resume_id:Vz,alias:F,status:z,task:Z}),Tz=async()=>(await A("get_inbox",{alias:F,limit:5}))?.messages||[],Lz=(z)=>A("ack_inbox",{alias:F,message_id:z}),Iz=(z,Z)=>A("send_message",{alias:z,message:Z,from_session:F}),p=N||void 0;async function uz(z,Z){let{query:$}=await import("@anthropic-ai/claude-agent-sdk"),Q=`你是 ${F},收到来自 ${Z} 的任务:
27
+ `),process.exit(0);if(U[z]==="--new-session"){v["new-session"]="true";continue}if(U[z]==="--channel"&&z+1<U.length){Jz.push(U[++z]);continue}if(U[z].startsWith("--")&&z+1<U.length)v[U[z].slice(2)]=U[++z]}function Bz(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:Bz(z.slice(Z+1)),raw:z}}function S(z){if(!a(z))return null;try{return JSON.parse(u(z,"utf-8"))}catch{return null}}var B={},y="";if(v.config){let z=v.config.startsWith("/")?v.config:P(process.cwd(),v.config),Z=S(z);if(Z)B=Z,y=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=P(process.cwd(),".anet","nodes",H,"config.json"),Z=P(process.cwd(),".anet","profiles",`${H}.json`),$=a(z)?z:Z,Q=S($);if(Q){if(B={...Q,...B},y=$,console.log(`[agent-node] Config: ${$}`),Q.env&&typeof Q.env==="object"){for(let[X,Y]of Object.entries(Q.env))if(!process.env[X]&&typeof Y==="string")process.env[X]=Bz(Y)}}}var A=S(P(qz,".anet","config.json"))||{};if(A.hub&&!B.hub)B.hub=A.hub;if(A.token&&!B.token)B.token=A.token;if(!v.config&&!Object.keys(B).length){let z=S(P(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"},N=xz[Gz]||"claude",Rz=Gz,h=v.url||v.hub||process.env.COMMHUB_URL||B.hub||"http://127.0.0.1:9200",M=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)||"",L=zz==="all"?Nz:zz.split(",").filter(Boolean),_z=parseInt(v["max-turns"]||B.flags?.maxTurns||B.maxTurns||"5"),Zz=parseFloat(v["max-budget"]||B.flags?.maxBudgetUsd||B.maxBudgetUsd||"0"),Az=v["new-session"]==="true",R=Az?"":v.session||B.session||B.resume||B.sessionId||"",c=v.prompt||B.systemPrompt||"",x=process.env.COMMHUB_TOKEN||B.token||A.token||"",t=v["log-dir"]||P(process.cwd(),".anet","nodes",H,"logs"),Lz={debug:0,info:1,warn:2,error:3},Cz=Lz[v["log-level"]||process.env.LOG_LEVEL||B.logLevel||"info"]??1,E=[...(Array.isArray(B.channels)?B.channels:[]).filter((z)=>!z.startsWith("server:")&&!z.startsWith("plugin:")),...Jz],jz=E.map((z)=>{try{return yz(z)}catch(Z){console.error(`[agent-node] ${Z.message}`),process.exit(1)}});function Kz(z){if(!y||!z)return;try{let Z=JSON.parse(u(y,"utf-8"));if(Z.session===z)return;Z.session=z,o(y,JSON.stringify(Z,null,2)+`
29
+ `),k(`session 写回: ${y} → ${z.slice(0,8)}...`)}catch(Z){_(`writebackSession failed: ${Z.message}`)}}function Oz(z){if(!a(z))return;for(let Z of u(z,"utf-8").split(`
30
+ `)){let $=Z.trim();if(!$||$.startsWith("#"))continue;let Q=$.indexOf("=");if(Q<=0)continue;let X=$.slice(0,Q).trim(),Y=$.slice(Q+1).trim().replace(/^['"]|['"]$/g,"");if(!process.env[X])process.env[X]=Y}}function Tz(z){return P(process.cwd(),".anet","nodes",H,"channels",z)}function Ez(z){let Z=z.path||Tz("telegram");Oz(P(Z,".env"));let $=process.env.TELEGRAM_BOT_TOKEN||"";if(!$)console.error(`[agent-node] telegram channel needs TELEGRAM_BOT_TOKEN in ${P(Z,".env")}`),process.exit(1);try{Dz(P(Z,".env"),384)}catch{}let Q=S(P(Z,"access.json"))||{},X=P(Z,"inbox");try{Fz(X,{recursive:!0})}catch{}return{type:"telegram",dir:Z,inboxDir:X,token:$,allowFrom:Array.isArray(Q.allowFrom)?Q.allowFrom.map(String):[]}}var m=jz.filter((z)=>z.type==="telegram").map(Ez),$z=jz.find((z)=>z.type!=="telegram");if($z)console.error(`[agent-node] unsupported channel: ${$z.raw}`),process.exit(1);if(m.length>0&&N!=="codex"&&!L.includes("Read"))L.push("Read");try{Fz(t,{recursive:!0})}catch{}function g(z,Z,$){if(Z<Cz)return;let Q=new Date().toTimeString().slice(0,8),X=z.toUpperCase().padEnd(5),Y=`[${Q}] [${X}] [${H}] ${$}`;console.log(Y);try{let J=new Date().toISOString().slice(0,10);Iz(P(t,`${J}.log`),Y+`
31
+ `)}catch{}}var q=(z)=>g("info",1,z),k=(z)=>g("debug",0,z),_=(z)=>g("warn",2,z),I=(z)=>g("error",3,z);async function f(z,Z,$=3){let Q={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(x)Q.Authorization=`Bearer ${x}`;let X;for(let Y=0;Y<=$;Y++)try{let J=await fetch(`${h}/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&&Y<$){X=Error(`HTTP ${J.status}`),await new Promise((j)=>setTimeout(j,1000*Math.pow(2,Y)));continue}let V=await J.text(),W=V.match(/data: (.+)/),K=W?JSON.parse(W[1]):JSON.parse(V),G=K?.result?.content?.[0]?.text;return G?JSON.parse(G):K}catch(J){if(X=J,Y<$)k(`callCommHub(${z}) attempt ${Y+1} failed: ${J.message}, retrying...`),await new Promise((V)=>setTimeout(V,1000*Math.pow(2,Y)))}throw X||Error(`callCommHub(${z}) failed after ${$} retries`)}var n=B.node_id||"",uz=B.node_name||"",T=B.network_id||process.env.ANET_NETWORK_ID||A.network_id||"",wz=n?`sdk-${n}`:`sdk-${H}-${Date.now().toString(36)}`,Sz=()=>f("report_status",{resume_id:wz,alias:H,status:"idle",server:e(),hostname:e(),agent:`agent-node:${N}`,project_dir:process.cwd(),node_id:n||void 0,node_name:uz||void 0,session_id:R||void 0,config_path:y||void 0,channels:E.length?JSON.stringify(E):void 0,model:M||void 0,network_id:T||void 0}),r=(z,Z)=>f("report_status",{resume_id:wz,alias:H,status:z,task:Z,node_id:n||void 0,session_id:d||R||void 0,config_path:y||void 0,channels:E.length?JSON.stringify(E):void 0,network_id:T||void 0}),hz=async()=>(await f("get_inbox",{alias:H,limit:20}))?.messages||[],fz=(z)=>f("ack_inbox",{alias:H,message_id:z}),pz=(z,Z,$)=>f("send_reply",{alias:z,text:Z,from_session:H,in_reply_to:$||void 0,status:"replied"}),d=R||void 0;async function dz(z,Z){let{query:$}=await import("@anthropic-ai/claude-agent-sdk"),Q=`你是 ${H},收到来自 ${Z} 的任务:
32
32
 
33
33
  ${z}
34
34
 
35
- 执行完后简要汇报结果。`,Y={model:y||void 0,tools:M.length?M:void 0,maxTurns:kz,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,settingSources:[],env:process.env,cwd:process.cwd(),stderr:(W)=>{if(W.trim())b(`[stderr] ${W.trim().slice(0,200)}`)},hooks:{PreToolUse:[{hooks:[async(W)=>{return B(`[tool] ${W.tool_name}(${JSON.stringify(W.tool_input).slice(0,80)})`),{continue:!0}}]}]}};if(a>0)Y.maxBudgetUsd=a;if(E)Y.systemPrompt=E;if(p)Y.resume=p;let X="",q=Date.now();for await(let W of $({prompt:Q,options:Y})){let K=W;if(K.type==="system"&&K.subtype==="init")p=K.session_id,B(`[claude] session=${K.session_id?.slice(0,8)} model=${y||"default"}`),Wz(K.session_id);if(K.type==="result"){let G=Date.now()-q,J=K.usage||{};B(`[claude] ${K.subtype} | ${G}ms | $${K.total_cost_usd?.toFixed(4)||"?"} | in=${J.input_tokens||0} out=${J.output_tokens||0} | turns=${K.num_turns}`),X=K.subtype==="success"?K.result||"任务完成":`执行出错: ${K.error||K.result||"未知错误"}`}}return X}var U=null;async function Sz(z,Z,$){let{Codex:Q}=await import("@openai/codex-sdk");if(!U){let K=E||`你是 ${F},一个 AI Agent 节点。你通过 CommHub 通信网络接收任务。收到任务后理解内容、执行任务(可以读写文件、执行命令)、返回执行结果。你的回复会被自动发送给任务发送者。当前工作目录:${process.cwd()}。重要:不要回复纯确认消息(如"收到""好的""ok"),必须有实质内容才回复。无实质进展时保持沉默。没有新任务时保持安静,不要主动发消息询问或提示"等待任务",等待下一条任务即可。`,G=new Q({config:{model_auto_compact_token_limit:200000,developer_instructions:K}}),v={skipGitRepoCheck:!0,approvalPolicy:"never",model:y||"gpt-5.4",sandboxMode:"danger-full-access",modelReasoningEffort:"low"};if(N)U=G.resumeThread(N,v),B(`codex resumed thread: ${N}`);else U=G.startThread(v)}B(`[codex] model=${y||"gpt-5.4"} thread=${U?.id||"new"}`);let X=`${z}
36
-
37
- (直接回答,不要调用任何通信工具,不要发消息给其他人)`,q=$?.length?[{type:"text",text:X},...$.map((K)=>({type:"local_image",path:K}))]:X,W=Date.now();try{let{events:K}=await U.runStreamed(q),G="",J=null,v=0;for await(let R of K)if(R.type==="item.started"){let w=R.item;b(`[codex] ${w.type}${w.command?`: ${w.command.slice(0,60)}`:w.tool?`: ${w.server}/${w.tool}`:""}`)}else if(R.type==="item.completed"){v++;let w=R.item;if(w.type==="agent_message")G=w.text||"";if(w.type==="command_execution")b(`[codex] cmd exit=${w.exit_code} | ${w.aggregated_output?.slice(0,80)}`);if(w.type==="reasoning")b(`[codex] thinking: ${w.text?.slice(0,80)}`);if(w.type==="mcp_tool_call")b(`[codex] mcp: ${w.server}/${w.tool} → ${w.status}`)}else if(R.type==="turn.completed")J=R.usage;let f=Date.now()-W,Fz=J?.input_tokens||0;if(B(`[codex] done | ${f}ms | in=${Fz} out=${J?.output_tokens||0} | items=${v}`),U?.id)Wz(U.id);return G||"(无回复)"}catch(K){B(`codex thread error: ${K.message}, 重建`),U=new Q({config:{model_auto_compact_token_limit:200000,developer_instructions:E||`你是 ${F},一个 AI Agent 节点。`}}).startThread({skipGitRepoCheck:!0,approvalPolicy:"never",model:y||"gpt-5.4",sandboxMode:"danger-full-access",modelReasoningEffort:"low"});let J=await U.run(q),v=Date.now()-W;return B(`[codex] retry done | ${v}ms`),J.finalResponse||"(无回复)"}}var s=Promise.resolve();function Bz(z,Z,$){let Q=async()=>{if(P==="codex")return Sz(z,Z,$);return uz(z,Z)},Y=s.then(Q,Q);return s=Y.then(()=>{},()=>{}),Y}async function hz(z,Z){B(`→ processing [${P}]: ${z.slice(0,80)}`),await I("working",z.slice(0,200));let $;try{$=await Bz(z,Z)}catch(Q){$=`${P} 错误: ${Q.message}`,O(`✗ ${Q.message}`)}return await I("idle"),$}var c={},fz=5000,pz=new Set(["收到","好的","ok","嗯","是的","了解","明白","确认","done","ack","roger","yes","no","在线","待命","正常","保持在线","通信正常","已收到","收到了","好","行","noted","copy","received","understood","等待任务","等待中","等待指令","无新任务","idle","waiting"]);function qz(z){if(!z)return!0;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(pz.has(Q))return!0;if(/^[\p{Emoji}\s]+$/u.test(z.trim()))return!0;return!1}function cz(z,Z){if(z===F)return"self";if(Z.startsWith(`[${F}]`))return"own-prefix";let $=Date.now();if(c[z]&&$-c[z]<fz)return"cooldown";if(qz(Z))return"low-value-inbound";return null}async function dz(){let z=await Tz();if(!z.length)return;for(let Z of z){let $=Z.from_session||"hub",Q=Z.content;B(`← [${$}] (${Z.priority||"normal"}) ${Q.slice(0,100)}`),await Lz(Z.id);let Y=cz($,Q);if(Y){b(`skip message from ${$}: ${Y}`);continue}let X=await hz(Q,$);if(c[$]=Date.now(),qz(X)){b(`skip reply: low-value (${X.slice(0,30)})`);continue}try{await Iz($,`[${F}] ${X.slice(0,2000)}`),B(`→ [${$}] ${X.slice(0,100)}`)}catch(q){L(`reply failed: ${q.message}`)}}}function Jz(z){return String(z.from?.id||z.chat?.id||"")}function Gz(z){return z.from?.username||z.from?.first_name||Jz(z)||"telegram"}function mz(z,Z){if(z.allowFrom.length===0)return!0;let $=Jz(Z),Q=Z.from?.username?String(Z.from.username):"";return z.allowFrom.includes($)||!!Q&&z.allowFrom.includes(Q)}async function u(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 e(z,Z,$,Q){let Y=$.match(/[\s\S]{1,4096}/g)||["(无回复)"];for(let X=0;X<Y.length;X++)await u(z,"sendMessage",{chat_id:Z,text:Y[X],...Q&&X===0?{reply_to_message_id:Q}:{}})}async function zz(z,Z,$){let Q=await u(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 q=Y.split(".").pop(),W=($||Y.split("/").pop()||Z).replace(/[^a-zA-Z0-9._-]/g,"_"),K=W.includes(".")||!q?W:`${W}.${q}`,G=D(z.channel.inboxDir,`${Date.now()}_${K}`);return m(G,Buffer.from(await X.arrayBuffer())),G}async function rz(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],q=await zz(z,X.file_id,`photo_${Z.message_id}.jpg`);Q.push(q)}let Y=String(Z.document?.mime_type||"");if(Z.document&&Y.startsWith("image/")){let X=await zz(z,Z.document.file_id,Z.document.file_name||`image_${Z.message_id}`);Q.push(X)}if(Q.length)$+=`
35
+ 执行完后简要汇报结果。`,X=process.env.COMMHUB_URL||h,Y=process.env.COMMHUB_TOKEN||x,J=X?[{name:"commhub",type:"url",url:`${X}/mcp`,authorizationToken:Y||void 0}]:[],V=(()=>{try{let{execSync:j}=p("child_process");return j("which claude",{encoding:"utf-8"}).trim()}catch{return}})(),W={model:M||void 0,tools:L.length?L:void 0,maxTurns:_z,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,settingSources:[],pathToClaudeCodeExecutable:V,env:process.env,cwd:process.cwd(),stderr:(j)=>{if(j.trim())k(`[stderr] ${j.trim().slice(0,200)}`)},hooks:{PreToolUse:[{hooks:[async(j)=>{return q(`[tool] ${j.tool_name}(${JSON.stringify(j.tool_input).slice(0,80)})`),{continue:!0}}]}]}};if(Zz>0)W.maxBudgetUsd=Zz;if(c)W.systemPrompt=c;if(d)W.resume=d;let K="",G=Date.now();for await(let j of $({prompt:Q,options:W})){let F=j;if(F.type==="system"&&F.subtype==="init")d=F.session_id,q(`[claude] session=${F.session_id?.slice(0,8)} model=${M||"default"}`),Kz(F.session_id);if(F.type==="result"){let C=Date.now()-G,b=F.usage||{};q(`[claude] ${F.subtype} | ${C}ms | $${F.total_cost_usd?.toFixed(4)||"?"} | in=${b.input_tokens||0} out=${b.output_tokens||0} | turns=${F.num_turns}`),K=F.subtype==="success"?F.result||"任务完成":`执行出错: ${F.error||F.result||"未知错误"}`}}return K}var D=null,cz=c||[`你是 ${H},一个 AI Agent 节点,工作目录:${process.cwd()}。`,"你通过通信网络接收任务。收到任务后执行并返回结果。","规则:","1. 只回复有实质内容的结果。",'2. 绝对不要回复"收到""好的""ok""在线""待命""等待任务"等确认消息。',"3. 没有新任务时保持完全沉默,不要主动发任何消息。","4. 不要调用任何通信工具(send_task/send_message 等)。","5. 你的回复会被系统自动发送给任务发送者。"].join(`
36
+ `),Qz={model_auto_compact_token_limit:200000,developer_instructions:cz};async function mz(z,Z,$){try{let{execSync:W}=await import("child_process"),K=W("which codex 2>/dev/null",{encoding:"utf-8"}).trim();if(K){let G=K.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(!D){let W=new Q({config:Qz}),G={skipGitRepoCheck:!0,approvalPolicy:"never",model:M||"gpt-5.4",sandboxMode:"danger-full-access",modelReasoningEffort:"low"};if(R)D=W.resumeThread(R,G),q(`codex resumed thread: ${R}`);else D=W.startThread(G)}q(`[codex] model=${M||"gpt-5.4"} thread=${D?.id||"new"}`);let Y=z,J=$?.length?[{type:"text",text:Y},...$.map((W)=>({type:"local_image",path:W}))]:Y,V=Date.now();try{let{events:W}=await D.runStreamed(J),K="",G=null,j=0;for await(let b of W)if(b.type==="item.started"){let w=b.item;k(`[codex] ${w.type}${w.command?`: ${w.command.slice(0,60)}`:w.tool?`: ${w.server}/${w.tool}`:""}`)}else if(b.type==="item.completed"){j++;let w=b.item;if(w.type==="agent_message")K=w.text||"";if(w.type==="command_execution")k(`[codex] cmd exit=${w.exit_code} | ${w.aggregated_output?.slice(0,80)}`);if(w.type==="reasoning")k(`[codex] thinking: ${w.text?.slice(0,80)}`);if(w.type==="mcp_tool_call")k(`[codex] mcp: ${w.server}/${w.tool} → ${w.status}`)}else if(b.type==="turn.completed")G=b.usage;let F=Date.now()-V,C=G?.input_tokens||0;if(q(`[codex] done | ${F}ms | in=${C} out=${G?.output_tokens||0} | items=${j}`),D?.id)Kz(D.id);return K||"(无回复)"}catch(W){q(`codex thread error: ${W.message}, 重建`),D=new Q({config:Qz}).startThread({skipGitRepoCheck:!0,approvalPolicy:"never",model:M||"gpt-5.4",sandboxMode:"danger-full-access",modelReasoningEffort:"low"});let G=await D.run(J),j=Date.now()-V;return q(`[codex] retry done | ${j}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||"",X=process.env.OPENAI_BASE_URL||B.apiBaseUrl||"https://api.openai.com/v1",Y=M||"gpt-4o-mini",J=!!Q,W=(Q||X).replace(/\/v1\/?$/,"");if(!$)return"错误: 需要设置 ANTHROPIC_API_KEY, OPENAI_API_KEY, 或 MINIMAX_CODING_API_KEY";let K=c||`你是 ${H},一个 AI 助手。收到来自 ${Z} 的任务后简要执行并汇报。`,G=Date.now();q(`[http-api] model=${Y} format=${J?"anthropic":"openai"} base=${W.replace(/\/v1$/,"")}`);let j="",F=null;if(J){let b=await fetch(`${W}/v1/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":$,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:Y,system:K,messages:[{role:"user",content:z}],max_tokens:2000})});if(!b.ok){let O=await b.text();return`Anthropic API 错误 ${b.status}: ${O.slice(0,200)}`}let w=await b.json();j=(Array.isArray(w.content)?w.content:[]).filter((O)=>O.type==="text").map((O)=>O.text).join(`
37
+ `)||"",F=w.usage}else{let b=await fetch(`${W}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$}`},body:JSON.stringify({model:Y,messages:[{role:"system",content:K},{role:"user",content:z}],max_tokens:2000})});if(!b.ok){let s=await b.text();return`OpenAI API 错误 ${b.status}: ${s.slice(0,200)}`}let w=await b.json();j=w.choices?.[0]?.message?.content||"",F=w.usage}let C=Date.now()-G;return q(`[http-api] done | ${C}ms | in=${F?.input_tokens||F?.prompt_tokens||0} out=${F?.output_tokens||F?.completion_tokens||0}`),j||"(无回复)"}var Yz=Promise.resolve();function vz(z,Z,$){let Q=async()=>{if(N==="codex")return mz(z,Z,$);if(N==="http")return nz(z,Z);return dz(z,Z)},X=Yz.then(Q,Q);return Yz=X.then(()=>{},()=>{}),X}async function rz(z,Z){q(`→ processing [${N}]: ${z.slice(0,80)}`),await r("working",z.slice(0,200)).catch(()=>{});let $;try{$=await vz(z,Z)}catch(Q){$=`${N} 错误: ${Q.message}`,I(`✗ ${Q.message}`)}finally{await r("idle").catch(()=>{})}return $}var i={},lz=5000,gz=new Set(["收到","好的","ok","嗯","是的","了解","明白","确认","done","ack","roger","yes","no","在线","待命","正常","保持在线","通信正常","已收到","收到了","好","行","noted","copy","received","understood","等待任务","等待中","等待指令","无新任务","idle","waiting"]);function Hz(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(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 $=Date.now();if(i[z]&&$-i[z]<lz)return"cooldown"}if(Hz(Z))return"low-value-inbound";return null}async function az(){let z=await hz();if(!z.length)return;for(let Z of z){let $=Z.from_session||"hub",Q=Z.content,X=Z.type||"task";if(q(`← [${$}] (${X}/${Z.priority||"normal"}) ${Q.slice(0,100)}`),await fz(Z.id),X!=="task"&&X!=="broadcast"){k(`skip non-task message: type=${X}`);continue}let Y=iz($,Q);if(Y){k(`skip message from ${$}: ${Y}`);continue}let J=await rz(Q,$);if(q(`processTask returned: "${J.slice(0,80)}" (${J.length} chars)`),Hz(J,!0)){q(`skip reply: low-value (${J.slice(0,30)})`);continue}try{q(`sending reply to ${$} (task ${Z.id.slice(0,8)})...`),await pz($,`[${H}] ${J.slice(0,2000)}`,Z.id),i[$]=Date.now(),q(`→ [${$}] ${J.slice(0,100)}`)}catch(V){_(`reply failed: ${V.message}`)}}}function bz(z){return String(z.from?.id||z.chat?.id||"")}function Pz(z){return z.from?.username||z.from?.first_name||bz(z)||"telegram"}function oz(z,Z){if(z.allowFrom.length===0)return!0;let $=bz(Z),Q=Z.from?.username?String(Z.from.username):"";return z.allowFrom.includes($)||!!Q&&z.allowFrom.includes(Q)}async function l(z,Z,$){let Q=await fetch(`${z.apiBase}/${Z}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify($)}),X=await Q.json();if(!X.ok)throw Error(`telegram ${Z} failed: ${X.description||Q.statusText}`);return X.result}async function Xz(z,Z,$,Q){let X=$.match(/[\s\S]{1,4096}/g)||["(无回复)"];for(let Y=0;Y<X.length;Y++)await l(z,"sendMessage",{chat_id:Z,text:X[Y],...Q&&Y===0?{reply_to_message_id:Q}:{}})}async function Vz(z,Z,$){let Q=await l(z,"getFile",{file_id:Z}),X=String(Q.file_path||""),Y=await fetch(`${z.fileBase}/${X}`);if(!Y.ok)throw Error(`telegram file download failed: ${Y.status} ${Y.statusText}`);let J=X.split(".").pop(),V=($||X.split("/").pop()||Z).replace(/[^a-zA-Z0-9._-]/g,"_"),W=V.includes(".")||!J?V:`${V}.${J}`,K=P(z.channel.inboxDir,`${Date.now()}_${W}`);return o(K,Buffer.from(await Y.arrayBuffer())),K}async function tz(z,Z){let $=Z.text||Z.caption||"",Q=[];if(Array.isArray(Z.photo)&&Z.photo.length>0){let Y=Z.photo[Z.photo.length-1],J=await Vz(z,Y.file_id,`photo_${Z.message_id}.jpg`);Q.push(J)}let X=String(Z.document?.mime_type||"");if(Z.document&&X.startsWith("image/")){let Y=await Vz(z,Z.document.file_id,Z.document.file_name||`image_${Z.message_id}`);Q.push(Y)}if(Q.length)$+=`
38
38
 
39
39
  [Telegram 附件已下载]
40
- ${Q.map((X)=>`- 图片: ${X}`).join(`
41
- `)}`;return{text:$.trim(),images:Q}}async function nz(z,Z){if(!mz(z.channel,Z))return;let $=Z.chat?.id,Q=Z.message_id,Y=`telegram:${Gz(Z)}`,{text:X,images:q}=await rz(z,Z);if(!$||!Q||!X)return;b(`[TG] processing: ${X.slice(0,80)}`);try{let W=await Bz(X,Y,q);await e(z,$,W,Q),B(`→ [${Y}] ${W.slice(0,100)}`)}catch(W){O(`telegram task failed: ${W.message}`),await e(z,$,`处理出错: ${W.message}`,Q).catch(()=>{})}}async function lz(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 W=await u(Z,"getMe",{});B(`Telegram bot: @${W.username} (${W.first_name})`)}catch(W){O(`Telegram token 无效: ${W.message}`),process.exit(1)}let $=D(z.dir,"state.json");try{let W=JSON.parse(S($,"utf-8"));if(W.offset)Z.offset=W.offset,b(`Telegram offset restored: ${Z.offset}`)}catch{}let Q=()=>{try{m($,JSON.stringify({offset:Z.offset})+`
42
- `)}catch{}},Y=!1,X=[];async function q(){if(Y)return;Y=!0;while(X.length){let{msg:W,updateId:K}=X.shift();try{await nz(Z,W),Z.offset=K+1,Q()}catch(G){O(`TG handle: ${G.message}`)}}Y=!1}B(`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 G of K.result||[])if(Z.offset=G.update_id+1,G.message){let J=G.message,v=Gz(J),f=J.text||J.caption||"";if(B(`← TG [${v}] ${f.slice(0,80)}${J.photo?" +img":""}${J.document?" +file":""}`),J.chat?.id&&J.message_id)u(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:G.update_id}),q()}}catch(W){L(`Telegram polling error: ${W.message}`),await new Promise((K)=>setTimeout(K,3000))}}async function iz(){let z=`${r}/events/${encodeURIComponent(F)}`,Z=3000;while(!0){b(`SSE connecting: ${z}`);try{let $={Accept:"text/event-stream","Cache-Control":"no-cache"};if(x)$.Authorization=`Bearer ${x}`;let Q=await fetch(z,{headers:$});if(!Q.ok||!Q.body){if(Q.status===401)O("SSE 401: token 无效或未配置。检查 ~/.anet/config.json 的 token 字段");else L(`SSE failed: ${Q.status}`);await new Promise((W)=>setTimeout(W,Z)),Z=Math.min(Z*1.5,60000);continue}Z=3000;let Y=Q.body.getReader(),X=new TextDecoder,q="";while(!0){let{done:W,value:K}=await Y.read();if(W)break;q+=X.decode(K,{stream:!0});let G=q.split(`
43
- `);q=G.pop()||"";for(let J of G){if(!J.startsWith("data: "))continue;try{let v=JSON.parse(J.slice(6));if(v.type==="connected"){B("SSE connected");continue}if(["new_task","broadcast"].includes(v.type))B(`← SSE ${v.type}`),await dz()}catch{}}}}catch($){L(`SSE error: ${$.message}`)}b(`SSE reconnecting (${Z/1000}s)...`),await new Promise(($)=>setTimeout($,Z)),Z=Math.min(Z*1.5,60000)}}B("启动");B(` runtime: ${yz}`);B(` model: ${y||(P==="codex"?"gpt-5.4":"claude-sonnet-4-6")} ${y?"":"(default)"}`);B(` hub: ${r}${x?" (auth)":" (no auth!)"}`);B(` tools: ${M.length?`[${M.join(",")}]`:"(none)"}`);B(` channels:${T.length?` telegram(${T.map((z)=>z.dir).join(",")})`:" (none)"}`);B(` session: ${N||"(new)"}`);B(` log-dir: ${n}`);await Ez();B("已注册到 CommHub");setInterval(()=>I("idle").catch(()=>{}),180000);var jz=async()=>{B("shutting down..."),await I("offline").catch(()=>{}),process.exit(0)};process.on("SIGINT",jz);process.on("SIGTERM",jz);for(let z of T)lz(z);iz();
40
+ ${Q.map((Y)=>`- 图片: ${Y}`).join(`
41
+ `)}`;return{text:$.trim(),images:Q}}async function sz(z,Z){if(!oz(z.channel,Z))return;let $=Z.chat?.id,Q=Z.message_id,X=`telegram:${Pz(Z)}`,{text:Y,images:J}=await tz(z,Z);if(!$||!Q||!Y)return;k(`[TG] processing: ${Y.slice(0,80)}`);try{let V=await vz(Y,X,J);await Xz(z,$,V,Q),q(`→ [${X}] ${V.slice(0,100)}`)}catch(V){I(`telegram task failed: ${V.message}`),await Xz(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 l(Z,"getMe",{});q(`Telegram bot: @${V.username} (${V.first_name})`)}catch(V){I(`Telegram token 无效: ${V.message}`),process.exit(1)}let $=P(z.dir,"state.json");try{let V=JSON.parse(u($,"utf-8"));if(V.offset)Z.offset=V.offset,k(`Telegram offset restored: ${Z.offset}`)}catch{}let Q=()=>{try{o($,JSON.stringify({offset:Z.offset})+`
42
+ `)}catch{}},X=!1,Y=[];async function J(){if(X)return;X=!0;while(Y.length){let{msg:V,updateId:W}=Y.shift();try{await sz(Z,V),Z.offset=W+1,Q()}catch(K){I(`TG handle: ${K.message}`)}}X=!1}q(`Telegram polling: ${z.dir}`);while(!0)try{let W=await(await fetch(`${Z.apiBase}/getUpdates?offset=${Z.offset}&timeout=30`)).json();if(!W.ok)throw Error(W.description||"getUpdates failed");for(let K of W.result||[])if(Z.offset=K.update_id+1,K.message){let G=K.message,j=Pz(G),F=G.text||G.caption||"";if(q(`← TG [${j}] ${F.slice(0,80)}${G.photo?" +img":""}${G.document?" +file":""}`),G.chat?.id&&G.message_id)l(Z,"setMessageReaction",{chat_id:G.chat.id,message_id:G.message_id,reaction:[{type:"emoji",emoji:Y.length>0?"⏳":"\uD83D\uDC40"}]}).catch(()=>{});Y.push({msg:G,updateId:K.update_id}),J()}}catch(V){_(`Telegram polling error: ${V.message}`),await new Promise((W)=>setTimeout(W,3000))}}async function zZ(){let z=`${h}/events/${encodeURIComponent(H)}`,Z=3000;while(!0){k(`SSE connecting: ${z}`);try{let $={Accept:"text/event-stream","Cache-Control":"no-cache"};if(x)$.Authorization=`Bearer ${x}`;let Q=await fetch(z,{headers:$});if(!Q.ok||!Q.body){if(Q.status===401)I("SSE 401: token 无效或未配置。检查 ~/.anet/config.json 的 token 字段");else _(`SSE failed: ${Q.status}`);await new Promise((V)=>setTimeout(V,Z)),Z=Math.min(Z*1.5,60000);continue}Z=3000;let X=Q.body.getReader(),Y=new TextDecoder,J="";while(!0){let{done:V,value:W}=await X.read();if(V)break;J+=Y.decode(W,{stream:!0});let K=J.split(`
43
+ `);J=K.pop()||"";for(let G of K){if(!G.startsWith("data: "))continue;try{let j=JSON.parse(G.slice(6));if(j.type==="connected"){q("SSE connected");continue}if(["new_task","broadcast"].includes(j.type))q(`← SSE ${j.type}`),await az();if(j.type==="new_reply")q(`← SSE reply from ${j.from||"?"}${j.in_reply_to?` (task ${j.in_reply_to.slice(0,8)})`:""}`)}catch{}}}}catch($){_(`SSE error: ${$.message}`)}k(`SSE reconnecting (${Z/1000}s)...`),await new Promise(($)=>setTimeout($,Z)),Z=Math.min(Z*1.5,60000)}}q("启动");q(` runtime: ${Rz}`);q(` model: ${M||(N==="codex"?"gpt-5.4":"claude-sonnet-4-6")} ${M?"":"(default)"}`);q(` hub: ${h}${x?" (auth)":" (no auth!)"}`);if(x)try{let z=await fetch(`${h}/api/auth/me`,{headers:{Authorization:`Bearer ${x}`}}).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: ${T||"(global)"}`);else if(z?.ok===!1)q(` network: ${T||"(global)"}`);else _(" token 验证失败 — 检查 token 是否有效。运行: anet login")}catch{q(` network: ${T||"(global)"}`)}else _(" 未配置 token — agent 数据不隔离。运行: anet login");q(` tools: ${L.length?`[${L.join(",")}]`:"(none)"}`);q(` channels:${m.length?` telegram(${m.map((z)=>z.dir).join(",")})`:" (none)"}`);q(` session: ${R||"(new)"}`);q(` log-dir: ${t}`);await Sz();q("已注册到 CommHub");setInterval(()=>r("idle").catch(()=>{}),180000);var Uz=async()=>{q("shutting down..."),await r("offline").catch(()=>{}),process.exit(0)};process.on("SIGINT",Uz);process.on("SIGTERM",Uz);for(let z of m)ez(z);zZ();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@sleep2agi/agent-node",
3
- "version": "2.0.0",
4
- "description": "One-command AI Agent node for CommHub networks. Claude + Codex dual runtime.",
3
+ "version": "2.1.0-preview.10",
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
  },
@@ -14,7 +14,19 @@
14
14
  "build": "bun build src/cli.ts --outfile dist/cli.js --target node --minify --external @anthropic-ai/claude-agent-sdk --external @openai/codex-sdk",
15
15
  "prepublishOnly": "npm run build"
16
16
  },
17
- "keywords": ["agent", "ai", "commhub", "claude", "codex", "gpt5", "sdk", "minimax", "swarm"],
17
+ "keywords": [
18
+ "agent",
19
+ "ai",
20
+ "commhub",
21
+ "claude",
22
+ "codex",
23
+ "gpt5",
24
+ "sdk",
25
+ "minimax",
26
+ "runtime",
27
+ "node",
28
+ "anthropic"
29
+ ],
18
30
  "author": "sleep2agi",
19
31
  "license": "MIT",
20
32
  "repository": {
@@ -22,9 +34,18 @@
22
34
  "url": "https://github.com/sleep2agi/agent-comm-hub",
23
35
  "directory": "agent-node"
24
36
  },
25
- "engines": { "node": ">=18.0.0" },
37
+ "engines": {
38
+ "node": ">=18.0.0"
39
+ },
26
40
  "dependencies": {
27
- "@anthropic-ai/claude-agent-sdk": "^0.2.96",
28
- "@openai/codex-sdk": "^0.118.0"
41
+ "@anthropic-ai/claude-agent-sdk": "^0.2.96"
42
+ },
43
+ "peerDependencies": {
44
+ "@openai/codex-sdk": ">=0.118.0"
45
+ },
46
+ "peerDependenciesMeta": {
47
+ "@openai/codex-sdk": {
48
+ "optional": true
49
+ }
29
50
  }
30
- }
51
+ }