@sleep2agi/agent-node 2.3.1 → 2.3.2-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 +15 -16
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as
|
|
2
|
+
import{createRequire as Pz}from"node:module";var R=Pz(import.meta.url);import{readFileSync as d,existsSync as e,writeFileSync as zz,chmodSync as xz}from"fs";import{join as D}from"path";import{hostname as Qz,homedir as Nz}from"os";import{mkdirSync as bz,appendFileSync as dz}from"fs";var __dirname="/home/vansin/agent-orchestra/agent-node/src";var Gz=Nz(),U=process.argv.slice(2),F={},jz=[],Kz="2.1.0";try{let z=new URL(".",import.meta.url).pathname;for(let Z of["../package.json","../../package.json"])try{let $=JSON.parse(d(D(z,Z),"utf-8"));if($.version){Kz=$.version;break}}catch{}}catch{}for(let z=0;z<U.length;z++){if(U[z]==="--version"||U[z]==="-v")console.log(`agent-node v${Kz}`),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 yz}from"node:module";var x=yz(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 模型 (codex
|
|
11
|
+
--runtime <type> claude-agent-sdk (default) | codex-sdk
|
|
12
|
+
--model <name> AI 模型 (codex 默认: gpt-5.4, claude-agent-sdk 默认: claude-sonnet-4-6)
|
|
13
13
|
--hub <url> CommHub URL
|
|
14
14
|
--tools <list> 工具列表,逗号分隔 ("all" = 全部)
|
|
15
15
|
--max-turns <n> 每任务最大轮次 (default: 50)
|
|
@@ -24,23 +24,22 @@ import{createRequire as yz}from"node:module";var x=yz(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 wz=
|
|
29
|
-
`),
|
|
30
|
-
`)){let $=Z.trim();if(!$||$.startsWith("#"))continue;let Q=$.indexOf("=");if(Q<=0)continue;let
|
|
31
|
-
`)}catch{}}var V=(z)=>
|
|
27
|
+
`),process.exit(0);if(U[z]==="--new-session"){F["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)F[U[z].slice(2)]=U[++z]}function Fz(z){return z.replace(/^~(?=\/|$)/,Gz)}function Lz(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:Fz(z.slice(Z+1)),raw:z}}function u(z){if(!e(z))return null;try{return JSON.parse(d(z,"utf-8"))}catch{return null}}var W={},k="";if(F.config){let z=F.config.startsWith("/")?F.config:D(process.cwd(),F.config),Z=u(z);if(Z)W=Z,k=z,console.log(`[agent-node] Config: ${z}`)}var w=F.alias||process.env.COMMHUB_ALIAS||process.env.ALIAS||W.alias;if(!F.config&&w){let z=D(process.cwd(),".anet","nodes",w,"config.json"),Z=D(process.cwd(),".anet","profiles",`${w}.json`),$=e(z)?z:Z,Q=u($);if(Q)W={...Q,...W},k=$,console.log(`[agent-node] Config: ${$}`)}var _=u(D(Gz,".anet","config.json"))||{};if(_.hub&&!W.hub)W.hub=_.hub;if(_.token&&!W.token)W.token=_.token;if(!F.config&&!Object.keys(W).length){let z=u(D(process.cwd(),".agent-node.json"));if(z)W=z,console.log("[agent-node] 配置: .agent-node.json")}if(W.env&&typeof W.env==="object"){for(let[z,Z]of Object.entries(W.env))if(!process.env[z]&&typeof Z==="string")process.env[z]=Fz(Z)}if(!w)console.error(`错误: 必须指定 --alias
|
|
28
|
+
用法: npx @sleep2agi/agent-node --alias "我的Agent"`),process.exit(1);var wz=F.runtime||process.env.RUNTIME||W.runtime||"claude-agent-sdk",Az={"claude-agent-sdk":"claude","claude-sdk":"claude","agent-sdk":"claude",claude:"claude","codex-sdk":"codex",codex:"codex"},E=Az[wz]||"claude",Cz=wz,f=F.url||F.hub||process.env.COMMHUB_URL||W.hub||"http://127.0.0.1:9200",C=F.model||process.env.MODEL||W.model,Oz=["Read","Write","Edit","Bash","Glob","Grep","WebSearch","WebFetch"],Yz=F.tools||(Array.isArray(W.tools)?W.tools.join(","):W.tools)||"",I=Yz==="all"?Oz:Yz.split(",").filter(Boolean),_z=parseInt(F["max-turns"]||W.flags?.maxTurns||W.maxTurns||"50"),Xz=parseFloat(F["max-budget"]||W.flags?.maxBudgetUsd||W.maxBudgetUsd||"0"),n=parseInt(F["claude-timeout-ms"]||process.env.CLAUDE_TIMEOUT_MS||W.flags?.claudeTimeoutMs||W.claudeTimeoutMs||"120000"),Ez=F["new-session"]==="true",O=Ez?"":F.session||W.session||W.resume||W.sessionId||"",T=F.prompt||W.systemPrompt||"",P=W.token||_.token||process.env.COMMHUB_TOKEN||"";if(process.env.COMMHUB_TOKEN&&W.token&&process.env.COMMHUB_TOKEN!==W.token)console.warn(`[${w}] ⚠ COMMHUB_TOKEN env override ignored (using node config token). Unset COMMHUB_TOKEN to silence this warning.`);function Iz(){if(!k)return!1;let z=u(k),Z=typeof z?.token==="string"?z.token:"";if(!Z||Z===P)return!1;return P=Z,W.token=Z,A(`reloaded node token from ${k}`),!0}var Zz=F["log-dir"]||D(process.cwd(),".anet","nodes",w,"logs"),uz={debug:0,info:1,warn:2,error:3},Tz=uz[F["log-level"]||process.env.LOG_LEVEL||W.logLevel||"info"]??1,h=[...(Array.isArray(W.channels)?W.channels:[]).filter((z)=>!z.startsWith("server:")&&!z.startsWith("plugin:")),...jz],Hz=h.map((z)=>{try{return Lz(z)}catch(Z){console.error(`[agent-node] ${Z.message}`),process.exit(1)}});function vz(z){if(!k||!z)return;try{let Z=JSON.parse(d(k,"utf-8"));if(Z.session===z)return;Z.session=z,zz(k,JSON.stringify(Z,null,2)+`
|
|
29
|
+
`),M(`session 写回: ${k} → ${z.slice(0,8)}...`)}catch(Z){A(`writebackSession failed: ${Z.message}`)}}function Sz(z){if(!e(z))return;for(let Z of d(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 hz(z){return D(process.cwd(),".anet","nodes",w,"channels",z)}function pz(z){let Z=z.path||hz("telegram");Sz(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{xz(D(Z,".env"),384)}catch{}let Q=u(D(Z,"access.json"))||{},X=D(Z,"inbox");try{bz(X,{recursive:!0})}catch{}return{type:"telegram",dir:Z,inboxDir:X,token:$,allowFrom:Array.isArray(Q.allowFrom)?Q.allowFrom.map(String):[]}}var l=Hz.filter((z)=>z.type==="telegram").map(pz),Vz=Hz.find((z)=>z.type!=="telegram");if(Vz)console.error(`[agent-node] unsupported channel: ${Vz.raw}`),process.exit(1);if(l.length>0&&E!=="codex"&&!I.includes("Read"))I.push("Read");try{bz(Zz,{recursive:!0})}catch{}function o(z,Z,$){if(Z<Tz)return;let Q=new Date().toTimeString().slice(0,8),X=z.toUpperCase().padEnd(5),Y=`[${Q}] [${X}] [${w}] ${$}`;console.log(Y);try{let q=new Date().toISOString().slice(0,10);dz(D(Zz,`${q}.log`),Y+`
|
|
31
|
+
`)}catch{}}var V=(z)=>o("info",1,z),M=(z)=>o("debug",0,z),A=(z)=>o("warn",2,z),p=(z)=>o("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 X;for(let Y=0;Y<=$;Y++)try{let q=await fetch(`${f}/mcp`,{method:"POST",headers:Q,body:JSON.stringify({jsonrpc:"2.0",id:Date.now(),method:"tools/call",params:{name:z,arguments:Z}})});if(!q.ok&&Y<$){X=Error(`HTTP ${q.status}`),await new Promise((b)=>setTimeout(b,1000*Math.pow(2,Y)));continue}let J=await q.text(),G=J.match(/data: (.+)/),K=G?JSON.parse(G[1]):JSON.parse(J),B=K?.result?.content?.[0]?.text;return B?JSON.parse(B):K}catch(q){if(X=q,Y<$)M(`callCommHub(${z}) attempt ${Y+1} failed: ${q.message}, retrying...`),await new Promise((J)=>setTimeout(J,1000*Math.pow(2,Y)))}throw X||Error(`callCommHub(${z}) failed after ${$} retries`)}var g=W.node_id||"",fz=W.node_name||"",S=W.network_id||process.env.ANET_NETWORK_ID||_.network_id||"",Dz=g?`sdk-${g}`:`sdk-${w}-${Date.now().toString(36)}`,cz=()=>c("report_status",{resume_id:Dz,alias:w,status:"idle",server:Qz(),hostname:Qz(),agent:`agent-node:${E}`,project_dir:process.cwd(),node_id:g||void 0,node_name:fz||void 0,session_id:O||void 0,config_path:k||void 0,channels:h.length?JSON.stringify(h):void 0,model:C||void 0,network_id:S||void 0}),i=(z,Z)=>c("report_status",{resume_id:Dz,alias:w,status:z,task:Z,node_id:g||void 0,session_id:r||O||void 0,config_path:k||void 0,channels:h.length?JSON.stringify(h):void 0,network_id:S||void 0}),mz=async()=>(await c("get_inbox",{alias:w,limit:20}))?.messages||[],nz=(z)=>c("ack_inbox",{alias:w,message_id:z}),rz=(z,Z,$,Q=!1)=>c("send_reply",{alias:z,text:Z,from_session:w,in_reply_to:$||void 0,status:Q?"failed":"replied"}),r=O||void 0;async function lz(z,Z){let{existsSync:$}=await import("fs"),Q=!1;try{let j=R.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 v=R.resolve("@anthropic-ai/claude-agent-sdk-linux-x64/claude");if($(v))Q=!0,V(`[claude] glibc binary installed: ${v}`)}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:
|
|
33
|
+
`);let{query:X}=await import("@anthropic-ai/claude-agent-sdk"),Y=process.env.CURRENT_TASK_ID||"",q=[`你是 ${w},一个 AI Agent 节点。收到来自 ${Z} 的任务 (task_id=${Y}):`,"",z,"","【若任务需要其他 agent 协助】","1. 先用 mcp_commhub__get_all_status 看哪些 agent 在线。",`2. 用 mcp_commhub__send_task(alias, task, parent_task_id="${Y}") 派给合适的 agent。`,` ⚠ 必须把 parent_task_id 设成你当前任务的 ID,这样系统会自动把子任务的最终结果串回给 ${Z}。`,`3. 用 mcp_commhub__get_task(task_id) 轮询子任务状态。允许中途给 ${Z} 发"还在等待"的进度汇报,但你必须继续轮询直到子任务 replied/failed。`,`4. 拿到子任务 reply 后把内容整合到你给 ${Z} 的最终汇报里。`,` 即便你的 session 中途断开,只要 parent_task_id 设了,系统也会自动把子任务结果交付给 ${Z},所以不必焦虑。`,"","【禁止】",`- 不要给自己(${w})发任务(死循环)。`,'- 不要回复"收到""ok""明白了"等无内容确认。',"- 不要在无新任务时主动调用通信工具。",`- send_task 时不要忘记 parent_task_id;忘了就要不回来 ${Z} 的链路。`,"","执行完后简要汇报结果。"].join(`
|
|
34
34
|
`),J=T?`${T}
|
|
35
35
|
|
|
36
36
|
收到来自 ${Z} 的任务:
|
|
37
37
|
|
|
38
|
-
${z}`:
|
|
39
|
-
`),Jz={model_auto_compact_token_limit:200000,developer_instructions:
|
|
40
|
-
`)||"",U=F.usage}else{let b=await fetch(`${j}/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(!b.ok){let I=await b.text();return`OpenAI API 错误 ${b.status}: ${I.slice(0,200)}`}let F=await b.json();w=F.choices?.[0]?.message?.content||"",U=F.usage}let E=Date.now()-G;return V(`[http-api] done | ${E}ms | in=${U?.input_tokens||U?.prompt_tokens||0} out=${U?.output_tokens||U?.completion_tokens||0}`),w||"(无回复)"}var qz=Promise.resolve();function Uz(z,Z,$,Q){let Y=async()=>{let W=process.env.CURRENT_TASK_ID;if($)process.env.CURRENT_TASK_ID=$;else delete process.env.CURRENT_TASK_ID;try{if(_==="codex")return await iz(z,Z,Q);if(_==="http")return await oz(z,Z);return await gz(z,Z)}finally{if(W!==void 0)process.env.CURRENT_TASK_ID=W;else delete process.env.CURRENT_TASK_ID}},X=qz.then(Y,Y);return qz=X.then(()=>{},()=>{}),X}async function az(z,Z,$=null){V(`→ processing [${_}]: ${z.slice(0,80)}`),await o("working",z.slice(0,200)).catch(()=>{});let Q,Y=!1;try{Q=await Uz(z,Z,$)}catch(X){Q=`${_} 错误: ${X.message}`,Y=!0,f(`✗ ${X.message}`)}finally{await o("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 s={},tz=5000,sz=new Set(["收到","好的","ok","嗯","是的","了解","明白","确认","done","ack","roger","yes","no","在线","待命","正常","保持在线","通信正常","已收到","收到了","好","行","noted","copy","received","understood","等待任务","等待中","等待指令","无新任务","idle","waiting"]);function Rz(z,Z=!1){if(!z)return!0;let Q=z.trim().replace(/^[\[【].+?[\]】]\s*/,"").trim().toLowerCase().replace(/[\s。!?.!?✅❌👀⏳,,]+$/g,"").trim();if(sz.has(Q))return!0;if(/^[\p{Emoji}\s]+$/u.test(z.trim())&&!/[0-9a-zA-Z#*]/.test(z))return!0;return!1}function ez(z,Z,$){if(z===H)return"self";if(Z.startsWith(`[${H}]`))return"own-prefix";if(z!=="hub"&&z!=="api"){let Q=Date.now();if(s[z]&&Q-s[z]<tz)return"cooldown"}if($!=="task"&&$!=="broadcast"&&Rz(Z))return"low-value-inbound";return null}async function zZ(){let z=await mz();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 nz(Z.id),Y!=="task"&&Y!=="broadcast"){k(`skip non-task message: type=${Y}`);continue}let X=ez($,Q,Y);if(X){k(`skip message from ${$}: ${X}`);continue}let{text:W,failed:J}=await az(Q,$,Z.id);if(V(`processTask returned: "${W.slice(0,80)}" (${W.length} chars, failed=${J})`),!J&&Rz(W,!0)){V(`skip reply: low-value (${W.slice(0,30)})`);continue}try{V(`sending reply to ${$} (task ${Z.id.slice(0,8)}, status=${J?"failed":"replied"})...`),await lz($,`[${H}] ${W.slice(0,2000)}`,Z.id,J),s[$]=Date.now(),V(`→ [${$}] ${W.slice(0,100)}`)}catch(j){O(`reply failed: ${j.message}`)}}}function Mz(z){return String(z.from?.id||z.chat?.id||"")}function xz(z){return z.from?.username||z.from?.first_name||Mz(z)||"telegram"}function ZZ(z,Z){if(z.allowFrom.length===0)return!0;let $=Mz(Z),Q=Z.from?.username?String(Z.from.username):"";return z.allowFrom.includes($)||!!Q&&z.allowFrom.includes(Q)}async function a(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 Wz(z,Z,$,Q){let Y=$.match(/[\s\S]{1,4096}/g)||["(无回复)"];for(let X=0;X<Y.length;X++)await a(z,"sendMessage",{chat_id:Z,text:Y[X],...Q&&X===0?{reply_to_message_id:Q}:{}})}async function Gz(z,Z,$){let Q=await a(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(),J=($||Y.split("/").pop()||Z).replace(/[^a-zA-Z0-9._-]/g,"_"),j=J.includes(".")||!W?J:`${J}.${W}`,K=R(z.channel.inboxDir,`${Date.now()}_${j}`);return zz(K,Buffer.from(await X.arrayBuffer())),K}async function $Z(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 Gz(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 Gz(z,Z.document.file_id,Z.document.file_name||`image_${Z.message_id}`);Q.push(X)}if(Q.length)$+=`
|
|
38
|
+
${z}`:q,G=process.env.COMMHUB_URL||f,K=process.env.COMMHUB_TOKEN||P,B={};if(G)B.commhub={type:"http",url:`${G}/mcp`,headers:K?{Authorization:`Bearer ${K}`}:void 0};let b=(()=>{try{let{execSync:j}=R("child_process"),v=R("fs");try{let y=R.resolve("@anthropic-ai/claude-agent-sdk-linux-x64/claude");if(v.existsSync(y))return j(`${y} --version`,{stdio:"pipe"}),V(`[claude] using glibc binary: ${y}`),y}catch{}try{let y=j("which claude",{encoding:"utf-8"}).trim();if(y)return V(`[claude] using global binary: ${y}`),y}catch{}V("[claude] no binary resolved, falling back to SDK default");return}catch{return}})(),x={model:C||void 0,tools:I.length?I:void 0,maxTurns:_z,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,settingSources:[],mcpServers:Object.keys(B).length?B:void 0,pathToClaudeCodeExecutable:b,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(Xz>0)x.maxBudgetUsd=Xz;if(T)x.systemPrompt=T;if(r)x.resume=r;let m="",N=Date.now();V(`[claude] claudePath=${b||"SDK default"}, mcpServers=${Object.keys(B).join(",")||"none"}`);let H=!1,t;if(n>0){let j=new AbortController;x.abortController=j,t=setTimeout(()=>{H=!0,j.abort()},n)}try{for await(let j of X({prompt:J,options:x})){let v=j;if(v.type==="system"&&v.subtype==="init")r=v.session_id,V(`[claude] session=${v.session_id?.slice(0,8)} model=${C||"default"}`),vz(v.session_id);if(v.type==="result"){let y=Date.now()-N,$z=v.usage||{};V(`[claude] ${v.subtype} | ${y}ms | $${v.total_cost_usd?.toFixed(4)||"?"} | in=${$z.input_tokens||0} out=${$z.output_tokens||0} | turns=${v.num_turns}`),m=v.subtype==="success"?v.result||"任务完成":`执行出错: ${v.error||v.result||"未知错误"}`}}}catch(j){if(H){let v=Date.now()-N;return V(`[claude] ✗ timed out after ${v}ms (CLAUDE_TIMEOUT_MS=${n}) — aborting query`),`执行出错: claude-agent-sdk 调用超时 (${Math.round(n/1000)}s 无响应) — 检查 ANTHROPIC_BASE_URL endpoint 是否可达且 Anthropic-compatible`}return V(`[claude] ✗ query error: ${String(j?.message||j).slice(0,200)}`),`执行出错: ${String(j?.message||j).slice(0,200)}`}finally{if(t)clearTimeout(t)}return m}var L=null,gz=T||[`你是 ${w},一个 AI Agent 节点,工作目录:${process.cwd()}。`,"你通过通信网络(CommHub)接收任务并和其他 agent 协作。","","【可用通信工具】","- mcp_commhub__send_task(alias, task):派任务给指定 agent,等其 LLM 处理完返回 reply(同步语义)。","- mcp_commhub__send_message(alias, message):发聊天消息(不要求对方回复)。","- mcp_commhub__get_task(task_id):查询某任务的当前状态/reply。","- mcp_commhub__get_all_status():查看网络上所有在线 agent。","","【协作模式】","当你的任务需要其他 agent 的能力时:","1. 先 get_all_status 看哪些 agent 在线。","2. 用 send_task(alias, task, parent_task_id=<env CURRENT_TASK_ID>) 派给合适的 agent。"," ⚠ 必须把 parent_task_id 设成你当前任务的 ID(环境变量 CURRENT_TASK_ID 里),系统会自动把子任务最终结果串回给你的上游。",'3. 用 get_task 轮询子任务直到 status=replied/failed。允许中途汇报"还在等",但要继续轮询。',"4. 拿到 reply 后整合进你给上游的最终汇报。"," 即使你的 session 中途断开,只要 parent_task_id 设了,结果也会被系统自动 chain 回上游,不必焦虑。","","【禁止】",'- 不要回复"收到""好的""ok""在线""待命"等无内容确认。',"- 不要给自己发任务(会死循环)。","- 收到的若是 reply 类型,不要再 send_task 给原方(会乒乓回复)。","- 没有新任务时保持沉默,不主动发消息。","","你的最终回复会被系统自动 send_reply 给任务发起者。"].join(`
|
|
39
|
+
`),Jz={model_auto_compact_token_limit:200000,developer_instructions:gz};async function iz(z,Z,$){try{let{execSync:G}=await import("child_process"),K=G("which codex 2>/dev/null",{encoding:"utf-8"}).trim();if(K){let B=K.replace(/\/codex$/,"");if(!process.env.PATH?.includes(B))process.env.PATH=`${B}:${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(!L){let G=new Q({config:Jz}),B={skipGitRepoCheck:!0,approvalPolicy:"never",model:C||"gpt-5.4",sandboxMode:"danger-full-access",modelReasoningEffort:"low"};if(O)L=G.resumeThread(O,B),V(`codex resumed thread: ${O}`);else L=G.startThread(B)}V(`[codex] model=${C||"gpt-5.4"} thread=${L?.id||"new"}`);let Y=z,q=$?.length?[{type:"text",text:Y},...$.map((G)=>({type:"local_image",path:G}))]:Y,J=Date.now();try{let{events:G}=await L.runStreamed(q),K="",B=null,b=0;for await(let N of G)if(N.type==="item.started"){let H=N.item;M(`[codex] ${H.type}${H.command?`: ${H.command.slice(0,60)}`:H.tool?`: ${H.server}/${H.tool}`:""}`)}else if(N.type==="item.completed"){b++;let H=N.item;if(H.type==="agent_message")K=H.text||"";if(H.type==="command_execution")M(`[codex] cmd exit=${H.exit_code} | ${H.aggregated_output?.slice(0,80)}`);if(H.type==="reasoning")M(`[codex] thinking: ${H.text?.slice(0,80)}`);if(H.type==="mcp_tool_call")M(`[codex] mcp: ${H.server}/${H.tool} → ${H.status}`)}else if(N.type==="turn.completed")B=N.usage;let x=Date.now()-J,m=B?.input_tokens||0;if(V(`[codex] done | ${x}ms | in=${m} out=${B?.output_tokens||0} | items=${b}`),L?.id)vz(L.id);return K||"(无回复)"}catch(G){V(`codex thread error: ${G.message}, 重建`),L=new Q({config:Jz}).startThread({skipGitRepoCheck:!0,approvalPolicy:"never",model:C||"gpt-5.4",sandboxMode:"danger-full-access",modelReasoningEffort:"low"});let B=await L.run(q),b=Date.now()-J;return V(`[codex] retry done | ${b}ms`),B.finalResponse||"(无回复)"}}var Wz=Promise.resolve();function Uz(z,Z,$,Q){let X=async()=>{let q=process.env.CURRENT_TASK_ID;if($)process.env.CURRENT_TASK_ID=$;else delete process.env.CURRENT_TASK_ID;try{if(E==="codex")return await iz(z,Z,Q);return await lz(z,Z)}finally{if(q!==void 0)process.env.CURRENT_TASK_ID=q;else delete process.env.CURRENT_TASK_ID}},Y=Wz.then(X,X);return Wz=Y.then(()=>{},()=>{}),Y}async function az(z,Z,$=null){V(`→ processing [${E}]: ${z.slice(0,80)}`),await i("working",z.slice(0,200)).catch(()=>{});let Q,X=!1;try{Q=await Uz(z,Z,$)}catch(Y){Q=`${E} 错误: ${Y.message}`,X=!0,p(`✗ ${Y.message}`)}finally{await i("idle").catch(()=>{})}if(!X&&/(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))X=!0;return{text:Q,failed:X}}var s={},oz=5000,tz=new Set(["收到","好的","ok","嗯","是的","了解","明白","确认","done","ack","roger","yes","no","在线","待命","正常","保持在线","通信正常","已收到","收到了","好","行","noted","copy","received","understood","等待任务","等待中","等待指令","无新任务","idle","waiting"]);function Rz(z,Z=!1){if(!z)return!0;let Q=z.trim().replace(/^[\[【].+?[\]】]\s*/,"").trim().toLowerCase().replace(/[\s。!?.!?✅❌👀⏳,,]+$/g,"").trim();if(tz.has(Q))return!0;if(/^[\p{Emoji}\s]+$/u.test(z.trim())&&!/[0-9a-zA-Z#*]/.test(z))return!0;return!1}function sz(z,Z,$){if(z===w)return"self";if(Z.startsWith(`[${w}]`))return"own-prefix";if(z!=="hub"&&z!=="api"){let Q=Date.now();if(s[z]&&Q-s[z]<oz)return"cooldown"}if($!=="task"&&$!=="broadcast"&&Rz(Z))return"low-value-inbound";return null}async function ez(){let z=await mz();if(!z.length)return;for(let Z of z){let $=Z.from_session||"hub",Q=Z.content,X=Z.type||"task";if(V(`← [${$}] (${X}/${Z.priority||"normal"}) ${Q.slice(0,100)}`),await nz(Z.id),X!=="task"&&X!=="broadcast"){M(`skip non-task message: type=${X}`);continue}let Y=sz($,Q,X);if(Y){M(`skip message from ${$}: ${Y}`);continue}let{text:q,failed:J}=await az(Q,$,Z.id);if(V(`processTask returned: "${q.slice(0,80)}" (${q.length} chars, failed=${J})`),!J&&Rz(q,!0)){V(`skip reply: low-value (${q.slice(0,30)})`);continue}try{V(`sending reply to ${$} (task ${Z.id.slice(0,8)}, status=${J?"failed":"replied"})...`),await rz($,`[${w}] ${q.slice(0,2000)}`,Z.id,J),s[$]=Date.now(),V(`→ [${$}] ${q.slice(0,100)}`)}catch(G){A(`reply failed: ${G.message}`)}}}function Mz(z){return String(z.from?.id||z.chat?.id||"")}function kz(z){return z.from?.username||z.from?.first_name||Mz(z)||"telegram"}function zZ(z,Z){if(z.allowFrom.length===0)return!0;let $=Mz(Z),Q=Z.from?.username?String(Z.from.username):"";return z.allowFrom.includes($)||!!Q&&z.allowFrom.includes(Q)}async function a(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 qz(z,Z,$,Q){let X=$.match(/[\s\S]{1,4096}/g)||["(无回复)"];for(let Y=0;Y<X.length;Y++)await a(z,"sendMessage",{chat_id:Z,text:X[Y],...Q&&Y===0?{reply_to_message_id:Q}:{}})}async function Bz(z,Z,$){let Q=await a(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 q=X.split(".").pop(),J=($||X.split("/").pop()||Z).replace(/[^a-zA-Z0-9._-]/g,"_"),G=J.includes(".")||!q?J:`${J}.${q}`,K=D(z.channel.inboxDir,`${Date.now()}_${G}`);return zz(K,Buffer.from(await Y.arrayBuffer())),K}async function ZZ(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],q=await Bz(z,Y.file_id,`photo_${Z.message_id}.jpg`);Q.push(q)}let X=String(Z.document?.mime_type||"");if(Z.document&&X.startsWith("image/")){let Y=await Bz(z,Z.document.file_id,Z.document.file_name||`image_${Z.message_id}`);Q.push(Y)}if(Q.length)$+=`
|
|
41
40
|
|
|
42
41
|
[Telegram 附件已下载]
|
|
43
|
-
${Q.map((
|
|
44
|
-
`)}`;return{text:$.trim(),images:Q}}async function
|
|
45
|
-
`)}catch{}},
|
|
46
|
-
`);
|
|
42
|
+
${Q.map((Y)=>`- 图片: ${Y}`).join(`
|
|
43
|
+
`)}`;return{text:$.trim(),images:Q}}async function $Z(z,Z){if(!zZ(z.channel,Z))return;let $=Z.chat?.id,Q=Z.message_id,X=`telegram:${kz(Z)}`,{text:Y,images:q}=await ZZ(z,Z);if(!$||!Q||!Y)return;M(`[TG] processing: ${Y.slice(0,80)}`);try{let J=await Uz(Y,X,q);await qz(z,$,J,Q),V(`→ [${X}] ${J.slice(0,100)}`)}catch(J){p(`telegram task failed: ${J.message}`),await qz(z,$,`处理出错: ${J.message}`,Q).catch(()=>{})}}async function QZ(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 J=await a(Z,"getMe",{});V(`Telegram bot: @${J.username} (${J.first_name})`)}catch(J){p(`Telegram token 无效: ${J.message}`),process.exit(1)}let $=D(z.dir,"state.json");try{let J=JSON.parse(d($,"utf-8"));if(J.offset)Z.offset=J.offset,M(`Telegram offset restored: ${Z.offset}`)}catch{}let Q=()=>{try{zz($,JSON.stringify({offset:Z.offset})+`
|
|
44
|
+
`)}catch{}},X=!1,Y=[];async function q(){if(X)return;X=!0;while(Y.length){let{msg:J,updateId:G}=Y.shift();try{await $Z(Z,J),Z.offset=G+1,Q()}catch(K){p(`TG handle: ${K.message}`)}}X=!1}V(`Telegram polling: ${z.dir}`);while(!0)try{let G=await(await fetch(`${Z.apiBase}/getUpdates?offset=${Z.offset}&timeout=30`)).json();if(!G.ok)throw Error(G.description||"getUpdates failed");for(let K of G.result||[])if(Z.offset=K.update_id+1,K.message){let B=K.message,b=kz(B),x=B.text||B.caption||"";if(V(`← TG [${b}] ${x.slice(0,80)}${B.photo?" +img":""}${B.document?" +file":""}`),B.chat?.id&&B.message_id)a(Z,"setMessageReaction",{chat_id:B.chat.id,message_id:B.message_id,reaction:[{type:"emoji",emoji:Y.length>0?"⏳":"\uD83D\uDC40"}]}).catch(()=>{});Y.push({msg:B,updateId:K.update_id}),q()}}catch(J){A(`Telegram polling error: ${J.message}`),await new Promise((G)=>setTimeout(G,3000))}}async function YZ(){let z=`${f}/events/${encodeURIComponent(w)}`,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){if(Iz()){A(`SSE 401: ntok_ 已刷新,正在用 .anet/nodes/${w}/config.json 里的新 token 重试`),await new Promise((J)=>setTimeout(J,500));continue}p("SSE 401: ntok_ 已失效(hub DB 可能被重置或 token 被撤销)。试 `anet doctor --fix`")}else A(`SSE failed: ${Q.status}`);await new Promise((J)=>setTimeout(J,Z)),Z=Math.min(Z*1.5,60000);continue}Z=3000;let X=Q.body.getReader(),Y=new TextDecoder,q="";while(!0){let{done:J,value:G}=await X.read();if(J)break;q+=Y.decode(G,{stream:!0});let K=q.split(`
|
|
45
|
+
`);q=K.pop()||"";for(let B of K){if(!B.startsWith("data: "))continue;try{let b=JSON.parse(B.slice(6));if(b.type==="connected"){V("SSE connected");continue}if(["new_task","broadcast"].includes(b.type))V(`← SSE ${b.type}`),await ez();if(b.type==="new_reply")V(`← SSE reply from ${b.from||"?"}${b.in_reply_to?` (task ${b.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)}}V("启动");V(` runtime: ${Cz}`);V(` model: ${C||(E==="codex"?"gpt-5.4":"claude-sonnet-4-6")} ${C?"":"(default)"}`);V(` hub: ${f}${P?" (auth)":" (no auth!)"}`);if(P)try{let z=await fetch(`${f}/api/auth/me`,{headers:{Authorization:`Bearer ${P}`}}).then((Z)=>Z.json()).catch(()=>null);if(z?.ok&&z.user)if(V(` user: ${z.user.username} (${z.user.role})`),z.current_network){let Z=z.networks?.find(($)=>$.network_id===z.current_network)?.network_name;V(` network: ${Z||z.current_network}`)}else V(` network: ${S||"(global)"}`);else if(z?.ok===!1)V(` network: ${S||"(global)"}`);else A(" token 验证失败 — 检查 token 是否有效。运行: anet login")}catch{V(` network: ${S||"(global)"}`)}else A(" 未配置 token — agent 数据不隔离。运行: anet login");V(` tools: ${I.length?`[${I.join(",")}]`:"(none)"}`);V(` channels:${l.length?` telegram(${l.map((z)=>z.dir).join(",")})`:" (none)"}`);V(` session: ${O||"(new)"}`);V(` log-dir: ${Zz}`);await cz();V("已注册到 CommHub");setInterval(()=>i("idle").catch(()=>{}),180000);var yz=async()=>{V("shutting down..."),await i("offline").catch(()=>{}),process.exit(0)};process.on("SIGINT",yz);process.on("SIGTERM",yz);for(let z of l)QZ(z);YZ();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sleep2agi/agent-node",
|
|
3
|
-
"version": "2.3.
|
|
3
|
+
"version": "2.3.2-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"
|