@sleep2agi/agent-network 0.0.7 → 0.0.8
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 +15 -15
- package/package.json +1 -1
package/dist/bin/cli.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as d}from"node:module";var
|
|
3
|
-
`);Z=
|
|
4
|
-
`)}function
|
|
5
|
-
`)}function y(){let Q=F();if(!q(Q))return[];return
|
|
2
|
+
import{createRequire as d}from"node:module";var f=Object.defineProperty;var g=(Q)=>Q;function m(Q,z){this[Q]=g.bind(null,z)}var c=(Q,z)=>{for(var V in z)f(Q,V,{get:z[V],enumerable:!0,configurable:!0,set:m.bind(z,V)})};var p=(Q,z)=>()=>(Q&&(z=Q(Q=0)),z);var l=d(import.meta.url);var C={};c(C,{default:()=>t,CommHub:()=>H});import{EventEmitter as n}from"events";import{hostname as D}from"os";var H,t;var P=p(()=>{H=class H extends n{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,z){let V={"Content-Type":"application/json"};if(this.token)V.Authorization=`Bearer ${this.token}`;let $=await(await fetch(`${this.url}/mcp`,{method:"POST",headers:V,body:JSON.stringify({jsonrpc:"2.0",id:Date.now(),method:"tools/call",params:{name:Q,arguments:z}})})).json(),Y=$?.result?.content?.[0]?.text;return Y?JSON.parse(Y):$}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,z,V="normal"){return this.call("send_task",{alias:Q,task:z,priority:V,from_session:this.alias})}async message(Q,z){return this.call("send_message",{alias:Q,message:z,from_session:this.alias})}async reply(Q,z,V="completed"){return this.call("reply",{task_id:Q,text:z,status:V})}async status(Q,z){return this.call("report_status",{resume_id:this.resumeId,alias:this.alias,status:Q,server:D(),hostname:D(),agent:this.agent,project_dir:process.cwd(),...z})}async getAllStatus(){return this.call("get_all_status",{})}async broadcast(Q,z){return this.call("broadcast",{message:Q,filter_server:z?.server,filter_status:z?.status})}async connectSSE(){let Q=encodeURIComponent(this.alias),z=`${this.url}/events/${Q}`,V=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(z,{headers:X,signal:this.sseAbort.signal});if(!$.ok||!$.body){this.log(`SSE failed: ${$.status}`),await this.sleep(V),V=Math.min(V*1.5,60000);continue}V=this.reconnectDelay;let Y=$.body.getReader(),N=new TextDecoder,Z="";while(this.running){let{done:L,value:T}=await Y.read();if(L)break;Z+=N.decode(T,{stream:!0});let U=Z.split(`
|
|
3
|
+
`);Z=U.pop()||"";for(let _ of U){if(!_.startsWith("data: "))continue;try{let B=JSON.parse(_.slice(6));if(B.type==="connected"){this.log("SSE connected"),this.emit("connected");continue}if(B.type==="new_task"||B.type==="new_message"||B.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 ${V/1000}s...`),await this.sleep(V),V=Math.min(V*1.5,60000)}}async processInbox(){try{let z=(await this.call("get_inbox",{alias:this.alias,limit:10}))?.messages||[];for(let V of z)await this.call("ack_inbox",{alias:this.alias,message_id:V.id}),this.log(`← ${V.from_session}: ${V.content.slice(0,60)}`),this.emit("task",V),this.emit("message",V)}catch(Q){this.log(`inbox error: ${Q.message}`)}}sleep(Q){return new Promise((z)=>setTimeout(z,Q))}};t=H});import{readFileSync as E,writeFileSync as K,existsSync as q,mkdirSync as G,readdirSync as b}from"fs";import{join as R}from"path";import{spawn as r}from"child_process";var W=process.argv.slice(2),A=W[0],O=process.env.HOME||process.env.USERPROFILE||"~";function S(){return R(O,".anet","config.json")}function F(){return R(process.cwd(),".anet","profiles")}function I(){let Q=S();if(q(Q))try{return JSON.parse(E(Q,"utf-8"))}catch{}return{}}function o(Q){let z=R(O,".anet");G(z,{recursive:!0}),K(R(z,"config.json"),JSON.stringify(Q,null,2)+`
|
|
4
|
+
`)}function J(Q){let z=R(F(),`${Q}.json`);if(q(z))try{return JSON.parse(E(z,"utf-8"))}catch{}return null}function a(Q,z){let V=F();G(V,{recursive:!0}),K(R(V,`${Q}.json`),JSON.stringify(z,null,2)+`
|
|
5
|
+
`)}function y(){let Q=F();if(!q(Q))return[];return b(Q).filter((z)=>z.endsWith(".json")).map((z)=>z.replace(/\.json$/,""))}function k(){let Q={_channels:[],_envs:[]};for(let z=0;z<W.length;z++){if(W[z]==="--channel"&&W[z+1]){Q._channels.push(W[++z]);continue}if(W[z]==="--env"&&W[z+1]){Q._envs.push(W[++z]);continue}if(W[z].startsWith("--")&&W[z+1]&&!W[z+1].startsWith("--"))Q[W[z].slice(2)]=W[++z]}return Q}function j(){console.log(`
|
|
6
6
|
anet — AI Agent Network CLI
|
|
7
7
|
|
|
8
8
|
anet init Configure hub URL (global, once)
|
|
@@ -18,20 +18,20 @@ Quick start:
|
|
|
18
18
|
anet init project
|
|
19
19
|
anet init profile cmd --alias 指挥室 --channel server:commhub
|
|
20
20
|
anet start cmd
|
|
21
|
-
`)}async function i(){let Q=k(),z=Q.hub;if(!z)process.stdout.write("CommHub URL (e.g. http://YOUR_IP:9200): "),z=await new Promise((X)=>{let $="";process.stdin.setEncoding("utf-8"),process.stdin.once("data",(Y)=>{X(Y.toString().trim())})});if(!z)console.error("Error: hub URL required"),process.exit(1);try{let $=await(await fetch(`${z}/health`)).json();console.log(`✅ CommHub v${$.version} — ${$.sessions} sessions, ${$.sse_connections} SSE`)}catch(X){console.error(`❌ Cannot reach ${z}: ${X.message}`),process.exit(1)}let V=
|
|
22
|
-
Saved to ${S()}`),console.log("Next: anet init project")}async function e(){let z=
|
|
23
|
-
`)
|
|
24
|
-
`),console.log(".mcp.json: commhub
|
|
25
|
-
✅ Project ready. Next: anet init profile <id> --alias <名字> --channel server:commhub`)}function s(){let Q=W[2];if(!Q)console.error("Usage: anet init profile <id> --alias <名字> [--channel ...] [--env ...]"),process.exit(1);let z=
|
|
21
|
+
`)}async function i(){let Q=k(),z=Q.hub;if(!z)process.stdout.write("CommHub URL (e.g. http://YOUR_IP:9200): "),z=await new Promise((X)=>{let $="";process.stdin.setEncoding("utf-8"),process.stdin.once("data",(Y)=>{X(Y.toString().trim())})});if(!z)console.error("Error: hub URL required"),process.exit(1);try{let $=await(await fetch(`${z}/health`)).json();console.log(`✅ CommHub v${$.version} — ${$.sessions} sessions, ${$.sse_connections} SSE`)}catch(X){console.error(`❌ Cannot reach ${z}: ${X.message}`),process.exit(1)}let V=I();if(V.hub=z,Q.token)V.token=Q.token;o(V),console.log(`
|
|
22
|
+
Saved to ${S()}`),console.log("Next: anet init project")}async function e(){let z=I().hub;if(!z)console.error("Run 'anet init' first to configure hub URL"),process.exit(1);let V=R(process.cwd(),".anet");G(V,{recursive:!0});let X=R(V,"server.ts");if(!q(X)){console.log("Downloading Channel plugin...");try{let L=await fetch("https://raw.githubusercontent.com/sleep2agi/agent-comm-hub/main/channel/server.ts");if(L.ok)K(X,await L.text()),console.log(" ✅ .anet/server.ts")}catch(L){console.log(` ❌ Failed: ${L.message}`),console.log(" Manual: curl -sL https://raw.githubusercontent.com/sleep2agi/agent-comm-hub/main/channel/server.ts -o .anet/server.ts")}}else console.log("Channel plugin: exists");let $=R(V,"package.json");if(!q($))try{let L=await fetch("https://raw.githubusercontent.com/sleep2agi/agent-comm-hub/main/channel/package.json");if(L.ok){K($,await L.text());try{let{execSync:T}=await import("child_process");T("bun install",{cwd:V,stdio:"pipe"}),console.log(" ✅ Dependencies installed")}catch{console.log(" ⚠️ Run: cd .anet && bun install")}}}catch{}let Y=R(V,".env");K(Y,`COMMHUB_URL=${z}
|
|
23
|
+
`),console.log(`CommHub URL: ${z}`);let N=R(process.cwd(),".mcp.json"),Z={};if(q(N))try{Z=JSON.parse(E(N,"utf-8"))}catch{}if(!Z.mcpServers?.commhub)Z.mcpServers=Z.mcpServers||{},Z.mcpServers.commhub={type:"stdio",command:"bun",args:[".anet/server.ts"]},K(N,JSON.stringify(Z,null,2)+`
|
|
24
|
+
`),console.log(".mcp.json: commhub → .anet/server.ts");else console.log(".mcp.json: commhub already set");console.log(`
|
|
25
|
+
✅ Project ready. Next: anet init profile <id> --alias <名字> --channel server:commhub`)}function s(){let Q=W[2];if(!Q)console.error("Usage: anet init profile <id> --alias <名字> [--channel ...] [--env ...]"),process.exit(1);let z=I(),V=k(),X=V.alias||Q,$=V.hub||z.hub;if(!$)console.error("Run 'anet init' first to configure hub URL"),process.exit(1);let Y={};for(let U of V._envs){let _=U.indexOf("=");if(_>0)Y[U.slice(0,_)]=U.slice(_+1)}let N={...V.name?{name:V.name}:{},alias:X,hub:$,channels:V._channels.length>0?V._channels:["server:commhub"],env:Y,flags:{dangerouslySkipPermissions:!0,...V["teammate-mode"]?{teammateMode:V["teammate-mode"]}:{}},...V.resume?{resume:V.resume}:{}},Z=R(O,".claude","channels","commhub"),L=process.cwd().replace(/\//g,"-"),T=R(Z,L);if(G(T,{recursive:!0}),K(R(T,".env"),`COMMHUB_ALIAS=${X}
|
|
26
26
|
`),a(Q,N),console.log(`
|
|
27
27
|
✅ Profile "${Q}" saved`),console.log(` alias: ${X}`),console.log(` channels: ${N.channels.join(", ")}`),Object.keys(Y).length)console.log(` env: ${Object.keys(Y).join(", ")}`);console.log(`
|
|
28
|
-
Start: anet start ${Q}`)}function
|
|
28
|
+
Start: anet start ${Q}`)}function v(){let Q=W[1];if(!Q){let Y=y();if(Y.length===0){console.log("No profiles. Run: anet init profile <id> --alias <名字>");return}console.log(`
|
|
29
29
|
Profiles:
|
|
30
|
-
`);for(let N of Y){let Z=
|
|
30
|
+
`);for(let N of Y){let Z=J(N);console.log(` ${N}${Z?.name?` (${Z.name})`:""} → ${Z?.alias} [${Z?.channels.join(", ")}]`)}console.log(`
|
|
31
31
|
anet start <id>
|
|
32
|
-
`);return}let z=
|
|
32
|
+
`);return}let z=J(Q);if(!z)console.error(`Profile "${Q}" not found. Run: anet ls`),process.exit(1);let V={...process.env,COMMHUB_ALIAS:z.alias};for(let[Y,N]of Object.entries(z.env))V[Y]=N.replace(/^~/,O);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(z.resume)X.push("--resume",z.resume);X.push("-n",z.name||z.alias),console.log(`[anet] Starting "${Q}" (${z.alias})...
|
|
33
33
|
`),r("claude",X,{env:V,stdio:"inherit",shell:!0}).on("exit",(Y)=>process.exit(Y||0))}async function zz(){let Q=y();if(Q.length>0){console.log(`
|
|
34
34
|
Profiles:
|
|
35
|
-
`);for(let Z of Q){let L=
|
|
36
|
-
`);return}let $=
|
|
37
|
-
`),console.log(" SESSION PID NETWORK"),console.log(" ──────────────────── ─────── ─────────────────────");for(let Z of X){let L=Z.sessionId.slice(0,18),
|
|
35
|
+
`);for(let Z of Q){let L=J(Z);console.log(` ${Z}${L?.name?` (${L.name})`:""} → ${L?.alias} [${L?.channels.join(", ")}]`)}console.log()}let z=process.cwd(),V=R(O,".claude","sessions"),X=[];if(q(V))for(let Z of b(V).filter((L)=>L.endsWith(".json")))try{let L=JSON.parse(E(R(V,Z),"utf-8"));if(L.cwd===z)X.push(L)}catch{}if(X.length===0&&Q.length===0){console.log("No sessions or profiles in this directory."),console.log(`Get started: anet init
|
|
36
|
+
`);return}let $=I(),Y=[],N={};if($.hub)try{let[Z,L]=await Promise.all([fetch(`${$.hub}/api/status`).then((T)=>T.json()),fetch(`${$.hub}/health`).then((T)=>T.json())]);Y=Z.sessions||[],N=L.sse_sessions||{}}catch{}if(X.length>0){console.log(`Sessions (${z}):
|
|
37
|
+
`),console.log(" SESSION PID NETWORK"),console.log(" ──────────────────── ─────── ─────────────────────");for(let Z of X){let L=Z.sessionId.slice(0,18),T=!1;try{process.kill(Z.pid,0),T=!0}catch{}let U="(not in network)",_=z.replace(/\//g,"-"),B=R(O,".claude","channels","commhub",_,".env");if(q(B)){let w=E(B,"utf-8").match(/COMMHUB_ALIAS=(.+)/);if(w){let M=w[1].trim(),x=Y.find((h)=>h.alias===M),u=N[M]?"●":"○";U=x?`${M} ${x.status} ${u}`:`${M} (not registered)`}}console.log(` ${L} ${(T?`${Z.pid}`:`${Z.pid}✕`).padEnd(7)} ${U}`)}console.log()}}async function Qz(){let Q=I(),z=k(),V=process.env.COMMHUB_URL||z.hub||Q.hub||"http://127.0.0.1:9200",X=process.env.COMMHUB_ALIAS||z.alias;if(!X)console.error("Error: --alias required"),process.exit(1);let{CommHub:$}=await Promise.resolve().then(() => (P(),C)),Y=new $({url:V,alias:X});Y.on("task",async(N)=>{console.log(`[${X}] ← ${N.from_session}: ${N.content.slice(0,100)}`),await Y.send(N.from_session,`[${X}] 收到: ${N.content.slice(0,200)}`)}),Y.on("connected",()=>console.log(`[${X}] Connected`)),Y.on("disconnected",()=>console.log(`[${X}] Reconnecting...`)),process.on("SIGINT",()=>Y.disconnect().then(()=>process.exit(0))),console.log(`[${X}] Listening on ${V}`)}switch(A){case"init":if(W[1]==="project")e();else if(W[1]==="profile")s();else i();break;case"start":v();break;case"ls":case"list":zz();break;case"run":Qz();break;case"--help":case"-h":case void 0:j();break;default:if(J(A))W.unshift("start"),v();else console.error(`Unknown: ${A}`),j(),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.8",
|
|
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",
|