@sleep2agi/agent-node 2.1.2-preview.2 → 2.2.0-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.
- package/dist/cli.js +14 -14
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as
|
|
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(`
|
|
3
3
|
@sleep2agi/agent-node — AI Agent 节点,一行命令加入 CommHub 网络
|
|
4
4
|
|
|
5
5
|
用法:
|
|
@@ -24,23 +24,23 @@ import{createRequire as Mz}from"node:module";var b=Mz(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(
|
|
28
|
-
用法: npx @sleep2agi/agent-node --alias "我的Agent"`),process.exit(1);var
|
|
29
|
-
`),
|
|
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
|
|
31
|
-
`)}catch{}}var V=(z)=>i("info",1,z),
|
|
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(`
|
|
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=[`你是 ${H},一个 AI Agent 节点。收到来自 ${Z}
|
|
34
|
-
`),
|
|
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(`
|
|
34
|
+
`),q=E?`${E}
|
|
35
35
|
|
|
36
36
|
收到来自 ${Z} 的任务:
|
|
37
37
|
|
|
38
|
-
${z}`:
|
|
39
|
-
`),
|
|
40
|
-
`)||"",
|
|
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.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)$+=`
|
|
41
41
|
|
|
42
42
|
[Telegram 附件已下载]
|
|
43
43
|
${Q.map((X)=>`- 图片: ${X}`).join(`
|
|
44
|
-
`)}`;return{text:$.trim(),images:Q}}async function
|
|
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
|
|
46
|
-
`);W=
|
|
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();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sleep2agi/agent-node",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.2.0-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"
|
|
@@ -49,4 +49,4 @@
|
|
|
49
49
|
"optional": true
|
|
50
50
|
}
|
|
51
51
|
}
|
|
52
|
-
}
|
|
52
|
+
}
|