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