@aerostack/gateway 0.17.0 → 0.17.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aerostack-connector.js +5 -5
- package/dist/index.js +18 -18
- package/package.json +1 -1
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
import{homedir as
|
|
3
|
+
import{homedir as H}from"node:os";import{readFile as V}from"node:fs/promises";import{join as x}from"node:path";import{execFile as L}from"node:child_process";const ue=process.env.AEROSTACK_WORKSPACE_URL||"https://api.aerostack.dev/api/gateway/ws/notification",S=process.env.AEROSTACK_TOKEN||"",K=parseInt(process.env.AEROSTACK_OPENCLAW_PORT||"18789",10),Y=6e4,ge=1e3,de=3e4,ye=3e4,Q=12e4,I=`aerostack-connector-${Date.now().toString(36)}`,w=ue.replace(/\/+$/,"");function r(e,t){const n=new Date().toISOString(),s=t?` ${JSON.stringify(t)}`:"";process.stderr.write(`[${n}] [INFO] ${e}${s}
|
|
4
4
|
`)}function u(e,t){const n=new Date().toISOString(),s=t?` ${JSON.stringify(t)}`:"";process.stderr.write(`[${n}] [WARN] ${e}${s}
|
|
5
5
|
`)}function m(e,t){const n=new Date().toISOString(),s=t?` ${JSON.stringify(t)}`:"";process.stderr.write(`[${n}] [ERROR] ${e}${s}
|
|
6
|
-
`)}async function C(e,t={},n=ye){const s=new AbortController,a=setTimeout(()=>s.abort(),n);try{return await fetch(e,{...t,signal:s.signal})}finally{clearTimeout(a)}}let D=null,_=!1,$=null,P=0,Z=0;const R=new Map,pe=100,fe=2e3,he=3e4,we=3e4;let B=null;async function me(){try{const e=x(
|
|
7
|
-
`).pop()||"";try{const h=JSON.parse(y);f=[{text:h.text||h.reply||h.message||y}]}catch{y&&(f=[{text:y}])}}f.length===0&&(f=[{text:`Processed your message (${l}ms).`}]),r("Agent turn completed (CLI fallback)",{sessionKey:e,durationMs:l,payloads:f.length}),a(f)})})}let
|
|
6
|
+
`)}async function C(e,t={},n=ye){const s=new AbortController,a=setTimeout(()=>s.abort(),n);try{return await fetch(e,{...t,signal:s.signal})}finally{clearTimeout(a)}}let D=null,_=!1,$=null,P=0,Z=0;const R=new Map,pe=100,fe=2e3,he=3e4,we=3e4;let B=null;async function me(){try{const e=x(H(),".openclaw","openclaw.json"),t=await V(e,"utf-8");return JSON.parse(t)?.gateway?.auth?.token??null}catch{return null}}async function E(){const e=await me();if(!e)return u("No OpenClaw gateway token found, skipping WS control"),!1;const t=`ws://127.0.0.1:${K}`;return new Promise(n=>{try{const s=new WebSocket(t);D=s;const a=setTimeout(()=>{r("Gateway WS connect timeout");try{s.close()}catch{}n(!1)},1e4);s.onopen=()=>{clearTimeout(a),r("Gateway WS connected, sending handshake"),ee({type:"req",id:String(++Z),method:"connect",params:{minProtocol:3,maxProtocol:3,client:{id:"openclaw-tui",displayName:"Aerostack Connector",version:"1.0.0",platform:process.platform,mode:"cli"},auth:{token:e},scopes:["operator.read","operator.write","operator.admin"],caps:["tool-events","sessions"]}})},s.onmessage=o=>{try{const i=JSON.parse(String(o.data));_e(i,n)}catch{}},s.onerror=()=>{clearTimeout(a),n(!1)},s.onclose=()=>{clearTimeout(a),D=null,_=!1,J||Te()}}catch{n(!1)}})}function ee(e){try{D?.send(JSON.stringify(e))}catch{}}function _e(e,t){if(e.type==="res"&&!_){e.ok?(_=!0,P=0,r("Gateway WS authenticated",{port:K}),t?.(!0),N("sessions.subscribe").then(n=>{n.ok&&r("Subscribed to gateway session events")})):(u("Gateway WS auth rejected",{error:e.error?.message}),t?.(!1));return}if(e.type==="res"&&e.id&&R.has(e.id)){const n=R.get(e.id);R.delete(e.id),n(e);return}e.type==="event"&&Se(e)}const b=new Map;function Se(e){const t=e.event,n=e.payload??{};if(t==="session.tool"){const s=n.data,a=s?.name??n.toolName??"unknown",o=s?.phase??"";(o==="start"||o==="end")&&Oe(a,o,"tool_call")}else if(t==="session.message"){const s=n.sessionKey??"",a=n.message,o=typeof a=="object"?a?.role:void 0;let i="";if(typeof a=="string")i=a;else if(a){const c=a.content;typeof c=="string"?i=c:Array.isArray(c)&&(i=c.map(l=>typeof l=="string"?l:l?.text??"").join("")),i||(i=a.text??n.text??"")}r("session.message",{sessionKey:s,role:o,textLength:i?.length??0});const g=b.get(s);g&&i&&o!=="user"&&(r("WS fast path: got agent response",{sessionKey:s,textLength:i.length}),g({text:i}))}else t==="sessions.changed"&&r("Gateway session changed",{key:n.sessionKey})}function N(e,t){return G(e,t,1e4)}function G(e,t,n=1e4){return new Promise(s=>{const a=String(++Z),o=setTimeout(()=>{R.delete(a),s({type:"res",id:a,ok:!1,error:{code:"TIMEOUT",message:"timeout"}})},n);R.set(a,i=>{clearTimeout(o),s(i)}),ee({type:"req",id:a,method:e,params:t})})}async function ke(){if(!_){U("disconnected");return}const e=await N("health");e.ok?U("healthy",e.payload):U("unhealthy",{error:e.error?.message})}async function U(e,t){try{await C(`${w}/chat/heartbeat`,{method:"POST",headers:{Authorization:`Bearer ${S}`,"Content-Type":"application/json"},body:JSON.stringify({agent_type:"openclaw-connector",user_agent:"aerostack-connector/1.0.0",bridge_id:I,gateway_status:e,gateway_data:t})})}catch{}}function Te(){if(J||$||P>=pe)return;const e=Math.min(fe*Math.pow(2,Math.min(P,5)),he);P++,r(`Gateway WS reconnecting in ${e/1e3}s`,{attempt:P}),$=setTimeout(async()=>{$=null,_=!1,R.clear(),await E()},e)}function Ce(){return new Promise(e=>{r("Restarting OpenClaw gateway"),L("openclaw",["gateway","restart"],{timeout:3e4},t=>{t?(m("Gateway restart failed",{error:t.message}),e(!1)):(r("Gateway restart triggered"),setTimeout(()=>{E()},5e3),e(!0))})})}function te(){return new Promise(e=>{r("Diagnose: restarting OpenClaw gateway (fast)"),L("openclaw",["gateway","restart"],{timeout:1e4},t=>{t?(m("Diagnose: gateway restart failed",{error:t.message}),e(!1)):(r("Diagnose: gateway restart triggered"),setTimeout(()=>{E()},3e3),e(!0))})})}async function Ae(e,t){const n=Date.now();r("Agent turn starting",{sessionKey:e,messageLength:t.length});const s=e;if(_)try{const a=`aerostack-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,o=`agent:main:${s}`,i=new Promise(c=>{const l=setTimeout(()=>{b.delete(o),c(null)},Q);b.set(o,f=>{clearTimeout(l),b.delete(o),c(f)})});N("sessions.messages.subscribe",{key:o});let g=await N("sessions.send",{key:o,message:t,idempotencyKey:a});if(!g.ok&&g.error?.message?.includes("session not found")&&(r("Creating new gateway session for thread",{key:s}),(await N("sessions.create",{key:s,agentId:"main"})).ok&&(g=await N("sessions.send",{key:o,message:t,idempotencyKey:a}))),!g.ok)b.delete(o),u("Gateway WS sessions.send rejected, falling back to CLI",{error:g.error?.message});else{const c=await i,l=Date.now()-n;if(c?.text)return r("Agent turn completed (WS fast path)",{sessionKey:o,durationMs:l}),[{text:c.text}];u("No response received via WS events, falling back to CLI",{durationMs:l})}}catch(a){b.delete(`agent:main:${s}`),u("Gateway WS fast path error, falling back to CLI",{error:a?.message})}return _||(u("Gateway disconnected, attempting reconnect before agent turn"),await E()||(u("Gateway unreachable, attempting restart"),await Ce(),await new Promise(o=>setTimeout(o,8e3)))),new Promise((a,o)=>{L("openclaw",["agent","--agent","main","--json","--session-id",e,"-m",t],{timeout:Q},(g,c)=>{const l=Date.now()-n;if(g){m("Agent turn failed",{sessionKey:e,durationMs:l,error:g.message}),o(g);return}let f=[];if(c)try{const y=JSON.parse(c.trim()),h=y?.result?.payloads;Array.isArray(h)&&h.length>0?f=h:(y.text||y.reply||y.message)&&(f=[{text:y.text||y.reply||y.message}])}catch{const y=c.trim().split(`
|
|
7
|
+
`).pop()||"";try{const h=JSON.parse(y);f=[{text:h.text||h.reply||h.message||y}]}catch{y&&(f=[{text:y}])}}f.length===0&&(f=[{text:`Processed your message (${l}ms).`}]),r("Agent turn completed (CLI fallback)",{sessionKey:e,durationMs:l,payloads:f.length}),a(f)})})}let J=!1,v=null;async function ne(){try{const e=await C(`${w}/chat/heartbeat`,{method:"POST",headers:{Authorization:`Bearer ${S}`,"Content-Type":"application/json"},body:JSON.stringify({agent_type:"openclaw-connector",user_agent:"aerostack-connector/1.0.0",bridge_id:I})});e.ok?r("Heartbeat OK"):u("Heartbeat failed",{status:e.status})}catch(e){u("Heartbeat error",{error:e?.message})}}async function z(e,t){try{const n=await C(`${w}/chat/messages`,{method:"POST",headers:{Authorization:`Bearer ${S}`,"Content-Type":"application/json"},body:JSON.stringify({content:e.slice(0,1e4),session_id:t||v})});n.ok?r("Reply sent",{length:e.length,sessionId:t}):u("Reply failed",{status:n.status})}catch(n){m("Reply error",{error:n?.message})}}async function Oe(e,t,n){try{await C(`${w}/chat/tool-status`,{method:"POST",headers:{Authorization:`Bearer ${S}`,"Content-Type":"application/json"},body:JSON.stringify({tool_name:e,phase:t,category:n})})}catch{}}const F=new Map,se=50,ae=10;function q(e,t,n){let s=F.get(e);s||(s=[],F.set(e,s)),s.push({role:t,content:n,ts:Date.now()}),s.length>se&&s.splice(0,s.length-se)}function Re(e){const t=F.get(e);return!t||t.length===0?"":`Previous conversation:
|
|
8
8
|
`+t.slice(-ae).map(n=>`[${n.role==="user"?"Admin":"You (Agent)"}] ${n.content}`).join(`
|
|
9
9
|
`)+`
|
|
10
10
|
|
|
11
|
-
`}async function be(e){try{const t=await C(`${w}/chat/history?limit=${ae}`,{headers:{Authorization:`Bearer ${S}`}});if(!t.ok)return;const n=await t.json();n.session_id&&(v=n.session_id);for(const s of n.messages??[]){const a=s.sender_type==="agent"?"agent":"user";q(n.session_id||e,a,s.content)}r("History seeded",{sessionId:n.session_id,count:n.messages?.length??0})}catch{}}let d=null,
|
|
11
|
+
`}async function be(e){try{const t=await C(`${w}/chat/history?limit=${ae}`,{headers:{Authorization:`Bearer ${S}`}});if(!t.ok)return;const n=await t.json();n.session_id&&(v=n.session_id);for(const s of n.messages??[]){const a=s.sender_type==="agent"?"agent":"user";q(n.session_id||e,a,s.content)}r("History seeded",{sessionId:n.session_id,count:n.messages?.length??0})}catch{}}let d=null,j=null,M=0,W=null;function Ne(e){return(e||"").replace(/[\r\n]+/g," ").replace(/\[/g,"(").replace(/\]/g,")").replace(/---/g,"\u2014")}import{writeFile as $e,mkdir as Pe}from"node:fs/promises";const oe=x(H(),".openclaw","media","inbound");async function Ee(e,t){try{const n=await C(`${w}/chat/media/${e}/${t.filename}`,{headers:{Authorization:`Bearer ${S}`}},15e3);if(!n.ok)return u("Media fetch failed",{messageId:e,filename:t.filename,status:n.status}),null;const s=Buffer.from(await n.arrayBuffer());await Pe(oe,{recursive:!0});const a=t.filename.split(".").pop()||"bin",o=x(oe,`file_0---${t.id||e}.${a}`);return await $e(o,s),r("Media saved locally",{localPath:o,size:s.length}),o}catch(n){return u("Media download error",{messageId:e,filename:t.filename,error:n?.message}),null}}function ve(e){return e.map(t=>`[media attached: ${t.path} (${t.mime}) | ${t.path}]`).join(`
|
|
12
12
|
`)}async function Me(e){const t=Date.now();try{const n=JSON.parse(e);if(n.type!=="chat_message")return;const s=n.session_id,a=n.session_title||null,o=Ne(n.sender_name||"Admin"),i=n.content||"",g=n.content_type||"text",c=n.message_id;let l=[];if(n.metadata_json)try{const p=JSON.parse(n.metadata_json);p?.v===1&&Array.isArray(p.attachments)&&(l=p.attachments)}catch{}if(!i&&l.length===0)return;r(">>> Chat message received via WebSocket (ChatRelayDO)",{transport:"websocket",wsDeliveryMs:Date.now()-t,sender:o,sessionId:s,sessionTitle:a,contentType:g,textLength:i.length,attachments:l.length}),s&&(v=s);const f=`aerostack-chat-${s||"_default"}`;let y=`[Style: concise, numbered lists, bold headers, short sub-bullets. No walls of text.]
|
|
13
13
|
[${o}]:`;if(i&&(y+=` ${i}`),l.length>0&&c){const p=[],A=await Promise.all(l.slice(0,5).map(k=>Ee(c,k).then(O=>O?{path:O,mime:k.mime_type}:null)));for(const k of A)k&&p.push(k);p.length>0&&(y=ve(p)+`
|
|
14
|
-
`+y)}q(s||"_default","user",i||`[${l.map(p=>p.filename).join(", ")}]`),X(s,!0);const h=Date.now();r(">>> Agent turn starting",{timeSinceWsReceived:`${h-t}ms`});try{const p=await Ae(f,y),A=Date.now();X(s,!1),r(">>> Agent turn completed \u2014 timing breakdown",{transport:"websocket",agentProcessingMs:A-h,totalFromWsReceiveMs:A-t});for(const O of p){let T=(typeof O.text=="string"?O.text:String(O.text??"")).trim();T=T.replace(/\[\[reply_to_current\]\]\s*/gi,"").trim(),T&&T.length>=2&&(q(s||"_default","agent",T),We(T,s)?r(">>> Reply sent via WS fast path (no HTTP POST needed)",{textLength:T.length}):await z(T,s))}const k=Date.now();r(">>> Full round-trip complete",{wsToAgentStartMs:h-t,agentProcessingMs:A-h,replyPostMs:k-A,totalRoundTripMs:k-t})}catch(p){X(s,!1),m("Agent turn failed, sending fallback",{error:p?.message}),await z("I received your message but encountered an error processing it. Please try again.",s)}}catch(n){m("handleChatMessage error",{error:n?.message})}}function We(e,t){if(!d||d.readyState!==WebSocket.OPEN)return!1;try{const n=t||v||null;return d.send(JSON.stringify({type:"chat_reply",content:e.slice(0,1e4),session_id:n,sender_name:"Agent",content_type:"text"})),
|
|
14
|
+
`+y)}q(s||"_default","user",i||`[${l.map(p=>p.filename).join(", ")}]`),X(s,!0);const h=Date.now();r(">>> Agent turn starting",{timeSinceWsReceived:`${h-t}ms`});try{const p=await Ae(f,y),A=Date.now();X(s,!1),r(">>> Agent turn completed \u2014 timing breakdown",{transport:"websocket",agentProcessingMs:A-h,totalFromWsReceiveMs:A-t});for(const O of p){let T=(typeof O.text=="string"?O.text:String(O.text??"")).trim();T=T.replace(/\[\[reply_to_current\]\]\s*/gi,"").trim(),T&&T.length>=2&&(q(s||"_default","agent",T),We(T,s)?r(">>> Reply sent via WS fast path (no HTTP POST needed)",{textLength:T.length}):await z(T,s))}const k=Date.now();r(">>> Full round-trip complete",{wsToAgentStartMs:h-t,agentProcessingMs:A-h,replyPostMs:k-A,totalRoundTripMs:k-t})}catch(p){X(s,!1),m("Agent turn failed, sending fallback",{error:p?.message}),await z("I received your message but encountered an error processing it. Please try again.",s)}}catch(n){m("handleChatMessage error",{error:n?.message})}}function We(e,t){if(!d||d.readyState!==WebSocket.OPEN)return!1;try{const n=t||v||null;return d.send(JSON.stringify({type:"chat_reply",content:e.slice(0,1e4),session_id:n,sender_name:"Agent",content_type:"text"})),j={content:e.slice(0,1e4),sessionId:n},!0}catch{return!1}}function X(e,t=!0){if(!(!d||d.readyState!==WebSocket.OPEN))try{d.send(JSON.stringify({type:"typing",session_id:e||v,is_typing:t}))}catch{}}async function xe(e){r(">>> Diagnose requested",{requestId:e});const t=[];t.push({step:"connector",status:"ok",message:"Connector running and connected"}),_?(await G("health",void 0,5e3)).ok?t.push({step:"gateway",status:"ok",message:"OpenClaw gateway healthy"}):(r(">>> Diagnose: gateway unhealthy, attempting restart"),await te()?(await new Promise(o=>setTimeout(o,5e3)),(await G("health",void 0,5e3)).ok?t.push({step:"gateway",status:"ok",message:"Gateway restarted and healthy"}):t.push({step:"gateway",status:"fail",message:"Gateway restarted but health check still fails. Run: openclaw gateway restart"})):t.push({step:"gateway",status:"fail",message:"Gateway restart failed. Run: openclaw gateway restart"})):(r(">>> Diagnose: gateway not connected, attempting restart"),await te()?(await new Promise(s=>setTimeout(s,5e3)),_?t.push({step:"gateway",status:"ok",message:"Gateway was down, restarted successfully"}):t.push({step:"gateway",status:"fail",message:"Gateway not reachable after restart. Run: openclaw gateway start"})):t.push({step:"gateway",status:"fail",message:"OpenClaw gateway not running. Run: openclaw gateway start"}));try{const n=x(H(),".openclaw","openclaw.json"),s=await V(n,"utf-8"),a=JSON.parse(s),o=a?.mcp?.servers||a?.mcpServers||{};Object.keys(o).some(g=>{const c=o[g];return g.toLowerCase().includes("aerostack")||g.toLowerCase().includes("notification")||typeof c?.url=="string"&&c.url.includes("aerostack")||Array.isArray(c?.args)&&c.args.some(l=>typeof l=="string"&&l.includes("aerostack"))})?t.push({step:"mcp_config",status:"ok",message:"Aerostack MCP server configured in OpenClaw"}):t.push({step:"mcp_config",status:"warn",message:"Aerostack MCP server not found in OpenClaw config",detail:{fix:"Add Aerostack MCP server via workspace Connect dialog"}})}catch(n){t.push({step:"mcp_config",status:"fail",message:"Cannot read OpenClaw config (~/.openclaw/openclaw.json)",detail:{error:n?.message}})}d&&d.readyState===WebSocket.OPEN?(d.send(JSON.stringify({type:"diagnose_result",request_id:e,steps:t})),t.push({step:"data_flow",status:"ok",message:"Diagnostic result sent via WebSocket"}),r(">>> Diagnose complete",{requestId:e,steps:t.length})):u("Cannot send diagnose result \u2014 ChatRelay WS not connected")}let re="";async function ie(){if(!(!_||!d||d.readyState!==WebSocket.OPEN))try{const e=await G("sessions.list",{limit:100},5e3);if(!e.ok||!e.payload?.sessions)return;const t=e.payload.sessions.map(s=>({key:String(s.key??""),inputTokens:Number(s.inputTokens)||0,outputTokens:Number(s.outputTokens)||0,totalTokens:Number(s.totalTokens)||0,model:s.model?String(s.model):void 0,contextTokens:Number(s.contextTokens)||0,runtimeMs:Number(s.runtimeMs)||0,updatedAt:Number(s.updatedAt)||0})),n=JSON.stringify(t);if(n===re)return;re=n,d.send(JSON.stringify({type:"token_analytics",sessions:t,timestamp:Date.now()})),r("Token analytics pushed",{sessionCount:t.length})}catch{}}function ce(){if(d){try{d.close()}catch{}d=null}try{const e=w.replace(/^http/,"ws")+`/chat-relay?token=${encodeURIComponent(S)}&client_type=connector&client_id=${encodeURIComponent(I)}`;r("Chat relay WS connecting",{url:w+"/chat-relay"});const t=new WebSocket(e);d=t,t.onopen=()=>{r("Chat relay WS connected"),M=0},t.onmessage=n=>{const s=typeof n.data=="string"?n.data:"";if(s)try{const a=JSON.parse(s);if(a.type==="pong")return;if(a.type==="ping"){t.send(JSON.stringify({type:"pong",ts:Date.now()}));return}if(a.type==="chat_reply_nack"){r(">>> chat_reply_nack received, retrying last reply via HTTP",{reason:a.reason});const o=j;o&&(j=null,z(o.content,o.sessionId).catch(i=>{u("HTTP fallback after NACK failed",{error:i?.message})}));return}if(a.type==="chat_reply_ack"){j=null;return}if(a.type==="diagnose"){xe(a.request_id).catch(o=>{u("Diagnose handler error",{error:o?.message})});return}r(">>> WebSocket frame received from ChatRelayDO",{type:a.type,dataLength:s.length}),Me(s)}catch{}},t.onclose=()=>{d=null,J||le()},t.onerror=()=>{M++}}catch(e){u("Chat relay WS connect error",{error:e?.message}),M++,le()}}function le(){if(W)return;const e=Math.min(ge*Math.pow(2,M),de);r(`Chat relay WS reconnecting in ${e/1e3}s`,{failures:M}),W=setTimeout(()=>{W=null,ce()},e)}async function Ie(){try{const e=await C(`${w}/chat/connection-test`,{headers:{Authorization:`Bearer ${S}`}},1e4);if(e.ok){const t=await e.json();return r(`Connected to "${t.workspace}"`,{tools:t.mcp_servers,token:t.token_name,role:t.token_role}),!0}else return e.status===401?(m("Token invalid \u2014 regenerate at dashboard \u2192 Workspace \u2192 Tokens"),!1):(u("Connection check failed",{status:e.status}),!1)}catch(e){return m("Connection check error",{error:e?.message}),!1}}async function De(){r("Aerostack Connector starting",{workspace:w,openclawPort:K,bridgeId:I}),S||(m("AEROSTACK_TOKEN is required"),process.exit(1)),await Ie()||u("Connection verification failed, continuing anyway (will retry)"),await be("_default"),await E()?r("Gateway WS control layer active"):u("Gateway WS not reachable \u2014 will keep retrying"),B=setInterval(ke,we),await ne();const n=setInterval(ne,Y);ie().catch(()=>{});const s=setInterval(ie,Y);ce(),r("Connector ready \u2014 listening for dashboard chat messages");const a=()=>{J=!0,r("Shutting down"),clearInterval(n),clearInterval(s),B&&clearInterval(B);try{d?.close(1e3)}catch{}W&&clearTimeout(W),$&&clearTimeout($);try{D?.close(1e3)}catch{}process.exit(0)};process.on("SIGTERM",a),process.on("SIGINT",a)}De().catch(e=>{m("Fatal error",{error:e?.message}),process.exit(1)});
|
package/dist/index.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
import{Server as we}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as Ae}from"@modelcontextprotocol/sdk/server/stdio.js";import{ListToolsRequestSchema as Se,CallToolRequestSchema as Te,ListResourcesRequestSchema as Ee,ReadResourceRequestSchema as ke,ListPromptsRequestSchema as Re,GetPromptRequestSchema as Oe}from"@modelcontextprotocol/sdk/types.js";import{readFile as Ce,writeFile as ve}from"node:fs/promises";import{join as $e}from"node:path";import{homedir as be}from"node:os";import{resolveApproval as
|
|
3
|
+
import{Server as we}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as Ae}from"@modelcontextprotocol/sdk/server/stdio.js";import{ListToolsRequestSchema as Se,CallToolRequestSchema as Te,ListResourcesRequestSchema as Ee,ReadResourceRequestSchema as ke,ListPromptsRequestSchema as Re,GetPromptRequestSchema as Oe}from"@modelcontextprotocol/sdk/types.js";import{readFile as Ce,writeFile as ve}from"node:fs/promises";import{join as $e}from"node:path";import{homedir as be}from"node:os";import{resolveApproval as Z}from"./resolution.js";import{startHookServer as Ne,installClaudeHook as Pe,stopHookServer as Ie}from"./hook-server.js";import{OpenClawConnector as xe,resolveOpenClawToken as Ue}from"./openclaw-connector.js";import{info as l,warn as y,error as Le}from"./logger.js";const ce=$e(be(),".openclaw","pre-authorized.json");async function De(e){try{let t={};try{t=JSON.parse(await Ce(ce,"utf-8"))}catch{}t[e]=Date.now(),await ve(ce,JSON.stringify(t))}catch{}}const ee=process.env.AEROSTACK_WORKSPACE_URL,h=process.env.AEROSTACK_TOKEN;function W(e,t,n){const s=parseInt(e??String(t),10);return Number.isFinite(s)&&s>=n?s:t}const te=W(process.env.AEROSTACK_APPROVAL_POLL_MS,3e3,500),se=W(process.env.AEROSTACK_APPROVAL_TIMEOUT_MS,864e5,5e3),le=W(process.env.AEROSTACK_REQUEST_TIMEOUT_MS,3e4,1e3),Me=process.env.AEROSTACK_HOOK_SERVER!=="false",je=W(process.env.AEROSTACK_HOOK_PORT,18321,1024),Ke=process.env.AEROSTACK_HOOK_AUTO_INSTALL!=="false",He=process.env.AEROSTACK_OPENCLAW_ENABLED!=="false",ue=W(process.env.AEROSTACK_OPENCLAW_PORT,18789,1024),We=process.env.AEROSTACK_OPENCLAW_TOKEN;ee||(process.stderr.write(`ERROR: AEROSTACK_WORKSPACE_URL is required
|
|
4
4
|
`),process.exit(1)),h||(process.stderr.write(`ERROR: AEROSTACK_TOKEN is required
|
|
5
|
-
`),process.exit(1));let B;try{if(B=new URL(
|
|
5
|
+
`),process.exit(1));let B;try{if(B=new URL(ee),B.protocol!=="https:"&&B.protocol!=="http:")throw new Error("must be http or https")}catch{process.stderr.write(`ERROR: AEROSTACK_WORKSPACE_URL must be a valid HTTP(S) URL
|
|
6
6
|
`),process.exit(1)}B.protocol==="http:"&&!B.hostname.match(/^(localhost|127\.0\.0\.1)$/)&&process.stderr.write(`WARNING: Using HTTP (not HTTPS) \u2014 token will be sent in plaintext
|
|
7
|
-
`);const m=
|
|
8
|
-
`);let s=null;for(const
|
|
9
|
-
${t.slice(-
|
|
7
|
+
`);const m=ee.replace(/\/+$/,""),ne=crypto.randomUUID();function Be(){return process.env.AEROSTACK_AGENT_TYPE?process.env.AEROSTACK_AGENT_TYPE:process.env.CLAUDECODE||process.env.CLAUDE_CODE?"claude-code":process.env.MCP_TRANSPORT==="stdio"?"mcp-stdio":"unknown"}const de=Be();let $=null,L=Date.now();const ze=3e4;async function O(e,t){const n={jsonrpc:"2.0",id:Date.now(),method:e,params:t??{}},s=new AbortController,o=setTimeout(()=>s.abort(),le);try{const a=await fetch(m,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h}`,"User-Agent":"aerostack-gateway/0.15.29","X-Agent-Id":"aerostack-gateway","X-Bridge-Id":ne,"X-Agent-Type":de},body:JSON.stringify(n),signal:s.signal});if(clearTimeout(o),(a.headers.get("content-type")??"").includes("text/event-stream")){const c=await a.text();return Fe(c,n.id)}return await a.json()}catch(a){clearTimeout(o);const r=a instanceof Error?a.message:"Unknown error";return a instanceof Error&&a.name==="AbortError"?{jsonrpc:"2.0",id:n.id,error:{code:-32603,message:"Request timed out"}}:{jsonrpc:"2.0",id:n.id,error:{code:-32603,message:`HTTP error: ${r}`}}}}function Fe(e,t){const n=e.split(`
|
|
8
|
+
`);let s=null;for(const o of n)if(o.startsWith("data: "))try{s=JSON.parse(o.slice(6))}catch{}return s??{jsonrpc:"2.0",id:t,error:{code:-32603,message:"Empty SSE response"}}}const qe=new Set(["aerostack__guardian_report","aerostack__check_approval","aerostack__guardian_check"]);function Je(e,t){if(qe.has(e))return;let n="other";const s=e.toLowerCase();s.includes("exec")||s.includes("bash")||s.includes("shell")||s.includes("command")||s.includes("run")?n="exec_command":s.includes("write")||s.includes("edit")||s.includes("create")||s.includes("patch")?n="file_write":s.includes("delete")||s.includes("remove")||s.includes("trash")||s.includes("unlink")?n="file_delete":s.includes("fetch")||s.includes("http")||s.includes("request")||s.includes("api")||s.includes("get")||s.includes("post")?n="api_call":s.includes("install")||s.includes("package")||s.includes("npm")||s.includes("pip")?n="package_install":s.includes("config")||s.includes("setting")||s.includes("env")?n="config_change":s.includes("deploy")||s.includes("publish")||s.includes("release")?n="deploy":s.includes("send")||s.includes("message")||s.includes("email")||s.includes("notify")||s.includes("slack")||s.includes("telegram")?n="message_send":(s.includes("read")||s.includes("query")||s.includes("search")||s.includes("list")||s.includes("get"))&&(n="data_access");let o;try{const a=JSON.stringify(t);o=a.length>500?a.slice(0,500)+"...":a}catch{o="(unable to serialize)"}O("tools/call",{name:"aerostack__guardian_report",arguments:{action:`${e}(${Object.keys(t).join(", ")})`,category:n,risk_level:"low",details:o}}).catch(()=>{})}const Ge=new Set(["aerostack__check_approval"]),pe=[{name:"aerostack__chat_check",description:"Check for new messages from the workspace owner. Call this periodically or when asked to check for instructions.",inputSchema:{type:"object",properties:{},required:[]}},{name:"aerostack__chat_reply",description:"Send a reply message to the workspace owner via Agent Chat.",inputSchema:{type:"object",properties:{message:{type:"string",description:"Your reply message to the workspace owner"}},required:["message"]}}],Ve=new Set(pe.map(e=>e.name));function w(e){return e.replace(/[\r\n]+/g," ").replace(/\[/g,"(").replace(/\]/g,")").replace(/---/g,"\u2014")}const Ye=new Set(["image/jpeg","image/png","image/gif","image/webp"]),Xe=2*1024*1024;async function oe(e,t,n,s,o){if(n!=="media"&&n!=="rich")return[{type:"text",text:`${w(o)}: ${w(s)}`}];let a=[];if(t)try{const c=JSON.parse(t);c?.v===1&&Array.isArray(c.attachments)&&(a=c.attachments)}catch{}if(a.length===0)return[{type:"text",text:`${w(o)}: ${w(s)}`}];const r=[];n==="rich"&&s?r.push({type:"text",text:`${w(o)}: ${w(s)}`}):a.length>0&&r.push({type:"text",text:`${w(o)} sent ${a.length} file(s):`});const i=e&&/^[a-zA-Z0-9_-]{1,128}$/.test(e)?e:null;for(const c of a){if(Ye.has(c.mime_type)&&c.size<=Xe&&i)try{const H=`${m}/chat/media/${i}/${encodeURIComponent(c.filename)}`,R=await T(H,{headers:{Authorization:`Bearer ${h}`}});if(R.ok){const g=Buffer.from(await R.arrayBuffer()).toString("base64");r.push({type:"image",data:g,mimeType:c.mime_type});continue}}catch{}const b=Math.round(c.size/1024),D=b>=1024?`${(b/1024).toFixed(1)} MB`:`${b} KB`,k=w(c.filename.slice(0,200)),C=w(c.mime_type.slice(0,100)),ie=i?`${m}/chat/media/${i}/${encodeURIComponent(c.filename)}`:"(unavailable)";r.push({type:"text",text:`Attached: ${k} (${C}, ${D}) \u2014 ${ie}`})}return r}const z=[],Qe=100,N=new Map,he=50,Ze=100,me=10;let P=null;const fe=new Set,F=new Map;let I=null;function j(e,t,n){let s=N.get(e);if(!s){if(N.size>=Ze){const o=N.keys().next().value;o&&N.delete(o)}s=[],N.set(e,s)}s.push({role:t,content:n,ts:Date.now()}),s.length>he&&s.splice(0,s.length-he)}async function et(e){if(!fe.has(e))try{const t=await T(`${m}/chat/history?limit=${me}`,{headers:{Authorization:`Bearer ${h}`}});if(!t.ok)return;const n=await t.json();n.session_id&&(P=n.session_id);for(const s of n.messages??[]){const o=s.sender_type==="agent"?"agent":"user",a=n.session_id||e;let r=N.get(a);r||(r=[],N.set(a,r));const i=s.content_type==="media"||s.content_type==="rich"?`${s.content} [has media attachment]`:s.content;r.push({role:o,content:i,ts:s.created_at,content_type:s.content_type})}fe.add(e),l("Thread history seeded from D1",{sessionId:n.session_id,count:n.messages?.length??0})}catch{}}function ye(e){const t=N.get(e);return!t||t.length===0?"":`Previous conversation:
|
|
9
|
+
${t.slice(-me).map(o=>`[${o.role==="user"?"Admin":"You (Agent)"}] ${o.content}`).join(`
|
|
10
10
|
`)}
|
|
11
11
|
|
|
12
|
-
`}async function
|
|
13
|
-
`):["[APPROVAL RECEIVED] Your request has been approved by the workspace owner.",
|
|
14
|
-
`);case"changes_requested":return["[CHANGES REQUESTED] The workspace owner reviewed your action and requested changes.","",`Original action: ${s}`,`Reviewer feedback: "${
|
|
15
|
-
`);case"rejected":return["[REJECTED] The workspace owner denied this action.","",`Action: ${s}`,
|
|
12
|
+
`}async function T(e,t){const n=new AbortController,s=setTimeout(()=>n.abort(),le);try{return await fetch(e,{...t,signal:n.signal})}finally{clearTimeout(s)}}async function tt(){const e=P||"_default";if(await et(e),z.length>0){const t=z.splice(0);L=Date.now();const n=ye(e),s=[];n&&s.push({type:"text",text:n}),s.push({type:"text",text:"New messages from workspace owner:"});for(const o of t){const a=await oe(o.message_id??null,o.metadata_json??null,o.content_type,o.content,o.sender_name);s.push(...a)}return s}try{const n=await T(`${m}/chat/pending?since=${L}`,{headers:{Authorization:`Bearer ${h}`}});if(!n.ok)return[{type:"text",text:"No new messages."}];const o=(await n.json()).messages??[];if(L=Date.now(),o.length===0)return[{type:"text",text:"No new messages from the workspace owner."}];for(const i of o)j(e,"user",i.content);const a=ye(e),r=[];a&&r.push({type:"text",text:a}),r.push({type:"text",text:"New messages from workspace owner:"});for(const i of o){const c=await oe(i.id??null,i.metadata_json??null,i.content_type,i.content,i.sender_name);r.push(...c)}return r}catch{return[{type:"text",text:"Failed to check messages."}]}}async function st(e){const t=typeof e.message=="string"?e.message.trim().slice(0,1e4):"";if(!t)return[{type:"text",text:"Error: message is required."}];try{const n=await T(`${m}/chat/messages`,{method:"POST",headers:{Authorization:`Bearer ${h}`,"Content-Type":"application/json"},body:JSON.stringify({content:t,session_id:P})});return n.ok?(j(P||"_default","agent",t),[{type:"text",text:"Reply sent to workspace owner."}]):[{type:"text",text:`Failed to send reply (HTTP ${n.status}).`}]}catch{return[{type:"text",text:"Failed to send reply."}]}}async function nt(e,t){Je(e,t);const n=await O("tools/call",{name:e,arguments:t});if(n.error?.code===-32050){const a=n.error.data,r=a?.approval_id;if(!r||!/^[a-zA-Z0-9_-]{4,128}$/.test(r))return{jsonrpc:"2.0",id:n.id,error:{code:-32603,message:"Approval required but no approval_id returned"}};l("Tool gate: blocking until approval resolves",{tool:e,approvalId:r});const i=await Z({approvalId:r,wsUrl:a?.ws_url,pollUrl:a?.polling_url??`${m}/approval-status/${r}`,pollIntervalMs:te,timeoutMs:se,token:h});l("Tool gate resolved",{tool:e,status:i.status}),q({approvalId:r,toolName:e,toolArgs:t,sessionKey:null,gate:"tool_gate",pollUrl:"",authToken:h},i.status,!0);const c=ae({approvalId:r,toolName:e,toolArgs:t,sessionKey:null,gate:"tool_gate",pollUrl:"",authToken:h},i);return{jsonrpc:"2.0",id:n.id,result:{content:[{type:"text",text:c}]}}}const o=n.result?._meta;if(o?.approval_id&&o?.status==="pending"){const a=o.approval_id;if(!/^[a-zA-Z0-9_-]{4,128}$/.test(a))return n;l("Permission gate: blocking until approval resolves",{tool:e,approvalId:a});const r=await Z({approvalId:a,wsUrl:o.ws_url,pollUrl:o.polling_url??`${m}/approval-status/${a}`,pollIntervalMs:te,timeoutMs:se,token:h});l("Permission gate resolved",{tool:e,status:r.status}),q({approvalId:a,toolName:e,toolArgs:t,sessionKey:null,gate:"permission_gate",pollUrl:"",authToken:h},r.status,!0);const i=ae({approvalId:a,toolName:e,toolArgs:t,sessionKey:null,gate:"permission_gate",pollUrl:"",authToken:h},r);return{jsonrpc:"2.0",id:n.id,result:{content:[{type:"text",text:i}]}}}return n}function kt(e){Z({approvalId:e.approvalId,wsUrl:e.wsUrl,pollUrl:e.pollUrl,pollIntervalMs:te,timeoutMs:se,token:e.authToken}).then(async t=>{l("Approval resolved",{tool:e.toolName,status:t.status,session:e.sessionKey});const n=ae(e,t),s=e.sessionKey??$?.getLastActiveSession()??null;if((t.status==="approved"||t.status==="executed")&&s&&De(s).catch(()=>{}),s&&$){if(await $.sendToSession(s,n)){l("Agent resumed via sessions.send",{session:s,status:t.status}),q(e,t.status,!0);return}y("sessions.send failed, falling back to channel notification",{session:s})}try{await x.notification({method:"notifications/claude/channel",params:{content:n,meta:{tool_name:e.toolName,approval_id:e.approvalId,status:t.status,gate:e.gate}}}),l("Agent resumed via channel notification",{tool:e.toolName,status:t.status}),q(e,t.status,!0)}catch(o){y("Channel notification failed",{error:o instanceof Error?o.message:String(o)}),q(e,t.status,!1)}}).catch(t=>{y("Background approval resolver error",{error:t instanceof Error?t.message:String(t)})})}function q(e,t,n){const s=typeof e.toolArgs.action=="string"?e.toolArgs.action:null,o=s??e.toolName.replace(/^(?:\w+__)*aerostack__/,"")??e.toolName,a=s?`${o}`:`${o}(${Object.keys(e.toolArgs).join(", ")})`,r=n?"resume sent to agent":"session unavailable \u2014 resume not delivered";let i;t==="approved"||t==="executed"?i=n?`[RESUMED] ${a} \u2014 ${r}`:`[RESUME FAILED] ${a} \u2014 ${r}`:t==="rejected"?i=`[REJECTED] ${a} \u2014 rejection sent to agent`:t==="changes_requested"?i=`[CHANGES REQUESTED] ${a} \u2014 feedback sent to agent`:i=`[EXPIRED] ${a} \u2014 approval timed out, expiry sent to agent`,O("tools/call",{name:"aerostack__guardian_report",arguments:{action:i.slice(0,500),category:"approval",risk_level:"low",details:JSON.stringify({tool:e.toolName,approvalId:e.approvalId,status:t,delivered:n,session:e.sessionKey}).slice(0,500)}}).catch(()=>{})}function ae(e,t){const n=t.reviewer_note?.trim()||null,s=`${e.toolName}(${Object.keys(e.toolArgs).join(", ")})`;switch(t.status){case"approved":case"executed":return e.gate==="tool_gate"?["[APPROVAL RECEIVED] Your pending action has been approved.","",`Action: ${s}`,n?`Reviewer note: "${n}"`:null,"",`Please now execute this action: call ${e.toolName} with the same parameters as before.`].filter(o=>o!==null).join(`
|
|
13
|
+
`):["[APPROVAL RECEIVED] Your request has been approved by the workspace owner.",n?`Reviewer note: "${n}"`:null,"","You may now proceed with the action you requested approval for."].filter(o=>o!==null).join(`
|
|
14
|
+
`);case"changes_requested":return["[CHANGES REQUESTED] The workspace owner reviewed your action and requested changes.","",`Original action: ${s}`,`Reviewer feedback: "${n??"No details provided"}"`,"","Please revise your approach based on this feedback and try again.","Do NOT proceed with the original plan."].join(`
|
|
15
|
+
`);case"rejected":return["[REJECTED] The workspace owner denied this action.","",`Action: ${s}`,n?`Reason: "${n}"`:"No reason provided.","","Do not retry this action. If you believe this was a mistake, inform the user."].join(`
|
|
16
16
|
`);case"expired":return[`[EXPIRED] The approval request for "${s}" timed out \u2014 no decision was made.`,"","You may resubmit the request if the action is still needed."].join(`
|
|
17
17
|
`);default:return`[APPROVAL UPDATE] Status for "${s}": ${t.status}.`}}const V=`
|
|
18
18
|
=== AEROSTACK GUARDIAN POLICY (MANDATORY) ===
|
|
@@ -42,26 +42,26 @@ or before starting a new one, call aerostack__chat_check to see if the owner sen
|
|
|
42
42
|
If there are messages, read them carefully and respond using aerostack__chat_reply. This keeps
|
|
43
43
|
the owner informed and allows them to steer your work in real time.
|
|
44
44
|
=== END WORKSPACE CHAT ===
|
|
45
|
-
`.trim(),
|
|
45
|
+
`.trim(),ot=["delete","remove","drop","truncate","destroy","wipe","reset","deploy","publish","release","push","exec","shell","bash","run","command","terminal","install","uninstall","send","email","notify","webhook"];function at(e,t){const n=e.toLowerCase(),s=ot.some(a=>n.includes(a)),o=t??"";return s?`[REQUIRES GUARDIAN APPROVAL] ${o}`.trim():o}let ge=null;async function K(){if(ge)return;const e=await O("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"aerostack-gateway",version:"0.15.29"}});if(e.result){const t=e.result,n=t.instructions??"";ge={protocolVersion:t.protocolVersion??"2024-11-05",instructions:n?`${n}
|
|
46
46
|
|
|
47
|
-
${V}`:V}}}const x=new we({name:"aerostack-gateway",version:"0.15.29"},{capabilities:{tools:{},resources:{},prompts:{},experimental:{"claude/channel":{}}},instructions:V});x.setRequestHandler(Se,async()=>{await K();const e=await O("tools/list");if(e.error)throw new Error(e.error.message);const
|
|
47
|
+
${V}`:V}}}const x=new we({name:"aerostack-gateway",version:"0.15.29"},{capabilities:{tools:{},resources:{},prompts:{},experimental:{"claude/channel":{}}},instructions:V});x.setRequestHandler(Se,async()=>{await K();const e=await O("tools/list");if(e.error)throw new Error(e.error.message);const n=(e.result.tools??[]).filter(s=>!Ge.has(s.name)).map(s=>({...s,description:at(s.name,s.description)}));return n.push(...pe),{tools:n}}),x.setRequestHandler(Te,async e=>{await K();const{name:t,arguments:n}=e.params;if(Ve.has(t))return{content:t==="aerostack__chat_check"?await tt():await st(n??{})};const s=await nt(t,n??{});if(s.error)return{content:[{type:"text",text:`Error: ${s.error.message}`}],isError:!0};const a=s.result.content??[{type:"text",text:JSON.stringify(s.result)}];if(Date.now()-L>ze)try{const i=await T(`${m}/chat/pending?since=${L}`,{headers:{Authorization:`Bearer ${h}`}});if(i.ok){const _=(await i.json()).messages??[];if(L=Date.now(),_.length>0){const b=[];for(const k of _){const C=await oe(k.id??null,k.metadata_json??null,k.content_type,k.content,k.sender_name);b.push(...C)}const D=[{type:"text",text:"--- WORKSPACE OWNER MESSAGE ---"},...b,{type:"text",text:"--- END MESSAGE \u2014 please acknowledge ---"}];a.unshift(...D)}}}catch{}return{content:a}});const rt={uri:"aerostack://guardian/policy",name:"Aerostack Guardian Policy",description:"Mandatory workspace monitoring policy. Read this to understand required approval workflows.",mimeType:"text/plain"};x.setRequestHandler(Ee,async()=>{await K();const e=await O("resources/list");if(e.error)throw new Error(e.error.message);const t=e.result;return{resources:[rt,...t.resources??[]]}}),x.setRequestHandler(ke,async e=>{if(await K(),e.params.uri==="aerostack://guardian/policy")return{contents:[{uri:e.params.uri,text:V,mimeType:"text/plain"}]};const t=await O("resources/read",{uri:e.params.uri});if(t.error)throw new Error(t.error.message);return{contents:t.result.contents??[]}}),x.setRequestHandler(Re,async()=>{await K();const e=await O("prompts/list");if(e.error)throw new Error(e.error.message);return{prompts:e.result.prompts??[]}}),x.setRequestHandler(Oe,async e=>{await K();const t=await O("prompts/get",{name:e.params.name,arguments:e.params.arguments});if(t.error)throw new Error(t.error.message);return{messages:t.result.messages??[]}});async function it(){const e=t=>process.stderr.write(t+`
|
|
48
48
|
`);e(`
|
|
49
49
|
Aerostack Connection Check
|
|
50
50
|
`);try{const t=await fetch(`${m}/chat/connection-test`,{headers:{Authorization:`Bearer ${h}`},signal:AbortSignal.timeout(1e4)});t.ok||(t.status===401&&(e(" \u2705 Workspace URL reachable"),e(" \u274C Token invalid (HTTP 401)"),e(`
|
|
51
51
|
Fix: Regenerate token at your dashboard \u2192 Workspace \u2192 Tokens
|
|
52
52
|
`),process.exit(1)),e(` \u274C Workspace unreachable (HTTP ${t.status})`),e(`
|
|
53
53
|
Fix: Check AEROSTACK_WORKSPACE_URL is correct
|
|
54
|
-
`),process.exit(1));const
|
|
55
|
-
All checks passed. Your agent is connected.`),e(` Dashboard: ${
|
|
56
|
-
`),
|
|
54
|
+
`),process.exit(1));const n=await t.json();e(` \u2705 Workspace URL reachable (${m})`),e(` \u2705 Token valid (${n.token_name}, role: ${n.token_role})`),e(` \u2705 Workspace connected ("${n.workspace}")`),e(` \u2705 Tools available (${n.mcp_servers} tools)`);try{const s=await fetch(`${m}/chat/heartbeat`,{method:"POST",headers:{Authorization:`Bearer ${h}`,"Content-Type":"application/json"},body:JSON.stringify({agent_type:"check",user_agent:"aerostack-gateway/check",bridge_id:"check"}),signal:AbortSignal.timeout(1e4)});e(s.ok?" \u2705 Dashboard registration (bridge visible in admin)":` \u26A0\uFE0F Dashboard registration (returned ${s.status})`)}catch{e(" \u26A0\uFE0F Dashboard registration (heartbeat failed \u2014 non-fatal)")}e(`
|
|
55
|
+
All checks passed. Your agent is connected.`),e(` Dashboard: ${n.dashboard_url||"https://app.aerostack.dev"}
|
|
56
|
+
`),n.mcp_servers===0&&e(` Note: 0 tools found. Add MCP servers or functions to your workspace first.
|
|
57
57
|
`),process.exit(0)}catch(t){t?.name==="TimeoutError"||t?.name==="AbortError"?(e(" \u274C Workspace unreachable (timeout after 10s)"),e(`
|
|
58
58
|
Fix: Check AEROSTACK_WORKSPACE_URL and your network connection
|
|
59
59
|
`)):(e(` \u274C Connection failed (${t?.message??"unknown error"})`),e(`
|
|
60
60
|
Fix: Check AEROSTACK_WORKSPACE_URL is correct
|
|
61
|
-
`)),process.exit(1)}}async function ct(){try{const e=await fetch(`${m}/chat/connection-test`,{headers:{Authorization:`Bearer ${h}`},signal:AbortSignal.timeout(5e3)});if(e.ok){const t=await e.json();
|
|
61
|
+
`)),process.exit(1)}}async function ct(){try{const e=await fetch(`${m}/chat/connection-test`,{headers:{Authorization:`Bearer ${h}`},signal:AbortSignal.timeout(5e3)});if(e.ok){const t=await e.json();l(`Connected to "${t.workspace}" (${t.mcp_servers} tools)`,{dashboard:"https://app.aerostack.dev"})}else e.status===401?y("Token invalid \u2014 regenerate at dashboard \u2192 Workspace \u2192 Tokens"):y("Connection check failed",{status:e.status})}catch{y("Could not verify connection (non-fatal)")}}async function lt(){l("Connecting to workspace",{url:m});const e=new Ae;await x.connect(e),process.stdin.on("end",()=>{l("stdin closed \u2014 MCP session ended, shutting down"),Y()}),process.stdin.on("close",()=>{l("stdin closed \u2014 MCP session ended, shutting down"),Y()}),l("Ready",{url:m}),ct().catch(()=>{});const t=()=>{T(`${m}/chat/heartbeat`,{method:"POST",headers:{Authorization:`Bearer ${h}`,"Content-Type":"application/json"},body:JSON.stringify({agent_type:de,user_agent:"aerostack-gateway/0.15.29",bridge_id:ne})}).catch(()=>{})};t();const n=setInterval(t,12e4);if(process.on("exit",()=>clearInterval(n)),Me)try{const o=await Ne(async a=>{try{const r=await fetch(`${m}/guardian-batch`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h}`,"User-Agent":"aerostack-gateway/0.15.29","X-Agent-Id":"aerostack-gateway"},body:JSON.stringify({events:a})});return r.ok?(await r.json()).config?.hook_tracking??null:null}catch{return null}},je);Ke&&await Pe(o)&&l("Claude Code hook auto-installed",{port:o})}catch(s){y("Hook server failed to start (non-fatal)",{error:s instanceof Error?s.message:String(s)})}if(He)try{const s=We??await Ue();s?($=new xe({port:ue,token:s,rpcCall:O,onToolEvent:a=>{const r=I;if(!r)return;const i=F.get(r);if(i){if(a.phase==="start")i.push({name:a.toolName,category:a.category,started_at:Date.now(),ended_at:null,duration_ms:null,status:"running",args_summary:a.summary});else if(a.phase==="end"){const c=[...i].reverse().find(_=>_.name===a.toolName&&_.status==="running");c&&(c.ended_at=Date.now(),c.duration_ms=c.ended_at-c.started_at,c.status=a.error?"error":"success",a.error&&(c.error=a.error))}T(`${m}/chat/tool-status`,{method:"POST",headers:{Authorization:`Bearer ${h}`,"Content-Type":"application/json"},body:JSON.stringify({tool_name:a.toolName,phase:a.phase,category:a.category})}).catch(()=>{})}}}),await $.connect()?l("OpenClaw connector started",{port:ue}):(l("OpenClaw gateway not reachable, skipping connector"),$=null)):l("OpenClaw integration skipped (no token found)")}catch(s){y("OpenClaw connector failed (non-fatal)",{error:s instanceof Error?s.message:String(s)})}process.env.AEROSTACK_CHAT_LISTENER!=="false"&&dt()}let E=null,J=!1;async function ut(){return typeof globalThis.WebSocket<"u"?globalThis.WebSocket:(await import("ws")).default}function dt(){J=!1;let e=null,t=0;const n=async()=>{if(!J){if(E){try{E.close()}catch{}E=null}try{const o=await ut(),a=m.replace(/^http/,"ws")+`/chat-relay?token=${encodeURIComponent(h||"")}&client_type=bridge&client_id=${encodeURIComponent(ne)}`,r=new o(a);E=r,r.onopen=()=>{l("[chat-relay] WebSocket connected to workspace"),t=0},r.onmessage=i=>{const c=typeof i.data=="string"?i.data:"";if(c)try{const _=JSON.parse(c);if(_.type==="pong")return;if(_.type==="ping"){try{r.send(JSON.stringify({type:"pong",ts:Date.now()}))}catch{}return}l("[chat-relay] WS frame received",{dataLength:c.length}),ht(c)}catch{}},r.onclose=i=>{l("[chat-relay] WebSocket closed",{code:i.code,reason:i.reason}),E=null,J||s()},r.onerror=()=>{y("[chat-relay] WebSocket error"),t++}}catch(o){y("[chat-relay] Connection failed",{error:o?.message}),t++,s()}}},s=()=>{if(J||e)return;const o=Math.min(2e3*Math.pow(2,t),3e4);l(`[chat-relay] Reconnecting in ${o/1e3}s (failures: ${t})`),e=setTimeout(()=>{e=null,n()},o)};n()}function _e(e,t){if(!E)return!1;try{return E.send(JSON.stringify({type:"chat_reply",content:e.slice(0,1e4),session_id:t||P,sender_name:"Agent",content_type:"text"})),!0}catch{return!1}}function re(e,t=!0){if(E)try{E.send(JSON.stringify({type:"typing",session_id:e||P,is_typing:t}))}catch{}}function pt(){if(J=!0,E){try{E.close()}catch{}E=null}}async function ht(e){try{const t=JSON.parse(e);if(t.type!=="chat_message"){l("[chat-trace] Event ignored (not chat_message)",{type:t.type});return}const n=Date.now();l("[chat-trace] Chat event received",{type:t.type,sender:t.sender_name,contentType:t.content_type,hasContent:!!t.content,sessionId:t.session_id,messageId:t.message_id});let s=[];if(t.metadata_json)try{const g=JSON.parse(t.metadata_json);g?.v===1&&Array.isArray(g.attachments)&&(s=g.attachments)}catch{}const o=!!t.content&&t.content_type!=="media",a=s.length>0;if(!o&&!a)return;const r=t.session_id;l("Chat message received from admin",{sender:t.sender_name,sessionId:r,contentType:t.content_type,attachments:s.length});const i=/^[a-zA-Z0-9_-]{1,128}$/.test(t.message_id??"")?t.message_id:null,c=s.map(g=>{const U=Math.round(g.size/1024),X=U>=1024?`${(U/1024).toFixed(1)} MB`:`${U} KB`,Q=w((g.filename||"file").slice(0,200)),M=w((g.mime_type||"application/octet-stream").slice(0,100)),v=i?`${m}/chat/media/${i}/${encodeURIComponent(g.filename)}`:"(unavailable)";return`[Attached: ${Q} (${M}, ${X}) \u2014 ${v}]`}),_=c.length>0?`
|
|
62
62
|
`+c.join(`
|
|
63
|
-
`):"",b=
|
|
63
|
+
`):"",b=o?t.content+(_?`
|
|
64
64
|
`+c.map(g=>g).join(`
|
|
65
65
|
`):""):c.join(`
|
|
66
|
-
`);r&&(P=r,j(r,"user",b)),z.length>=Qe&&z.shift(),z.push({sender_name:t.sender_name??"Admin",content:
|
|
67
|
-
`).pop()||v.trim();
|
|
66
|
+
`);r&&(P=r,j(r,"user",b)),z.length>=Qe&&z.shift(),z.push({sender_name:t.sender_name??"Admin",content:o?t.content:c.join(", "),created_at:Date.now(),session_id:r,content_type:t.content_type,metadata_json:t.metadata_json,message_id:t.message_id}),L=Date.now();const D=w(t.sender_name??"Admin"),k=o?w(t.content):"",C=r||P||"_default",H=`aerostack-chat-${/^[a-zA-Z0-9_-]{1,64}$/.test(C)?C:"_default"}`,R=`turn-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,A=[];F.set(R,A),I=R;try{const g=k?k+_:_.trim(),U=`[${D} via Aerostack Dashboard]: ${g}`;if(re(r,!0),$){const M=Date.now();l("[chat-trace] WS fast path starting",{session:H,promptLength:U.length,elapsedMs:M-n});const v=await $.sendChatMessage(U);if(v){const S=v.trim(),u=Date.now();l("[chat-trace] WS fast path got response",{responseLength:S.length,llmMs:u-M,totalMs:u-n}),await new Promise(d=>setTimeout(d,500));for(const d of A)d.status==="running"&&(d.status="timeout",d.ended_at=Date.now(),d.duration_ms=d.ended_at-d.started_at);if(A.length>0){const d=A.reduce((p,G)=>p+(G.duration_ms||0),0),f=A.length;try{await T(`${m}/chat/messages`,{method:"POST",headers:{Authorization:`Bearer ${h}`,"Content-Type":"application/json"},body:JSON.stringify({content:`Used ${f} tool${f>1?"s":""}`,content_type:"tool_activity",session_id:r,metadata:JSON.stringify({v:1,tools:A.map(p=>({name:p.name,category:p.category,duration_ms:p.duration_ms,status:p.status,args_summary:p.args_summary?.slice(0,500),error:p.error?.slice(0,500)})),total_duration_ms:d})})})}catch{}}if(F.delete(R),I===R&&(I=null),re(r,!1),S.length>=2)if(j(C,"agent",S),_e(S,r))l("[chat-trace] Reply sent via WS upstream fast path (no HTTP POST needed)",{totalMs:Date.now()-n});else{const f=Date.now();try{const p=await T(`${m}/chat/messages`,{method:"POST",headers:{Authorization:`Bearer ${h}`,"Content-Type":"application/json"},body:JSON.stringify({content:S.slice(0,1e4),session_id:r})}),G=Date.now()-f;p.ok?l("[chat-trace] Reply sent (HTTP fallback)",{replyMs:G,totalMs:Date.now()-n}):y("[chat-trace] Reply failed (HTTP fallback)",{status:p.status,replyMs:G})}catch(p){y("[chat-trace] Reply error (HTTP fallback)",{error:p?.message,replyMs:Date.now()-f})}}return}l("[chat-trace] WS fast path failed, falling back to CLI",{elapsedMs:Date.now()-n})}const{execFile:X}=await import("child_process"),Q=Date.now();l("[chat-trace] CLI fallback starting",{sender:D,session:H,elapsedMs:Q-n}),X("openclaw",["agent","--agent","main","--json","--session-id",H,"-m",U],{timeout:12e4},async(M,v)=>{let S=[];if(!M&&v)try{const u=JSON.parse(v.trim()),d=u?.result?.payloads;Array.isArray(d)&&d.length>0?S=d:(u.text||u.reply||u.message)&&(S=[{text:u.text||u.reply||u.message}])}catch{const u=v.trim().split(`
|
|
67
|
+
`).pop()||v.trim();u&&(S=[{text:u}])}S.length===0&&(S=[{text:`Message received. I'll process "${k.slice(0,100)}" shortly.`}]),await new Promise(u=>setTimeout(u,500));for(const u of A)u.status==="running"&&(u.status="timeout",u.ended_at=Date.now(),u.duration_ms=u.ended_at-u.started_at);if(A.length>0){const u=A.reduce((f,p)=>f+(p.duration_ms||0),0),d=A.length;try{await T(`${m}/chat/messages`,{method:"POST",headers:{Authorization:`Bearer ${h}`,"Content-Type":"application/json"},body:JSON.stringify({content:`Used ${d} tool${d>1?"s":""}`,content_type:"tool_activity",session_id:r,metadata:JSON.stringify({v:1,tools:A.map(f=>({name:f.name,category:f.category,duration_ms:f.duration_ms,status:f.status,args_summary:f.args_summary?.slice(0,500),error:f.error?.slice(0,500)})),total_duration_ms:u})})})}catch{}}F.delete(R),I===R&&(I=null),re(r,!1);for(const u of S){const d=u.text?.trim()||"";if(u.mediaUrl){let f=!1;try{f=new URL(u.mediaUrl).protocol==="https:"}catch{}if(f)try{const p=await T(`${m}/chat/media`,{method:"POST",headers:{Authorization:`Bearer ${h}`,"Content-Type":"application/json"},body:JSON.stringify({media_url:u.mediaUrl,content:d||void 0,session_id:r})});p.ok?l("Chat media sent to workspace",{mediaUrl:u.mediaUrl}):y("Chat media upload failed",{status:p.status})}catch(p){y("Failed to send chat media",{error:p?.message})}else y("Skipping invalid media URL",{mediaUrl:u.mediaUrl});j(C,"agent",d||`[media: ${u.mediaUrl}]`)}else if(d&&d.length>=2)if(j(C,"agent",d),_e(d,r))l("Chat reply sent via WS upstream (no HTTP POST needed)");else try{const p=await T(`${m}/chat/messages`,{method:"POST",headers:{Authorization:`Bearer ${h}`,"Content-Type":"application/json"},body:JSON.stringify({content:d.slice(0,1e4),session_id:r})});p.ok?l("Chat reply sent to workspace"):y("Chat reply failed",{status:p.status})}catch(p){y("Failed to send chat reply",{error:p?.message})}}})}catch(g){y("Failed to spawn agent turn",{error:g?.message}),F.delete(R),I===R&&(I=null)}}catch{}}function Y(){pt(),$?.stop(),Ie(),process.exit(0)}process.on("SIGTERM",()=>{Y()}),process.on("SIGINT",()=>{Y()}),process.argv.includes("--check")?it():lt().catch(e=>{Le("Fatal error",{error:e instanceof Error?e.message:String(e)}),process.exit(1)});
|