@sleep2agi/agent-node 1.4.1 → 1.4.2
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 +10 -10
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as wz}from"node:module";var l=wz(import.meta.url);import{readFileSync as S,existsSync as d,writeFileSync as m,chmodSync as Dz}from"fs";import{join as D}from"path";import{hostname as
|
|
2
|
+
import{createRequire as wz}from"node:module";var l=wz(import.meta.url);import{readFileSync as S,existsSync as d,writeFileSync as m,chmodSync as Dz}from"fs";import{join as D}from"path";import{hostname as i,homedir as vz}from"os";import{mkdirSync as Kz,appendFileSync as Az}from"fs";var Zz=vz(),H=process.argv.slice(2),j={},$z=[],Hz="1.4.2";for(let z=0;z<H.length;z++){if(H[z]==="--version"||H[z]==="-v")console.log(`agent-node v${Hz}`),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 wz}from"node:module";var l=wz(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(H[z]==="--new-session"){j["new-session"]="true";continue}if(H[z]==="--channel"&&z+1<H.length){$z.push(H[++z]);continue}if(H[z].startsWith("--")&&z+1<H.length)j[H[z].slice(2)]=H[++z]}function Qz(z){return z.replace(/^~(?=\/|$)/,Zz)}function bz(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:Qz(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 V={},
|
|
28
|
-
用法: npx @sleep2agi/agent-node --alias "我的Agent"`),process.exit(1);var Xz=j.runtime||process.env.RUNTIME||V.runtime||"claude-agent-sdk",Uz={"claude-agent-sdk":"claude","claude-sdk":"claude","agent-sdk":"claude",claude:"claude","codex-sdk":"codex",codex:"codex"},
|
|
29
|
-
`),b(`session 写回: ${
|
|
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 Oz(z){return D(process.cwd(),".anet","nodes",F,"channels",z)}function Cz(z){let Z=z.path||Oz("telegram");xz(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{Dz(D(Z,".env"),384)}catch{}let Q=C(D(Z,"access.json"))||{},Y=D(Z,"inbox");try{Kz(Y,{recursive:!0})}catch{}return{type:"telegram",dir:Z,inboxDir:Y,token:$,allowFrom:Array.isArray(Q.allowFrom)?Q.allowFrom.map(String):[]}}var T=Yz.filter((z)=>z.type==="telegram").map(Cz),o=Yz.find((z)=>z.type!=="telegram");if(o)console.error(`[agent-node] unsupported channel: ${o.raw}`),process.exit(1);if(T.length>0&&
|
|
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 A(z,Z){let $={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(x)$.Authorization=`Bearer ${x}`;let Y=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(),X=Y.match(/data: (.+)/),q=X?JSON.parse(X[1]):JSON.parse(Y),W=q?.result?.content?.[0]?.text;return W?JSON.parse(W):q}var t=V.node_id||"",Vz=t?`sdk-${t}`:`sdk-${F}-${Date.now().toString(36)}`,Ez=()=>A("report_status",{resume_id:Vz,alias:F,status:"idle",server:
|
|
27
|
+
`),process.exit(0);if(H[z]==="--new-session"){j["new-session"]="true";continue}if(H[z]==="--channel"&&z+1<H.length){$z.push(H[++z]);continue}if(H[z].startsWith("--")&&z+1<H.length)j[H[z].slice(2)]=H[++z]}function Qz(z){return z.replace(/^~(?=\/|$)/,Zz)}function bz(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:Qz(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 V={},k="";if(j.config){let z=j.config.startsWith("/")?j.config:D(process.cwd(),j.config),Z=C(z);if(Z)V=Z,k=z,console.log(`[agent-node] Config: ${z}`)}var F=j.alias||process.env.COMMHUB_ALIAS||process.env.ALIAS||V.alias;if(!j.config&&F){let z=D(process.cwd(),".anet","nodes",F,"config.json"),Z=D(process.cwd(),".anet","profiles",`${F}.json`),$=d(z)?z:Z,Q=C($);if(Q){if(V={...Q,...V},k=$,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]=Qz(X)}}}var _=C(D(Zz,".anet","config.json"))||{};if(_.hub&&!V.hub)V.hub=_.hub;if(_.token&&!V.token)V.token=_.token;if(!j.config&&!Object.keys(V).length){let z=C(D(process.cwd(),".agent-node.json"));if(z)V=z,console.log("[agent-node] 配置: .agent-node.json")}if(!F)console.error(`错误: 必须指定 --alias
|
|
28
|
+
用法: npx @sleep2agi/agent-node --alias "我的Agent"`),process.exit(1);var Xz=j.runtime||process.env.RUNTIME||V.runtime||"claude-agent-sdk",Uz={"claude-agent-sdk":"claude","claude-sdk":"claude","agent-sdk":"claude",claude:"claude","codex-sdk":"codex",codex:"codex"},P=Uz[Xz]||"claude",yz=Xz,r=j.url||j.hub||process.env.COMMHUB_URL||V.hub||"http://127.0.0.1:9200",y=j.model||process.env.MODEL||V.model,Rz=["Read","Write","Edit","Bash","Glob","Grep","WebSearch","WebFetch"],g=j.tools||(Array.isArray(V.tools)?V.tools.join(","):V.tools)||"",M=g==="all"?Rz:g.split(",").filter(Boolean),kz=parseInt(j["max-turns"]||V.flags?.maxTurns||V.maxTurns||"5"),a=parseFloat(j["max-budget"]||V.flags?.maxBudgetUsd||V.maxBudgetUsd||"0"),Pz=j["new-session"]==="true",N=Pz?"":j.session||V.session||V.resume||V.sessionId||"",E=j.prompt||V.systemPrompt||"",x=process.env.COMMHUB_TOKEN||V.token||_.token||"",n=j["log-dir"]||D(process.cwd(),".anet","nodes",F,"logs"),Mz={debug:0,info:1,warn:2,error:3},Nz=Mz[j["log-level"]||process.env.LOG_LEVEL||V.logLevel||"info"]??1,_z=[...(Array.isArray(V.channels)?V.channels:[]).filter((z)=>!z.startsWith("server:")&&!z.startsWith("plugin:")),...$z],Yz=_z.map((z)=>{try{return bz(z)}catch(Z){console.error(`[agent-node] ${Z.message}`),process.exit(1)}});function Wz(z){if(!k||!z)return;try{let Z=JSON.parse(S(k,"utf-8"));if(Z.session===z)return;Z.session=z,m(k,JSON.stringify(Z,null,2)+`
|
|
29
|
+
`),b(`session 写回: ${k} → ${z.slice(0,8)}...`)}catch{}}function xz(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 Y=$.slice(0,Q).trim(),X=$.slice(Q+1).trim().replace(/^['"]|['"]$/g,"");if(!process.env[Y])process.env[Y]=X}}function Oz(z){return D(process.cwd(),".anet","nodes",F,"channels",z)}function Cz(z){let Z=z.path||Oz("telegram");xz(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{Dz(D(Z,".env"),384)}catch{}let Q=C(D(Z,"access.json"))||{},Y=D(Z,"inbox");try{Kz(Y,{recursive:!0})}catch{}return{type:"telegram",dir:Z,inboxDir:Y,token:$,allowFrom:Array.isArray(Q.allowFrom)?Q.allowFrom.map(String):[]}}var T=Yz.filter((z)=>z.type==="telegram").map(Cz),o=Yz.find((z)=>z.type!=="telegram");if(o)console.error(`[agent-node] unsupported channel: ${o.raw}`),process.exit(1);if(T.length>0&&P!=="codex"&&!M.includes("Read"))M.push("Read");try{Kz(n,{recursive:!0})}catch{}function h(z,Z,$){if(Z<Nz)return;let Q=new Date().toTimeString().slice(0,8),Y=z.toUpperCase().padEnd(5),X=`[${Q}] [${Y}] [${F}] ${$}`;console.log(X);try{let q=new Date().toISOString().slice(0,10);Az(D(n,`${q}.log`),X+`
|
|
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 A(z,Z){let $={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(x)$.Authorization=`Bearer ${x}`;let Y=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(),X=Y.match(/data: (.+)/),q=X?JSON.parse(X[1]):JSON.parse(Y),W=q?.result?.content?.[0]?.text;return W?JSON.parse(W):q}var t=V.node_id||"",Vz=t?`sdk-${t}`:`sdk-${F}-${Date.now().toString(36)}`,Ez=()=>A("report_status",{resume_id:Vz,alias:F,status:"idle",server:i(),hostname:i(),agent:`agent-node:${P}`,project_dir:process.cwd()}),I=(z,Z)=>A("report_status",{resume_id:Vz,alias:F,status:z,task:Z}),Tz=async()=>(await A("get_inbox",{alias:F,limit:5}))?.messages||[],Lz=(z)=>A("ack_inbox",{alias:F,message_id:z}),Iz=(z,Z)=>A("send_message",{alias:z,message:Z,from_session:F}),p=N||void 0;async function uz(z,Z){let{query:$}=await import("@anthropic-ai/claude-agent-sdk"),Q=`你是 ${F},收到来自 ${Z} 的任务:
|
|
32
32
|
|
|
33
33
|
${z}
|
|
34
34
|
|
|
35
|
-
执行完后简要汇报结果。`,Y={model:y||void 0,tools:M.length?M:void 0,maxTurns:
|
|
35
|
+
执行完后简要汇报结果。`,Y={model:y||void 0,tools:M.length?M:void 0,maxTurns:kz,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,settingSources:[],env:process.env,cwd:process.cwd(),stderr:(W)=>{if(W.trim())b(`[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(a>0)Y.maxBudgetUsd=a;if(E)Y.systemPrompt=E;if(p)Y.resume=p;let X="",q=Date.now();for await(let W of $({prompt:Q,options:Y})){let K=W;if(K.type==="system"&&K.subtype==="init")p=K.session_id,B(`[claude] session=${K.session_id?.slice(0,8)} model=${y||"default"}`),Wz(K.session_id);if(K.type==="result"){let G=Date.now()-q,J=K.usage||{};B(`[claude] ${K.subtype} | ${G}ms | $${K.total_cost_usd?.toFixed(4)||"?"} | in=${J.input_tokens||0} out=${J.output_tokens||0} | turns=${K.num_turns}`),X=K.subtype==="success"?K.result||"任务完成":`执行出错: ${K.error||K.result||"未知错误"}`}}return X}var U=null;async function Sz(z,Z,$){let{Codex:Q}=await import("@openai/codex-sdk");if(!U){let K=E||`你是 ${F},一个 AI Agent 节点。你通过 CommHub 通信网络接收任务。收到任务后理解内容、执行任务(可以读写文件、执行命令)、返回执行结果。你的回复会被自动发送给任务发送者。当前工作目录:${process.cwd()}。重要:不要回复纯确认消息(如"收到""好的""ok"),必须有实质内容才回复。无实质进展时保持沉默。没有新任务时保持安静,不要主动发消息询问或提示"等待任务",等待下一条任务即可。`,G=new Q({config:{model_auto_compact_token_limit:200000,developer_instructions:K}}),v={skipGitRepoCheck:!0,approvalPolicy:"never",model:y||"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=${y||"gpt-5.4"} thread=${U?.id||"new"}`);let X=`${z}
|
|
36
36
|
|
|
37
|
-
(直接回答,不要调用任何通信工具,不要发消息给其他人)`,q=$?.length?[{type:"text",text:X},...$.map((K)=>({type:"local_image",path:K}))]:X,W=Date.now();try{let{events:K}=await U.runStreamed(q),G="",J=null,v=0;for await(let R of K)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()-W,Fz=J?.input_tokens||0;if(B(`[codex] done | ${f}ms | in=${Fz} out=${J?.output_tokens||0} | items=${v}`),U?.id)Wz(U.id);return G||"(无回复)"}catch(K){B(`codex thread error: ${K.message}, 重建`),U=new Q({config:{model_auto_compact_token_limit:200000,developer_instructions:E||`你是 ${F},一个 AI Agent 节点。`}}).startThread({skipGitRepoCheck:!0,approvalPolicy:"never",model:y||"gpt-5.4",sandboxMode:"danger-full-access",modelReasoningEffort:"low"});let J=await U.run(q),v=Date.now()-W;return B(`[codex] retry done | ${v}ms`),J.finalResponse||"(无回复)"}}var s=Promise.resolve();function Bz(z,Z,$){let Q=async()=>{if(
|
|
37
|
+
(直接回答,不要调用任何通信工具,不要发消息给其他人)`,q=$?.length?[{type:"text",text:X},...$.map((K)=>({type:"local_image",path:K}))]:X,W=Date.now();try{let{events:K}=await U.runStreamed(q),G="",J=null,v=0;for await(let R of K)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()-W,Fz=J?.input_tokens||0;if(B(`[codex] done | ${f}ms | in=${Fz} out=${J?.output_tokens||0} | items=${v}`),U?.id)Wz(U.id);return G||"(无回复)"}catch(K){B(`codex thread error: ${K.message}, 重建`),U=new Q({config:{model_auto_compact_token_limit:200000,developer_instructions:E||`你是 ${F},一个 AI Agent 节点。`}}).startThread({skipGitRepoCheck:!0,approvalPolicy:"never",model:y||"gpt-5.4",sandboxMode:"danger-full-access",modelReasoningEffort:"low"});let J=await U.run(q),v=Date.now()-W;return B(`[codex] retry done | ${v}ms`),J.finalResponse||"(无回复)"}}var s=Promise.resolve();function Bz(z,Z,$){let Q=async()=>{if(P==="codex")return Sz(z,Z,$);return uz(z,Z)},Y=s.then(Q,Q);return s=Y.then(()=>{},()=>{}),Y}async function hz(z,Z){B(`→ processing [${P}]: ${z.slice(0,80)}`),await I("working",z.slice(0,200));let $;try{$=await Bz(z,Z)}catch(Q){$=`${P} 错误: ${Q.message}`,O(`✗ ${Q.message}`)}return await I("idle"),$}var c={},fz=5000,pz=new Set(["收到","好的","ok","嗯","是的","了解","明白","确认","done","ack","roger","yes","no","在线","待命","正常","保持在线","通信正常","已收到","收到了","好","行","noted","copy","received","understood","等待任务","等待中","等待指令","无新任务","idle","waiting"]);function qz(z){if(!z)return!0;if(z.replace(/[\s\p{P}\p{S}\p{Emoji}]/gu,"").length<3)return!0;let Q=z.trim().replace(/^[\[【].+?[\]】]\s*/,"").trim().toLowerCase().replace(/[\s。!?.!?✅❌👀⏳,,]+$/g,"").trim();if(pz.has(Q))return!0;if(/^[\p{Emoji}\s]+$/u.test(z.trim()))return!0;return!1}function cz(z,Z){if(z===F)return"self";if(Z.startsWith(`[${F}]`))return"own-prefix";let $=Date.now();if(c[z]&&$-c[z]<fz)return"cooldown";if(qz(Z))return"low-value-inbound";return null}async function dz(){let z=await Tz();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 Lz(Z.id);let Y=cz($,Q);if(Y){b(`skip message from ${$}: ${Y}`);continue}let X=await hz(Q,$);if(c[$]=Date.now(),qz(X)){b(`skip reply: low-value (${X.slice(0,30)})`);continue}try{await Iz($,`[${F}] ${X.slice(0,2000)}`),B(`→ [${$}] ${X.slice(0,100)}`)}catch(q){L(`reply failed: ${q.message}`)}}}function Jz(z){return String(z.from?.id||z.chat?.id||"")}function Gz(z){return z.from?.username||z.from?.first_name||Jz(z)||"telegram"}function mz(z,Z){if(z.allowFrom.length===0)return!0;let $=Jz(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($)}),Y=await Q.json();if(!Y.ok)throw Error(`telegram ${Z} failed: ${Y.description||Q.statusText}`);return Y.result}async function e(z,Z,$,Q){let Y=$.match(/[\s\S]{1,4096}/g)||["(无回复)"];for(let X=0;X<Y.length;X++)await u(z,"sendMessage",{chat_id:Z,text:Y[X],...Q&&X===0?{reply_to_message_id:Q}:{}})}async function zz(z,Z,$){let Q=await u(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 q=Y.split(".").pop(),W=($||Y.split("/").pop()||Z).replace(/[^a-zA-Z0-9._-]/g,"_"),K=W.includes(".")||!q?W:`${W}.${q}`,G=D(z.channel.inboxDir,`${Date.now()}_${K}`);return m(G,Buffer.from(await X.arrayBuffer())),G}async function rz(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],q=await zz(z,X.file_id,`photo_${Z.message_id}.jpg`);Q.push(q)}let Y=String(Z.document?.mime_type||"");if(Z.document&&Y.startsWith("image/")){let X=await zz(z,Z.document.file_id,Z.document.file_name||`image_${Z.message_id}`);Q.push(X)}if(Q.length)$+=`
|
|
38
38
|
|
|
39
39
|
[Telegram 附件已下载]
|
|
40
40
|
${Q.map((X)=>`- 图片: ${X}`).join(`
|
|
41
41
|
`)}`;return{text:$.trim(),images:Q}}async function nz(z,Z){if(!mz(z.channel,Z))return;let $=Z.chat?.id,Q=Z.message_id,Y=`telegram:${Gz(Z)}`,{text:X,images:q}=await rz(z,Z);if(!$||!Q||!X)return;b(`[TG] processing: ${X.slice(0,80)}`);try{let W=await Bz(X,Y,q);await e(z,$,W,Q),B(`→ [${Y}] ${W.slice(0,100)}`)}catch(W){O(`telegram task failed: ${W.message}`),await e(z,$,`处理出错: ${W.message}`,Q).catch(()=>{})}}async function lz(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 u(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,b(`Telegram offset restored: ${Z.offset}`)}catch{}let Q=()=>{try{m($,JSON.stringify({offset:Z.offset})+`
|
|
42
|
-
`)}catch{}},Y=!1,X=[];async function q(){if(Y)return;Y=!0;while(X.length){let{msg:W,updateId:K}=X.shift();try{await nz(Z,W),Z.offset=K+1,Q()}catch(G){O(`TG handle: ${G.message}`)}}Y=!1}B(`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 G of K.result||[])if(Z.offset=G.update_id+1,G.message){let J=G.message,v=Gz(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:X.length>0?"⏳":"\uD83D\uDC40"}]}).catch(()=>{});X.push({msg:J,updateId:G.update_id}),q()}}catch(W){L(`Telegram polling error: ${W.message}`),await new Promise((K)=>setTimeout(K,3000))}}async function
|
|
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 dz()}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: ${yz}`);B(` model: ${y||(
|
|
42
|
+
`)}catch{}},Y=!1,X=[];async function q(){if(Y)return;Y=!0;while(X.length){let{msg:W,updateId:K}=X.shift();try{await nz(Z,W),Z.offset=K+1,Q()}catch(G){O(`TG handle: ${G.message}`)}}Y=!1}B(`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 G of K.result||[])if(Z.offset=G.update_id+1,G.message){let J=G.message,v=Gz(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:X.length>0?"⏳":"\uD83D\uDC40"}]}).catch(()=>{});X.push({msg:J,updateId:G.update_id}),q()}}catch(W){L(`Telegram polling error: ${W.message}`),await new Promise((K)=>setTimeout(K,3000))}}async function iz(){let z=`${r}/events/${encodeURIComponent(F)}`,Z=3000;while(!0){b(`SSE connecting: ${z}`);try{let $={Accept:"text/event-stream","Cache-Control":"no-cache"};if(x)$.Authorization=`Bearer ${x}`;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((W)=>setTimeout(W,Z)),Z=Math.min(Z*1.5,60000);continue}Z=3000;let Y=Q.body.getReader(),X=new TextDecoder,q="";while(!0){let{done:W,value:K}=await Y.read();if(W)break;q+=X.decode(K,{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 dz()}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: ${yz}`);B(` model: ${y||(P==="codex"?"gpt-5.4":"claude-sonnet-4-6")} ${y?"":"(default)"}`);B(` hub: ${r}${x?" (auth)":" (no auth!)"}`);B(` tools: ${M.length?`[${M.join(",")}]`:"(none)"}`);B(` channels:${T.length?` telegram(${T.map((z)=>z.dir).join(",")})`:" (none)"}`);B(` session: ${N||"(new)"}`);B(` log-dir: ${n}`);await Ez();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)lz(z);iz();
|