@sleep2agi/agent-node 2.1.0-preview.3 → 2.1.0-preview.4
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/README.md +11 -7
- package/dist/cli.js +12 -11
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -21,8 +21,11 @@ agent-node
|
|
|
21
21
|
├── runtime: claude ──→ @anthropic-ai/claude-agent-sdk
|
|
22
22
|
│ └── query() → spawn claude CLI → AI 处理 + 工具调用
|
|
23
23
|
│
|
|
24
|
-
|
|
25
|
-
|
|
24
|
+
├── runtime: codex ───→ @openai/codex-sdk
|
|
25
|
+
│ └── exec() → spawn codex CLI → AI 处理 + 工具调用
|
|
26
|
+
│
|
|
27
|
+
└── runtime: http-api ─→ 直接 HTTP 调用 (V2 新增)
|
|
28
|
+
└── OpenAI/Anthropic 兼容 API → MiniMax/DeepSeek 等
|
|
26
29
|
```
|
|
27
30
|
|
|
28
31
|
### Claude Agent SDK(`--runtime claude`,默认)
|
|
@@ -121,9 +124,9 @@ SSE 长连接 /events/:alias
|
|
|
121
124
|
│ ↓
|
|
122
125
|
│ report_status: working
|
|
123
126
|
│ ↓
|
|
124
|
-
│ AI 处理(claude
|
|
127
|
+
│ AI 处理(claude/codex/http-api)
|
|
125
128
|
│ ↓
|
|
126
|
-
│
|
|
129
|
+
│ send_reply → 回报结果(V2: 关联 task_id)
|
|
127
130
|
│ ↓
|
|
128
131
|
│ report_status: idle
|
|
129
132
|
│ ↓
|
|
@@ -213,8 +216,8 @@ npx @sleep2agi/agent-node --alias Claude马 --hub http://IP:9200 --tools all
|
|
|
213
216
|
|------|--------|------|
|
|
214
217
|
| `--alias` | 必填 | Agent 名称 |
|
|
215
218
|
| `--hub` | `http://127.0.0.1:9200` | CommHub URL |
|
|
216
|
-
| `--runtime` | `claude` | `claude`
|
|
217
|
-
| `--model` |
|
|
219
|
+
| `--runtime` | `claude` | `claude` / `codex` / `http-api` / `minimax` |
|
|
220
|
+
| `--model` | 按 runtime | codex: `gpt-5.4`, http-api: `claude-3-5-haiku-20241022` |
|
|
218
221
|
| `--tools` | 无 | `all` 或逗号分隔 |
|
|
219
222
|
| `--max-turns` | `5` | 每任务最大轮次 |
|
|
220
223
|
| `--max-budget` | 无 | 每任务预算(美元) |
|
|
@@ -229,8 +232,9 @@ npx @sleep2agi/agent-node --alias Claude马 --hub http://IP:9200 --tools all
|
|
|
229
232
|
|---|------------|
|
|
230
233
|
| `@anthropic-ai/claude-agent-sdk` | `--runtime claude` 时(动态 import) |
|
|
231
234
|
| `@openai/codex-sdk` | `--runtime codex` 时(动态 import) |
|
|
235
|
+
| 无外部依赖 | `--runtime http-api` 时(内置 fetch) |
|
|
232
236
|
|
|
233
|
-
未使用的 runtime
|
|
237
|
+
未使用的 runtime 不会加载依赖。`http-api` runtime 零依赖。
|
|
234
238
|
|
|
235
239
|
---
|
|
236
240
|
|
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as
|
|
2
|
+
import{createRequire as Dz}from"node:module";var t=Dz(import.meta.url);import{readFileSync as E,existsSync as l,writeFileSync as g,chmodSync as Rz}from"fs";import{join as U}from"path";import{hostname as s,homedir as Pz}from"os";import{mkdirSync as jz,appendFileSync as Ez}from"fs";var Xz=Pz(),b=process.argv.slice(2),F={},Vz=[],qz="2.1.0";try{let z=new URL(".",import.meta.url).pathname;for(let Z of["../package.json","../../package.json"])try{let $=JSON.parse(E(U(z,Z),"utf-8"));if($.version){qz=$.version;break}}catch{}}catch{}for(let z=0;z<b.length;z++){if(b[z]==="--version"||b[z]==="-v")console.log(`agent-node v${qz}`),process.exit(0);if(b[z]==="-h"||b[z]==="--help")console.log(`
|
|
3
3
|
@sleep2agi/agent-node — AI Agent 节点,一行命令加入 CommHub 网络
|
|
4
4
|
|
|
5
5
|
用法:
|
|
@@ -24,19 +24,20 @@ import{createRequire as Uz}from"node:module";var a=Uz(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
|
-
`),D(`session 写回: ${k} → ${z.slice(0,8)}...`)}catch(Z){C(`writebackSession failed: ${Z.message}`)}}function
|
|
30
|
-
`)){let $=Z.trim();if(!$||$.startsWith("#"))continue;let Q=$.indexOf("=");if(Q<=0)continue;let W=$.slice(0,Q).trim(),Y=$.slice(Q+1).trim().replace(/^['"]|['"]$/g,"");if(!process.env[W])process.env[W]=Y}}function Cz(z){return
|
|
31
|
-
`)}catch{}}var J=(z)=>
|
|
27
|
+
`),process.exit(0);if(b[z]==="--new-session"){F["new-session"]="true";continue}if(b[z]==="--channel"&&z+1<b.length){Vz.push(b[++z]);continue}if(b[z].startsWith("--")&&z+1<b.length)F[b[z].slice(2)]=b[++z]}function Jz(z){return z.replace(/^~(?=\/|$)/,Xz)}function Mz(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:Jz(z.slice(Z+1)),raw:z}}function I(z){if(!l(z))return null;try{return JSON.parse(E(z,"utf-8"))}catch{return null}}var B={},k="";if(F.config){let z=F.config.startsWith("/")?F.config:U(process.cwd(),F.config),Z=I(z);if(Z)B=Z,k=z,console.log(`[agent-node] Config: ${z}`)}var H=F.alias||process.env.COMMHUB_ALIAS||process.env.ALIAS||B.alias;if(!F.config&&H){let z=U(process.cwd(),".anet","nodes",H,"config.json"),Z=U(process.cwd(),".anet","profiles",`${H}.json`),$=l(z)?z:Z,Q=I($);if(Q){if(B={...Q,...B},k=$,console.log(`[agent-node] Config: ${$}`),Q.env&&typeof Q.env==="object"){for(let[W,Y]of Object.entries(Q.env))if(!process.env[W]&&typeof Y==="string")process.env[W]=Jz(Y)}}}var A=I(U(Xz,".anet","config.json"))||{};if(A.hub&&!B.hub)B.hub=A.hub;if(A.token&&!B.token)B.token=A.token;if(!F.config&&!Object.keys(B).length){let z=I(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 Bz=F.runtime||process.env.RUNTIME||B.runtime||"claude-agent-sdk",kz={"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"},y=kz[Bz]||"claude",xz=Bz,i=F.url||F.hub||process.env.COMMHUB_URL||B.hub||"http://127.0.0.1:9200",M=F.model||process.env.MODEL||B.model,yz=["Read","Write","Edit","Bash","Glob","Grep","WebSearch","WebFetch"],e=F.tools||(Array.isArray(B.tools)?B.tools.join(","):B.tools)||"",_=e==="all"?yz:e.split(",").filter(Boolean),_z=parseInt(F["max-turns"]||B.flags?.maxTurns||B.maxTurns||"5"),zz=parseFloat(F["max-budget"]||B.flags?.maxBudgetUsd||B.maxBudgetUsd||"0"),Nz=F["new-session"]==="true",x=Nz?"":F.session||B.session||B.resume||B.sessionId||"",h=F.prompt||B.systemPrompt||"",O=process.env.COMMHUB_TOKEN||B.token||A.token||"",o=F["log-dir"]||U(process.cwd(),".anet","nodes",H,"logs"),Az={debug:0,info:1,warn:2,error:3},Oz=Az[F["log-level"]||process.env.LOG_LEVEL||B.logLevel||"info"]??1,L=[...(Array.isArray(B.channels)?B.channels:[]).filter((z)=>!z.startsWith("server:")&&!z.startsWith("plugin:")),...Vz],Kz=L.map((z)=>{try{return Mz(z)}catch(Z){console.error(`[agent-node] ${Z.message}`),process.exit(1)}});function Gz(z){if(!k||!z)return;try{let Z=JSON.parse(E(k,"utf-8"));if(Z.session===z)return;Z.session=z,g(k,JSON.stringify(Z,null,2)+`
|
|
29
|
+
`),D(`session 写回: ${k} → ${z.slice(0,8)}...`)}catch(Z){C(`writebackSession failed: ${Z.message}`)}}function Lz(z){if(!l(z))return;for(let Z of E(z,"utf-8").split(`
|
|
30
|
+
`)){let $=Z.trim();if(!$||$.startsWith("#"))continue;let Q=$.indexOf("=");if(Q<=0)continue;let W=$.slice(0,Q).trim(),Y=$.slice(Q+1).trim().replace(/^['"]|['"]$/g,"");if(!process.env[W])process.env[W]=Y}}function Cz(z){return U(process.cwd(),".anet","nodes",H,"channels",z)}function Tz(z){let Z=z.path||Cz("telegram");Lz(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{Rz(U(Z,".env"),384)}catch{}let Q=I(U(Z,"access.json"))||{},W=U(Z,"inbox");try{jz(W,{recursive:!0})}catch{}return{type:"telegram",dir:Z,inboxDir:W,token:$,allowFrom:Array.isArray(Q.allowFrom)?Q.allowFrom.map(String):[]}}var f=Kz.filter((z)=>z.type==="telegram").map(Tz),Zz=Kz.find((z)=>z.type!=="telegram");if(Zz)console.error(`[agent-node] unsupported channel: ${Zz.raw}`),process.exit(1);if(f.length>0&&y!=="codex"&&!_.includes("Read"))_.push("Read");try{jz(o,{recursive:!0})}catch{}function m(z,Z,$){if(Z<Oz)return;let Q=new Date().toTimeString().slice(0,8),W=z.toUpperCase().padEnd(5),Y=`[${Q}] [${W}] [${H}] ${$}`;console.log(Y);try{let q=new Date().toISOString().slice(0,10);Ez(U(o,`${q}.log`),Y+`
|
|
31
|
+
`)}catch{}}var J=(z)=>m("info",1,z),D=(z)=>m("debug",0,z),C=(z)=>m("warn",2,z),T=(z)=>m("error",3,z);async function u(z,Z,$=3){let Q={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(O)Q.Authorization=`Bearer ${O}`;let W;for(let Y=0;Y<=$;Y++)try{let q=await fetch(`${i}/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<$){W=Error(`HTTP ${q.status}`),await new Promise((w)=>setTimeout(w,1000*Math.pow(2,Y)));continue}let X=await q.text(),V=X.match(/data: (.+)/),G=V?JSON.parse(V[1]):JSON.parse(X),K=G?.result?.content?.[0]?.text;return K?JSON.parse(K):G}catch(q){if(W=q,Y<$)D(`callCommHub(${z}) attempt ${Y+1} failed: ${q.message}, retrying...`),await new Promise((X)=>setTimeout(X,1000*Math.pow(2,Y)))}throw W||Error(`callCommHub(${z}) failed after ${$} retries`)}var c=B.node_id||"",Iz=B.node_name||"",Fz=c?`sdk-${c}`:`sdk-${H}-${Date.now().toString(36)}`,uz=()=>u("report_status",{resume_id:Fz,alias:H,status:"idle",server:s(),hostname:s(),agent:`agent-node:${y}`,project_dir:process.cwd(),node_id:c||void 0,node_name:Iz||void 0,session_id:x||void 0,config_path:k||void 0,channels:L.length?JSON.stringify(L):void 0,model:M||void 0}),p=(z,Z)=>u("report_status",{resume_id:Fz,alias:H,status:z,task:Z,node_id:c||void 0,session_id:S||x||void 0,config_path:k||void 0,channels:L.length?JSON.stringify(L):void 0}),Sz=async()=>(await u("get_inbox",{alias:H,limit:20}))?.messages||[],hz=(z)=>u("ack_inbox",{alias:H,message_id:z}),fz=(z,Z,$)=>u("send_reply",{alias:z,text:Z,from_session:H,in_reply_to:$||void 0,status:"replied"}),S=x||void 0;async function cz(z,Z){let{query:$}=await import("@anthropic-ai/claude-agent-sdk"),Q=`你是 ${H},收到来自 ${Z} 的任务:
|
|
32
32
|
|
|
33
33
|
${z}
|
|
34
34
|
|
|
35
|
-
执行完后简要汇报结果。`,W={model:M||void 0,tools:_.length?_:void 0,maxTurns:
|
|
36
|
-
`)
|
|
35
|
+
执行完后简要汇报结果。`,W={model:M||void 0,tools:_.length?_:void 0,maxTurns:_z,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,settingSources:[],env:process.env,cwd:process.cwd(),stderr:(X)=>{if(X.trim())D(`[stderr] ${X.trim().slice(0,200)}`)},hooks:{PreToolUse:[{hooks:[async(X)=>{return J(`[tool] ${X.tool_name}(${JSON.stringify(X.tool_input).slice(0,80)})`),{continue:!0}}]}]}};if(zz>0)W.maxBudgetUsd=zz;if(h)W.systemPrompt=h;if(S)W.resume=S;let Y="",q=Date.now();for await(let X of $({prompt:Q,options:W})){let V=X;if(V.type==="system"&&V.subtype==="init")S=V.session_id,J(`[claude] session=${V.session_id?.slice(0,8)} model=${M||"default"}`),Gz(V.session_id);if(V.type==="result"){let G=Date.now()-q,K=V.usage||{};J(`[claude] ${V.subtype} | ${G}ms | $${V.total_cost_usd?.toFixed(4)||"?"} | in=${K.input_tokens||0} out=${K.output_tokens||0} | turns=${V.num_turns}`),Y=V.subtype==="success"?V.result||"任务完成":`执行出错: ${V.error||V.result||"未知错误"}`}}return Y}var P=null,pz=h||[`你是 ${H},一个 AI Agent 节点,工作目录:${process.cwd()}。`,"你通过通信网络接收任务。收到任务后执行并返回结果。","规则:","1. 只回复有实质内容的结果。",'2. 绝对不要回复"收到""好的""ok""在线""待命""等待任务"等确认消息。',"3. 没有新任务时保持完全沉默,不要主动发任何消息。","4. 不要调用任何通信工具(send_task/send_message 等)。","5. 你的回复会被系统自动发送给任务发送者。"].join(`
|
|
36
|
+
`),$z={model_auto_compact_token_limit:200000,developer_instructions:pz};async function dz(z,Z,$){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(!P){let V=new Q({config:$z}),K={skipGitRepoCheck:!0,approvalPolicy:"never",model:M||"gpt-5.4",sandboxMode:"danger-full-access",modelReasoningEffort:"low"};if(x)P=V.resumeThread(x,K),J(`codex resumed thread: ${x}`);else P=V.startThread(K)}J(`[codex] model=${M||"gpt-5.4"} thread=${P?.id||"new"}`);let Y=z,q=$?.length?[{type:"text",text:Y},...$.map((V)=>({type:"local_image",path:V}))]:Y,X=Date.now();try{let{events:V}=await P.runStreamed(q),G="",K=null,w=0;for await(let v of V)if(v.type==="item.started"){let j=v.item;D(`[codex] ${j.type}${j.command?`: ${j.command.slice(0,60)}`:j.tool?`: ${j.server}/${j.tool}`:""}`)}else if(v.type==="item.completed"){w++;let j=v.item;if(j.type==="agent_message")G=j.text||"";if(j.type==="command_execution")D(`[codex] cmd exit=${j.exit_code} | ${j.aggregated_output?.slice(0,80)}`);if(j.type==="reasoning")D(`[codex] thinking: ${j.text?.slice(0,80)}`);if(j.type==="mcp_tool_call")D(`[codex] mcp: ${j.server}/${j.tool} → ${j.status}`)}else if(v.type==="turn.completed")K=v.usage;let R=Date.now()-X,n=K?.input_tokens||0;if(J(`[codex] done | ${R}ms | in=${n} out=${K?.output_tokens||0} | items=${w}`),P?.id)Gz(P.id);return G||"(无回复)"}catch(V){J(`codex thread error: ${V.message}, 重建`),P=new Q({config:$z}).startThread({skipGitRepoCheck:!0,approvalPolicy:"never",model:M||"gpt-5.4",sandboxMode:"danger-full-access",modelReasoningEffort:"low"});let K=await P.run(q),w=Date.now()-X;return J(`[codex] retry done | ${w}ms`),K.finalResponse||"(无回复)"}}async function mz(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||"",W=process.env.OPENAI_BASE_URL||B.apiBaseUrl||"https://api.openai.com/v1",Y=M||"gpt-4o-mini",q=!!Q,V=(Q||W).replace(/\/v1\/?$/,"");if(!$)return"错误: 需要设置 ANTHROPIC_API_KEY, OPENAI_API_KEY, 或 MINIMAX_CODING_API_KEY";let G=h||`你是 ${H},一个 AI 助手。收到来自 ${Z} 的任务后简要执行并汇报。`,K=Date.now();J(`[http-api] model=${Y} format=${q?"anthropic":"openai"} base=${V.replace(/\/v1$/,"")}`);let w="",R=null;if(q){let v=await fetch(`${V}/v1/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":$,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:Y,system:G,messages:[{role:"user",content:z}],max_tokens:2000})});if(!v.ok){let N=await v.text();return`Anthropic API 错误 ${v.status}: ${N.slice(0,200)}`}let j=await v.json();w=(Array.isArray(j.content)?j.content:[]).filter((N)=>N.type==="text").map((N)=>N.text).join(`
|
|
37
|
+
`)||"",R=j.usage}else{let v=await fetch(`${V}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$}`},body:JSON.stringify({model:Y,messages:[{role:"system",content:G},{role:"user",content:z}],max_tokens:2000})});if(!v.ok){let a=await v.text();return`OpenAI API 错误 ${v.status}: ${a.slice(0,200)}`}let j=await v.json();w=j.choices?.[0]?.message?.content||"",R=j.usage}let n=Date.now()-K;return J(`[http-api] done | ${n}ms | in=${R?.input_tokens||R?.prompt_tokens||0} out=${R?.output_tokens||R?.completion_tokens||0}`),w||"(无回复)"}var Qz=Promise.resolve();function wz(z,Z,$){let Q=async()=>{if(y==="codex")return dz(z,Z,$);if(y==="http")return mz(z,Z);return cz(z,Z)},W=Qz.then(Q,Q);return Qz=W.then(()=>{},()=>{}),W}async function nz(z,Z){J(`→ processing [${y}]: ${z.slice(0,80)}`),await p("working",z.slice(0,200));let $;try{$=await wz(z,Z)}catch(Q){$=`${y} 错误: ${Q.message}`,T(`✗ ${Q.message}`)}return await p("idle"),$}var r={},rz=5000,lz=new Set(["收到","好的","ok","嗯","是的","了解","明白","确认","done","ack","roger","yes","no","在线","待命","正常","保持在线","通信正常","已收到","收到了","好","行","noted","copy","received","understood","等待任务","等待中","等待指令","无新任务","idle","waiting"]);function Hz(z,Z=!1){if(!z)return!0;if(!Z){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(lz.has(Q))return!0;if(/^[\p{Emoji}\s]+$/u.test(z.trim())&&!/[0-9a-zA-Z#*]/.test(z))return!0;return!1}function gz(z,Z){if(z===H)return"self";if(Z.startsWith(`[${H}]`))return"own-prefix";let $=Date.now();if(r[z]&&$-r[z]<rz)return"cooldown";if(Hz(Z))return"low-value-inbound";return null}async function iz(){let z=await Sz();if(!z.length)return;for(let Z of z){let $=Z.from_session||"hub",Q=Z.content,W=Z.type||"task";if(J(`← [${$}] (${W}/${Z.priority||"normal"}) ${Q.slice(0,100)}`),await hz(Z.id),W!=="task"&&W!=="broadcast"){D(`skip non-task message: type=${W}`);continue}let Y=gz($,Q);if(Y){D(`skip message from ${$}: ${Y}`);continue}let q=await nz(Q,$);if(J(`processTask returned: "${q.slice(0,80)}" (${q.length} chars)`),Hz(q,!0)){J(`skip reply: low-value (${q.slice(0,30)})`);continue}try{J(`sending reply to ${$} (task ${Z.id.slice(0,8)})...`),await fz($,`[${H}] ${q.slice(0,2000)}`,Z.id),r[$]=Date.now(),J(`→ [${$}] ${q.slice(0,100)}`)}catch(X){C(`reply failed: ${X.message}`)}}}function vz(z){return String(z.from?.id||z.chat?.id||"")}function Uz(z){return z.from?.username||z.from?.first_name||vz(z)||"telegram"}function oz(z,Z){if(z.allowFrom.length===0)return!0;let $=vz(Z),Q=Z.from?.username?String(Z.from.username):"";return z.allowFrom.includes($)||!!Q&&z.allowFrom.includes(Q)}async function d(z,Z,$){let Q=await fetch(`${z.apiBase}/${Z}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify($)}),W=await Q.json();if(!W.ok)throw Error(`telegram ${Z} failed: ${W.description||Q.statusText}`);return W.result}async function Yz(z,Z,$,Q){let W=$.match(/[\s\S]{1,4096}/g)||["(无回复)"];for(let Y=0;Y<W.length;Y++)await d(z,"sendMessage",{chat_id:Z,text:W[Y],...Q&&Y===0?{reply_to_message_id:Q}:{}})}async function Wz(z,Z,$){let Q=await d(z,"getFile",{file_id:Z}),W=String(Q.file_path||""),Y=await fetch(`${z.fileBase}/${W}`);if(!Y.ok)throw Error(`telegram file download failed: ${Y.status} ${Y.statusText}`);let q=W.split(".").pop(),X=($||W.split("/").pop()||Z).replace(/[^a-zA-Z0-9._-]/g,"_"),V=X.includes(".")||!q?X:`${X}.${q}`,G=U(z.channel.inboxDir,`${Date.now()}_${V}`);return g(G,Buffer.from(await Y.arrayBuffer())),G}async function az(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 Wz(z,Y.file_id,`photo_${Z.message_id}.jpg`);Q.push(q)}let W=String(Z.document?.mime_type||"");if(Z.document&&W.startsWith("image/")){let Y=await Wz(z,Z.document.file_id,Z.document.file_name||`image_${Z.message_id}`);Q.push(Y)}if(Q.length)$+=`
|
|
37
38
|
|
|
38
39
|
[Telegram 附件已下载]
|
|
39
40
|
${Q.map((Y)=>`- 图片: ${Y}`).join(`
|
|
40
|
-
`)}`;return{text:$.trim(),images:Q}}async function
|
|
41
|
-
`)}catch{}},W=!1,Y=[];async function q(){if(W)return;W=!0;while(Y.length){let{msg:X,updateId:V}=Y.shift();try{await
|
|
42
|
-
`);q=G.pop()||"";for(let K of G){if(!K.startsWith("data: "))continue;try{let w=JSON.parse(K.slice(6));if(w.type==="connected"){J("SSE connected");continue}if(["new_task","broadcast"].includes(w.type))J(`← SSE ${w.type}`),await
|
|
41
|
+
`)}`;return{text:$.trim(),images:Q}}async function tz(z,Z){if(!oz(z.channel,Z))return;let $=Z.chat?.id,Q=Z.message_id,W=`telegram:${Uz(Z)}`,{text:Y,images:q}=await az(z,Z);if(!$||!Q||!Y)return;D(`[TG] processing: ${Y.slice(0,80)}`);try{let X=await wz(Y,W,q);await Yz(z,$,X,Q),J(`→ [${W}] ${X.slice(0,100)}`)}catch(X){T(`telegram task failed: ${X.message}`),await Yz(z,$,`处理出错: ${X.message}`,Q).catch(()=>{})}}async function sz(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 d(Z,"getMe",{});J(`Telegram bot: @${X.username} (${X.first_name})`)}catch(X){T(`Telegram token 无效: ${X.message}`),process.exit(1)}let $=U(z.dir,"state.json");try{let X=JSON.parse(E($,"utf-8"));if(X.offset)Z.offset=X.offset,D(`Telegram offset restored: ${Z.offset}`)}catch{}let Q=()=>{try{g($,JSON.stringify({offset:Z.offset})+`
|
|
42
|
+
`)}catch{}},W=!1,Y=[];async function q(){if(W)return;W=!0;while(Y.length){let{msg:X,updateId:V}=Y.shift();try{await tz(Z,X),Z.offset=V+1,Q()}catch(G){T(`TG handle: ${G.message}`)}}W=!1}J(`Telegram polling: ${z.dir}`);while(!0)try{let V=await(await fetch(`${Z.apiBase}/getUpdates?offset=${Z.offset}&timeout=30`)).json();if(!V.ok)throw Error(V.description||"getUpdates failed");for(let G of V.result||[])if(Z.offset=G.update_id+1,G.message){let K=G.message,w=Uz(K),R=K.text||K.caption||"";if(J(`← TG [${w}] ${R.slice(0,80)}${K.photo?" +img":""}${K.document?" +file":""}`),K.chat?.id&&K.message_id)d(Z,"setMessageReaction",{chat_id:K.chat.id,message_id:K.message_id,reaction:[{type:"emoji",emoji:Y.length>0?"⏳":"\uD83D\uDC40"}]}).catch(()=>{});Y.push({msg:K,updateId:G.update_id}),q()}}catch(X){C(`Telegram polling error: ${X.message}`),await new Promise((V)=>setTimeout(V,3000))}}async function ez(){let z=`${i}/events/${encodeURIComponent(H)}`,Z=3000;while(!0){D(`SSE connecting: ${z}`);try{let $={Accept:"text/event-stream","Cache-Control":"no-cache"};if(O)$.Authorization=`Bearer ${O}`;let Q=await fetch(z,{headers:$});if(!Q.ok||!Q.body){if(Q.status===401)T("SSE 401: token 无效或未配置。检查 ~/.anet/config.json 的 token 字段");else C(`SSE failed: ${Q.status}`);await new Promise((X)=>setTimeout(X,Z)),Z=Math.min(Z*1.5,60000);continue}Z=3000;let W=Q.body.getReader(),Y=new TextDecoder,q="";while(!0){let{done:X,value:V}=await W.read();if(X)break;q+=Y.decode(V,{stream:!0});let G=q.split(`
|
|
43
|
+
`);q=G.pop()||"";for(let K of G){if(!K.startsWith("data: "))continue;try{let w=JSON.parse(K.slice(6));if(w.type==="connected"){J("SSE connected");continue}if(["new_task","broadcast"].includes(w.type))J(`← SSE ${w.type}`),await iz();if(w.type==="new_reply")J(`← SSE reply from ${w.from||"?"}${w.in_reply_to?` (task ${w.in_reply_to.slice(0,8)})`:""}`)}catch{}}}}catch($){C(`SSE error: ${$.message}`)}D(`SSE reconnecting (${Z/1000}s)...`),await new Promise(($)=>setTimeout($,Z)),Z=Math.min(Z*1.5,60000)}}J("启动");J(` runtime: ${xz}`);J(` model: ${M||(y==="codex"?"gpt-5.4":"claude-sonnet-4-6")} ${M?"":"(default)"}`);J(` hub: ${i}${O?" (auth)":" (no auth!)"}`);J(` tools: ${_.length?`[${_.join(",")}]`:"(none)"}`);J(` channels:${f.length?` telegram(${f.map((z)=>z.dir).join(",")})`:" (none)"}`);J(` session: ${x||"(new)"}`);J(` log-dir: ${o}`);await uz();J("已注册到 CommHub");setInterval(()=>p("idle").catch(()=>{}),180000);var bz=async()=>{J("shutting down..."),await p("offline").catch(()=>{}),process.exit(0)};process.on("SIGINT",bz);process.on("SIGTERM",bz);for(let z of f)sz(z);ez();
|
package/package.json
CHANGED