@sleep2agi/agent-node 1.0.2 → 1.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 +12 -12
- 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 Gz}from"node:module";var n=Gz(import.meta.url);import{readFileSync as S,existsSync as c,writeFileSync as d,chmodSync as jz}from"fs";import{join as D}from"path";import{hostname as l,homedir as Fz}from"os";import{mkdirSync as Wz,appendFileSync as kz}from"fs";var zz=Fz(),v=process.argv.slice(2),j={},Zz=[],wz="1.1.0";for(let z=0;z<v.length;z++){if(v[z]==="--version"||v[z]==="-v")console.log(`agent-node v${wz}`),process.exit(0);if(v[z]==="-h"||v[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 r=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(
|
|
28
|
-
用法: npx @sleep2agi/agent-node --alias "我的Agent"`),process.exit(1);var
|
|
29
|
-
`),
|
|
30
|
-
`)){let $=Z.trim();if(!$||$.startsWith("#"))continue;let
|
|
31
|
-
`)}catch{}}var B=(z)=>u("info",1,z),
|
|
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 Dz(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",vz={"claude-agent-sdk":"claude","claude-sdk":"claude","agent-sdk":"claude",claude:"claude","codex-sdk":"codex",codex:"codex"},y=vz[Yz]||"claude",Hz=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,bz=["Read","Write","Edit","Bash","Glob","Grep","WebSearch","WebFetch"],i=j.tools||(Array.isArray(K.tools)?K.tools.join(","):K.tools)||"",M=i==="all"?bz:i.split(",").filter(Boolean),Uz=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"),Pz={debug:0,info:1,warn:2,error:3},Rz=Pz[j["log-level"]||process.env.LOG_LEVEL||K.logLevel||"info"]??1,xz=[...(Array.isArray(K.channels)?K.channels:[]).filter((z)=>!z.startsWith("server:")&&!z.startsWith("plugin:")),...Zz],Qz=xz.map((z)=>{try{return Dz(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 yz(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 Mz(z){return D(process.cwd(),".anet","nodes",w,"channels",z)}function _z(z){let Z=z.path||Mz("telegram");yz(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{jz(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 T=Qz.filter((z)=>z.type==="telegram").map(_z),o=Qz.find((z)=>z.type!=="telegram");if(o)console.error(`[agent-node] unsupported channel: ${o.raw}`),process.exit(1);if(T.length>0&&y!=="codex"&&!M.includes("Read"))M.push("Read");try{Wz(r,{recursive:!0})}catch{}function u(z,Z,$){if(Z<Rz)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);kz(D(r,`${J}.log`),V+`
|
|
31
|
+
`)}catch{}}var B=(z)=>u("info",1,z),H=(z)=>u("debug",0,z),C=(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)}`,Nz=()=>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}),Oz=async()=>(await A("get_inbox",{alias:w,limit:5}))?.messages||[],Ez=(z)=>A("ack_inbox",{alias:w,message_id:z}),Az=(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} 的任务:
|
|
32
32
|
|
|
33
33
|
${z}
|
|
34
34
|
|
|
35
|
-
执行完后简要汇报结果。`,
|
|
35
|
+
执行完后简要汇报结果。`,Q={model:P||void 0,tools:M.length?M:void 0,maxTurns:Uz,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 Cz(z,Z,$){let{Codex:Y}=await import("@openai/codex-sdk");if(!U){let X=new Y,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}
|
|
36
36
|
|
|
37
|
-
(直接回答,不要调用任何通信工具,不要发消息给其他人)`,J=$?.length?[{type:"text",text:
|
|
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;if(B(`[codex] done | ${h}ms | in=${q?.input_tokens||0} 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().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 Cz(z,Z,$);return Tz(z,Z)},Q=t.then(Y,Y);return t=Q.then(()=>{},()=>{}),Q}async function Lz(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={},Iz=5000;function Sz(z,Z){if(z===w)return"self";if(Z.startsWith(`[${w}]`))return"own-prefix";let $=Date.now();if(p[z]&&$-p[z]<Iz)return"cooldown";return null}async function uz(){let z=await Oz();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 Ez(Z.id);let Q=Sz($,Y);if(Q){H(`skip message from ${$}: ${Q}`);continue}let V=await Lz(Y,$);p[$]=Date.now();try{await Az($,`[${w}] ${V.slice(0,2000)}`),B(`→ [${$}] ${V.slice(0,100)}`)}catch(J){C(`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 hz(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 fz(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)$+=`
|
|
38
38
|
|
|
39
39
|
[Telegram 附件已下载]
|
|
40
|
-
${
|
|
41
|
-
`)}`;return{text:$.trim(),images:
|
|
42
|
-
`)}catch{}},
|
|
43
|
-
`);J=G.pop()||"";for(let q of G){if(!q.startsWith("data: "))continue;try{let
|
|
40
|
+
${Y.map((V)=>`- 图片: ${V}`).join(`
|
|
41
|
+
`)}`;return{text:$.trim(),images:Y}}async function pz(z,Z){if(!hz(z.channel,Z))return;let $=Z.chat?.id,Y=Z.message_id,Q=`telegram:${qz(Z)}`,{text:V,images:J}=await fz(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 cz(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 pz(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){C(`Telegram polling error: ${W.message}`),await new Promise((X)=>setTimeout(X,3000))}}async function dz(){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 C(`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 uz()}catch{}}}}catch($){C(`SSE error: ${$.message}`)}H(`SSE reconnecting (${Z/1000}s)...`),await new Promise(($)=>setTimeout($,Z)),Z=Math.min(Z*1.5,60000)}}B("启动");B(` runtime: ${Hz}`);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:${T.length?` telegram(${T.map((z)=>z.dir).join(",")})`:" (none)"}`);B(` session: ${_||"(new)"}`);B(` log-dir: ${r}`);await Nz();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 T)cz(z);dz();
|