@sleep2agi/agent-network 0.0.25 → 0.0.27

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 CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as s}from"node:module";var t=Object.defineProperty;var r=(B)=>B;function o(B,Q){this[B]=r.bind(null,Q)}var a=(B,Q)=>{for(var z in Q)t(B,z,{get:Q[z],enumerable:!0,configurable:!0,set:o.bind(Q,z)})};var i=(B,Q)=>()=>(B&&(Q=B(B=0)),Q);var e=s(import.meta.url);var v={};a(v,{default:()=>Bz,CommHub:()=>x});import{EventEmitter as zz}from"events";import{hostname as P}from"os";var x,Bz;var b=i(()=>{x=class x extends zz{url;alias;token;agent;resumeId;heartbeatInterval;reconnectDelay;heartbeatTimer;sseAbort;running=!1;constructor(B){super();if(this.url=B.url.replace(/\/$/,""),this.alias=B.alias,this.token=B.token,this.agent=B.agent||"sdk",this.resumeId=`sdk-${B.alias}-${Date.now().toString(36)}`,this.heartbeatInterval=B.heartbeatInterval??180000,this.reconnectDelay=B.reconnectDelay??3000,B.autoConnect!==!1)this.connect()}log(B){console.log(`[${new Date().toTimeString().slice(0,8)}] [commhub:${this.alias}] ${B}`)}async call(B,Q){let z={"Content-Type":"application/json"};if(this.token)z.Authorization=`Bearer ${this.token}`;let N=await(await fetch(`${this.url}/mcp`,{method:"POST",headers:z,body:JSON.stringify({jsonrpc:"2.0",id:Date.now(),method:"tools/call",params:{name:B,arguments:Q}})})).json(),Y=N?.result?.content?.[0]?.text;return Y?JSON.parse(Y):N}async connect(){if(this.running)return;this.running=!0,await this.status("idle"),this.log("registered"),this.heartbeatTimer=setInterval(()=>{this.status("idle").catch((B)=>this.log(`heartbeat failed: ${B.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(B,Q,z="normal"){return this.call("send_task",{alias:B,task:Q,priority:z,from_session:this.alias})}async message(B,Q){return this.call("send_message",{alias:B,message:Q,from_session:this.alias})}async reply(B,Q,z="completed"){return this.call("reply",{task_id:B,text:Q,status:z})}async status(B,Q){return this.call("report_status",{resume_id:this.resumeId,alias:this.alias,status:B,server:P(),hostname:P(),agent:this.agent,project_dir:process.cwd(),...Q})}async getAllStatus(){return this.call("get_all_status",{})}async broadcast(B,Q){return this.call("broadcast",{message:B,filter_server:Q?.server,filter_status:Q?.status})}async connectSSE(){let B=encodeURIComponent(this.alias),Q=`${this.url}/events/${B}`,z=this.reconnectDelay;while(this.running){try{this.sseAbort=new AbortController;let W={Accept:"text/event-stream"};if(this.token)W.Authorization=`Bearer ${this.token}`;let N=await fetch(Q,{headers:W,signal:this.sseAbort.signal});if(!N.ok||!N.body){this.log(`SSE failed: ${N.status}`),await this.sleep(z),z=Math.min(z*1.5,60000);continue}z=this.reconnectDelay;let Y=N.body.getReader(),Z=new TextDecoder,$="";while(this.running){let{done:X,value:U}=await Y.read();if(X)break;$+=Z.decode(U,{stream:!0});let E=$.split(`
3
- `);$=E.pop()||"";for(let O of E){if(!O.startsWith("data: "))continue;try{let L=JSON.parse(O.slice(6));if(L.type==="connected"){this.log("SSE connected"),this.emit("connected");continue}if(L.type==="new_task"||L.type==="new_message"||L.type==="broadcast")await this.processInbox()}catch{}}}}catch(W){if(W.name==="AbortError")break;this.emit("error",W),this.log(`SSE error: ${W.message}`)}if(this.running)this.emit("disconnected"),this.log(`SSE reconnecting in ${z/1000}s...`),await this.sleep(z),z=Math.min(z*1.5,60000)}}async processInbox(){try{let Q=(await this.call("get_inbox",{alias:this.alias,limit:10}))?.messages||[];for(let z of Q)await this.call("ack_inbox",{alias:this.alias,message_id:z.id}),this.log(`← ${z.from_session}: ${z.content.slice(0,60)}`),this.emit("task",z),this.emit("message",z)}catch(B){this.log(`inbox error: ${B.message}`)}}sleep(B){return new Promise((Q)=>setTimeout(Q,B))}};Bz=x});import{readFileSync as _,writeFileSync as V,existsSync as R,mkdirSync as F,readdirSync as u}from"fs";import{join as K}from"path";import{spawn as S}from"child_process";import{createInterface as Zz}from"readline";var T=process.argv.slice(2),C=T[0],q=process.env.HOME||process.env.USERPROFILE||"~";function g(){return K(q,".anet","config.json")}function w(){return K(process.cwd(),".anet","profiles")}function H(){let B=g();if(R(B))try{return JSON.parse(_(B,"utf-8"))}catch{}return{}}function Qz(B){let Q=K(q,".anet");F(Q,{recursive:!0}),V(K(Q,"config.json"),JSON.stringify(B,null,2)+`
4
- `)}function M(B){let Q=K(w(),`${B}.json`);if(R(Q))try{return JSON.parse(_(Q,"utf-8"))}catch{}return null}function f(B,Q){let z=w();F(z,{recursive:!0}),V(K(z,`${B}.json`),JSON.stringify(Q,null,2)+`
5
- `)}function m(){let B=w();if(!R(B))return[];return u(B).filter((Q)=>Q.endsWith(".json")).map((Q)=>Q.replace(/\.json$/,""))}function A(){let B={_channels:[],_envs:[]};for(let Q=0;Q<T.length;Q++){if(T[Q]==="--channel"&&T[Q+1]){B._channels.push(T[++Q]);continue}if(T[Q]==="--env"&&T[Q+1]){B._envs.push(T[++Q]);continue}if(T[Q].startsWith("--")&&T[Q+1]&&!T[Q+1].startsWith("--"))B[T[Q].slice(2)]=T[++Q]}return B}function y(){console.log(`
2
+ import{createRequire as e}from"node:module";var r=Object.defineProperty;var o=(B)=>B;function a(B,Q){this[B]=o.bind(null,Q)}var i=(B,Q)=>{for(var z in Q)r(B,z,{get:Q[z],enumerable:!0,configurable:!0,set:a.bind(Q,z)})};var s=(B,Q)=>()=>(B&&(Q=B(B=0)),Q);var b=e(import.meta.url);var S={};i(S,{default:()=>Bz,CommHub:()=>x});import{EventEmitter as zz}from"events";import{hostname as v}from"os";var x,Bz;var y=s(()=>{x=class x extends zz{url;alias;token;agent;resumeId;heartbeatInterval;reconnectDelay;heartbeatTimer;sseAbort;running=!1;constructor(B){super();if(this.url=B.url.replace(/\/$/,""),this.alias=B.alias,this.token=B.token,this.agent=B.agent||"sdk",this.resumeId=`sdk-${B.alias}-${Date.now().toString(36)}`,this.heartbeatInterval=B.heartbeatInterval??180000,this.reconnectDelay=B.reconnectDelay??3000,B.autoConnect!==!1)this.connect()}log(B){console.log(`[${new Date().toTimeString().slice(0,8)}] [commhub:${this.alias}] ${B}`)}async call(B,Q){let z={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(this.token)z.Authorization=`Bearer ${this.token}`;let N=await(await fetch(`${this.url}/mcp`,{method:"POST",headers:z,body:JSON.stringify({jsonrpc:"2.0",id:Date.now(),method:"tools/call",params:{name:B,arguments:Q}})})).text(),$=N.match(/data: (.+)/),X=$?JSON.parse($[1]):JSON.parse(N),Z=X?.result?.content?.[0]?.text;return Z?JSON.parse(Z):X}async connect(){if(this.running)return;this.running=!0,await this.status("idle"),this.log("registered"),this.heartbeatTimer=setInterval(()=>{this.status("idle").catch((B)=>this.log(`heartbeat failed: ${B.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(B,Q,z="normal"){return this.call("send_task",{alias:B,task:Q,priority:z,from_session:this.alias})}async message(B,Q){return this.call("send_message",{alias:B,message:Q,from_session:this.alias})}async reply(B,Q,z="completed"){return this.call("reply",{task_id:B,text:Q,status:z})}async status(B,Q){return this.call("report_status",{resume_id:this.resumeId,alias:this.alias,status:B,server:v(),hostname:v(),agent:this.agent,project_dir:process.cwd(),...Q})}async getAllStatus(){return this.call("get_all_status",{})}async broadcast(B,Q){return this.call("broadcast",{message:B,filter_server:Q?.server,filter_status:Q?.status})}async connectSSE(){let B=encodeURIComponent(this.alias),Q=`${this.url}/events/${B}`,z=this.reconnectDelay;while(this.running){try{this.sseAbort=new AbortController;let W={Accept:"text/event-stream"};if(this.token)W.Authorization=`Bearer ${this.token}`;let N=await fetch(Q,{headers:W,signal:this.sseAbort.signal});if(!N.ok||!N.body){this.log(`SSE failed: ${N.status}`),await this.sleep(z),z=Math.min(z*1.5,60000);continue}z=this.reconnectDelay;let $=N.body.getReader(),X=new TextDecoder,Z="";while(this.running){let{done:Y,value:U}=await $.read();if(Y)break;Z+=X.decode(U,{stream:!0});let O=Z.split(`
3
+ `);Z=O.pop()||"";for(let T of O){if(!T.startsWith("data: "))continue;try{let E=JSON.parse(T.slice(6));if(E.type==="connected"){this.log("SSE connected"),this.emit("connected");continue}if(E.type==="new_task"||E.type==="new_message"||E.type==="broadcast")await this.processInbox()}catch{}}}}catch(W){if(W.name==="AbortError")break;this.emit("error",W),this.log(`SSE error: ${W.message}`)}if(this.running)this.emit("disconnected"),this.log(`SSE reconnecting in ${z/1000}s...`),await this.sleep(z),z=Math.min(z*1.5,60000)}}async processInbox(){try{let Q=(await this.call("get_inbox",{alias:this.alias,limit:10}))?.messages||[];for(let z of Q)await this.call("ack_inbox",{alias:this.alias,message_id:z.id}),this.log(`← ${z.from_session}: ${z.content.slice(0,60)}`),this.emit("task",z),this.emit("message",z)}catch(B){this.log(`inbox error: ${B.message}`)}}sleep(B){return new Promise((Q)=>setTimeout(Q,B))}};Bz=x});import{readFileSync as G,writeFileSync as H,existsSync as I,mkdirSync as F,readdirSync as f}from"fs";import{join as K}from"path";import{spawn as w}from"child_process";import{createInterface as Zz}from"readline";var L=process.argv.slice(2),A=L[0],J=process.env.HOME||process.env.USERPROFILE||"~";function g(){return K(J,".anet","config.json")}function k(){return K(process.cwd(),".anet","profiles")}function _(){let B=g();if(I(B))try{return JSON.parse(G(B,"utf-8"))}catch{}return{}}function Qz(B){let Q=K(J,".anet");F(Q,{recursive:!0}),H(K(Q,"config.json"),JSON.stringify(B,null,2)+`
4
+ `)}function M(B){let Q=K(k(),`${B}.json`);if(I(Q))try{return JSON.parse(G(Q,"utf-8"))}catch{}return null}function m(B,Q){let z=k();F(z,{recursive:!0}),H(K(z,`${B}.json`),JSON.stringify(Q,null,2)+`
5
+ `)}function c(){let B=k();if(!I(B))return[];return f(B).filter((Q)=>Q.endsWith(".json")).map((Q)=>Q.replace(/\.json$/,""))}function C(){let B={_channels:[],_envs:[]};for(let Q=0;Q<L.length;Q++){if(L[Q]==="--channel"&&L[Q+1]){B._channels.push(L[++Q]);continue}if(L[Q]==="--env"&&L[Q+1]){B._envs.push(L[++Q]);continue}if(L[Q].startsWith("--")&&L[Q+1]&&!L[Q+1].startsWith("--"))B[L[Q].slice(2)]=L[++Q]}return B}function u(){console.log(`
6
6
  anet — AI Agent Network CLI
7
7
 
8
8
  anet init Configure hub URL (global, once)
@@ -11,20 +11,20 @@ anet — AI Agent Network CLI
11
11
  anet start <id> New session with profile
12
12
  anet resume <id> Resume last session with profile
13
13
  anet ls Show profiles + sessions + network
14
+ anet server start Start CommHub Server
14
15
  anet run Run standalone SSE agent
15
16
  anet --help This help
16
17
 
17
18
  Quick start:
18
- anet init
19
- anet init project
20
- anet init profile 指挥室 --alias 指挥室 --channel server:commhub
21
- anet start 指挥室 # 新建
22
- anet resume 指挥室 # 下次恢复
23
- `)}async function Wz(){let B=A(),Q=B.hub;if(!Q)Q=await J("CommHub URL (e.g. http://YOUR_IP:9200)"),c();if(!Q)console.error("Error: hub URL required"),process.exit(1);Q=Q.replace(/\/+$/,"");try{let N=await(await fetch(`${Q}/health`)).json();console.log(`✅ CommHub v${N.version} ${N.sessions} sessions, ${N.sse_connections} SSE`)}catch(W){console.error(`❌ Cannot reach ${Q}: ${W.message}`),process.exit(1)}let z=H();if(z.hub=Q,B.token)z.token=B.token;Qz(z),console.log(`
24
- Saved to ${g()}`),console.log("Next: anet init project")}async function Xz(){let Q=H().hub;if(!Q)console.error("Run 'anet init' first to configure hub URL"),process.exit(1);let z=K(process.cwd(),".anet");F(z,{recursive:!0});let W=K(z,"node-server.ts");if(!R(W)){let U=[K(new URL(".",import.meta.url).pathname,"..","..","src","node-server.ts"),K(new URL(".",import.meta.url).pathname,"..","src","node-server.ts"),K(process.argv[1],"..","..","src","node-server.ts")],E=!1;for(let O of U)if(R(O)){V(W,_(O,"utf-8")),console.log(" ✅ .anet/node-server.ts"),E=!0;break}if(!E)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 N=K(z,"package.json");if(!R(N)){V(N,JSON.stringify({private:!0,dependencies:{"@modelcontextprotocol/sdk":"^1.12.0"}},null,2)+`
25
- `);try{let{execSync:U}=await import("child_process");U("bun install",{cwd:z,stdio:"pipe"}),console.log(" ✅ Dependencies installed")}catch{console.log(" ⚠️ Run: cd .anet && bun install")}}let Y=K(z,".env");V(Y,`COMMHUB_URL=${Q}
26
- `),console.log(`CommHub URL: ${Q}`);let Z=K(process.cwd(),".mcp.json"),$={};if(R(Z))try{$=JSON.parse(_(Z,"utf-8"))}catch{}if(!$.mcpServers?.commhub)$.mcpServers=$.mcpServers||{},$.mcpServers.commhub={type:"stdio",command:"bun",args:[".anet/node-server.ts"]},V(Z,JSON.stringify($,null,2)+`
27
- `),console.log(".mcp.json: commhub → .anet/node-server.ts");else console.log(".mcp.json: commhub already set");let X=K(process.cwd(),"CLAUDE.md");if(!R(X))V(X,`# Agent Network (CommHub)
19
+ anet server start # 启动 CommHub Server
20
+ anet init --hub http://IP:9200
21
+ anet start 指挥室 # Claude Code Agent
22
+ anet start 小明 # MiniMax Agent (runtime: agent-sdk)
23
+ `)}async function Wz(){let B=C(),Q=B.hub;if(!Q)Q=await V("CommHub URL (e.g. http://YOUR_IP:9200)"),p();if(!Q)console.error("Error: hub URL required"),process.exit(1);Q=Q.replace(/\/+$/,"");try{let N=await(await fetch(`${Q}/health`)).json();console.log(`✅ CommHub v${N.version} — ${N.sessions} sessions, ${N.sse_connections} SSE`)}catch(W){console.error(`❌ Cannot reach ${Q}: ${W.message}`),process.exit(1)}let z=_();if(z.hub=Q,B.token)z.token=B.token;Qz(z),console.log(`
24
+ Saved to ${g()}`),console.log("Next: anet init project")}async function Xz(){let Q=_().hub;if(!Q)console.error("Run 'anet init' first to configure hub URL"),process.exit(1);let z=K(process.cwd(),".anet");F(z,{recursive:!0});let W=K(z,"node-server.ts");if(!I(W)){let U=[K(new URL(".",import.meta.url).pathname,"..","..","src","node-server.ts"),K(new URL(".",import.meta.url).pathname,"..","src","node-server.ts"),K(process.argv[1],"..","..","src","node-server.ts")],O=!1;for(let T of U)if(I(T)){H(W,G(T,"utf-8")),console.log(" ✅ .anet/node-server.ts"),O=!0;break}if(!O)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 N=K(z,"package.json");if(!I(N)){H(N,JSON.stringify({private:!0,dependencies:{"@modelcontextprotocol/sdk":"^1.12.0"}},null,2)+`
25
+ `);try{let{execSync:U}=await import("child_process");U("bun install",{cwd:z,stdio:"pipe"}),console.log(" ✅ Dependencies installed")}catch{console.log(" ⚠️ Run: cd .anet && bun install")}}let $=K(z,".env");H($,`COMMHUB_URL=${Q}
26
+ `),console.log(`CommHub URL: ${Q}`);let X=K(process.cwd(),".mcp.json"),Z={};if(I(X))try{Z=JSON.parse(G(X,"utf-8"))}catch{}if(!Z.mcpServers?.commhub)Z.mcpServers=Z.mcpServers||{},Z.mcpServers.commhub={type:"stdio",command:"bun",args:[".anet/node-server.ts"]},H(X,JSON.stringify(Z,null,2)+`
27
+ `),console.log(".mcp.json: commhub → .anet/node-server.ts");else console.log(".mcp.json: commhub already set");let Y=K(process.cwd(),"CLAUDE.md");if(!I(Y))H(Y,`# Agent Network (CommHub)
28
28
 
29
29
  ## 通信方式
30
30
 
@@ -63,24 +63,38 @@ commhub_get_all_status()
63
63
  - 回复指挥室用 commhub_send_task(不是 commhub_reply,reply 不推送)
64
64
  - 不要猜 alias,用 get_all_status 查
65
65
  `),console.log("CLAUDE.md: created");else console.log("CLAUDE.md: already exists");console.log(`
66
- ✅ Project ready. Next: anet init profile <id> --alias <名字> --channel server:commhub`)}function Yz(){let B=T[2];if(!B)console.error("Usage: anet init profile <id> --alias <名字> [--channel ...] [--env ...]"),process.exit(1);let Q=H(),z=A(),W=z.alias||B,N=z.hub||Q.hub;if(!N)console.error("Run 'anet init' first to configure hub URL"),process.exit(1);let Y={};for(let O of z._envs){let L=O.indexOf("=");if(L>0)Y[O.slice(0,L)]=O.slice(L+1)}let Z=z.runtime||"claude-code",$={anet_version:"0.0.24",...z.name?{name:z.name}:{},runtime:Z,alias:W,hub:N,...z.model?{model:z.model}:{},...z.tools?{tools:z.tools.split(",").map((O)=>O.trim())}:{},channels:z._channels.length>0?z._channels:Z==="claude-code"?["server:commhub"]:[],env:Y,flags:{dangerouslySkipPermissions:!0,...Z==="claude-code"?{teammateMode:z["teammate-mode"]||"in-process"}:{},...z["max-turns"]?{maxTurns:parseInt(z["max-turns"])}:{}},...z.resume?{resume:z.resume}:{},...z["resume-alias"]?{resumeAlias:z["resume-alias"]}:{}},X=K(q,".claude","channels","commhub"),U=process.cwd().replace(/\//g,"-"),E=K(X,U);if(F(E,{recursive:!0}),V(K(E,".env"),`COMMHUB_ALIAS=${W}
67
- `),f(B,$),console.log(`
68
- ✅ Profile "${B}" saved`),console.log(` alias: ${W}`),console.log(` channels: ${$.channels.join(", ")}`),Object.keys(Y).length)console.log(` env: ${Object.keys(Y).join(", ")}`);console.log(`
69
- Start: anet start ${B}`)}var G=null;function $z(){if(!G)G=Zz({input:process.stdin,output:process.stdout});return G}function c(){if(G)G.close(),G=null}function J(B,Q){let z=Q?` [${Q}]`:"";return new Promise((W)=>{$z().question(`${B}${z}: `,(N)=>{W(N.trim()||Q||"")})})}async function Nz(B){let Q=H();console.log(`
66
+ ✅ Project ready. Next: anet init profile <id> --alias <名字> --channel server:commhub`)}function Yz(){let B=L[2];if(!B)console.error("Usage: anet init profile <id> --alias <名字> [--channel ...] [--env ...]"),process.exit(1);let Q=_(),z=C(),W=z.alias||B,N=z.hub||Q.hub;if(!N)console.error("Run 'anet init' first to configure hub URL"),process.exit(1);let $={};for(let T of z._envs){let E=T.indexOf("=");if(E>0)$[T.slice(0,E)]=T.slice(E+1)}let X=z.runtime||"claude-code",Z={anet_version:"0.0.24",...z.name?{name:z.name}:{},runtime:X,alias:W,hub:N,...z.model?{model:z.model}:{},...z.tools?{tools:z.tools.split(",").map((T)=>T.trim())}:{},channels:z._channels.length>0?z._channels:X==="claude-code"?["server:commhub"]:[],env:$,flags:{dangerouslySkipPermissions:!0,...X==="claude-code"?{teammateMode:z["teammate-mode"]||"in-process"}:{},...z["max-turns"]?{maxTurns:parseInt(z["max-turns"])}:{}},...z.resume?{resume:z.resume}:{},...z["resume-alias"]?{resumeAlias:z["resume-alias"]}:{}},Y=K(J,".claude","channels","commhub"),U=process.cwd().replace(/\//g,"-"),O=K(Y,U);if(F(O,{recursive:!0}),H(K(O,".env"),`COMMHUB_ALIAS=${W}
67
+ `),m(B,Z),console.log(`
68
+ ✅ Profile "${B}" saved`),console.log(` alias: ${W}`),console.log(` channels: ${Z.channels.join(", ")}`),Object.keys($).length)console.log(` env: ${Object.keys($).join(", ")}`);console.log(`
69
+ Start: anet start ${B}`)}var q=null;function $z(){if(!q)q=Zz({input:process.stdin,output:process.stdout});return q}function p(){if(q)q.close(),q=null}function V(B,Q){let z=Q?` [${Q}]`:"";return new Promise((W)=>{$z().question(`${B}${z}: `,(N)=>{W(N.trim()||Q||"")})})}async function Nz(B){let Q=_();console.log(`
70
70
  Profile "${B}" not found. Let's create it:
71
- `);let z=await J("Runtime (claude-code / agent-sdk)","claude-code"),W=await J("Alias",B),N,Y=[],Z=[],$="";if(z==="agent-sdk")N=await J("Model","MiniMax-M2.7"),Y=(await J("Tools (comma-separated)","Read,Bash,Grep")).split(",").map((I)=>I.trim()).filter(Boolean);else Z=(await J("Channels (comma-separated)","server:commhub")).split(",").map((I)=>I.trim()).filter(Boolean),$=await J("Teammate mode","in-process");let X=await J("Extra env (K=V, comma-separated, empty to skip)"),U={};if(X)for(let L of X.split(",")){let I=L.trim().indexOf("=");if(I>0)U[L.trim().slice(0,I)]=L.trim().slice(I+1)}let E=Q.hub;if(!E)console.error(`
72
- Run 'anet init' first to configure hub URL`),process.exit(1);let O={anet_version:"0.0.23",alias:W,hub:E,runtime:z,...N?{model:N}:{},...Y.length?{tools:Y}:{},channels:Z,env:U,flags:{dangerouslySkipPermissions:!0,...$?{teammateMode:$}:{}}};return f(B,O),c(),console.log(`
71
+ `);let z=await V("Runtime (claude-code / agent-sdk)","claude-code"),W=await V("Alias",B),N,$=[],X=[],Z="";if(z==="agent-sdk")N=await V("Model","MiniMax-M2.7"),$=(await V("Tools (comma-separated)","Read,Bash,Grep")).split(",").map((R)=>R.trim()).filter(Boolean);else X=(await V("Channels (comma-separated)","server:commhub")).split(",").map((R)=>R.trim()).filter(Boolean),Z=await V("Teammate mode","in-process");let Y=await V("Extra env (K=V, comma-separated, empty to skip)"),U={};if(Y)for(let E of Y.split(",")){let R=E.trim().indexOf("=");if(R>0)U[E.trim().slice(0,R)]=E.trim().slice(R+1)}let O=Q.hub;if(!O)console.error(`
72
+ Run 'anet init' first to configure hub URL`),process.exit(1);let T={anet_version:"0.0.23",alias:W,hub:O,runtime:z,...N?{model:N}:{},...$.length?{tools:$}:{},channels:X,env:U,flags:{dangerouslySkipPermissions:!0,...Z?{teammateMode:Z}:{}}};return m(B,T),p(),console.log(`
73
73
  ✅ Profile "${B}" saved
74
- `),O}async function p(B,Q){let z=M(B);if(!z)z=await Nz(B);let W=z.runtime||"claude-code";if(console.log(`[anet] ${Q==="start"?"Starting new":"Resuming"} "${B}" (${z.alias}) [${W}]...
75
- `),W==="agent-sdk"){let Y=["@sleep2agi/agent-node","--alias",z.alias,"--hub",z.hub];if(z.model)Y.push("--model",z.model);if(z.tools?.length)Y.push("--tools",z.tools.join(","));if(z.flags?.maxTurns)Y.push("--max-turns",String(z.flags.maxTurns));let Z={...process.env};for(let[X,U]of Object.entries(z.env))Z[X]=U.replace(/^~/,q);S("npx",Y,{env:Z,stdio:"inherit",shell:!0}).on("exit",(X)=>process.exit(X||0))}else{let Y={...process.env,COMMHUB_ALIAS:z.alias};for(let[X,U]of Object.entries(z.env))Y[X]=U.replace(/^~/,q);let Z=[];if(z.flags.dangerouslySkipPermissions)Z.push("--dangerously-skip-permissions");for(let X of z.channels)if(X.startsWith("server:"))Z.push("--dangerously-load-development-channels",X);else Z.push("--channels",X);if(z.flags.teammateMode)Z.push("--teammate-mode",z.flags.teammateMode);if(Q==="resume"){let X=z.resumeAlias||z.name||z.alias;Z.push("--resume",X)}Z.push("-n",z.name||z.alias),S("claude",Z,{env:Y,stdio:"inherit",shell:!0}).on("exit",(X)=>process.exit(X||0))}}async function h(){let B=T[1];if(!B){d("start");return}await p(B,"start")}async function Uz(){let B=T[1];if(!B){d("resume");return}if(!M(B))console.log(`Profile "${B}" not found. Create one first:
74
+ `),T}async function d(B,Q){let z=M(B);if(!z)z=await Nz(B);let W=z.runtime||"claude-code";if(console.log(`[anet] ${Q==="start"?"Starting new":"Resuming"} "${B}" (${z.alias}) [${W}]...
75
+ `),W==="agent-sdk"){let $=["@sleep2agi/agent-node","--alias",z.alias,"--hub",z.hub];if(z.model)$.push("--model",z.model);if(z.tools?.length)$.push("--tools",z.tools.join(","));if(z.flags?.maxTurns)$.push("--max-turns",String(z.flags.maxTurns));let X={...process.env};for(let[Y,U]of Object.entries(z.env))X[Y]=U.replace(/^~/,J);w("npx",$,{env:X,stdio:"inherit",shell:!0}).on("exit",(Y)=>process.exit(Y||0))}else{let $={...process.env,COMMHUB_ALIAS:z.alias};for(let[Y,U]of Object.entries(z.env))$[Y]=U.replace(/^~/,J);let X=[];if(z.flags.dangerouslySkipPermissions)X.push("--dangerously-skip-permissions");for(let Y of z.channels)if(Y.startsWith("server:"))X.push("--dangerously-load-development-channels",Y);else X.push("--channels",Y);if(z.flags.teammateMode)X.push("--teammate-mode",z.flags.teammateMode);if(Q==="resume"){let Y=z.resumeAlias||z.name||z.alias;X.push("--resume",Y)}X.push("-n",z.name||z.alias),w("claude",X,{env:$,stdio:"inherit",shell:!0}).on("exit",(Y)=>process.exit(Y||0))}}async function h(){let B=L[1];if(!B){l("start");return}await d(B,"start")}async function Uz(){let B=L[1];if(!B){l("resume");return}if(!M(B))console.log(`Profile "${B}" not found. Create one first:
76
76
 
77
77
  anet start ${B}
78
- `),process.exit(1);await p(B,"resume")}function d(B){let Q=m();if(Q.length===0){console.log("No profiles. Run: anet init profile <id> --alias <名字>");return}console.log(`
78
+ `),process.exit(1);await d(B,"resume")}function l(B){let Q=c();if(Q.length===0){console.log("No profiles. Run: anet init profile <id> --alias <名字>");return}console.log(`
79
79
  Profiles:
80
80
  `);for(let z of Q){let W=M(z);console.log(` ${z}${W?.name?` (${W.name})`:""} → ${W?.alias} [${W?.channels.join(", ")}]`)}console.log(`
81
81
  anet ${B} <id>
82
- `)}async function Kz(){let B=m();if(B.length>0){console.log(`
82
+ `)}async function Kz(){let B=c();if(B.length>0){console.log(`
83
83
  Profiles:
84
- `);for(let $ of B){let X=M($);console.log(` ${$}${X?.name?` (${X.name})`:""} → ${X?.alias} [${X?.channels.join(", ")}]`)}console.log()}let Q=process.cwd(),z=K(q,".claude","sessions"),W=[];if(R(z))for(let $ of u(z).filter((X)=>X.endsWith(".json")))try{let X=JSON.parse(_(K(z,$),"utf-8"));if(X.cwd===Q)W.push(X)}catch{}if(W.length===0&&B.length===0){console.log("No sessions or profiles in this directory."),console.log(`Get started: anet init
85
- `);return}let N=H(),Y=[],Z={};if(N.hub)try{let[$,X]=await Promise.all([fetch(`${N.hub}/api/status`).then((U)=>U.json()),fetch(`${N.hub}/health`).then((U)=>U.json())]);Y=$.sessions||[],Z=X.sse_sessions||{}}catch{}if(W.length>0){console.log(`Sessions (${Q}):
86
- `),console.log(" SESSION PID NETWORK"),console.log(" ──────────────────── ─────── ─────────────────────");for(let $ of W){let X=$.sessionId.slice(0,18),U=!1;try{process.kill($.pid,0),U=!0}catch{}let E="(not in network)",O=Q.replace(/\//g,"-"),L=K(q,".claude","channels","commhub",O,".env");if(R(L)){let k=_(L,"utf-8").match(/COMMHUB_ALIAS=(.+)/);if(k){let D=k[1].trim(),j=Y.find((l)=>l.alias===D),n=Z[D]?"●":"○";E=j?`${D} ${j.status} ${n}`:`${D} (not registered)`}}console.log(` ${X} ${(U?`${$.pid}`:`${$.pid}✕`).padEnd(7)} ${E}`)}console.log()}}async function Tz(){let B=H(),Q=A(),z=process.env.COMMHUB_URL||Q.hub||B.hub||"http://127.0.0.1:9200",W=process.env.COMMHUB_ALIAS||Q.alias;if(!W)console.error("Error: --alias required"),process.exit(1);let{CommHub:N}=await Promise.resolve().then(() => (b(),v)),Y=new N({url:z,alias:W});Y.on("task",async(Z)=>{console.log(`[${W}] ← ${Z.from_session}: ${Z.content.slice(0,100)}`),await Y.send(Z.from_session,`[${W}] 收到: ${Z.content.slice(0,200)}`)}),Y.on("connected",()=>console.log(`[${W}] Connected`)),Y.on("disconnected",()=>console.log(`[${W}] Reconnecting...`)),process.on("SIGINT",()=>Y.disconnect().then(()=>process.exit(0))),console.log(`[${W}] Listening on ${z}`)}switch(C){case"init":if(T[1]==="project")Xz();else if(T[1]==="profile")Yz();else Wz();break;case"start":h();break;case"resume":Uz();break;case"ls":case"list":Kz();break;case"run":Tz();break;case"--help":case"-h":case void 0:y();break;default:if(M(C))T.unshift("start"),h();else console.error(`Unknown: ${C}`),y(),process.exit(1)}
84
+ `);for(let Z of B){let Y=M(Z);console.log(` ${Z}${Y?.name?` (${Y.name})`:""} → ${Y?.alias} [${Y?.channels.join(", ")}]`)}console.log()}let Q=process.cwd(),z=K(J,".claude","sessions"),W=[];if(I(z))for(let Z of f(z).filter((Y)=>Y.endsWith(".json")))try{let Y=JSON.parse(G(K(z,Z),"utf-8"));if(Y.cwd===Q)W.push(Y)}catch{}if(W.length===0&&B.length===0){console.log("No sessions or profiles in this directory."),console.log(`Get started: anet init
85
+ `);return}let N=_(),$=[],X={};if(N.hub)try{let[Z,Y]=await Promise.all([fetch(`${N.hub}/api/status`).then((U)=>U.json()),fetch(`${N.hub}/health`).then((U)=>U.json())]);$=Z.sessions||[],X=Y.sse_sessions||{}}catch{}if(W.length>0){console.log(`Sessions (${Q}):
86
+ `),console.log(" SESSION PID NETWORK"),console.log(" ──────────────────── ─────── ─────────────────────");for(let Z of W){let Y=Z.sessionId.slice(0,18),U=!1;try{process.kill(Z.pid,0),U=!0}catch{}let O="(not in network)",T=Q.replace(/\//g,"-"),E=K(J,".claude","channels","commhub",T,".env");if(I(E)){let j=G(E,"utf-8").match(/COMMHUB_ALIAS=(.+)/);if(j){let D=j[1].trim(),P=$.find((t)=>t.alias===D),n=X[D]?"●":"○";O=P?`${D} ${P.status} ${n}`:`${D} (not registered)`}}console.log(` ${Y} ${(U?`${Z.pid}`:`${Z.pid}✕`).padEnd(7)} ${O}`)}console.log()}}async function Lz(){let B=_(),Q=C(),z=process.env.COMMHUB_URL||Q.hub||B.hub||"http://127.0.0.1:9200",W=process.env.COMMHUB_ALIAS||Q.alias;if(!W)console.error("Error: --alias required"),process.exit(1);let{CommHub:N}=await Promise.resolve().then(() => (y(),S)),$=new N({url:z,alias:W});$.on("task",async(X)=>{console.log(`[${W}] ← ${X.from_session}: ${X.content.slice(0,100)}`),await $.send(X.from_session,`[${W}] 收到: ${X.content.slice(0,200)}`)}),$.on("connected",()=>console.log(`[${W}] Connected`)),$.on("disconnected",()=>console.log(`[${W}] Reconnecting...`)),process.on("SIGINT",()=>$.disconnect().then(()=>process.exit(0))),console.log(`[${W}] Listening on ${z}`)}async function Tz(){if(L[1]==="start"){let Q=C(),z=Q.port||"9200",W=Q.host||"0.0.0.0",N=Q.token||"",$=[K(process.cwd(),"server","src","index.ts"),K(J,"agent-orchestra","server","src","index.ts"),K(J,"agent-network","server","src","index.ts")],X="";for(let U of $)if(I(U)){X=U;break}if(!X)try{let{execSync:U}=await import("child_process"),O=U("npm root -g",{encoding:"utf-8"}).trim(),T=K(O,"@sleep2agi","commhub-server","src","index.ts");if(I(T))X=T}catch{}if(!X)console.error("CommHub Server not found."),console.error("Install: npm install -g @sleep2agi/commhub-server"),console.error("Or clone: git clone https://github.com/sleep2agi/agent-network.git && cd agent-network/server && bun install"),process.exit(1);console.log(`[anet] Starting CommHub Server on ${W}:${z}...`);let Z={...process.env,PORT:z,HOST:W};if(N)Z.COMMHUB_AUTH_TOKEN=N;w("bun",["run",X],{env:Z,stdio:"inherit"}).on("exit",(U)=>process.exit(U||0))}else console.log(`
87
+ anet server <command>
88
+
89
+ start [options] Start CommHub Server
90
+
91
+ Options:
92
+ --port <port> Port (default: 9200)
93
+ --host <host> Bind address (default: 0.0.0.0)
94
+ --token <token> Auth token
95
+
96
+ Example:
97
+ anet server start
98
+ anet server start --port 9200 --token my-secret
99
+ anet server start --host 0.0.0.0 --port 9200
100
+ `)}switch(A){case"init":if(L[1]==="project")Xz();else if(L[1]==="profile")Yz();else Wz();break;case"server":Tz();break;case"start":h();break;case"resume":Uz();break;case"ls":case"list":Kz();break;case"run":Lz();break;case"--help":case"-h":case void 0:u();break;default:if(M(A))L.unshift("start"),h();else console.error(`Unknown: ${A}`),u(),process.exit(1)}
@@ -1,2 +1,2 @@
1
- import{EventEmitter as W}from"events";import{hostname as P}from"os";class Q extends W{url;alias;token;agent;resumeId;heartbeatInterval;reconnectDelay;heartbeatTimer;sseAbort;running=!1;constructor(j){super();if(this.url=j.url.replace(/\/$/,""),this.alias=j.alias,this.token=j.token,this.agent=j.agent||"sdk",this.resumeId=`sdk-${j.alias}-${Date.now().toString(36)}`,this.heartbeatInterval=j.heartbeatInterval??180000,this.reconnectDelay=j.reconnectDelay??3000,j.autoConnect!==!1)this.connect()}log(j){console.log(`[${new Date().toTimeString().slice(0,8)}] [commhub:${this.alias}] ${j}`)}async call(j,w){let q={"Content-Type":"application/json"};if(this.token)q.Authorization=`Bearer ${this.token}`;let B=await(await fetch(`${this.url}/mcp`,{method:"POST",headers:q,body:JSON.stringify({jsonrpc:"2.0",id:Date.now(),method:"tools/call",params:{name:j,arguments:w}})})).json(),D=B?.result?.content?.[0]?.text;return D?JSON.parse(D):B}async connect(){if(this.running)return;this.running=!0,await this.status("idle"),this.log("registered"),this.heartbeatTimer=setInterval(()=>{this.status("idle").catch((j)=>this.log(`heartbeat failed: ${j.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(j,w,q="normal"){return this.call("send_task",{alias:j,task:w,priority:q,from_session:this.alias})}async message(j,w){return this.call("send_message",{alias:j,message:w,from_session:this.alias})}async reply(j,w,q="completed"){return this.call("reply",{task_id:j,text:w,status:q})}async status(j,w){return this.call("report_status",{resume_id:this.resumeId,alias:this.alias,status:j,server:P(),hostname:P(),agent:this.agent,project_dir:process.cwd(),...w})}async getAllStatus(){return this.call("get_all_status",{})}async broadcast(j,w){return this.call("broadcast",{message:j,filter_server:w?.server,filter_status:w?.status})}async connectSSE(){let j=encodeURIComponent(this.alias),w=`${this.url}/events/${j}`,q=this.reconnectDelay;while(this.running){try{this.sseAbort=new AbortController;let z={Accept:"text/event-stream"};if(this.token)z.Authorization=`Bearer ${this.token}`;let B=await fetch(w,{headers:z,signal:this.sseAbort.signal});if(!B.ok||!B.body){this.log(`SSE failed: ${B.status}`),await this.sleep(q),q=Math.min(q*1.5,60000);continue}q=this.reconnectDelay;let D=B.body.getReader(),R=new TextDecoder,G="";while(this.running){let{done:T,value:V}=await D.read();if(T)break;G+=R.decode(V,{stream:!0});let L=G.split(`
2
- `);G=L.pop()||"";for(let M of L){if(!M.startsWith("data: "))continue;try{let F=JSON.parse(M.slice(6));if(F.type==="connected"){this.log("SSE connected"),this.emit("connected");continue}if(F.type==="new_task"||F.type==="new_message"||F.type==="broadcast")await this.processInbox()}catch{}}}}catch(z){if(z.name==="AbortError")break;this.emit("error",z),this.log(`SSE error: ${z.message}`)}if(this.running)this.emit("disconnected"),this.log(`SSE reconnecting in ${q/1000}s...`),await this.sleep(q),q=Math.min(q*1.5,60000)}}async processInbox(){try{let w=(await this.call("get_inbox",{alias:this.alias,limit:10}))?.messages||[];for(let q of w)await this.call("ack_inbox",{alias:this.alias,message_id:q.id}),this.log(`← ${q.from_session}: ${q.content.slice(0,60)}`),this.emit("task",q),this.emit("message",q)}catch(j){this.log(`inbox error: ${j.message}`)}}sleep(j){return new Promise((w)=>setTimeout(w,j))}}var _=Q;export{_ as default,Q as CommHub};
1
+ import{EventEmitter as X}from"events";import{hostname as R}from"os";class T extends X{url;alias;token;agent;resumeId;heartbeatInterval;reconnectDelay;heartbeatTimer;sseAbort;running=!1;constructor(j){super();if(this.url=j.url.replace(/\/$/,""),this.alias=j.alias,this.token=j.token,this.agent=j.agent||"sdk",this.resumeId=`sdk-${j.alias}-${Date.now().toString(36)}`,this.heartbeatInterval=j.heartbeatInterval??180000,this.reconnectDelay=j.reconnectDelay??3000,j.autoConnect!==!1)this.connect()}log(j){console.log(`[${new Date().toTimeString().slice(0,8)}] [commhub:${this.alias}] ${j}`)}async call(j,z){let q={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(this.token)q.Authorization=`Bearer ${this.token}`;let D=await(await fetch(`${this.url}/mcp`,{method:"POST",headers:q,body:JSON.stringify({jsonrpc:"2.0",id:Date.now(),method:"tools/call",params:{name:j,arguments:z}})})).text(),G=D.match(/data: (.+)/),L=G?JSON.parse(G[1]):JSON.parse(D),F=L?.result?.content?.[0]?.text;return F?JSON.parse(F):L}async connect(){if(this.running)return;this.running=!0,await this.status("idle"),this.log("registered"),this.heartbeatTimer=setInterval(()=>{this.status("idle").catch((j)=>this.log(`heartbeat failed: ${j.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(j,z,q="normal"){return this.call("send_task",{alias:j,task:z,priority:q,from_session:this.alias})}async message(j,z){return this.call("send_message",{alias:j,message:z,from_session:this.alias})}async reply(j,z,q="completed"){return this.call("reply",{task_id:j,text:z,status:q})}async status(j,z){return this.call("report_status",{resume_id:this.resumeId,alias:this.alias,status:j,server:R(),hostname:R(),agent:this.agent,project_dir:process.cwd(),...z})}async getAllStatus(){return this.call("get_all_status",{})}async broadcast(j,z){return this.call("broadcast",{message:j,filter_server:z?.server,filter_status:z?.status})}async connectSSE(){let j=encodeURIComponent(this.alias),z=`${this.url}/events/${j}`,q=this.reconnectDelay;while(this.running){try{this.sseAbort=new AbortController;let B={Accept:"text/event-stream"};if(this.token)B.Authorization=`Bearer ${this.token}`;let D=await fetch(z,{headers:B,signal:this.sseAbort.signal});if(!D.ok||!D.body){this.log(`SSE failed: ${D.status}`),await this.sleep(q),q=Math.min(q*1.5,60000);continue}q=this.reconnectDelay;let G=D.body.getReader(),L=new TextDecoder,F="";while(this.running){let{done:V,value:W}=await G.read();if(V)break;F+=L.decode(W,{stream:!0});let P=F.split(`
2
+ `);F=P.pop()||"";for(let Q of P){if(!Q.startsWith("data: "))continue;try{let M=JSON.parse(Q.slice(6));if(M.type==="connected"){this.log("SSE connected"),this.emit("connected");continue}if(M.type==="new_task"||M.type==="new_message"||M.type==="broadcast")await this.processInbox()}catch{}}}}catch(B){if(B.name==="AbortError")break;this.emit("error",B),this.log(`SSE error: ${B.message}`)}if(this.running)this.emit("disconnected"),this.log(`SSE reconnecting in ${q/1000}s...`),await this.sleep(q),q=Math.min(q*1.5,60000)}}async processInbox(){try{let z=(await this.call("get_inbox",{alias:this.alias,limit:10}))?.messages||[];for(let q of z)await this.call("ack_inbox",{alias:this.alias,message_id:q.id}),this.log(`← ${q.from_session}: ${q.content.slice(0,60)}`),this.emit("task",q),this.emit("message",q)}catch(j){this.log(`inbox error: ${j.message}`)}}sleep(j){return new Promise((z)=>setTimeout(z,j))}}var $=T;export{$ as default,T as CommHub};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sleep2agi/agent-network",
3
- "version": "0.0.25",
3
+ "version": "0.0.27",
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",