@sleep2agi/agent-network 0.0.50 → 0.0.52
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/bin/cli.js +51 -44
- package/package.json +1 -1
package/dist/bin/cli.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var QB=Object.defineProperty;var WB=(Q)=>Q;function XB(Q,W){this[Q]=WB.bind(null,W)}var YB=(Q,W)=>{for(var B in W)QB(Q,B,{get:W[B],enumerable:!0,configurable:!0,set:XB.bind(W,B)})};var ZB=(Q,W)=>()=>(Q&&(W=Q(Q=0)),W);var m={};YB(m,{default:()=>zB,CommHub:()=>b});import{EventEmitter as $B}from"events";import{hostname as f}from"os";var b,zB;var p=ZB(()=>{b=class b extends $B{url;alias;token;agent;resumeId;heartbeatInterval;reconnectDelay;heartbeatTimer;sseAbort;running=!1;constructor(Q){super();if(this.url=Q.url.replace(/\/$/,""),this.alias=Q.alias,this.token=Q.token,this.agent=Q.agent||"sdk",this.resumeId=`sdk-${Q.alias}-${Date.now().toString(36)}`,this.heartbeatInterval=Q.heartbeatInterval??180000,this.reconnectDelay=Q.reconnectDelay??3000,Q.autoConnect!==!1)this.connect()}log(Q){console.log(`[${new Date().toTimeString().slice(0,8)}] [commhub:${this.alias}] ${Q}`)}async call(Q,W){let B={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(this.token)B.Authorization=`Bearer ${this.token}`;let $=await(await fetch(`${this.url}/mcp`,{method:"POST",headers:B,body:JSON.stringify({jsonrpc:"2.0",id:Date.now(),method:"tools/call",params:{name:Q,arguments:W}})})).text(),
|
|
3
|
-
`);
|
|
4
|
-
`)}function c(){let Q=
|
|
5
|
-
`)}function
|
|
6
|
-
`)}function
|
|
2
|
+
var QB=Object.defineProperty;var WB=(Q)=>Q;function XB(Q,W){this[Q]=WB.bind(null,W)}var YB=(Q,W)=>{for(var B in W)QB(Q,B,{get:W[B],enumerable:!0,configurable:!0,set:XB.bind(W,B)})};var ZB=(Q,W)=>()=>(Q&&(W=Q(Q=0)),W);var m={};YB(m,{default:()=>zB,CommHub:()=>b});import{EventEmitter as $B}from"events";import{hostname as f}from"os";var b,zB;var p=ZB(()=>{b=class b extends $B{url;alias;token;agent;resumeId;heartbeatInterval;reconnectDelay;heartbeatTimer;sseAbort;running=!1;constructor(Q){super();if(this.url=Q.url.replace(/\/$/,""),this.alias=Q.alias,this.token=Q.token,this.agent=Q.agent||"sdk",this.resumeId=`sdk-${Q.alias}-${Date.now().toString(36)}`,this.heartbeatInterval=Q.heartbeatInterval??180000,this.reconnectDelay=Q.reconnectDelay??3000,Q.autoConnect!==!1)this.connect()}log(Q){console.log(`[${new Date().toTimeString().slice(0,8)}] [commhub:${this.alias}] ${Q}`)}async call(Q,W){let B={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(this.token)B.Authorization=`Bearer ${this.token}`;let $=await(await fetch(`${this.url}/mcp`,{method:"POST",headers:B,body:JSON.stringify({jsonrpc:"2.0",id:Date.now(),method:"tools/call",params:{name:Q,arguments:W}})})).text(),Z=$.match(/data: (.+)/),z=Z?JSON.parse(Z[1]):JSON.parse($),Y=z?.result?.content?.[0]?.text;return Y?JSON.parse(Y):z}async connect(){if(this.running)return;this.running=!0,await this.status("idle"),this.log("registered"),this.heartbeatTimer=setInterval(()=>{this.status("idle").catch((Q)=>this.log(`heartbeat failed: ${Q.message}`))},this.heartbeatInterval),this.connectSSE()}async disconnect(){if(this.running=!1,this.sseAbort?.abort(),this.heartbeatTimer)clearInterval(this.heartbeatTimer);await this.status("offline").catch(()=>{}),this.log("disconnected")}async send(Q,W,B="normal"){return this.call("send_task",{alias:Q,task:W,priority:B,from_session:this.alias})}async message(Q,W){return this.call("send_message",{alias:Q,message:W,from_session:this.alias})}async reply(Q,W,B="completed"){return this.call("reply",{task_id:Q,text:W,status:B})}async status(Q,W){return this.call("report_status",{resume_id:this.resumeId,alias:this.alias,status:Q,server:f(),hostname:f(),agent:this.agent,project_dir:process.cwd(),...W})}async getAllStatus(){return this.call("get_all_status",{})}async broadcast(Q,W){return this.call("broadcast",{message:Q,filter_server:W?.server,filter_status:W?.status})}async connectSSE(){let Q=encodeURIComponent(this.alias),W=`${this.url}/events/${Q}`,B=this.reconnectDelay;while(this.running){try{this.sseAbort=new AbortController;let X={Accept:"text/event-stream"};if(this.token)X.Authorization=`Bearer ${this.token}`;let $=await fetch(W,{headers:X,signal:this.sseAbort.signal});if(!$.ok||!$.body){this.log(`SSE failed: ${$.status}`),await this.sleep(B),B=Math.min(B*1.5,60000);continue}B=this.reconnectDelay;let Z=$.body.getReader(),z=new TextDecoder,Y="";while(this.running){let{done:N,value:U}=await Z.read();if(N)break;Y+=z.decode(U,{stream:!0});let E=Y.split(`
|
|
3
|
+
`);Y=E.pop()||"";for(let R of E){if(!R.startsWith("data: "))continue;try{let V=JSON.parse(R.slice(6));if(V.type==="connected"){this.log("SSE connected"),this.emit("connected");continue}if(V.type==="new_task"||V.type==="new_message"||V.type==="broadcast")await this.processInbox()}catch{}}}}catch(X){if(X.name==="AbortError")break;this.emit("error",X),this.log(`SSE error: ${X.message}`)}if(this.running)this.emit("disconnected"),this.log(`SSE reconnecting in ${B/1000}s...`),await this.sleep(B),B=Math.min(B*1.5,60000)}}async processInbox(){try{let W=(await this.call("get_inbox",{alias:this.alias,limit:10}))?.messages||[];for(let B of W)await this.call("ack_inbox",{alias:this.alias,message_id:B.id}),this.log(`← ${B.from_session}: ${B.content.slice(0,60)}`),this.emit("task",B),this.emit("message",B)}catch(Q){this.log(`inbox error: ${Q.message}`)}}sleep(Q){return new Promise((W)=>setTimeout(W,Q))}};zB=b});import{readFileSync as T,writeFileSync as K,existsSync as q,mkdirSync as M,readdirSync as w,statSync as D}from"fs";import{join as L}from"path";import{spawn as j,execSync as r}from"child_process";import{createInterface as EB}from"readline";var _=process.argv.slice(2),k=_[0],G=process.env.HOME||process.env.USERPROFILE||"~";function t(){return L(G,".anet","config.json")}function u(){return L(G,".anet","server","config.json")}function F(){return L(process.cwd(),".anet","nodes")}function n(){return I().token||process.env.COMMHUB_TOKEN||J().token||""}function y(Q){let W=Q||n();return W?{Authorization:`Bearer ${W}`}:{}}function J(){let Q=t();if(q(Q))try{return JSON.parse(T(Q,"utf-8"))}catch{}return{}}function i(Q){let W=L(G,".anet");M(W,{recursive:!0}),K(L(W,"config.json"),JSON.stringify(Q,null,2)+`
|
|
4
|
+
`)}function c(){let Q=u();if(q(Q))try{return JSON.parse(T(Q,"utf-8"))}catch{}return{}}function d(Q){let W=L(G,".anet","server");M(W,{recursive:!0}),K(L(W,"config.json"),JSON.stringify(Q,null,2)+`
|
|
5
|
+
`)}function x(Q){let W=L(F(),Q,"config.json");if(!q(W))return null;try{let B=JSON.parse(T(W,"utf-8")),X=J();return{...B,hub:B.hub||X.hub||"",token:B.token||X.token||"",env:{...B.env},flags:{...B.flags}}}catch{return null}}function P(Q,W){let B=L(F(),Q);M(B,{recursive:!0}),K(L(B,"config.json"),JSON.stringify(W,null,2)+`
|
|
6
|
+
`)}function S(){let Q=F();if(!q(Q))return[];return w(Q).filter((W)=>q(L(Q,W,"config.json")))}function I(){let Q={_channels:[],_envs:[]};for(let W=0;W<_.length;W++){if(_[W]==="--channel"&&_[W+1]){Q._channels.push(_[++W]);continue}if(_[W]==="--env"&&_[W+1]){Q._envs.push(_[++W]);continue}if(_[W].startsWith("--")&&_[W+1]&&!_[W+1].startsWith("--"))Q[_[W].slice(2)]=_[++W]}return Q}function l(){console.log(`
|
|
7
7
|
anet — AI Agent Network CLI
|
|
8
8
|
|
|
9
9
|
anet init Configure hub URL (global, once)
|
|
@@ -23,12 +23,12 @@ Quick start:
|
|
|
23
23
|
anet init --hub http://IP:9200
|
|
24
24
|
anet start 指挥室 # Claude Code Agent
|
|
25
25
|
anet start 小明 # MiniMax Agent (runtime: agent-sdk)
|
|
26
|
-
`)}async function NB(){let Q=
|
|
27
|
-
Saved to ${t()}`),console.log("Next: anet init project")}async function UB(){let Q=
|
|
28
|
-
`);try{
|
|
29
|
-
`;if(
|
|
30
|
-
`;
|
|
31
|
-
`),console.log(".mcp.json: commhub → .anet/node-server.ts");else console.log(".mcp.json: commhub already set");let L
|
|
26
|
+
`)}async function NB(){let Q=I(),W=Q.hub;if(!W)W=await O("CommHub URL (e.g. http://YOUR_IP:9200)");if(!W)v(),console.error("Error: hub URL required"),process.exit(1);W=W.replace(/\/+$/,"");let B=Q.token||"";if(!B)B=await O("Auth token (empty to skip)");v();try{let Z=await(await fetch(`${W}/health`,{headers:B?{Authorization:`Bearer ${B}`}:{}})).json();console.log(`✅ CommHub v${Z.version} — ${Z.sessions} sessions, ${Z.sse_connections} SSE`)}catch($){console.error(`❌ Cannot reach ${W}: ${$.message}`),process.exit(1)}let X=J();if(X.hub=W,B)X.token=B;else if(!X.token)delete X.token;i(X),console.log(`
|
|
27
|
+
Saved to ${t()}`),console.log("Next: anet init project")}async function UB(){let Q=J(),W=Q.hub;if(!W)console.error("Run 'anet init' first to configure hub URL"),process.exit(1);let B=L(process.cwd(),".anet");M(B,{recursive:!0});let X=L(B,"node-server.ts");if(!q(X)){let R=[L(new URL(".",import.meta.url).pathname,"..","..","src","node-server.ts"),L(new URL(".",import.meta.url).pathname,"..","src","node-server.ts"),L(process.argv[1],"..","..","src","node-server.ts")],V=!1;for(let H of R)if(q(H)){K(X,T(H,"utf-8")),console.log(" ✅ .anet/node-server.ts"),V=!0;break}if(!V)console.log(" ❌ Cannot find node-server.ts"),console.log(" Fix: cp $(npm root -g)/@sleep2agi/agent-network/src/node-server.ts .anet/node-server.ts")}else console.log(" Channel plugin: exists");let $=L(B,"package.json");if(!q($)){K($,JSON.stringify({private:!0,dependencies:{"@modelcontextprotocol/sdk":"^1.12.0"}},null,2)+`
|
|
28
|
+
`);try{r("bun install",{cwd:B,stdio:"pipe"}),console.log(" ✅ Dependencies installed")}catch{console.log(" ⚠️ Run: cd .anet && bun install")}}let Z=L(B,".env"),z=Q.token||"",Y=`COMMHUB_URL=${W}
|
|
29
|
+
`;if(z)Y+=`COMMHUB_TOKEN=${z}
|
|
30
|
+
`;K(Z,Y),console.log(`CommHub URL: ${W}${z?" (with token)":""}`);let N=L(process.cwd(),".mcp.json"),U={};if(q(N))try{U=JSON.parse(T(N,"utf-8"))}catch{}if(!U.mcpServers?.commhub)U.mcpServers=U.mcpServers||{},U.mcpServers.commhub={type:"stdio",command:"bun",args:[".anet/node-server.ts"]},K(N,JSON.stringify(U,null,2)+`
|
|
31
|
+
`),console.log(".mcp.json: commhub → .anet/node-server.ts");else console.log(".mcp.json: commhub already set");let E=L(process.cwd(),"CLAUDE.md");if(!q(E))K(E,`# Agent Network (CommHub)
|
|
32
32
|
|
|
33
33
|
## 通信方式
|
|
34
34
|
|
|
@@ -67,32 +67,32 @@ commhub_get_all_status()
|
|
|
67
67
|
- 回复指挥室用 commhub_send_task(不是 commhub_reply,reply 不推送)
|
|
68
68
|
- 不要猜 alias,用 get_all_status 查
|
|
69
69
|
`),console.log("CLAUDE.md: created");else console.log("CLAUDE.md: already exists");console.log(`
|
|
70
|
-
✅ Project ready. Next: anet init profile <id> --alias <名字> --channel server:commhub`)}function
|
|
71
|
-
`),P(Q,
|
|
72
|
-
✅ Profile "${Q}" saved`),console.log(` alias: ${X}`),console.log(` channels: ${
|
|
73
|
-
Start: anet start ${Q}`)}var
|
|
70
|
+
✅ Project ready. Next: anet init profile <id> --alias <名字> --channel server:commhub`)}function LB(){let Q=_[2];if(!Q)console.error("Usage: anet init profile <id> --alias <名字> [--channel ...] [--env ...]"),process.exit(1);let W=J(),B=I(),X=B.alias||Q,$=B.hub||W.hub;if(!$)console.error("Run 'anet init' first to configure hub URL"),process.exit(1);let Z={};for(let R of B._envs){let V=R.indexOf("=");if(V>0)Z[R.slice(0,V)]=R.slice(V+1)}let z=B.runtime||"claude-code",Y={anet_version:"0.0.24",...B.name?{name:B.name}:{},runtime:z,alias:X,hub:$,...B.model?{model:B.model}:{},...B.tools?{tools:B.tools.split(",").map((R)=>R.trim())}:{},channels:B._channels.length>0?B._channels:z==="claude-code"?["server:commhub"]:[],env:Z,flags:{dangerouslySkipPermissions:!0,...z==="claude-code"?{teammateMode:B["teammate-mode"]||"in-process"}:{},...B["max-turns"]?{maxTurns:parseInt(B["max-turns"])}:{}},...B.resume?{resume:B.resume}:{},...B["resume-alias"]?{resumeAlias:B["resume-alias"]}:{}},N=L(G,".claude","channels","commhub"),U=process.cwd().replace(/\//g,"-"),E=L(N,U);if(M(E,{recursive:!0}),K(L(E,".env"),`COMMHUB_ALIAS=${X}
|
|
71
|
+
`),P(Q,Y),console.log(`
|
|
72
|
+
✅ Profile "${Q}" saved`),console.log(` alias: ${X}`),console.log(` channels: ${Y.channels.join(", ")}`),Object.keys(Z).length)console.log(` env: ${Object.keys(Z).join(", ")}`);console.log(`
|
|
73
|
+
Start: anet start ${Q}`)}var A=null;function RB(){if(!A)A=EB({input:process.stdin,output:process.stdout});return A}function v(){if(A)A.close(),A=null}function O(Q,W){let B=W?` [${W}]`:"";return new Promise((X)=>{RB().question(`${Q}${B}: `,($)=>{X($.trim()||W||"")})})}async function VB(Q){let W=J();console.log(`
|
|
74
74
|
Profile "${Q}" not found. Let's create it:
|
|
75
|
-
`);let B=await
|
|
76
|
-
Run 'anet init' first to configure hub URL`),process.exit(1);let R={anet_version:"0.0.23",alias:X,hub:
|
|
75
|
+
`);let B=await O("Runtime (claude-code / agent-sdk)","claude-code"),X=await O("Alias",Q),$,Z=[],z=[],Y="";if(B==="agent-sdk")$=await O("Model","MiniMax-M2.7"),Z=(await O("Tools (comma-separated)","Read,Bash,Grep")).split(",").map((H)=>H.trim()).filter(Boolean);else z=(await O("Channels (comma-separated)","server:commhub")).split(",").map((H)=>H.trim()).filter(Boolean),Y=await O("Teammate mode","in-process");let N=await O("Extra env (K=V, comma-separated, empty to skip)"),U={};if(N)for(let V of N.split(",")){let H=V.trim().indexOf("=");if(H>0)U[V.trim().slice(0,H)]=V.trim().slice(H+1)}let E=W.hub;if(!E)console.error(`
|
|
76
|
+
Run 'anet init' first to configure hub URL`),process.exit(1);let R={anet_version:"0.0.23",alias:X,hub:E,runtime:B,...$?{model:$}:{},...Z.length?{tools:Z}:{},channels:z,env:U,flags:{dangerouslySkipPermissions:!0,...Y?{teammateMode:Y}:{}}};return P(Q,R),v(),console.log(`
|
|
77
77
|
✅ Profile "${Q}" saved
|
|
78
|
-
`),R}function
|
|
79
|
-
`);try{
|
|
80
|
-
`),console.log("[anet] .mcp.json: added commhub");let
|
|
81
|
-
`;if(
|
|
82
|
-
`;
|
|
83
|
-
`),console.log("[anet] .mcp.json: added commhub channel server")}async function o(Q,W){let B=
|
|
84
|
-
`),
|
|
85
|
-
`),console.log(`Quick setup: anet resume ${Q} --session <session-id>`),console.log(`Or create: anet init profile ${Q} --alias ${Q} --resume <session-id>`),process.exit(1);if(!$)console.error("Run 'anet init' first"),process.exit(1);W={runtime:"claude-code",alias:B.alias||Q,hub:$,channels:["server:commhub"],env:{},flags:{dangerouslySkipPermissions:!0,teammateMode:"in-process"},resume:
|
|
86
|
-
`)}await o(Q,"resume")}function s(Q){let W=
|
|
78
|
+
`),R}function _B(Q){if((Q.runtime||"claude-code")!=="claude-code")return;if(!Q.channels?.some((R)=>R.includes("commhub")))return;let W=L(process.cwd(),".mcp.json"),B={};if(q(W))try{B=JSON.parse(T(W,"utf-8"))}catch{}let X=L(process.cwd(),".anet"),$=L(X,"node-server.ts"),Z=[L(new URL(".",import.meta.url).pathname,"..","..","src","node-server.ts"),L(new URL(".",import.meta.url).pathname,"..","src","node-server.ts"),L(process.argv[1],"..","..","src","node-server.ts")];for(let R of Z)if(q(R)){M(X,{recursive:!0});let V=T(R,"utf-8"),H=q($)?T($,"utf-8"):"";if(V!==H)K($,V),console.log("[anet] Updated .anet/node-server.ts");break}let z=L(X,"package.json");if(!q(z)){M(X,{recursive:!0}),K(z,JSON.stringify({private:!0,dependencies:{"@modelcontextprotocol/sdk":"^1.12.0"}},null,2)+`
|
|
79
|
+
`);try{r("bun install",{cwd:X,stdio:"pipe"})}catch{}}if(B.mcpServers=B.mcpServers||{},!Object.keys(B.mcpServers).some((R)=>R.includes("commhub")))B.mcpServers.commhub={type:"stdio",command:"bun",args:[".anet/node-server.ts"]},K(W,JSON.stringify(B,null,2)+`
|
|
80
|
+
`),console.log("[anet] .mcp.json: added commhub");let N=L(X,".env"),U=Q.token||"",E=`COMMHUB_URL=${Q.hub||"http://127.0.0.1:9200"}
|
|
81
|
+
`;if(U)E+=`COMMHUB_TOKEN=${U}
|
|
82
|
+
`;K(N,E),B.mcpServers=B.mcpServers||{},B.mcpServers.commhub={type:"stdio",command:"bun",args:[".anet/node-server.ts"]},K(W,JSON.stringify(B,null,2)+`
|
|
83
|
+
`),console.log("[anet] .mcp.json: added commhub channel server")}async function o(Q,W){let B=x(Q);if(!B)B=await VB(Q);let X=B.runtime||"claude-code";console.log(`[anet] ${W==="start"?"Starting new":"Resuming"} "${Q}" (${B.alias}) [${X}]...
|
|
84
|
+
`),_B(B);let Z=B.token||"";if(X==="agent-sdk"){let z=["@sleep2agi/agent-node","--alias",B.alias,"--hub",B.hub];if(B.model)z.push("--model",B.model);if(B.tools?.length)z.push("--tools",B.tools.join(","));if(B.flags?.maxTurns)z.push("--max-turns",String(B.flags.maxTurns));if(B.codexRuntime)z.push("--runtime",B.codexRuntime);if(W==="resume"&&B.resume)z.push("--session",B.resume);let Y=L(F(),Q,"channels");if(q(Y)){for(let E of w(Y))if(q(L(Y,E,".env")))z.push("--channel",`${E}:${L(Y,E)}`)}let N={...process.env,...Z?{COMMHUB_TOKEN:Z}:{}};for(let[E,R]of Object.entries(B.env))N[E]=R.replace(/^~/,G);j("npx",z,{env:N,stdio:"inherit",shell:!0}).on("exit",(E)=>process.exit(E||0))}else{let z={...process.env,COMMHUB_ALIAS:B.alias,...Z?{COMMHUB_TOKEN:Z}:{}};for(let[U,E]of Object.entries(B.env))z[U]=E.replace(/^~/,G);let Y=[];if(B.flags.dangerouslySkipPermissions)Y.push("--dangerously-skip-permissions");for(let U of B.channels)if(U.startsWith("server:"))Y.push("--dangerously-load-development-channels",U);else Y.push("--channels",U);if(B.flags.teammateMode)Y.push("--teammate-mode",B.flags.teammateMode);if(W==="resume"){let U=B.resume||B.resumeAlias||B.name||B.alias;Y.push("--resume",U)}Y.push("-n",B.name||B.alias),j("claude",Y,{env:z,stdio:"inherit",shell:!0}).on("exit",(U)=>process.exit(U||0))}}async function a(){let Q=_[1];if(!Q){s("start");return}await o(Q,"start")}async function qB(){let Q=_[1];if(!Q){s("resume");return}let W=x(Q);if(!W){let B=I(),X=J(),$=B.hub||X.hub,Z=B.session;if(!Z)console.log(`Profile "${Q}" not found.
|
|
85
|
+
`),console.log(`Quick setup: anet resume ${Q} --session <session-id>`),console.log(`Or create: anet init profile ${Q} --alias ${Q} --resume <session-id>`),process.exit(1);if(!$)console.error("Run 'anet init' first"),process.exit(1);W={runtime:"claude-code",alias:B.alias||Q,hub:$,channels:["server:commhub"],env:{},flags:{dangerouslySkipPermissions:!0,teammateMode:"in-process"},resume:Z},P(Q,W),console.log(`[anet] Created .anet/nodes/${Q}/config.json (resume: ${Z.slice(0,8)}...)
|
|
86
|
+
`)}await o(Q,"resume")}function s(Q){let W=S();if(W.length===0){console.log("No profiles. Run: anet init profile <id> --alias <名字>");return}console.log(`
|
|
87
87
|
Profiles:
|
|
88
|
-
`);for(let B of W){let X=
|
|
88
|
+
`);for(let B of W){let X=x(B);console.log(` ${B}${X?.name?` (${X.name})`:""} → ${X?.alias} [${X?.channels.join(", ")}]`)}console.log(`
|
|
89
89
|
anet ${Q} <id>
|
|
90
|
-
`)}async function
|
|
90
|
+
`)}async function KB(){let Q=S();if(Q.length>0){console.log(`
|
|
91
91
|
Profiles:
|
|
92
|
-
`);for(let
|
|
93
|
-
`);return}let $=
|
|
94
|
-
`),console.log(" SESSION PID NETWORK"),console.log(" ──────────────────── ─────── ─────────────────────");for(let
|
|
95
|
-
`);d({port:X,host:$,token:
|
|
92
|
+
`);for(let Y of Q){let N=x(Y);console.log(` ${Y}${N?.name?` (${N.name})`:""} → ${N?.alias} [${N?.channels.join(", ")}]`)}console.log()}let W=process.cwd(),B=L(G,".claude","sessions"),X=[];if(q(B))for(let Y of w(B).filter((N)=>N.endsWith(".json")))try{let N=JSON.parse(T(L(B,Y),"utf-8"));if(N.cwd===W)X.push(N)}catch{}if(X.length===0&&Q.length===0){console.log("No sessions or profiles in this directory."),console.log(`Get started: anet init
|
|
93
|
+
`);return}let $=J(),Z=[],z={};if($.hub)try{let[Y,N]=await Promise.all([fetch(`${$.hub}/api/status`,{headers:y()}).then((U)=>U.json()),fetch(`${$.hub}/health`,{headers:y()}).then((U)=>U.json())]);Z=Y.sessions||[],z=N.sse_sessions||{}}catch{}if(X.length>0){console.log(`Sessions (${W}):
|
|
94
|
+
`),console.log(" SESSION PID NETWORK"),console.log(" ──────────────────── ─────── ─────────────────────");for(let Y of X){let N=Y.sessionId.slice(0,18),U=!1;try{process.kill(Y.pid,0),U=!0}catch{}let E="(not in network)",R=W.replace(/\//g,"-"),V=L(G,".claude","channels","commhub",R,".env");if(q(V)){let h=T(V,"utf-8").match(/COMMHUB_ALIAS=(.+)/);if(h){let C=h[1].trim(),g=Z.find((BB)=>BB.alias===C),e=z[C]?"●":"○";E=g?`${C} ${g.status} ${e}`:`${C} (not registered)`}}console.log(` ${N} ${(U?`${Y.pid}`:`${Y.pid}✕`).padEnd(7)} ${E}`)}console.log()}}async function HB(){let Q=J(),W=I(),B=process.env.COMMHUB_URL||W.hub||Q.hub||"http://127.0.0.1:9200",X=process.env.COMMHUB_ALIAS||W.alias;if(!X)console.error("Error: --alias required"),process.exit(1);let{CommHub:$}=await Promise.resolve().then(() => (p(),m)),Z=new $({url:B,alias:X});Z.on("task",async(z)=>{console.log(`[${X}] ← ${z.from_session}: ${z.content.slice(0,100)}`),await Z.send(z.from_session,`[${X}] 收到: ${z.content.slice(0,200)}`)}),Z.on("connected",()=>console.log(`[${X}] Connected`)),Z.on("disconnected",()=>console.log(`[${X}] Reconnecting...`)),process.on("SIGINT",()=>Z.disconnect().then(()=>process.exit(0))),console.log(`[${X}] Listening on ${B}`)}async function OB(){let Q=_[1];if(Q==="start"){let W=I(),B=c(),X=W.port||B.port||"9200",$=W.host||B.host||"0.0.0.0",Z=W.token||B.token||n();if(!Z)Z=crypto.randomUUID().replace(/-/g,""),console.log(`[anet] Generated auth token: ${Z}`),console.log(`[anet] Save this token — agents need it to connect.
|
|
95
|
+
`);d({port:X,host:$,token:Z});let z=J();if(!z.token)z.token=Z,i(z);console.log(`[anet] Starting CommHub Server on ${$}:${X}${Z?" (auth enabled)":""}...`);let Y={...process.env,PORT:X,HOST:$};if(Z)Y.COMMHUB_AUTH_TOKEN=Z;j("bunx",["@sleep2agi/commhub-server"],{env:Y,stdio:"inherit",shell:!0}).on("exit",(U)=>process.exit(U||0))}else if(Q==="config"){let W=I(),B=c();if(W.port)B.port=W.port;if(W.host)B.host=W.host;if(W.token)B.token=W.token;if(W.port||W.host||W.token)d(B),console.log(`Server config saved: ${u()}`);console.log(JSON.stringify(B,null,2))}else console.log(`
|
|
96
96
|
anet server <command>
|
|
97
97
|
|
|
98
98
|
start [options] Start CommHub Server
|
|
@@ -103,22 +103,22 @@ Options:
|
|
|
103
103
|
--host <host> Bind address (default: 0.0.0.0)
|
|
104
104
|
--token <token> Auth token
|
|
105
105
|
|
|
106
|
-
Config: ${
|
|
106
|
+
Config: ${u()}
|
|
107
107
|
First 'anet server start' saves config, after that just 'anet server start'.
|
|
108
108
|
|
|
109
109
|
Example:
|
|
110
110
|
anet server start --port 9200 --token my-secret # 首次,保存配置
|
|
111
111
|
anet server start # 之后直接启动
|
|
112
112
|
anet server config # 查看配置
|
|
113
|
-
`)}async function TB(){let Q=
|
|
114
|
-
`),console.log(` ✅ ${
|
|
115
|
-
Imported ${
|
|
113
|
+
`)}async function TB(){let Q=J(),B=I().hub||Q.hub;if(!B)console.error("Run 'anet init' first"),process.exit(1);let X=[];try{X=(await(await fetch(`${B}/api/status`,{headers:y()})).json()).sessions||[]}catch(N){console.error(`Cannot reach ${B}: ${N.message}`),process.exit(1)}if(X.length===0){console.log("No sessions in CommHub.");return}let $=X.filter((N)=>N.agent==="claude-code"&&N.project_dir);if($.length===0){console.log("No claude-code sessions found.");return}let Z=_[1],z=Z?$.filter((N)=>N.alias===Z):$;if(z.length===0){console.log(`No session found for "${Z}".`);return}let Y=0;for(let N of z){let U=N.project_dir,E=L(U,".anet","nodes",N.alias),R=L(E,"config.json");if(q(R)){console.log(` ⏭ ${N.alias} — already exists (${U})`);continue}if(!q(U)){console.log(` ⚠ ${N.alias} — project_dir not found: ${U}`);continue}let V={runtime:"claude-code",alias:N.alias,hub:B,channels:["server:commhub"],env:{},flags:{dangerouslySkipPermissions:!0,teammateMode:"in-process"},resume:N.resume_id};M(E,{recursive:!0}),K(R,JSON.stringify(V,null,2)+`
|
|
114
|
+
`),console.log(` ✅ ${N.alias} → ${U}/.anet/nodes/${N.alias}/config.json`),Y++}console.log(`
|
|
115
|
+
Imported ${Y} session(s). Use: cd <project> && anet resume <alias>`)}function JB(){let Q=_[1];if(Q==="ls"||Q==="list"||!Q){let W=process.cwd(),B=W.replace(/\//g,"-"),X=L(G,".claude","projects",B);if(!q(X)){console.log(`No sessions for ${W}`);return}let $=w(X).filter((Z)=>Z.endsWith(".jsonl")).sort((Z,z)=>{let Y=D(L(X,Z));return D(L(X,z)).mtimeMs-Y.mtimeMs});if($.length===0){console.log("No sessions.");return}console.log(`
|
|
116
116
|
Sessions in ${W} (${$.length} total):
|
|
117
|
-
`),console.log(" SESSION ID SIZE MODIFIED"),console.log(" ────────────────────────────────────── ──────── ────────────────");for(let
|
|
117
|
+
`),console.log(" SESSION ID SIZE MODIFIED"),console.log(" ────────────────────────────────────── ──────── ────────────────");for(let Z of $){let z=Z.replace(".jsonl",""),Y=D(L(X,Z)),N=Y.size<1024?`${Y.size}B`:Y.size<1048576?`${(Y.size/1024).toFixed(0)}KB`:`${(Y.size/1024/1024).toFixed(1)}MB`,U=Y.mtime.toISOString().replace("T"," ").slice(0,16);console.log(` ${z} ${N.padStart(8)} ${U}`)}console.log()}else console.log(`
|
|
118
118
|
anet session <command>
|
|
119
119
|
|
|
120
120
|
ls List Claude Code sessions in current project
|
|
121
|
-
`)}async function MB(){let Q=
|
|
121
|
+
`)}async function MB(){let Q=_[1],W=I();if(Q==="add"){let B=_[2],X=_[3];if(!B||!X){console.log(`
|
|
122
122
|
anet channel add <type> <node-id> [options]
|
|
123
123
|
|
|
124
124
|
Types: telegram
|
|
@@ -127,19 +127,26 @@ Options:
|
|
|
127
127
|
--bot-token <token> Bot token
|
|
128
128
|
--allow <user-id> Allow user ID
|
|
129
129
|
|
|
130
|
+
Options:
|
|
131
|
+
--bot-token <token> Bot token
|
|
132
|
+
--allow <user-id> Allow user ID
|
|
133
|
+
--runtime <rt> claude-code (默认) / codex / claude-sdk(node 不存在时)
|
|
134
|
+
--model <model> 模型名(codex 默认 gpt-5.4)
|
|
135
|
+
|
|
130
136
|
Example:
|
|
131
137
|
anet channel add telegram 指挥室 --bot-token 123:ABC --allow 7612221352
|
|
138
|
+
anet channel add telegram A站牛 --runtime codex --bot-token 123:ABC --allow 7612221352
|
|
132
139
|
anet channel add telegram 指挥室 # 交互式
|
|
133
|
-
`);return}if(B!=="telegram")console.error(`P0 only supports telegram channels. Unsupported type: ${B}`),process.exit(1);let $=
|
|
134
|
-
`),
|
|
135
|
-
`);let
|
|
136
|
-
✅ ${B} channel added to "${X}"`),console.log(` ${
|
|
140
|
+
`);return}if(B!=="telegram")console.error(`P0 only supports telegram channels. Unsupported type: ${B}`),process.exit(1);let $=x(X);if(!$){let E=J(),R=W.runtime;if(!R)R=await O("Runtime (claude-code/codex/claude-sdk)","claude-code");let V=R!=="claude-code";$={runtime:V?"agent-sdk":"claude-code",...V?{codexRuntime:R==="codex"?"codex":"claude"}:{},alias:X,hub:E.hub||"",channels:["server:commhub"],env:{},flags:{dangerouslySkipPermissions:!0,teammateMode:"in-process"},...V&&R==="codex"?{model:W.model||"gpt-5.4"}:{}},P(X,$),console.log(`[anet] Created node "${X}" (${R})`)}let Z=W["bot-token"],z=W.allow;if(!Z)Z=await O(`${B} Bot Token`);if(!z)z=await O("Allow User ID (发 @userinfobot 获取数字ID)","7612221352");if(v(),!Z||!z)console.error("Error: bot-token and allow required"),process.exit(1);let Y=L(F(),X,"channels",B);M(Y,{recursive:!0}),M(L(Y,"inbox"),{recursive:!0});let N="TELEGRAM_BOT_TOKEN";K(L(Y,".env"),`${N}=${Z}
|
|
141
|
+
`),K(L(Y,"access.json"),JSON.stringify({dmPolicy:"allowlist",allowFrom:[z],groups:{},pending:{}},null,2)+`
|
|
142
|
+
`);let U=($.runtime||"claude-code")==="agent-sdk"?`telegram:${Y}`:"plugin:telegram@claude-plugins-official";if(!$.channels.includes(U))$.channels.push(U);$.env.TELEGRAM_STATE_DIR=Y,P(X,$),console.log(`
|
|
143
|
+
✅ ${B} channel added to "${X}"`),console.log(` ${Y}/`),console.log(" config.json updated")}else if(Q==="ls"){let B=_[2],X=B?[B]:S(),$=!1;for(let Z of X){let z=L(F(),Z,"channels");if(!q(z))continue;let Y=w(z).filter((N)=>{try{return D(L(z,N)).isDirectory()}catch{return!1}});if(Y.length===0)continue;if(!$)console.log(`
|
|
137
144
|
Node Channels:
|
|
138
|
-
`),$=!0;for(let
|
|
145
|
+
`),$=!0;for(let N of Y){let U=L(z,N,"access.json"),E="";if(q(U))try{E=JSON.parse(T(U,"utf-8")).allowFrom?.join(", ")||""}catch{}console.log(` ${Z.padEnd(20)} ${N.padEnd(12)} allow: ${E||"(none)"}`)}}if(!$)console.log("No channels. Add one: anet channel add telegram <node-id>");console.log()}else console.log(`
|
|
139
146
|
anet channel <command>
|
|
140
147
|
|
|
141
148
|
add <type> <node-id> Add channel to a node
|
|
142
149
|
ls [node-id] List channels
|
|
143
150
|
|
|
144
151
|
Data: .anet/nodes/<node-id>/channels/<type>/
|
|
145
|
-
`)}switch(
|
|
152
|
+
`)}switch(k){case"init":if(_[1]==="project")UB();else if(_[1]==="profile")LB();else NB();break;case"server":OB();break;case"start":a();break;case"resume":qB();break;case"import":TB();break;case"channel":MB();break;case"session":JB();break;case"ls":case"list":KB();break;case"run":HB();break;case"-v":case"--version":case"version":{let Q=JSON.parse(T(L(new URL(".",import.meta.url).pathname,"..","..","package.json"),"utf-8"));console.log(`anet v${Q.version}`);break}case"--help":case"-h":case void 0:l();break;default:if(x(k))_.unshift("start"),a();else console.error(`Unknown: ${k}`),l(),process.exit(1)}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sleep2agi/agent-network",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.52",
|
|
4
4
|
"description": "AI Agent Network — Server + Client + Setup in one package. SSE real-time communication for multi-agent orchestration.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/src/client.js",
|