@sleep2agi/agent-node 1.3.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +12 -12
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as jz}from"node:module";var n=jz(import.meta.url);import{readFileSync as S,existsSync as c,writeFileSync as d,chmodSync as Fz}from"fs";import{join as D}from"path";import{hostname as l,homedir as wz}from"os";import{mkdirSync as Wz,appendFileSync as Nz}from"fs";var zz=wz(),v=process.argv.slice(2),j={},Zz=[],Dz="1.3.0";for(let z=0;z<v.length;z++){if(v[z]==="--version"||v[z]==="-v")console.log(`agent-node v${Dz}`),process.exit(0);if(v[z]==="-h"||v[z]==="--help")console.log(`
2
+ import{createRequire as jz}from"node:module";var l=jz(import.meta.url);import{readFileSync as S,existsSync as d,writeFileSync as m,chmodSync as Fz}from"fs";import{join as D}from"path";import{hostname as i,homedir as wz}from"os";import{mkdirSync as Xz,appendFileSync as Mz}from"fs";var zz=wz(),H=process.argv.slice(2),F={},Zz=[],Dz="1.3.1";for(let z=0;z<H.length;z++){if(H[z]==="--version"||H[z]==="-v")console.log(`agent-node v${Dz}`),process.exit(0);if(H[z]==="-h"||H[z]==="--help")console.log(`
3
3
  @sleep2agi/agent-node — AI Agent 节点,一行命令加入 CommHub 网络
4
4
 
5
5
  用法:
@@ -24,20 +24,20 @@ import{createRequire as jz}from"node:module";var n=jz(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(v[z]==="--channel"&&z+1<v.length){Zz.push(v[++z]);continue}if(v[z].startsWith("--")&&z+1<v.length)j[v[z].slice(2)]=v[++z]}function $z(z){return z.replace(/^~(?=\/|$)/,zz)}function vz(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:$z(z.slice(Z+1)),raw:z}}function E(z){if(!c(z))return null;try{return JSON.parse(S(z,"utf-8"))}catch{return null}}var K={},x="";if(j.config){let z=j.config.startsWith("/")?j.config:D(process.cwd(),j.config),Z=E(z);if(Z)K=Z,x=z,console.log(`[agent-node] Config: ${z}`)}var w=j.alias||process.env.COMMHUB_ALIAS||process.env.ALIAS||K.alias;if(!j.config&&w){let z=D(process.cwd(),".anet","nodes",w,"config.json"),Z=D(process.cwd(),".anet","profiles",`${w}.json`),$=c(z)?z:Z,Y=E($);if(Y){if(K={...Y,...K},x=$,console.log(`[agent-node] Config: ${$}`),Y.env&&typeof Y.env==="object"){for(let[Q,V]of Object.entries(Y.env))if(!process.env[Q]&&typeof V==="string")process.env[Q]=$z(V)}}}var k=E(D(zz,".anet","config.json"))||{};if(k.hub&&!K.hub)K.hub=k.hub;if(k.token&&!K.token)K.token=k.token;if(!j.config&&!Object.keys(K).length){let z=E(D(process.cwd(),".agent-node.json"));if(z)K=z,console.log("[agent-node] 配置: .agent-node.json")}if(!w)console.error(`错误: 必须指定 --alias
28
- 用法: npx @sleep2agi/agent-node --alias "我的Agent"`),process.exit(1);var Yz=j.runtime||process.env.RUNTIME||K.runtime||"claude-agent-sdk",Hz={"claude-agent-sdk":"claude","claude-sdk":"claude","agent-sdk":"claude",claude:"claude","codex-sdk":"codex",codex:"codex"},y=Hz[Yz]||"claude",bz=Yz,m=j.url||j.hub||process.env.COMMHUB_URL||K.hub||"http://127.0.0.1:9200",P=j.model||process.env.MODEL||K.model,Uz=["Read","Write","Edit","Bash","Glob","Grep","WebSearch","WebFetch"],i=j.tools||(Array.isArray(K.tools)?K.tools.join(","):K.tools)||"",M=i==="all"?Uz:i.split(",").filter(Boolean),Pz=parseInt(j["max-turns"]||K.flags?.maxTurns||K.maxTurns||"5"),g=parseFloat(j["max-budget"]||K.flags?.maxBudgetUsd||K.maxBudgetUsd||"0"),_=j.session||K.session||K.resume||K.sessionId||"",a=j.prompt||K.systemPrompt||"",N=process.env.COMMHUB_TOKEN||K.token||k.token||"",r=j["log-dir"]||D(process.cwd(),".anet","nodes",w,"logs"),Rz={debug:0,info:1,warn:2,error:3},xz=Rz[j["log-level"]||process.env.LOG_LEVEL||K.logLevel||"info"]??1,yz=[...(Array.isArray(K.channels)?K.channels:[]).filter((z)=>!z.startsWith("server:")&&!z.startsWith("plugin:")),...Zz],Qz=yz.map((z)=>{try{return vz(z)}catch(Z){console.error(`[agent-node] ${Z.message}`),process.exit(1)}});function Vz(z){if(!x||!z)return;try{let Z=JSON.parse(S(x,"utf-8"));if(Z.session===z)return;Z.session=z,d(x,JSON.stringify(Z,null,2)+`
29
- `),H(`session 写回: ${x} → ${z.slice(0,8)}...`)}catch{}}function Mz(z){if(!c(z))return;for(let Z of S(z,"utf-8").split(`
30
- `)){let $=Z.trim();if(!$||$.startsWith("#"))continue;let Y=$.indexOf("=");if(Y<=0)continue;let Q=$.slice(0,Y).trim(),V=$.slice(Y+1).trim().replace(/^['"]|['"]$/g,"");if(!process.env[Q])process.env[Q]=V}}function _z(z){return D(process.cwd(),".anet","nodes",w,"channels",z)}function kz(z){let Z=z.path||_z("telegram");Mz(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{Fz(D(Z,".env"),384)}catch{}let Y=E(D(Z,"access.json"))||{},Q=D(Z,"inbox");try{Wz(Q,{recursive:!0})}catch{}return{type:"telegram",dir:Z,inboxDir:Q,token:$,allowFrom:Array.isArray(Y.allowFrom)?Y.allowFrom.map(String):[]}}var C=Qz.filter((z)=>z.type==="telegram").map(kz),o=Qz.find((z)=>z.type!=="telegram");if(o)console.error(`[agent-node] unsupported channel: ${o.raw}`),process.exit(1);if(C.length>0&&y!=="codex"&&!M.includes("Read"))M.push("Read");try{Wz(r,{recursive:!0})}catch{}function u(z,Z,$){if(Z<xz)return;let Y=new Date().toTimeString().slice(0,8),Q=z.toUpperCase().padEnd(5),V=`[${Y}] [${Q}] [${w}] ${$}`;console.log(V);try{let J=new Date().toISOString().slice(0,10);Nz(D(r,`${J}.log`),V+`
31
- `)}catch{}}var B=(z)=>u("info",1,z),H=(z)=>u("debug",0,z),T=(z)=>u("warn",2,z),O=(z)=>u("error",3,z);async function A(z,Z){let $={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(N)$.Authorization=`Bearer ${N}`;let Q=await(await fetch(`${m}/mcp`,{method:"POST",headers:$,body:JSON.stringify({jsonrpc:"2.0",id:Date.now(),method:"tools/call",params:{name:z,arguments:Z}})})).text(),V=Q.match(/data: (.+)/),J=V?JSON.parse(V[1]):JSON.parse(Q),W=J?.result?.content?.[0]?.text;return W?JSON.parse(W):J}var Xz=`sdk-${w}-${Date.now().toString(36)}`,Oz=()=>A("report_status",{resume_id:Xz,alias:w,status:"idle",server:l(),hostname:l(),agent:`agent-node:${y}`,project_dir:process.cwd()}),L=(z,Z)=>A("report_status",{resume_id:Xz,alias:w,status:z,task:Z}),Ez=async()=>(await A("get_inbox",{alias:w,limit:5}))?.messages||[],Az=(z)=>A("ack_inbox",{alias:w,message_id:z}),Cz=(z,Z)=>A("send_task",{alias:z,task:Z,priority:"normal",from_session:w}),f=_||void 0;async function Tz(z,Z){let{query:$}=await import("@anthropic-ai/claude-agent-sdk"),Y=`你是 ${w},收到来自 ${Z} 的任务:
27
+ `),process.exit(0);if(H[z]==="--channel"&&z+1<H.length){Zz.push(H[++z]);continue}if(H[z].startsWith("--")&&z+1<H.length)F[H[z].slice(2)]=H[++z]}function $z(z){return z.replace(/^~(?=\/|$)/,zz)}function vz(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:$z(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 K={},y="";if(F.config){let z=F.config.startsWith("/")?F.config:D(process.cwd(),F.config),Z=C(z);if(Z)K=Z,y=z,console.log(`[agent-node] Config: ${z}`)}var j=F.alias||process.env.COMMHUB_ALIAS||process.env.ALIAS||K.alias;if(!F.config&&j){let z=D(process.cwd(),".anet","nodes",j,"config.json"),Z=D(process.cwd(),".anet","profiles",`${j}.json`),$=d(z)?z:Z,Q=C($);if(Q){if(K={...Q,...K},y=$,console.log(`[agent-node] Config: ${$}`),Q.env&&typeof Q.env==="object"){for(let[V,W]of Object.entries(Q.env))if(!process.env[V]&&typeof W==="string")process.env[V]=$z(W)}}}var _=C(D(zz,".anet","config.json"))||{};if(_.hub&&!K.hub)K.hub=_.hub;if(_.token&&!K.token)K.token=_.token;if(!F.config&&!Object.keys(K).length){let z=C(D(process.cwd(),".agent-node.json"));if(z)K=z,console.log("[agent-node] 配置: .agent-node.json")}if(!j)console.error(`错误: 必须指定 --alias
28
+ 用法: npx @sleep2agi/agent-node --alias "我的Agent"`),process.exit(1);var Qz=F.runtime||process.env.RUNTIME||K.runtime||"claude-agent-sdk",Hz={"claude-agent-sdk":"claude","claude-sdk":"claude","agent-sdk":"claude",claude:"claude","codex-sdk":"codex",codex:"codex"},P=Hz[Qz]||"claude",bz=Qz,r=F.url||F.hub||process.env.COMMHUB_URL||K.hub||"http://127.0.0.1:9200",x=F.model||process.env.MODEL||K.model,Uz=["Read","Write","Edit","Bash","Glob","Grep","WebSearch","WebFetch"],g=F.tools||(Array.isArray(K.tools)?K.tools.join(","):K.tools)||"",k=g==="all"?Uz:g.split(",").filter(Boolean),xz=parseInt(F["max-turns"]||K.flags?.maxTurns||K.maxTurns||"5"),a=parseFloat(F["max-budget"]||K.flags?.maxBudgetUsd||K.maxBudgetUsd||"0"),N=F.session||K.session||K.resume||K.sessionId||"",A=F.prompt||K.systemPrompt||"",M=process.env.COMMHUB_TOKEN||K.token||_.token||"",n=F["log-dir"]||D(process.cwd(),".anet","nodes",j,"logs"),Rz={debug:0,info:1,warn:2,error:3},yz=Rz[F["log-level"]||process.env.LOG_LEVEL||K.logLevel||"info"]??1,Pz=[...(Array.isArray(K.channels)?K.channels:[]).filter((z)=>!z.startsWith("server:")&&!z.startsWith("plugin:")),...Zz],Vz=Pz.map((z)=>{try{return vz(z)}catch(Z){console.error(`[agent-node] ${Z.message}`),process.exit(1)}});function Wz(z){if(!y||!z)return;try{let Z=JSON.parse(S(y,"utf-8"));if(Z.session===z)return;Z.session=z,m(y,JSON.stringify(Z,null,2)+`
29
+ `),b(`session 写回: ${y} → ${z.slice(0,8)}...`)}catch{}}function kz(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 V=$.slice(0,Q).trim(),W=$.slice(Q+1).trim().replace(/^['"]|['"]$/g,"");if(!process.env[V])process.env[V]=W}}function Nz(z){return D(process.cwd(),".anet","nodes",j,"channels",z)}function _z(z){let Z=z.path||Nz("telegram");kz(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{Fz(D(Z,".env"),384)}catch{}let Q=C(D(Z,"access.json"))||{},V=D(Z,"inbox");try{Xz(V,{recursive:!0})}catch{}return{type:"telegram",dir:Z,inboxDir:V,token:$,allowFrom:Array.isArray(Q.allowFrom)?Q.allowFrom.map(String):[]}}var T=Vz.filter((z)=>z.type==="telegram").map(_z),o=Vz.find((z)=>z.type!=="telegram");if(o)console.error(`[agent-node] unsupported channel: ${o.raw}`),process.exit(1);if(T.length>0&&P!=="codex"&&!k.includes("Read"))k.push("Read");try{Xz(n,{recursive:!0})}catch{}function h(z,Z,$){if(Z<yz)return;let Q=new Date().toTimeString().slice(0,8),V=z.toUpperCase().padEnd(5),W=`[${Q}] [${V}] [${j}] ${$}`;console.log(W);try{let q=new Date().toISOString().slice(0,10);Mz(D(n,`${q}.log`),W+`
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 E(z,Z){let $={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(M)$.Authorization=`Bearer ${M}`;let V=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(),W=V.match(/data: (.+)/),q=W?JSON.parse(W[1]):JSON.parse(V),X=q?.result?.content?.[0]?.text;return X?JSON.parse(X):q}var Yz=`sdk-${j}-${Date.now().toString(36)}`,Oz=()=>E("report_status",{resume_id:Yz,alias:j,status:"idle",server:i(),hostname:i(),agent:`agent-node:${P}`,project_dir:process.cwd()}),I=(z,Z)=>E("report_status",{resume_id:Yz,alias:j,status:z,task:Z}),Cz=async()=>(await E("get_inbox",{alias:j,limit:5}))?.messages||[],Ez=(z)=>E("ack_inbox",{alias:j,message_id:z}),Az=(z,Z)=>E("send_task",{alias:z,task:Z,priority:"normal",from_session:j}),p=N||void 0;async function Tz(z,Z){let{query:$}=await import("@anthropic-ai/claude-agent-sdk"),Q=`你是 ${j},收到来自 ${Z} 的任务:
32
32
 
33
33
  ${z}
34
34
 
35
- 执行完后简要汇报结果。`,Q={model:P||void 0,tools:M.length?M:void 0,maxTurns:Pz,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,settingSources:[],env:process.env,cwd:process.cwd(),stderr:(W)=>{if(W.trim())H(`[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(g>0)Q.maxBudgetUsd=g;if(a)Q.systemPrompt=a;if(f)Q.resume=f;let V="",J=Date.now();for await(let W of $({prompt:Y,options:Q})){let X=W;if(X.type==="system"&&X.subtype==="init")f=X.session_id,B(`[claude] session=${X.session_id?.slice(0,8)} model=${P||"default"}`),Vz(X.session_id);if(X.type==="result"){let G=Date.now()-J,q=X.usage||{};B(`[claude] ${X.subtype} | ${G}ms | $${X.total_cost_usd?.toFixed(4)||"?"} | in=${q.input_tokens||0} out=${q.output_tokens||0} | turns=${X.num_turns}`),V=X.subtype==="success"?X.result||"任务完成":`执行出错: ${X.error||X.result||"未知错误"}`}}return V}var U=null;async function Lz(z,Z,$){let{Codex:Y}=await import("@openai/codex-sdk");if(!U){let X=new Y({config:{model_auto_compact_token_limit:200000}}),q={skipGitRepoCheck:!0,approvalPolicy:"never",model:P||"gpt-5.4",sandboxMode:"danger-full-access",modelReasoningEffort:"low"};if(_)U=X.resumeThread(_,q),B(`codex resumed thread: ${_}`);else U=X.startThread(q)}B(`[codex] model=${P||"gpt-5.4"} thread=${U?.id||"new"}`);let V=`${z}
35
+ 执行完后简要汇报结果。`,V={model:x||void 0,tools:k.length?k:void 0,maxTurns:xz,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,settingSources:[],env:process.env,cwd:process.cwd(),stderr:(X)=>{if(X.trim())b(`[stderr] ${X.trim().slice(0,200)}`)},hooks:{PreToolUse:[{hooks:[async(X)=>{return B(`[tool] ${X.tool_name}(${JSON.stringify(X.tool_input).slice(0,80)})`),{continue:!0}}]}]}};if(a>0)V.maxBudgetUsd=a;if(A)V.systemPrompt=A;if(p)V.resume=p;let W="",q=Date.now();for await(let X of $({prompt:Q,options:V})){let Y=X;if(Y.type==="system"&&Y.subtype==="init")p=Y.session_id,B(`[claude] session=${Y.session_id?.slice(0,8)} model=${x||"default"}`),Wz(Y.session_id);if(Y.type==="result"){let G=Date.now()-q,J=Y.usage||{};B(`[claude] ${Y.subtype} | ${G}ms | $${Y.total_cost_usd?.toFixed(4)||"?"} | in=${J.input_tokens||0} out=${J.output_tokens||0} | turns=${Y.num_turns}`),W=Y.subtype==="success"?Y.result||"任务完成":`执行出错: ${Y.error||Y.result||"未知错误"}`}}return W}var U=null;async function Lz(z,Z,$){let{Codex:Q}=await import("@openai/codex-sdk");if(!U){let Y=A||`你是 ${j},一个 AI Agent 节点。你通过 CommHub 通信网络接收任务。收到任务后理解内容、执行任务(可以读写文件、执行命令)、返回执行结果。你的回复会被自动发送给任务发送者。当前工作目录:${process.cwd()}`,G=new Q({config:{model_auto_compact_token_limit:200000,developer_instructions:Y}}),v={skipGitRepoCheck:!0,approvalPolicy:"never",model:x||"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=${x||"gpt-5.4"} thread=${U?.id||"new"}`);let W=`${z}
36
36
 
37
- (直接回答,不要调用任何通信工具,不要发消息给其他人)`,J=$?.length?[{type:"text",text:V},...$.map((X)=>({type:"local_image",path:X}))]:V,W=Date.now();try{let{events:X}=await U.runStreamed(J),G="",q=null,b=0;for await(let R of X)if(R.type==="item.started"){let F=R.item;H(`[codex] ${F.type}${F.command?`: ${F.command.slice(0,60)}`:F.tool?`: ${F.server}/${F.tool}`:""}`)}else if(R.type==="item.completed"){b++;let F=R.item;if(F.type==="agent_message")G=F.text||"";if(F.type==="command_execution")H(`[codex] cmd exit=${F.exit_code} | ${F.aggregated_output?.slice(0,80)}`);if(F.type==="reasoning")H(`[codex] thinking: ${F.text?.slice(0,80)}`);if(F.type==="mcp_tool_call")H(`[codex] mcp: ${F.server}/${F.tool} → ${F.status}`)}else if(R.type==="turn.completed")q=R.usage;let h=Date.now()-W,Gz=q?.input_tokens||0;if(B(`[codex] done | ${h}ms | in=${Gz} out=${q?.output_tokens||0} | items=${b}`),U?.id)Vz(U.id);return G||"(无回复)"}catch(X){B(`codex thread error: ${X.message}, 重建`),U=new Y({config:{model_auto_compact_token_limit:200000}}).startThread({skipGitRepoCheck:!0,approvalPolicy:"never",model:P||"gpt-5.4",sandboxMode:"danger-full-access",modelReasoningEffort:"low"});let q=await U.run(J),b=Date.now()-W;return B(`[codex] retry done | ${b}ms`),q.finalResponse||"(无回复)"}}var t=Promise.resolve();function Kz(z,Z,$){let Y=async()=>{if(y==="codex")return Lz(z,Z,$);return Tz(z,Z)},Q=t.then(Y,Y);return t=Q.then(()=>{},()=>{}),Q}async function Iz(z,Z){B(`→ processing [${y}]: ${z.slice(0,80)}`),await L("working",z.slice(0,200));let $;try{$=await Kz(z,Z)}catch(Y){$=`${y} 错误: ${Y.message}`,O(`✗ ${Y.message}`)}return await L("idle"),$}var p={},Sz=5000;function uz(z,Z){if(z===w)return"self";if(Z.startsWith(`[${w}]`))return"own-prefix";let $=Date.now();if(p[z]&&$-p[z]<Sz)return"cooldown";return null}async function hz(){let z=await Ez();if(!z.length)return;for(let Z of z){let $=Z.from_session||"hub",Y=Z.content;B(`← [${$}] (${Z.priority||"normal"}) ${Y.slice(0,100)}`),await Az(Z.id);let Q=uz($,Y);if(Q){H(`skip message from ${$}: ${Q}`);continue}let V=await Iz(Y,$);p[$]=Date.now();try{await Cz($,`[${w}] ${V.slice(0,2000)}`),B(`→ [${$}] ${V.slice(0,100)}`)}catch(J){T(`reply failed: ${J.message}`)}}}function Bz(z){return String(z.from?.id||z.chat?.id||"")}function qz(z){return z.from?.username||z.from?.first_name||Bz(z)||"telegram"}function fz(z,Z){if(z.allowFrom.length===0)return!0;let $=Bz(Z),Y=Z.from?.username?String(Z.from.username):"";return z.allowFrom.includes($)||!!Y&&z.allowFrom.includes(Y)}async function I(z,Z,$){let Y=await fetch(`${z.apiBase}/${Z}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify($)}),Q=await Y.json();if(!Q.ok)throw Error(`telegram ${Z} failed: ${Q.description||Y.statusText}`);return Q.result}async function s(z,Z,$,Y){let Q=$.match(/[\s\S]{1,4096}/g)||["(无回复)"];for(let V=0;V<Q.length;V++)await I(z,"sendMessage",{chat_id:Z,text:Q[V],...Y&&V===0?{reply_to_message_id:Y}:{}})}async function e(z,Z,$){let Y=await I(z,"getFile",{file_id:Z}),Q=String(Y.file_path||""),V=await fetch(`${z.fileBase}/${Q}`);if(!V.ok)throw Error(`telegram file download failed: ${V.status} ${V.statusText}`);let J=Q.split(".").pop(),W=($||Q.split("/").pop()||Z).replace(/[^a-zA-Z0-9._-]/g,"_"),X=W.includes(".")||!J?W:`${W}.${J}`,G=D(z.channel.inboxDir,`${Date.now()}_${X}`);return d(G,Buffer.from(await V.arrayBuffer())),G}async function pz(z,Z){let $=Z.text||Z.caption||"",Y=[];if(Array.isArray(Z.photo)&&Z.photo.length>0){let V=Z.photo[Z.photo.length-1],J=await e(z,V.file_id,`photo_${Z.message_id}.jpg`);Y.push(J)}let Q=String(Z.document?.mime_type||"");if(Z.document&&Q.startsWith("image/")){let V=await e(z,Z.document.file_id,Z.document.file_name||`image_${Z.message_id}`);Y.push(V)}if(Y.length)$+=`
37
+ (直接回答,不要调用任何通信工具,不要发消息给其他人)`,q=$?.length?[{type:"text",text:W},...$.map((Y)=>({type:"local_image",path:Y}))]:W,X=Date.now();try{let{events:Y}=await U.runStreamed(q),G="",J=null,v=0;for await(let R of Y)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()-X,Gz=J?.input_tokens||0;if(B(`[codex] done | ${f}ms | in=${Gz} out=${J?.output_tokens||0} | items=${v}`),U?.id)Wz(U.id);return G||"(无回复)"}catch(Y){B(`codex thread error: ${Y.message}, 重建`),U=new Q({config:{model_auto_compact_token_limit:200000,developer_instructions:A||`你是 ${j},一个 AI Agent 节点。`}}).startThread({skipGitRepoCheck:!0,approvalPolicy:"never",model:x||"gpt-5.4",sandboxMode:"danger-full-access",modelReasoningEffort:"low"});let J=await U.run(q),v=Date.now()-X;return B(`[codex] retry done | ${v}ms`),J.finalResponse||"(无回复)"}}var t=Promise.resolve();function Kz(z,Z,$){let Q=async()=>{if(P==="codex")return Lz(z,Z,$);return Tz(z,Z)},V=t.then(Q,Q);return t=V.then(()=>{},()=>{}),V}async function Iz(z,Z){B(`→ processing [${P}]: ${z.slice(0,80)}`),await I("working",z.slice(0,200));let $;try{$=await Kz(z,Z)}catch(Q){$=`${P} 错误: ${Q.message}`,O(`✗ ${Q.message}`)}return await I("idle"),$}var c={},uz=5000;function Sz(z,Z){if(z===j)return"self";if(Z.startsWith(`[${j}]`))return"own-prefix";let $=Date.now();if(c[z]&&$-c[z]<uz)return"cooldown";return null}async function hz(){let z=await Cz();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 Ez(Z.id);let V=Sz($,Q);if(V){b(`skip message from ${$}: ${V}`);continue}let W=await Iz(Q,$);c[$]=Date.now();try{await Az($,`[${j}] ${W.slice(0,2000)}`),B(`→ [${$}] ${W.slice(0,100)}`)}catch(q){L(`reply failed: ${q.message}`)}}}function Bz(z){return String(z.from?.id||z.chat?.id||"")}function qz(z){return z.from?.username||z.from?.first_name||Bz(z)||"telegram"}function fz(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 u(z,Z,$){let Q=await fetch(`${z.apiBase}/${Z}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify($)}),V=await Q.json();if(!V.ok)throw Error(`telegram ${Z} failed: ${V.description||Q.statusText}`);return V.result}async function s(z,Z,$,Q){let V=$.match(/[\s\S]{1,4096}/g)||["(无回复)"];for(let W=0;W<V.length;W++)await u(z,"sendMessage",{chat_id:Z,text:V[W],...Q&&W===0?{reply_to_message_id:Q}:{}})}async function e(z,Z,$){let Q=await u(z,"getFile",{file_id:Z}),V=String(Q.file_path||""),W=await fetch(`${z.fileBase}/${V}`);if(!W.ok)throw Error(`telegram file download failed: ${W.status} ${W.statusText}`);let q=V.split(".").pop(),X=($||V.split("/").pop()||Z).replace(/[^a-zA-Z0-9._-]/g,"_"),Y=X.includes(".")||!q?X:`${X}.${q}`,G=D(z.channel.inboxDir,`${Date.now()}_${Y}`);return m(G,Buffer.from(await W.arrayBuffer())),G}async function pz(z,Z){let $=Z.text||Z.caption||"",Q=[];if(Array.isArray(Z.photo)&&Z.photo.length>0){let W=Z.photo[Z.photo.length-1],q=await e(z,W.file_id,`photo_${Z.message_id}.jpg`);Q.push(q)}let V=String(Z.document?.mime_type||"");if(Z.document&&V.startsWith("image/")){let W=await e(z,Z.document.file_id,Z.document.file_name||`image_${Z.message_id}`);Q.push(W)}if(Q.length)$+=`
38
38
 
39
39
  [Telegram 附件已下载]
40
- ${Y.map((V)=>`- 图片: ${V}`).join(`
41
- `)}`;return{text:$.trim(),images:Y}}async function cz(z,Z){if(!fz(z.channel,Z))return;let $=Z.chat?.id,Y=Z.message_id,Q=`telegram:${qz(Z)}`,{text:V,images:J}=await pz(z,Z);if(!$||!Y||!V)return;H(`[TG] processing: ${V.slice(0,80)}`);try{let W=await Kz(V,Q,J);await s(z,$,W,Y),B(`→ [${Q}] ${W.slice(0,100)}`)}catch(W){O(`telegram task failed: ${W.message}`),await s(z,$,`处理出错: ${W.message}`,Y).catch(()=>{})}}async function dz(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 I(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,H(`Telegram offset restored: ${Z.offset}`)}catch{}let Y=()=>{try{d($,JSON.stringify({offset:Z.offset})+`
42
- `)}catch{}},Q=!1,V=[];async function J(){if(Q)return;Q=!0;while(V.length){let{msg:W,updateId:X}=V.shift();try{await cz(Z,W),Z.offset=X+1,Y()}catch(G){O(`TG handle: ${G.message}`)}}Q=!1}B(`Telegram polling: ${z.dir}`);while(!0)try{let X=await(await fetch(`${Z.apiBase}/getUpdates?offset=${Z.offset}&timeout=30`)).json();if(!X.ok)throw Error(X.description||"getUpdates failed");for(let G of X.result||[])if(Z.offset=G.update_id+1,G.message){let q=G.message,b=qz(q),h=q.text||q.caption||"";if(B(`← TG [${b}] ${h.slice(0,80)}${q.photo?" +img":""}${q.document?" +file":""}`),q.chat?.id&&q.message_id)I(Z,"setMessageReaction",{chat_id:q.chat.id,message_id:q.message_id,reaction:[{type:"emoji",emoji:V.length>0?"⏳":"\uD83D\uDC40"}]}).catch(()=>{});V.push({msg:q,updateId:G.update_id}),J()}}catch(W){T(`Telegram polling error: ${W.message}`),await new Promise((X)=>setTimeout(X,3000))}}async function mz(){let z=`${m}/events/${encodeURIComponent(w)}`,Z=3000;while(!0){H(`SSE connecting: ${z}`);try{let $={Accept:"text/event-stream","Cache-Control":"no-cache"};if(N)$.Authorization=`Bearer ${N}`;let Y=await fetch(z,{headers:$});if(!Y.ok||!Y.body){if(Y.status===401)O("SSE 401: token 无效或未配置。检查 ~/.anet/config.json 的 token 字段");else T(`SSE failed: ${Y.status}`);await new Promise((W)=>setTimeout(W,Z)),Z=Math.min(Z*1.5,60000);continue}Z=3000;let Q=Y.body.getReader(),V=new TextDecoder,J="";while(!0){let{done:W,value:X}=await Q.read();if(W)break;J+=V.decode(X,{stream:!0});let G=J.split(`
43
- `);J=G.pop()||"";for(let q of G){if(!q.startsWith("data: "))continue;try{let b=JSON.parse(q.slice(6));if(b.type==="connected"){B("SSE connected");continue}if(["new_task","new_message","broadcast"].includes(b.type))B(`← SSE ${b.type}`),await hz()}catch{}}}}catch($){T(`SSE error: ${$.message}`)}H(`SSE reconnecting (${Z/1000}s)...`),await new Promise(($)=>setTimeout($,Z)),Z=Math.min(Z*1.5,60000)}}B("启动");B(` runtime: ${bz}`);B(` model: ${P||(y==="codex"?"gpt-5.4":"claude-sonnet-4-6")} ${P?"":"(default)"}`);B(` hub: ${m}${N?" (auth)":" (no auth!)"}`);B(` tools: ${M.length?`[${M.join(",")}]`:"(none)"}`);B(` channels:${C.length?` telegram(${C.map((z)=>z.dir).join(",")})`:" (none)"}`);B(` session: ${_||"(new)"}`);B(` log-dir: ${r}`);await Oz();B("已注册到 CommHub");setInterval(()=>L("idle").catch(()=>{}),180000);var Jz=async()=>{B("shutting down..."),await L("offline").catch(()=>{}),process.exit(0)};process.on("SIGINT",Jz);process.on("SIGTERM",Jz);for(let z of C)dz(z);mz();
40
+ ${Q.map((W)=>`- 图片: ${W}`).join(`
41
+ `)}`;return{text:$.trim(),images:Q}}async function cz(z,Z){if(!fz(z.channel,Z))return;let $=Z.chat?.id,Q=Z.message_id,V=`telegram:${qz(Z)}`,{text:W,images:q}=await pz(z,Z);if(!$||!Q||!W)return;b(`[TG] processing: ${W.slice(0,80)}`);try{let X=await Kz(W,V,q);await s(z,$,X,Q),B(`→ [${V}] ${X.slice(0,100)}`)}catch(X){O(`telegram task failed: ${X.message}`),await s(z,$,`处理出错: ${X.message}`,Q).catch(()=>{})}}async function dz(z){let Z={channel:z,apiBase:`https://api.telegram.org/bot${z.token}`,fileBase:`https://api.telegram.org/file/bot${z.token}`,offset:0};try{let X=await u(Z,"getMe",{});B(`Telegram bot: @${X.username} (${X.first_name})`)}catch(X){O(`Telegram token 无效: ${X.message}`),process.exit(1)}let $=D(z.dir,"state.json");try{let X=JSON.parse(S($,"utf-8"));if(X.offset)Z.offset=X.offset,b(`Telegram offset restored: ${Z.offset}`)}catch{}let Q=()=>{try{m($,JSON.stringify({offset:Z.offset})+`
42
+ `)}catch{}},V=!1,W=[];async function q(){if(V)return;V=!0;while(W.length){let{msg:X,updateId:Y}=W.shift();try{await cz(Z,X),Z.offset=Y+1,Q()}catch(G){O(`TG handle: ${G.message}`)}}V=!1}B(`Telegram polling: ${z.dir}`);while(!0)try{let Y=await(await fetch(`${Z.apiBase}/getUpdates?offset=${Z.offset}&timeout=30`)).json();if(!Y.ok)throw Error(Y.description||"getUpdates failed");for(let G of Y.result||[])if(Z.offset=G.update_id+1,G.message){let J=G.message,v=qz(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:W.length>0?"⏳":"\uD83D\uDC40"}]}).catch(()=>{});W.push({msg:J,updateId:G.update_id}),q()}}catch(X){L(`Telegram polling error: ${X.message}`),await new Promise((Y)=>setTimeout(Y,3000))}}async function mz(){let z=`${r}/events/${encodeURIComponent(j)}`,Z=3000;while(!0){b(`SSE connecting: ${z}`);try{let $={Accept:"text/event-stream","Cache-Control":"no-cache"};if(M)$.Authorization=`Bearer ${M}`;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((X)=>setTimeout(X,Z)),Z=Math.min(Z*1.5,60000);continue}Z=3000;let V=Q.body.getReader(),W=new TextDecoder,q="";while(!0){let{done:X,value:Y}=await V.read();if(X)break;q+=W.decode(Y,{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","new_message","broadcast"].includes(v.type))B(`← SSE ${v.type}`),await hz()}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: ${bz}`);B(` model: ${x||(P==="codex"?"gpt-5.4":"claude-sonnet-4-6")} ${x?"":"(default)"}`);B(` hub: ${r}${M?" (auth)":" (no auth!)"}`);B(` tools: ${k.length?`[${k.join(",")}]`:"(none)"}`);B(` channels:${T.length?` telegram(${T.map((z)=>z.dir).join(",")})`:" (none)"}`);B(` session: ${N||"(new)"}`);B(` log-dir: ${n}`);await Oz();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)dz(z);mz();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sleep2agi/agent-node",
3
- "version": "1.3.0",
3
+ "version": "1.3.1",
4
4
  "description": "One-command AI Agent node for CommHub networks. Claude + Codex dual runtime.",
5
5
  "bin": {
6
6
  "agent-node": "./dist/cli.js"