@aerostack/gateway 0.15.25 → 0.15.26

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/index.js CHANGED
@@ -1,28 +1,28 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import{Server as X}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as Q}from"@modelcontextprotocol/sdk/server/stdio.js";import{ListToolsRequestSchema as Z,CallToolRequestSchema as ee,ListResourcesRequestSchema as te,ReadResourceRequestSchema as se,ListPromptsRequestSchema as oe,GetPromptRequestSchema as re}from"@modelcontextprotocol/sdk/types.js";import{readFile as ne,writeFile as ae}from"node:fs/promises";import{join as ie}from"node:path";import{homedir as ce}from"node:os";import{resolveApproval as I}from"./resolution.js";import{startHookServer as le,installClaudeHook as ue,stopHookServer as pe}from"./hook-server.js";import{OpenClawConnector as de,resolveOpenClawToken as he}from"./openclaw-connector.js";import{info as c,warn as h,error as me}from"./logger.js";const j=ie(ce(),".openclaw","pre-authorized.json");async function fe(e){try{let s={};try{s=JSON.parse(await ne(j,"utf-8"))}catch{}s[e]=Date.now(),await ae(j,JSON.stringify(s))}catch{}}const L=process.env.AEROSTACK_WORKSPACE_URL,l=process.env.AEROSTACK_TOKEN;function R(e,s,o){const t=parseInt(e??String(s),10);return Number.isFinite(t)&&t>=o?t:s}const D=R(process.env.AEROSTACK_APPROVAL_POLL_MS,3e3,500),U=R(process.env.AEROSTACK_APPROVAL_TIMEOUT_MS,864e5,5e3),H=R(process.env.AEROSTACK_REQUEST_TIMEOUT_MS,3e4,1e3),ge=process.env.AEROSTACK_HOOK_SERVER!=="false",we=R(process.env.AEROSTACK_HOOK_PORT,18321,1024),ye=process.env.AEROSTACK_HOOK_AUTO_INSTALL!=="false",_e=process.env.AEROSTACK_OPENCLAW_ENABLED!=="false",W=R(process.env.AEROSTACK_OPENCLAW_PORT,18789,1024),Ae=process.env.AEROSTACK_OPENCLAW_TOKEN;L||(process.stderr.write(`ERROR: AEROSTACK_WORKSPACE_URL is required
3
+ import{Server as de}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as pe}from"@modelcontextprotocol/sdk/server/stdio.js";import{ListToolsRequestSchema as me,CallToolRequestSchema as he,ListResourcesRequestSchema as fe,ReadResourceRequestSchema as ge,ListPromptsRequestSchema as _e,GetPromptRequestSchema as ye}from"@modelcontextprotocol/sdk/types.js";import{readFile as we,writeFile as Ae}from"node:fs/promises";import{join as Ee}from"node:path";import{homedir as Te}from"node:os";import{resolveApproval as G}from"./resolution.js";import{startHookServer as Se,installClaudeHook as ke,stopHookServer as Re}from"./hook-server.js";import{OpenClawConnector as Oe,resolveOpenClawToken as Ce}from"./openclaw-connector.js";import{info as u,warn as h,error as ve}from"./logger.js";const Z=Ee(Te(),".openclaw","pre-authorized.json");async function $e(e){try{let s={};try{s=JSON.parse(await we(Z,"utf-8"))}catch{}s[e]=Date.now(),await Ae(Z,JSON.stringify(s))}catch{}}const V=process.env.AEROSTACK_WORKSPACE_URL,l=process.env.AEROSTACK_TOKEN;function D(e,s,o){const t=parseInt(e??String(s),10);return Number.isFinite(t)&&t>=o?t:s}const J=D(process.env.AEROSTACK_APPROVAL_POLL_MS,3e3,500),Y=D(process.env.AEROSTACK_APPROVAL_TIMEOUT_MS,864e5,5e3),ee=D(process.env.AEROSTACK_REQUEST_TIMEOUT_MS,3e4,1e3),be=process.env.AEROSTACK_HOOK_SERVER!=="false",Ne=D(process.env.AEROSTACK_HOOK_PORT,18321,1024),Pe=process.env.AEROSTACK_HOOK_AUTO_INSTALL!=="false",xe=process.env.AEROSTACK_OPENCLAW_ENABLED!=="false",te=D(process.env.AEROSTACK_OPENCLAW_PORT,18789,1024),Ie=process.env.AEROSTACK_OPENCLAW_TOKEN;V||(process.stderr.write(`ERROR: AEROSTACK_WORKSPACE_URL is required
4
4
  `),process.exit(1)),l||(process.stderr.write(`ERROR: AEROSTACK_TOKEN is required
5
- `),process.exit(1));let S;try{if(S=new URL(L),S.protocol!=="https:"&&S.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
- `),process.exit(1)}S.protocol==="http:"&&!S.hostname.match(/^(localhost|127\.0\.0\.1)$/)&&process.stderr.write(`WARNING: Using HTTP (not HTTPS) \u2014 token will be sent in plaintext
7
- `);const u=L.replace(/\/+$/,""),M=crypto.randomUUID();function Ee(){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 q=Ee();let A=null,E=Date.now();const Te=3e4;async function f(e,s){const o={jsonrpc:"2.0",id:Date.now(),method:e,params:s??{}},t=new AbortController,r=setTimeout(()=>t.abort(),H);try{const n=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`,"User-Agent":"aerostack-gateway/0.15.14","X-Agent-Id":"aerostack-gateway","X-Bridge-Id":M,"X-Agent-Type":q},body:JSON.stringify(o),signal:t.signal});if(clearTimeout(r),(n.headers.get("content-type")??"").includes("text/event-stream")){const g=await n.text();return ke(g,o.id)}return await n.json()}catch(n){clearTimeout(r);const a=n instanceof Error?n.message:"Unknown error";return n instanceof Error&&n.name==="AbortError"?{jsonrpc:"2.0",id:o.id,error:{code:-32603,message:"Request timed out"}}:{jsonrpc:"2.0",id:o.id,error:{code:-32603,message:`HTTP error: ${a}`}}}}function ke(e,s){const o=e.split(`
8
- `);let t=null;for(const r of o)if(r.startsWith("data: "))try{t=JSON.parse(r.slice(6))}catch{}return t??{jsonrpc:"2.0",id:s,error:{code:-32603,message:"Empty SSE response"}}}const Re=new Set(["aerostack__guardian_report","aerostack__check_approval","aerostack__guardian_check"]);function Se(e,s){if(Re.has(e))return;let o="other";const t=e.toLowerCase();t.includes("exec")||t.includes("bash")||t.includes("shell")||t.includes("command")||t.includes("run")?o="exec_command":t.includes("write")||t.includes("edit")||t.includes("create")||t.includes("patch")?o="file_write":t.includes("delete")||t.includes("remove")||t.includes("trash")||t.includes("unlink")?o="file_delete":t.includes("fetch")||t.includes("http")||t.includes("request")||t.includes("api")||t.includes("get")||t.includes("post")?o="api_call":t.includes("install")||t.includes("package")||t.includes("npm")||t.includes("pip")?o="package_install":t.includes("config")||t.includes("setting")||t.includes("env")?o="config_change":t.includes("deploy")||t.includes("publish")||t.includes("release")?o="deploy":t.includes("send")||t.includes("message")||t.includes("email")||t.includes("notify")||t.includes("slack")||t.includes("telegram")?o="message_send":(t.includes("read")||t.includes("query")||t.includes("search")||t.includes("list")||t.includes("get"))&&(o="data_access");let r;try{const n=JSON.stringify(s);r=n.length>500?n.slice(0,500)+"...":n}catch{r="(unable to serialize)"}f("tools/call",{name:"aerostack__guardian_report",arguments:{action:`${e}(${Object.keys(s).join(", ")})`,category:o,risk_level:"low",details:r}}).catch(()=>{})}const Oe=new Set(["aerostack__check_approval"]),F=[{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(F.map(e=>e.name));function w(e){return e.replace(/\[/g,"(").replace(/\]/g,")")}const O=[],Ce=100,v=new Map,G=50,V=10;let C=null,B=!1;function P(e,s,o){let t=v.get(e);t||(t=[],v.set(e,t)),t.push({role:s,content:o,ts:Date.now()}),t.length>G&&t.splice(0,t.length-G)}async function be(e){if(!B)try{const s=await T(`${u}/chat/history?limit=${V}`,{headers:{Authorization:`Bearer ${l}`}});if(!s.ok)return;const o=await s.json();o.session_id&&(C=o.session_id);for(const t of o.messages??[]){const r=t.sender_type==="agent"?"agent":"user",n=o.session_id||e;let a=v.get(n);a||(a=[],v.set(n,a)),a.push({role:r,content:t.content,ts:t.created_at})}B=!0,c("Thread history seeded from D1",{sessionId:o.session_id,count:o.messages?.length??0})}catch{}}function z(e){const s=v.get(e);return!s||s.length===0?"":`Previous conversation:
9
- ${s.slice(-V).map(r=>`[${r.role==="user"?"Admin":"You (Agent)"}] ${r.content}`).join(`
5
+ `),process.exit(1));let j;try{if(j=new URL(V),j.protocol!=="https:"&&j.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
+ `),process.exit(1)}j.protocol==="http:"&&!j.hostname.match(/^(localhost|127\.0\.0\.1)$/)&&process.stderr.write(`WARNING: Using HTTP (not HTTPS) \u2014 token will be sent in plaintext
7
+ `);const d=V.replace(/\/+$/,""),se=crypto.randomUUID();function Ue(){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 oe=Ue();let v=null,$=Date.now();const Le=3e4;async function A(e,s){const o={jsonrpc:"2.0",id:Date.now(),method:e,params:s??{}},t=new AbortController,r=setTimeout(()=>t.abort(),ee);try{const n=await fetch(d,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`,"User-Agent":"aerostack-gateway/0.15.14","X-Agent-Id":"aerostack-gateway","X-Bridge-Id":se,"X-Agent-Type":oe},body:JSON.stringify(o),signal:t.signal});if(clearTimeout(r),(n.headers.get("content-type")??"").includes("text/event-stream")){const p=await n.text();return De(p,o.id)}return await n.json()}catch(n){clearTimeout(r);const a=n instanceof Error?n.message:"Unknown error";return n instanceof Error&&n.name==="AbortError"?{jsonrpc:"2.0",id:o.id,error:{code:-32603,message:"Request timed out"}}:{jsonrpc:"2.0",id:o.id,error:{code:-32603,message:`HTTP error: ${a}`}}}}function De(e,s){const o=e.split(`
8
+ `);let t=null;for(const r of o)if(r.startsWith("data: "))try{t=JSON.parse(r.slice(6))}catch{}return t??{jsonrpc:"2.0",id:s,error:{code:-32603,message:"Empty SSE response"}}}const je=new Set(["aerostack__guardian_report","aerostack__check_approval","aerostack__guardian_check"]);function Ke(e,s){if(je.has(e))return;let o="other";const t=e.toLowerCase();t.includes("exec")||t.includes("bash")||t.includes("shell")||t.includes("command")||t.includes("run")?o="exec_command":t.includes("write")||t.includes("edit")||t.includes("create")||t.includes("patch")?o="file_write":t.includes("delete")||t.includes("remove")||t.includes("trash")||t.includes("unlink")?o="file_delete":t.includes("fetch")||t.includes("http")||t.includes("request")||t.includes("api")||t.includes("get")||t.includes("post")?o="api_call":t.includes("install")||t.includes("package")||t.includes("npm")||t.includes("pip")?o="package_install":t.includes("config")||t.includes("setting")||t.includes("env")?o="config_change":t.includes("deploy")||t.includes("publish")||t.includes("release")?o="deploy":t.includes("send")||t.includes("message")||t.includes("email")||t.includes("notify")||t.includes("slack")||t.includes("telegram")?o="message_send":(t.includes("read")||t.includes("query")||t.includes("search")||t.includes("list")||t.includes("get"))&&(o="data_access");let r;try{const n=JSON.stringify(s);r=n.length>500?n.slice(0,500)+"...":n}catch{r="(unable to serialize)"}A("tools/call",{name:"aerostack__guardian_report",arguments:{action:`${e}(${Object.keys(s).join(", ")})`,category:o,risk_level:"low",details:r}}).catch(()=>{})}const He=new Set(["aerostack__check_approval"]),ne=[{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"]}}],Me=new Set(ne.map(e=>e.name));function E(e){return e.replace(/[\r\n]+/g," ").replace(/\[/g,"(").replace(/\]/g,")").replace(/---/g,"\u2014")}const K=[],We=100,R=new Map,re=50,ze=100,ae=10;let x=null;const ie=new Set,z=new Map;let I=null;function H(e,s,o){let t=R.get(e);if(!t){if(R.size>=ze){const r=R.keys().next().value;r&&R.delete(r)}t=[],R.set(e,t)}t.push({role:s,content:o,ts:Date.now()}),t.length>re&&t.splice(0,t.length-re)}async function qe(e){if(!ie.has(e))try{const s=await S(`${d}/chat/history?limit=${ae}`,{headers:{Authorization:`Bearer ${l}`}});if(!s.ok)return;const o=await s.json();o.session_id&&(x=o.session_id);for(const t of o.messages??[]){const r=t.sender_type==="agent"?"agent":"user",n=o.session_id||e;let a=R.get(n);a||(a=[],R.set(n,a)),a.push({role:r,content:t.content,ts:t.created_at})}ie.add(e),u("Thread history seeded from D1",{sessionId:o.session_id,count:o.messages?.length??0})}catch{}}function ce(e){const s=R.get(e);return!s||s.length===0?"":`Previous conversation:
9
+ ${s.slice(-ae).map(r=>`[${r.role==="user"?"Admin":"You (Agent)"}] ${r.content}`).join(`
10
10
  `)}
11
11
 
12
- `}async function T(e,s){const o=new AbortController,t=setTimeout(()=>o.abort(),H);try{return await fetch(e,{...s,signal:o.signal})}finally{clearTimeout(t)}}async function $e(){const e=C||"_default";if(await be(e),O.length>0){const s=O.splice(0);E=Date.now();const o=z(e),t=s.map(r=>`${w(r.sender_name)}: ${w(r.content)}`).join(`
12
+ `}async function S(e,s){const o=new AbortController,t=setTimeout(()=>o.abort(),ee);try{return await fetch(e,{...s,signal:o.signal})}finally{clearTimeout(t)}}async function Be(){const e=x||"_default";if(await qe(e),K.length>0){const s=K.splice(0);$=Date.now();const o=ce(e),t=s.map(r=>`${E(r.sender_name)}: ${E(r.content)}`).join(`
13
13
 
14
14
  `);return[{type:"text",text:`${o}New messages from workspace owner:
15
15
 
16
- ${t}`}]}try{const o=await T(`${u}/chat/pending?since=${E}`,{headers:{Authorization:`Bearer ${l}`}});if(!o.ok)return[{type:"text",text:"No new messages."}];const r=(await o.json()).messages??[];if(E=Date.now(),r.length===0)return[{type:"text",text:"No new messages from the workspace owner."}];for(const i of r)P(e,"user",i.content);const n=z(e),a=r.map(i=>`${w(i.sender_name)}: ${w(i.content)}`).join(`
16
+ ${t}`}]}try{const o=await S(`${d}/chat/pending?since=${$}`,{headers:{Authorization:`Bearer ${l}`}});if(!o.ok)return[{type:"text",text:"No new messages."}];const r=(await o.json()).messages??[];if($=Date.now(),r.length===0)return[{type:"text",text:"No new messages from the workspace owner."}];for(const i of r)H(e,"user",i.content);const n=ce(e),a=r.map(i=>`${E(i.sender_name)}: ${E(i.content)}`).join(`
17
17
 
18
18
  `);return[{type:"text",text:`${n}New messages from workspace owner:
19
19
 
20
- ${a}`}]}catch{return[{type:"text",text:"Failed to check messages."}]}}async function Ne(e){const s=typeof e.message=="string"?e.message.trim().slice(0,1e4):"";if(!s)return[{type:"text",text:"Error: message is required."}];try{const o=await T(`${u}/chat/messages`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},body:JSON.stringify({content:s})});return o.ok?(P(C||"_default","agent",s),[{type:"text",text:"Reply sent to workspace owner."}]):[{type:"text",text:`Failed to send reply: ${(await o.json().catch(()=>({error:"Unknown error"}))).error||o.statusText}`}]}catch{return[{type:"text",text:"Failed to send reply."}]}}async function Pe(e,s){Se(e,s);const o=await f("tools/call",{name:e,arguments:s});if(o.error?.code===-32050){const n=o.error.data,a=n?.approval_id;if(!a||!/^[a-zA-Z0-9_-]{4,128}$/.test(a))return{jsonrpc:"2.0",id:o.id,error:{code:-32603,message:"Approval required but no approval_id returned"}};c("Tool gate: blocking until approval resolves",{tool:e,approvalId:a});const i=await I({approvalId:a,wsUrl:n?.ws_url,pollUrl:n?.polling_url??`${u}/approval-status/${a}`,pollIntervalMs:D,timeoutMs:U,token:l});c("Tool gate resolved",{tool:e,status:i.status}),b({approvalId:a,toolName:e,toolArgs:s,sessionKey:null,gate:"tool_gate",pollUrl:"",authToken:l},i.status,!0);const g=K({approvalId:a,toolName:e,toolArgs:s,sessionKey:null,gate:"tool_gate",pollUrl:"",authToken:l},i);return{jsonrpc:"2.0",id:o.id,result:{content:[{type:"text",text:g}]}}}const r=o.result?._meta;if(r?.approval_id&&r?.status==="pending"){const n=r.approval_id;if(!/^[a-zA-Z0-9_-]{4,128}$/.test(n))return o;c("Permission gate: blocking until approval resolves",{tool:e,approvalId:n});const a=await I({approvalId:n,wsUrl:r.ws_url,pollUrl:r.polling_url??`${u}/approval-status/${n}`,pollIntervalMs:D,timeoutMs:U,token:l});c("Permission gate resolved",{tool:e,status:a.status}),b({approvalId:n,toolName:e,toolArgs:s,sessionKey:null,gate:"permission_gate",pollUrl:"",authToken:l},a.status,!0);const i=K({approvalId:n,toolName:e,toolArgs:s,sessionKey:null,gate:"permission_gate",pollUrl:"",authToken:l},a);return{jsonrpc:"2.0",id:o.id,result:{content:[{type:"text",text:i}]}}}return o}function Xe(e){I({approvalId:e.approvalId,wsUrl:e.wsUrl,pollUrl:e.pollUrl,pollIntervalMs:D,timeoutMs:U,token:e.authToken}).then(async s=>{c("Approval resolved",{tool:e.toolName,status:s.status,session:e.sessionKey});const o=K(e,s),t=e.sessionKey??A?.getLastActiveSession()??null;if((s.status==="approved"||s.status==="executed")&&t&&fe(t).catch(()=>{}),t&&A){if(await A.sendToSession(t,o)){c("Agent resumed via sessions.send",{session:t,status:s.status}),b(e,s.status,!0);return}h("sessions.send failed, falling back to channel notification",{session:t})}try{await y.notification({method:"notifications/claude/channel",params:{content:o,meta:{tool_name:e.toolName,approval_id:e.approvalId,status:s.status,gate:e.gate}}}),c("Agent resumed via channel notification",{tool:e.toolName,status:s.status}),b(e,s.status,!0)}catch(r){h("Channel notification failed",{error:r instanceof Error?r.message:String(r)}),b(e,s.status,!1)}}).catch(s=>{h("Background approval resolver error",{error:s instanceof Error?s.message:String(s)})})}function b(e,s,o){const t=typeof e.toolArgs.action=="string"?e.toolArgs.action:null,r=t??e.toolName.replace(/^(?:\w+__)*aerostack__/,"")??e.toolName,n=t?`${r}`:`${r}(${Object.keys(e.toolArgs).join(", ")})`,a=o?"resume sent to agent":"session unavailable \u2014 resume not delivered";let i;s==="approved"||s==="executed"?i=o?`[RESUMED] ${n} \u2014 ${a}`:`[RESUME FAILED] ${n} \u2014 ${a}`:s==="rejected"?i=`[REJECTED] ${n} \u2014 rejection sent to agent`:s==="changes_requested"?i=`[CHANGES REQUESTED] ${n} \u2014 feedback sent to agent`:i=`[EXPIRED] ${n} \u2014 approval timed out, expiry sent to agent`,f("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:s,delivered:o,session:e.sessionKey}).slice(0,500)}}).catch(()=>{})}function K(e,s){const o=s.reviewer_note?.trim()||null,t=`${e.toolName}(${Object.keys(e.toolArgs).join(", ")})`;switch(s.status){case"approved":case"executed":return e.gate==="tool_gate"?["[APPROVAL RECEIVED] Your pending action has been approved.","",`Action: ${t}`,o?`Reviewer note: "${o}"`:null,"",`Please now execute this action: call ${e.toolName} with the same parameters as before.`].filter(r=>r!==null).join(`
20
+ ${a}`}]}catch{return[{type:"text",text:"Failed to check messages."}]}}async function Fe(e){const s=typeof e.message=="string"?e.message.trim().slice(0,1e4):"";if(!s)return[{type:"text",text:"Error: message is required."}];try{const o=await S(`${d}/chat/messages`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},body:JSON.stringify({content:s,session_id:x})});return o.ok?(H(x||"_default","agent",s),[{type:"text",text:"Reply sent to workspace owner."}]):[{type:"text",text:`Failed to send reply (HTTP ${o.status}).`}]}catch{return[{type:"text",text:"Failed to send reply."}]}}async function Ge(e,s){Ke(e,s);const o=await A("tools/call",{name:e,arguments:s});if(o.error?.code===-32050){const n=o.error.data,a=n?.approval_id;if(!a||!/^[a-zA-Z0-9_-]{4,128}$/.test(a))return{jsonrpc:"2.0",id:o.id,error:{code:-32603,message:"Approval required but no approval_id returned"}};u("Tool gate: blocking until approval resolves",{tool:e,approvalId:a});const i=await G({approvalId:a,wsUrl:n?.ws_url,pollUrl:n?.polling_url??`${d}/approval-status/${a}`,pollIntervalMs:J,timeoutMs:Y,token:l});u("Tool gate resolved",{tool:e,status:i.status}),M({approvalId:a,toolName:e,toolArgs:s,sessionKey:null,gate:"tool_gate",pollUrl:"",authToken:l},i.status,!0);const p=X({approvalId:a,toolName:e,toolArgs:s,sessionKey:null,gate:"tool_gate",pollUrl:"",authToken:l},i);return{jsonrpc:"2.0",id:o.id,result:{content:[{type:"text",text:p}]}}}const r=o.result?._meta;if(r?.approval_id&&r?.status==="pending"){const n=r.approval_id;if(!/^[a-zA-Z0-9_-]{4,128}$/.test(n))return o;u("Permission gate: blocking until approval resolves",{tool:e,approvalId:n});const a=await G({approvalId:n,wsUrl:r.ws_url,pollUrl:r.polling_url??`${d}/approval-status/${n}`,pollIntervalMs:J,timeoutMs:Y,token:l});u("Permission gate resolved",{tool:e,status:a.status}),M({approvalId:n,toolName:e,toolArgs:s,sessionKey:null,gate:"permission_gate",pollUrl:"",authToken:l},a.status,!0);const i=X({approvalId:n,toolName:e,toolArgs:s,sessionKey:null,gate:"permission_gate",pollUrl:"",authToken:l},a);return{jsonrpc:"2.0",id:o.id,result:{content:[{type:"text",text:i}]}}}return o}function mt(e){G({approvalId:e.approvalId,wsUrl:e.wsUrl,pollUrl:e.pollUrl,pollIntervalMs:J,timeoutMs:Y,token:e.authToken}).then(async s=>{u("Approval resolved",{tool:e.toolName,status:s.status,session:e.sessionKey});const o=X(e,s),t=e.sessionKey??v?.getLastActiveSession()??null;if((s.status==="approved"||s.status==="executed")&&t&&$e(t).catch(()=>{}),t&&v){if(await v.sendToSession(t,o)){u("Agent resumed via sessions.send",{session:t,status:s.status}),M(e,s.status,!0);return}h("sessions.send failed, falling back to channel notification",{session:t})}try{await O.notification({method:"notifications/claude/channel",params:{content:o,meta:{tool_name:e.toolName,approval_id:e.approvalId,status:s.status,gate:e.gate}}}),u("Agent resumed via channel notification",{tool:e.toolName,status:s.status}),M(e,s.status,!0)}catch(r){h("Channel notification failed",{error:r instanceof Error?r.message:String(r)}),M(e,s.status,!1)}}).catch(s=>{h("Background approval resolver error",{error:s instanceof Error?s.message:String(s)})})}function M(e,s,o){const t=typeof e.toolArgs.action=="string"?e.toolArgs.action:null,r=t??e.toolName.replace(/^(?:\w+__)*aerostack__/,"")??e.toolName,n=t?`${r}`:`${r}(${Object.keys(e.toolArgs).join(", ")})`,a=o?"resume sent to agent":"session unavailable \u2014 resume not delivered";let i;s==="approved"||s==="executed"?i=o?`[RESUMED] ${n} \u2014 ${a}`:`[RESUME FAILED] ${n} \u2014 ${a}`:s==="rejected"?i=`[REJECTED] ${n} \u2014 rejection sent to agent`:s==="changes_requested"?i=`[CHANGES REQUESTED] ${n} \u2014 feedback sent to agent`:i=`[EXPIRED] ${n} \u2014 approval timed out, expiry sent to agent`,A("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:s,delivered:o,session:e.sessionKey}).slice(0,500)}}).catch(()=>{})}function X(e,s){const o=s.reviewer_note?.trim()||null,t=`${e.toolName}(${Object.keys(e.toolArgs).join(", ")})`;switch(s.status){case"approved":case"executed":return e.gate==="tool_gate"?["[APPROVAL RECEIVED] Your pending action has been approved.","",`Action: ${t}`,o?`Reviewer note: "${o}"`:null,"",`Please now execute this action: call ${e.toolName} with the same parameters as before.`].filter(r=>r!==null).join(`
21
21
  `):["[APPROVAL RECEIVED] Your request has been approved by the workspace owner.",o?`Reviewer note: "${o}"`:null,"","You may now proceed with the action you requested approval for."].filter(r=>r!==null).join(`
22
22
  `);case"changes_requested":return["[CHANGES REQUESTED] The workspace owner reviewed your action and requested changes.","",`Original action: ${t}`,`Reviewer feedback: "${o??"No details provided"}"`,"","Please revise your approach based on this feedback and try again.","Do NOT proceed with the original plan."].join(`
23
23
  `);case"rejected":return["[REJECTED] The workspace owner denied this action.","",`Action: ${t}`,o?`Reason: "${o}"`:"No reason provided.","","Do not retry this action. If you believe this was a mistake, inform the user."].join(`
24
24
  `);case"expired":return[`[EXPIRED] The approval request for "${t}" timed out \u2014 no decision was made.`,"","You may resubmit the request if the action is still needed."].join(`
25
- `);default:return`[APPROVAL UPDATE] Status for "${t}": ${s.status}.`}}const x=`
25
+ `);default:return`[APPROVAL UPDATE] Status for "${t}": ${s.status}.`}}const q=`
26
26
  === AEROSTACK GUARDIAN POLICY (MANDATORY) ===
27
27
 
28
28
  You are operating under Aerostack workspace monitoring. These rules apply to ALL actions:
@@ -50,25 +50,30 @@ or before starting a new one, call aerostack__chat_check to see if the owner sen
50
50
  If there are messages, read them carefully and respond using aerostack__chat_reply. This keeps
51
51
  the owner informed and allows them to steer your work in real time.
52
52
  === END WORKSPACE CHAT ===
53
- `.trim(),xe=["delete","remove","drop","truncate","destroy","wipe","reset","deploy","publish","release","push","exec","shell","bash","run","command","terminal","install","uninstall","send","email","notify","webhook"];function Ie(e,s){const o=e.toLowerCase(),t=xe.some(n=>o.includes(n)),r=s??"";return t?`[REQUIRES GUARDIAN APPROVAL] ${r}`.trim():r}let Y=null;async function k(){if(Y)return;const e=await f("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"aerostack-gateway",version:"0.15.14"}});if(e.result){const s=e.result,o=s.instructions??"";Y={protocolVersion:s.protocolVersion??"2024-11-05",instructions:o?`${o}
53
+ `.trim(),Ve=["delete","remove","drop","truncate","destroy","wipe","reset","deploy","publish","release","push","exec","shell","bash","run","command","terminal","install","uninstall","send","email","notify","webhook"];function Je(e,s){const o=e.toLowerCase(),t=Ve.some(n=>o.includes(n)),r=s??"";return t?`[REQUIRES GUARDIAN APPROVAL] ${r}`.trim():r}let le=null;async function U(){if(le)return;const e=await A("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"aerostack-gateway",version:"0.15.14"}});if(e.result){const s=e.result,o=s.instructions??"";le={protocolVersion:s.protocolVersion??"2024-11-05",instructions:o?`${o}
54
54
 
55
- ${x}`:x}}}const y=new X({name:"aerostack-gateway",version:"0.15.14"},{capabilities:{tools:{},resources:{},prompts:{},experimental:{"claude/channel":{}}},instructions:x});y.setRequestHandler(Z,async()=>{await k();const e=await f("tools/list");if(e.error)throw new Error(e.error.message);const o=(e.result.tools??[]).filter(t=>!Oe.has(t.name)).map(t=>({...t,description:Ie(t.name,t.description)}));return o.push(...F),{tools:o}}),y.setRequestHandler(ee,async e=>{await k();const{name:s,arguments:o}=e.params;if(ve.has(s))return{content:(s==="aerostack__chat_check"?await $e():await Ne(o??{})).map(i=>({...i,type:"text"}))};const t=await Pe(s,o??{});if(t.error)return{content:[{type:"text",text:`Error: ${t.error.message}`}],isError:!0};const n=t.result.content??[{type:"text",text:JSON.stringify(t.result)}];if(Date.now()-E>Te)try{const i=await T(`${u}/chat/pending?since=${E}`,{headers:{Authorization:`Bearer ${l}`}});if(i.ok){const _=(await i.json()).messages??[];if(E=Date.now(),_.length>0){const m=_.map(p=>`${w(p.sender_name)}: ${w(p.content)}`).join(`
55
+ ${q}`:q}}}const O=new de({name:"aerostack-gateway",version:"0.15.14"},{capabilities:{tools:{},resources:{},prompts:{},experimental:{"claude/channel":{}}},instructions:q});O.setRequestHandler(me,async()=>{await U();const e=await A("tools/list");if(e.error)throw new Error(e.error.message);const o=(e.result.tools??[]).filter(t=>!He.has(t.name)).map(t=>({...t,description:Je(t.name,t.description)}));return o.push(...ne),{tools:o}}),O.setRequestHandler(he,async e=>{await U();const{name:s,arguments:o}=e.params;if(Me.has(s))return{content:(s==="aerostack__chat_check"?await Be():await Fe(o??{})).map(i=>({...i,type:"text"}))};const t=await Ge(s,o??{});if(t.error)return{content:[{type:"text",text:`Error: ${t.error.message}`}],isError:!0};const n=t.result.content??[{type:"text",text:JSON.stringify(t.result)}];if(Date.now()-$>Le)try{const i=await S(`${d}/chat/pending?since=${$}`,{headers:{Authorization:`Bearer ${l}`}});if(i.ok){const y=(await i.json()).messages??[];if($=Date.now(),y.length>0){const T=y.map(_=>`${E(_.sender_name)}: ${E(_.content)}`).join(`
56
56
  `);n.unshift({type:"text",text:`--- WORKSPACE OWNER MESSAGE ---
57
- ${m}
58
- --- END MESSAGE \u2014 please acknowledge ---`})}}}catch{}return{content:n}});const Le={uri:"aerostack://guardian/policy",name:"Aerostack Guardian Policy",description:"Mandatory workspace monitoring policy. Read this to understand required approval workflows.",mimeType:"text/plain"};y.setRequestHandler(te,async()=>{await k();const e=await f("resources/list");if(e.error)throw new Error(e.error.message);const s=e.result;return{resources:[Le,...s.resources??[]]}}),y.setRequestHandler(se,async e=>{if(await k(),e.params.uri==="aerostack://guardian/policy")return{contents:[{uri:e.params.uri,text:x,mimeType:"text/plain"}]};const s=await f("resources/read",{uri:e.params.uri});if(s.error)throw new Error(s.error.message);return{contents:s.result.contents??[]}}),y.setRequestHandler(oe,async()=>{await k();const e=await f("prompts/list");if(e.error)throw new Error(e.error.message);return{prompts:e.result.prompts??[]}}),y.setRequestHandler(re,async e=>{await k();const s=await f("prompts/get",{name:e.params.name,arguments:e.params.arguments});if(s.error)throw new Error(s.error.message);return{messages:s.result.messages??[]}});async function De(){const e=s=>process.stderr.write(s+`
57
+ ${T}
58
+ --- END MESSAGE \u2014 please acknowledge ---`})}}}catch{}return{content:n}});const Ye={uri:"aerostack://guardian/policy",name:"Aerostack Guardian Policy",description:"Mandatory workspace monitoring policy. Read this to understand required approval workflows.",mimeType:"text/plain"};O.setRequestHandler(fe,async()=>{await U();const e=await A("resources/list");if(e.error)throw new Error(e.error.message);const s=e.result;return{resources:[Ye,...s.resources??[]]}}),O.setRequestHandler(ge,async e=>{if(await U(),e.params.uri==="aerostack://guardian/policy")return{contents:[{uri:e.params.uri,text:q,mimeType:"text/plain"}]};const s=await A("resources/read",{uri:e.params.uri});if(s.error)throw new Error(s.error.message);return{contents:s.result.contents??[]}}),O.setRequestHandler(_e,async()=>{await U();const e=await A("prompts/list");if(e.error)throw new Error(e.error.message);return{prompts:e.result.prompts??[]}}),O.setRequestHandler(ye,async e=>{await U();const s=await A("prompts/get",{name:e.params.name,arguments:e.params.arguments});if(s.error)throw new Error(s.error.message);return{messages:s.result.messages??[]}});async function Xe(){const e=s=>process.stderr.write(s+`
59
59
  `);e(`
60
60
  Aerostack Connection Check
61
- `);try{const s=await fetch(`${u}/chat/connection-test`,{headers:{Authorization:`Bearer ${l}`},signal:AbortSignal.timeout(1e4)});s.ok||(s.status===401&&(e(" \u2705 Workspace URL reachable"),e(" \u274C Token invalid (HTTP 401)"),e(`
61
+ `);try{const s=await fetch(`${d}/chat/connection-test`,{headers:{Authorization:`Bearer ${l}`},signal:AbortSignal.timeout(1e4)});s.ok||(s.status===401&&(e(" \u2705 Workspace URL reachable"),e(" \u274C Token invalid (HTTP 401)"),e(`
62
62
  Fix: Regenerate token at your dashboard \u2192 Workspace \u2192 Tokens
63
63
  `),process.exit(1)),e(` \u274C Workspace unreachable (HTTP ${s.status})`),e(`
64
64
  Fix: Check AEROSTACK_WORKSPACE_URL is correct
65
- `),process.exit(1));const o=await s.json();e(` \u2705 Workspace URL reachable (${u})`),e(` \u2705 Token valid (${o.token_name}, role: ${o.token_role})`),e(` \u2705 Workspace connected ("${o.workspace}")`),e(` \u2705 Tools available (${o.mcp_servers} tools)`);try{const t=await fetch(`${u}/chat/heartbeat`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},body:JSON.stringify({agent_type:"check",user_agent:"aerostack-gateway/check",bridge_id:"check"}),signal:AbortSignal.timeout(1e4)});e(t.ok?" \u2705 Dashboard registration (bridge visible in admin)":` \u26A0\uFE0F Dashboard registration (returned ${t.status})`)}catch{e(" \u26A0\uFE0F Dashboard registration (heartbeat failed \u2014 non-fatal)")}e(`
65
+ `),process.exit(1));const o=await s.json();e(` \u2705 Workspace URL reachable (${d})`),e(` \u2705 Token valid (${o.token_name}, role: ${o.token_role})`),e(` \u2705 Workspace connected ("${o.workspace}")`),e(` \u2705 Tools available (${o.mcp_servers} tools)`);try{const t=await fetch(`${d}/chat/heartbeat`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},body:JSON.stringify({agent_type:"check",user_agent:"aerostack-gateway/check",bridge_id:"check"}),signal:AbortSignal.timeout(1e4)});e(t.ok?" \u2705 Dashboard registration (bridge visible in admin)":` \u26A0\uFE0F Dashboard registration (returned ${t.status})`)}catch{e(" \u26A0\uFE0F Dashboard registration (heartbeat failed \u2014 non-fatal)")}e(`
66
66
  All checks passed. Your agent is connected.`),e(` Dashboard: ${o.dashboard_url||"https://app.aerostack.dev"}
67
67
  `),o.mcp_servers===0&&e(` Note: 0 tools found. Add MCP servers or functions to your workspace first.
68
68
  `),process.exit(0)}catch(s){s?.name==="TimeoutError"||s?.name==="AbortError"?(e(" \u274C Workspace unreachable (timeout after 10s)"),e(`
69
69
  Fix: Check AEROSTACK_WORKSPACE_URL and your network connection
70
70
  `)):(e(` \u274C Connection failed (${s?.message??"unknown error"})`),e(`
71
71
  Fix: Check AEROSTACK_WORKSPACE_URL is correct
72
- `)),process.exit(1)}}async function Ue(){try{const e=await fetch(`${u}/chat/connection-test`,{headers:{Authorization:`Bearer ${l}`},signal:AbortSignal.timeout(5e3)});if(e.ok){const s=await e.json();c(`Connected to "${s.workspace}" (${s.mcp_servers} tools)`,{dashboard:"https://app.aerostack.dev"})}else e.status===401?h("Token invalid \u2014 regenerate at dashboard \u2192 Workspace \u2192 Tokens"):h("Connection check failed",{status:e.status})}catch{h("Could not verify connection (non-fatal)")}}async function Ke(){c("Connecting to workspace",{url:u});const e=new Q;await y.connect(e),c("Ready",{url:u}),Ue().catch(()=>{});const s=()=>{T(`${u}/chat/heartbeat`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},body:JSON.stringify({agent_type:q,user_agent:"aerostack-gateway/0.15.14",bridge_id:M})}).catch(()=>{})};s();const o=setInterval(s,12e4);if(process.on("exit",()=>clearInterval(o)),ge)try{const r=await le(async n=>{try{const a=await fetch(`${u}/guardian-batch`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`,"User-Agent":"aerostack-gateway/0.15.14","X-Agent-Id":"aerostack-gateway"},body:JSON.stringify({events:n})});return a.ok?(await a.json()).config?.hook_tracking??null:null}catch{return null}},we);ye&&await ue(r)&&c("Claude Code hook auto-installed",{port:r})}catch(t){h("Hook server failed to start (non-fatal)",{error:t instanceof Error?t.message:String(t)})}if(_e)try{const t=Ae??await he();t?(A=new de({port:W,token:t,rpcCall:f}),await A.connect()?c("OpenClaw connector started",{port:W}):(c("OpenClaw gateway not reachable, skipping connector"),A=null)):c("OpenClaw integration skipped (no token found)")}catch(t){h("OpenClaw connector failed (non-fatal)",{error:t instanceof Error?t.message:String(t)})}je()}let $=null;function je(){$&&$.abort(),$=new AbortController;const e=async()=>{try{const t=await fetch(u,{method:"GET",headers:{Authorization:`Bearer ${l}`,Accept:"text/event-stream"},signal:$.signal});if(!t.ok||!t.body){h("Chat event listener: failed to connect",{status:t.status}),o();return}c("Chat event listener connected");const r=t.body.getReader(),n=new TextDecoder;let a="";for(;;){const{done:i,value:g}=await r.read();if(i)break;a+=n.decode(g,{stream:!0});const _=a.split(`
73
- `);a=_.pop()??"";let m="",p="";for(const d of _)d.startsWith("event: ")?m=d.slice(7).trim():d.startsWith("data: ")?p=d.slice(6):d===""&&m&&p&&(m==="aerostack_event"&&He(p),m="",p="")}c("Chat event listener: stream ended, reconnecting"),o()}catch(t){if(t?.name==="AbortError")return;h("Chat event listener error",{error:t?.message}),o()}};let s=null;const o=()=>{s||(s=setTimeout(()=>{s=null,e()},5e3))};e()}async function He(e){try{const s=JSON.parse(e);if(s.type!=="chat_message"||!s.content)return;const o=s.session_id;c("Chat message received from admin",{sender:s.sender_name,sessionId:o}),o&&(C=o,P(o,"user",s.content)),O.length>=Ce&&O.shift(),O.push({sender_name:s.sender_name??"Admin",content:s.content,created_at:Date.now(),session_id:o}),E=Date.now();const t=w(s.sender_name??"Admin"),r=w(s.content),n=o||C||"_default",a=`aerostack-chat-${n}`;try{const{execFile:i}=await import("child_process");c("Spawning full agent turn for chat",{sender:t,session:a});const g=`[Aerostack Dashboard \u2014 ${t}]: ${r}`;i("openclaw",["agent","--agent","main","--json","--session-id",a,"-m",g],{timeout:12e4},async(_,m)=>{let p="";if(!_&&m)try{const d=JSON.parse(m.trim()),N=d?.result?.payloads;Array.isArray(N)&&N.length>0&&N[0].text?p=N[0].text:p=d.text||d.reply||d.message||""}catch{p=m.trim().split(`
74
- `).pop()||m.trim()}(!p||p.length<2)&&(p=`Message received. I'll process "${r.slice(0,100)}" shortly.`),P(n,"agent",p);try{const d=await T(`${u}/chat/messages`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},body:JSON.stringify({content:p.slice(0,1e4)})});d.ok?c("Chat reply sent to workspace"):h("Chat reply failed",{status:d.status})}catch(d){h("Failed to send chat reply",{error:d?.message})}})}catch(i){h("Failed to spawn agent turn",{error:i?.message})}}catch{}}function J(){$?.abort(),A?.stop(),pe(),process.exit(0)}process.on("SIGTERM",()=>{J()}),process.on("SIGINT",()=>{J()}),process.argv.includes("--check")?De():Ke().catch(e=>{me("Fatal error",{error:e instanceof Error?e.message:String(e)}),process.exit(1)});
72
+ `)),process.exit(1)}}async function Qe(){try{const e=await fetch(`${d}/chat/connection-test`,{headers:{Authorization:`Bearer ${l}`},signal:AbortSignal.timeout(5e3)});if(e.ok){const s=await e.json();u(`Connected to "${s.workspace}" (${s.mcp_servers} tools)`,{dashboard:"https://app.aerostack.dev"})}else e.status===401?h("Token invalid \u2014 regenerate at dashboard \u2192 Workspace \u2192 Tokens"):h("Connection check failed",{status:e.status})}catch{h("Could not verify connection (non-fatal)")}}async function Ze(){u("Connecting to workspace",{url:d});const e=new pe;await O.connect(e),u("Ready",{url:d}),Qe().catch(()=>{});const s=()=>{S(`${d}/chat/heartbeat`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},body:JSON.stringify({agent_type:oe,user_agent:"aerostack-gateway/0.15.14",bridge_id:se})}).catch(()=>{})};s();const o=setInterval(s,12e4);if(process.on("exit",()=>clearInterval(o)),be)try{const r=await Se(async n=>{try{const a=await fetch(`${d}/guardian-batch`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`,"User-Agent":"aerostack-gateway/0.15.14","X-Agent-Id":"aerostack-gateway"},body:JSON.stringify({events:n})});return a.ok?(await a.json()).config?.hook_tracking??null:null}catch{return null}},Ne);Pe&&await ke(r)&&u("Claude Code hook auto-installed",{port:r})}catch(t){h("Hook server failed to start (non-fatal)",{error:t instanceof Error?t.message:String(t)})}if(xe)try{const t=Ie??await Ce();t?(v=new Oe({port:te,token:t,rpcCall:A,onToolEvent:n=>{const a=I;if(!a)return;const i=z.get(a);if(i){if(n.phase==="start")i.push({name:n.toolName,category:n.category,started_at:Date.now(),ended_at:null,duration_ms:null,status:"running",args_summary:n.summary});else if(n.phase==="end"){const p=[...i].reverse().find(y=>y.name===n.toolName&&y.status==="running");p&&(p.ended_at=Date.now(),p.duration_ms=p.ended_at-p.started_at,p.status=n.error?"error":"success",n.error&&(p.error=n.error))}S(`${d}/chat/tool-status`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},body:JSON.stringify({tool_name:n.toolName,phase:n.phase,category:n.category})}).catch(()=>{})}}}),await v.connect()?u("OpenClaw connector started",{port:te}):(u("OpenClaw gateway not reachable, skipping connector"),v=null)):u("OpenClaw integration skipped (no token found)")}catch(t){h("OpenClaw connector failed (non-fatal)",{error:t instanceof Error?t.message:String(t)})}et()}let W=null;function et(){W&&W.abort(),W=new AbortController;const e=async()=>{try{const t=await fetch(d,{method:"GET",headers:{Authorization:`Bearer ${l}`,Accept:"text/event-stream"},signal:W.signal});if(!t.ok||!t.body){h("Chat event listener: failed to connect",{status:t.status}),o();return}u("Chat event listener connected");const r=t.body.getReader(),n=new TextDecoder;let a="";for(;;){const{done:i,value:p}=await r.read();if(i)break;a+=n.decode(p,{stream:!0});const y=a.split(`
73
+ `);a=y.pop()??"";let T="",_="";for(const w of y)w.startsWith("event: ")?T=w.slice(7).trim():w.startsWith("data: ")?_=w.slice(6):w===""&&T&&_&&(T==="aerostack_event"&&tt(_),T="",_="")}u("Chat event listener: stream ended, reconnecting"),o()}catch(t){if(t?.name==="AbortError")return;h("Chat event listener error",{error:t?.message}),o()}};let s=null;const o=()=>{s||(s=setTimeout(()=>{s=null,e()},5e3))};e()}async function tt(e){try{const s=JSON.parse(e);if(s.type!=="chat_message")return;let o=[];if(s.metadata_json)try{const f=JSON.parse(s.metadata_json);f?.v===1&&Array.isArray(f.attachments)&&(o=f.attachments)}catch{}const t=!!s.content&&s.content_type!=="media",r=o.length>0;if(!t&&!r)return;const n=s.session_id;u("Chat message received from admin",{sender:s.sender_name,sessionId:n,contentType:s.content_type,attachments:o.length});const a=/^[a-zA-Z0-9_-]{1,128}$/.test(s.message_id??"")?s.message_id:null,i=o.map(f=>{const L=Math.round(f.size/1024),B=L>=1024?`${(L/1024).toFixed(1)} MB`:`${L} KB`,F=E((f.filename||"file").slice(0,200)),P=E((f.mime_type||"application/octet-stream").slice(0,100)),k=a?`${d}/chat/media/${a}/${encodeURIComponent(f.filename)}`:"(unavailable)";return`[Attached: ${F} (${P}, ${B}) \u2014 ${k}]`}),p=i.length>0?`
74
+ `+i.join(`
75
+ `):"",y=t?s.content+(p?`
76
+ `+i.map(f=>f).join(`
77
+ `):""):i.join(`
78
+ `);n&&(x=n,H(n,"user",y)),K.length>=We&&K.shift(),K.push({sender_name:s.sender_name??"Admin",content:t?s.content:i.join(", "),created_at:Date.now(),session_id:n}),$=Date.now();const T=E(s.sender_name??"Admin"),_=t?E(s.content):"",w=n||x||"_default",Q=`aerostack-chat-${/^[a-zA-Z0-9_-]{1,64}$/.test(w)?w:"_default"}`,b=`turn-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,N=[];z.set(b,N),I=b;try{const{execFile:f}=await import("child_process");u("Spawning full agent turn for chat",{sender:T,session:Q});const L=_?_+p:p.trim(),B=`[Aerostack Dashboard \u2014 ${T}]: ${L}`;f("openclaw",["agent","--agent","main","--json","--session-id",Q,"-m",B],{timeout:12e4},async(F,P)=>{let k=[];if(!F&&P)try{const c=JSON.parse(P.trim()),g=c?.result?.payloads;Array.isArray(g)&&g.length>0?k=g:(c.text||c.reply||c.message)&&(k=[{text:c.text||c.reply||c.message}])}catch{const c=P.trim().split(`
79
+ `).pop()||P.trim();c&&(k=[{text:c}])}k.length===0&&(k=[{text:`Message received. I'll process "${_.slice(0,100)}" shortly.`}]),await new Promise(c=>setTimeout(c,500));for(const c of N)c.status==="running"&&(c.status="timeout",c.ended_at=Date.now(),c.duration_ms=c.ended_at-c.started_at);if(N.length>0){const c=N.reduce((m,C)=>m+(C.duration_ms||0),0),g=N.length;try{await S(`${d}/chat/messages`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},body:JSON.stringify({content:`Used ${g} tool${g>1?"s":""}`,content_type:"tool_activity",session_id:n,metadata:JSON.stringify({v:1,tools:N.map(m=>({name:m.name,category:m.category,duration_ms:m.duration_ms,status:m.status,args_summary:m.args_summary?.slice(0,500),error:m.error?.slice(0,500)})),total_duration_ms:c})})})}catch{}}z.delete(b),I===b&&(I=null);for(const c of k){const g=c.text?.trim()||"";if(c.mediaUrl){let m=!1;try{m=new URL(c.mediaUrl).protocol==="https:"}catch{}if(m)try{const C=await S(`${d}/chat/media`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},body:JSON.stringify({media_url:c.mediaUrl,content:g||void 0,session_id:n})});C.ok?u("Chat media sent to workspace",{mediaUrl:c.mediaUrl}):h("Chat media upload failed",{status:C.status})}catch(C){h("Failed to send chat media",{error:C?.message})}else h("Skipping invalid media URL",{mediaUrl:c.mediaUrl});H(w,"agent",g||`[media: ${c.mediaUrl}]`)}else if(g&&g.length>=2){H(w,"agent",g);try{const m=await S(`${d}/chat/messages`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},body:JSON.stringify({content:g.slice(0,1e4),session_id:n})});m.ok?u("Chat reply sent to workspace"):h("Chat reply failed",{status:m.status})}catch(m){h("Failed to send chat reply",{error:m?.message})}}}})}catch(f){h("Failed to spawn agent turn",{error:f?.message}),z.delete(b),I===b&&(I=null)}}catch{}}function ue(){W?.abort(),v?.stop(),Re(),process.exit(0)}process.on("SIGTERM",()=>{ue()}),process.on("SIGINT",()=>{ue()}),process.argv.includes("--check")?Xe():Ze().catch(e=>{ve("Fatal error",{error:e instanceof Error?e.message:String(e)}),process.exit(1)});
@@ -1 +1 @@
1
- import{readFile as m}from"node:fs/promises";import{join as g}from"node:path";import{homedir as f}from"node:os";import{info as u,warn as c,debug as l}from"./logger.js";import{addToBatch as p,detectCategory as b,summarizeToolInput as w}from"./hook-server.js";function y(a){return a.replace(/^(?:\w+__)*aerostack__/,"").replace(/__/g,":")||a}async function R(){try{const a=g(f(),".openclaw","openclaw.json"),e=await m(a,"utf-8");return JSON.parse(e)?.gateway?.auth?.token??null}catch{return null}}async function N(){try{const a=g(f(),".openclaw","exec-approvals.json"),e=await m(a,"utf-8");return JSON.parse(e)?.socket?.token??null}catch{return null}}const S=1e3,v=3e4;class E{opts;ws=null;destroyed=!1;reconnectMs=S;reconnectTimer=null;requestId=0;seenSessions=new Set;pendingRequests=new Map;lastActiveSession=null;constructor(e){this.opts=e}async connect(){if(this.destroyed)return!1;const e=await this.getWebSocket(),s=`ws://127.0.0.1:${this.opts.port}`;return new Promise(t=>{try{const n=new e(s);this.ws=n;const o=setTimeout(()=>{l("OpenClaw connect timeout");try{n.close()}catch{}t(!1)},1e4);n.onopen=()=>{clearTimeout(o),l("OpenClaw WS connected, sending handshake"),this.sendHandshake()},n.onmessage=i=>{try{const r=JSON.parse(String(i.data));this.handleFrame(r,t)}catch{}},n.onerror=()=>{clearTimeout(o),t(!1)},n.onclose=()=>{clearTimeout(o),this.ws=null,this.destroyed||this.scheduleReconnect()}}catch{t(!1)}})}getLastActiveSession(){return this.lastActiveSession}async sendToSession(e,s){if(!this.ws||!this.connected)return!1;const t=await this.sendRequest("sessions.send",{key:e,message:s,idempotencyKey:`aerostack-${Date.now()}`});return t.ok||c("sendToSession failed",{key:e,error:t.error?.message}),t.ok??!1}stop(){if(this.destroyed=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws){try{this.ws.close(1e3)}catch{}this.ws=null}this.pendingRequests.clear()}sendHandshake(){this.send({type:"req",id:String(++this.requestId),method:"connect",params:{minProtocol:3,maxProtocol:3,client:{id:"openclaw-tui",displayName:"Aerostack Guardian",version:"0.15.8",platform:process.platform,mode:"cli"},auth:{token:this.opts.token},scopes:["operator.read","operator.write"],caps:["tool-events"]}})}connected=!1;subscribedSessions=new Set;handleFrame(e,s){if(e.type==="res"&&!this.connected){e.ok?(this.connected=!0,this.reconnectMs=S,u("OpenClaw connector connected",{port:this.opts.port}),s?.(!0),this.subscribeAllSessions().catch(t=>c("subscribeAllSessions failed",{error:t?.message}))):(c("OpenClaw connect rejected",{error:e.error?.message}),s?.(!1));return}if(e.type==="res"&&e.id&&this.pendingRequests.has(e.id)){const t=this.pendingRequests.get(e.id);this.pendingRequests.delete(e.id),t(e);return}if(e.type==="res"&&e.ok===!1&&e.error){c("OpenClaw RPC error",{error:e.error.message,code:e.error.code});return}e.type==="event"&&this.handleEvent(e)}subscribeToSessionMessages(e){if(this.subscribedSessions.has(e))return;this.subscribedSessions.add(e);const s=String(++this.requestId);this.pendingRequests.set(s,t=>{t.ok?l("OpenClaw subscribed to session messages",{key:e}):c("OpenClaw messages.subscribe failed",{key:e,error:t.error?.message})}),this.send({type:"req",id:s,method:"sessions.messages.subscribe",params:{key:e}}),setTimeout(()=>this.pendingRequests.delete(s),1e4)}async subscribeAllSessions(){const e=await this.sendRequest("sessions.subscribe");e.ok?u("OpenClaw subscribed to all session events (tool + lifecycle)"):c("OpenClaw sessions.subscribe failed",{error:e.error?.message});const s=await this.sendRequest("sessions.list",{limit:50});if(!s.ok){c("OpenClaw sessions.list failed",{error:s.error?.message});return}const t=s.payload?.sessions,n=Array.isArray(t)?t:[];u("OpenClaw active sessions",{count:n.length});for(const o of n)o.key&&this.subscribeToSessionMessages(o.key)}sendRequest(e,s){return new Promise(t=>{const n=String(++this.requestId),o=setTimeout(()=>{this.pendingRequests.delete(n),t({type:"res",id:n,ok:!1,error:{code:"TIMEOUT",message:"request timeout"}})},1e4);this.pendingRequests.set(n,i=>{clearTimeout(o),t(i)}),this.send({type:"req",id:n,method:e,params:s})})}handleEvent(e){const s=e.event,t=e.payload??{};s==="agent"?this.handleAgentEvent(t):s==="session.tool"?this.handleToolEvent(t):s==="session.message"?this.handleMessageEvent(t):s==="sessions.changed"?this.handleSessionChanged(t):(s==="exec.approval"||s==="exec.request"||s==="tool.approval")&&this.handleExecApprovalEvent(t)}handleAgentEvent(e){const s=e.stream,t=e.data,n=e.sessionKey??"";if(n&&this.seenSessions.add(n),s==="tool"){const o=t?.name??t?.toolName??e.toolName??"unknown",i=t?.phase??"",r=t?.args??e.args??{};if(i==="start"){const{category:d,risk:h}=b(o,r),k=w(o,r);p({action:`OpenClaw ${y(o)}: ${k}`.slice(0,500),category:d,risk_level:h,details:JSON.stringify({tool:o,session:n,...r}).slice(0,500),agent_name:"OpenClaw"}),l("OpenClaw agent tool event",{tool:o,category:d,risk:h})}}if(s==="lifecycle"&&t){const o=t.phase??"";(o==="start"||o==="end")&&l("OpenClaw agent lifecycle",{phase:o,session:n})}}handleToolEvent(e){const s=e.data,t=s?.name??s?.toolName??e.toolName??"unknown",n=s?.phase??"",o=s?.args??e.args??{},i=e.sessionKey??"";if(n!=="start"&&n!=="end"||n==="end")return;const{category:r,risk:d}=b(t,o),h=w(t,o);p({action:`OpenClaw ${y(t)}: ${h}`.slice(0,500),category:r,risk_level:d,details:JSON.stringify({tool:t,session:i,...o}).slice(0,500),agent_name:"OpenClaw"}),l("OpenClaw tool event",{tool:t,category:r,risk:d,session:i}),i&&(this.seenSessions.add(i),this.lastActiveSession=i)}handleExecApprovalEvent(e){const s=e.command??e.cmd??"",t=e.sessionKey??"",n=e.agentId??"";if(!s)return;const o=s.toLowerCase();let i="medium",r="exec_command";/\brm\s+-rf?\b|\bdrop\b|\bdelete\b|\btruncate\b/.test(o)?(i="critical",r="file_delete"):/\brm\b|\bgit\s+push\b|\bgit\s+reset\b|\bdeploy\b|\bkill\b/.test(o)?(i="high",r="deploy"):/\binstall\b|\bpip\b|\bnpm\b|\bcurl\b|\bwget\b/.test(o)&&(i="medium",r="package_install"),p({action:`[approval requested] exec: ${s}`.slice(0,500),category:r,risk_level:i,details:JSON.stringify({command:s,agent:n,session:t,source:"exec.approval"}).slice(0,500),agent_name:"OpenClaw"}),this.opts.rpcCall("tools/call",{name:"aerostack__guardian_report",arguments:{action:`OpenClaw exec approval: ${s}`.slice(0,500),category:r,risk_level:i,details:JSON.stringify({command:s,agent:n,session:t}).slice(0,500)}}).catch(()=>{}),u("OpenClaw exec approval event",{command:s.slice(0,100),risk:i})}handleMessageEvent(e){const s=e.sessionKey??"";s&&(this.seenSessions.add(s),this.lastActiveSession=s)}handleSessionChanged(e){const s=e.sessionKey??"";s&&(this.seenSessions.add(s),this.subscribeToSessionMessages(s))}send(e){if(this.ws)try{this.ws.send(JSON.stringify(e))}catch{}}scheduleReconnect(){this.destroyed||this.reconnectTimer||(l("OpenClaw reconnecting in",{ms:this.reconnectMs}),this.reconnectTimer=setTimeout(async()=>{this.reconnectTimer=null,this.connected=!1,this.seenSessions.clear(),this.subscribedSessions.clear(),this.pendingRequests.clear(),await this.connect()},this.reconnectMs),this.reconnectMs=Math.min(this.reconnectMs*2,v))}async getWebSocket(){return typeof globalThis.WebSocket<"u"?globalThis.WebSocket:(await import("ws")).default}}export{E as OpenClawConnector,N as resolveExecApprovalToken,R as resolveOpenClawToken};
1
+ import{readFile as m}from"node:fs/promises";import{join as f}from"node:path";import{homedir as b}from"node:os";import{info as p,warn as c,debug as l}from"./logger.js";import{addToBatch as u,detectCategory as w,summarizeToolInput as y}from"./hook-server.js";function S(a){return a.replace(/^(?:\w+__)*aerostack__/,"").replace(/__/g,":")||a}async function R(){try{const a=f(b(),".openclaw","openclaw.json"),e=await m(a,"utf-8");return JSON.parse(e)?.gateway?.auth?.token??null}catch{return null}}async function E(){try{const a=f(b(),".openclaw","exec-approvals.json"),e=await m(a,"utf-8");return JSON.parse(e)?.socket?.token??null}catch{return null}}const k=1e3,T=3e4;class A{opts;ws=null;destroyed=!1;reconnectMs=k;reconnectTimer=null;requestId=0;seenSessions=new Set;pendingRequests=new Map;lastActiveSession=null;constructor(e){this.opts=e}async connect(){if(this.destroyed)return!1;const e=await this.getWebSocket(),s=`ws://127.0.0.1:${this.opts.port}`;return new Promise(t=>{try{const n=new e(s);this.ws=n;const o=setTimeout(()=>{l("OpenClaw connect timeout");try{n.close()}catch{}t(!1)},1e4);n.onopen=()=>{clearTimeout(o),l("OpenClaw WS connected, sending handshake"),this.sendHandshake()},n.onmessage=i=>{try{const r=JSON.parse(String(i.data));this.handleFrame(r,t)}catch{}},n.onerror=()=>{clearTimeout(o),t(!1)},n.onclose=()=>{clearTimeout(o),this.ws=null,this.destroyed||this.scheduleReconnect()}}catch{t(!1)}})}getLastActiveSession(){return this.lastActiveSession}async sendToSession(e,s){if(!this.ws||!this.connected)return!1;const t=await this.sendRequest("sessions.send",{key:e,message:s,idempotencyKey:`aerostack-${Date.now()}`});return t.ok||c("sendToSession failed",{key:e,error:t.error?.message}),t.ok??!1}stop(){if(this.destroyed=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws){try{this.ws.close(1e3)}catch{}this.ws=null}this.pendingRequests.clear()}sendHandshake(){this.send({type:"req",id:String(++this.requestId),method:"connect",params:{minProtocol:3,maxProtocol:3,client:{id:"openclaw-tui",displayName:"Aerostack Guardian",version:"0.15.8",platform:process.platform,mode:"cli"},auth:{token:this.opts.token},scopes:["operator.read","operator.write"],caps:["tool-events"]}})}connected=!1;subscribedSessions=new Set;handleFrame(e,s){if(e.type==="res"&&!this.connected){e.ok?(this.connected=!0,this.reconnectMs=k,p("OpenClaw connector connected",{port:this.opts.port}),s?.(!0),this.subscribeAllSessions().catch(t=>c("subscribeAllSessions failed",{error:t?.message}))):(c("OpenClaw connect rejected",{error:e.error?.message}),s?.(!1));return}if(e.type==="res"&&e.id&&this.pendingRequests.has(e.id)){const t=this.pendingRequests.get(e.id);this.pendingRequests.delete(e.id),t(e);return}if(e.type==="res"&&e.ok===!1&&e.error){c("OpenClaw RPC error",{error:e.error.message,code:e.error.code});return}e.type==="event"&&this.handleEvent(e)}subscribeToSessionMessages(e){if(this.subscribedSessions.has(e))return;this.subscribedSessions.add(e);const s=String(++this.requestId);this.pendingRequests.set(s,t=>{t.ok?l("OpenClaw subscribed to session messages",{key:e}):c("OpenClaw messages.subscribe failed",{key:e,error:t.error?.message})}),this.send({type:"req",id:s,method:"sessions.messages.subscribe",params:{key:e}}),setTimeout(()=>this.pendingRequests.delete(s),1e4)}async subscribeAllSessions(){const e=await this.sendRequest("sessions.subscribe");e.ok?p("OpenClaw subscribed to all session events (tool + lifecycle)"):c("OpenClaw sessions.subscribe failed",{error:e.error?.message});const s=await this.sendRequest("sessions.list",{limit:50});if(!s.ok){c("OpenClaw sessions.list failed",{error:s.error?.message});return}const t=s.payload?.sessions,n=Array.isArray(t)?t:[];p("OpenClaw active sessions",{count:n.length});for(const o of n)o.key&&this.subscribeToSessionMessages(o.key)}sendRequest(e,s){return new Promise(t=>{const n=String(++this.requestId),o=setTimeout(()=>{this.pendingRequests.delete(n),t({type:"res",id:n,ok:!1,error:{code:"TIMEOUT",message:"request timeout"}})},1e4);this.pendingRequests.set(n,i=>{clearTimeout(o),t(i)}),this.send({type:"req",id:n,method:e,params:s})})}handleEvent(e){const s=e.event,t=e.payload??{};s==="agent"?this.handleAgentEvent(t):s==="session.tool"?this.handleToolEvent(t):s==="session.message"?this.handleMessageEvent(t):s==="sessions.changed"?this.handleSessionChanged(t):(s==="exec.approval"||s==="exec.request"||s==="tool.approval")&&this.handleExecApprovalEvent(t)}handleAgentEvent(e){const s=e.stream,t=e.data,n=e.sessionKey??"";if(n&&this.seenSessions.add(n),s==="tool"){const o=t?.name??t?.toolName??e.toolName??"unknown",i=t?.phase??"",r=t?.args??e.args??{};if(i==="start"){const{category:d,risk:h}=w(o,r),g=y(o,r);u({action:`OpenClaw ${S(o)}: ${g}`.slice(0,500),category:d,risk_level:h,details:JSON.stringify({tool:o,session:n,...r}).slice(0,500),agent_name:"OpenClaw"}),l("OpenClaw agent tool event",{tool:o,category:d,risk:h})}}if(s==="lifecycle"&&t){const o=t.phase??"";(o==="start"||o==="end")&&l("OpenClaw agent lifecycle",{phase:o,session:n})}}handleToolEvent(e){const s=e.data,t=s?.name??s?.toolName??e.toolName??"unknown",n=s?.phase??"",o=s?.args??e.args??{},i=e.sessionKey??"";if(n!=="start"&&n!=="end")return;const{category:r,risk:d}=w(t,o),h=y(t,o);if(n==="start"&&u({action:`OpenClaw ${S(t)}: ${h}`.slice(0,500),category:r,risk_level:d,details:JSON.stringify({tool:t,session:i,...o}).slice(0,500),agent_name:"OpenClaw"}),l("OpenClaw tool event",{tool:t,phase:n,category:r,risk:d,session:i}),!new Set(["aerostack__guardian_report","aerostack__chat_check","aerostack__chat_reply","aerostack__check_approval","aerostack__local_guardian","aerostack__guardian_check"]).has(t)){const _=s?.error??e.error??void 0;this.opts.onToolEvent?.({toolName:t,phase:n,category:r,summary:h,error:_})}i&&(this.seenSessions.add(i),this.lastActiveSession=i)}handleExecApprovalEvent(e){const s=e.command??e.cmd??"",t=e.sessionKey??"",n=e.agentId??"";if(!s)return;const o=s.toLowerCase();let i="medium",r="exec_command";/\brm\s+-rf?\b|\bdrop\b|\bdelete\b|\btruncate\b/.test(o)?(i="critical",r="file_delete"):/\brm\b|\bgit\s+push\b|\bgit\s+reset\b|\bdeploy\b|\bkill\b/.test(o)?(i="high",r="deploy"):/\binstall\b|\bpip\b|\bnpm\b|\bcurl\b|\bwget\b/.test(o)&&(i="medium",r="package_install"),u({action:`[approval requested] exec: ${s}`.slice(0,500),category:r,risk_level:i,details:JSON.stringify({command:s,agent:n,session:t,source:"exec.approval"}).slice(0,500),agent_name:"OpenClaw"}),this.opts.rpcCall("tools/call",{name:"aerostack__guardian_report",arguments:{action:`OpenClaw exec approval: ${s}`.slice(0,500),category:r,risk_level:i,details:JSON.stringify({command:s,agent:n,session:t}).slice(0,500)}}).catch(()=>{}),p("OpenClaw exec approval event",{command:s.slice(0,100),risk:i})}handleMessageEvent(e){const s=e.sessionKey??"";s&&(this.seenSessions.add(s),this.lastActiveSession=s)}handleSessionChanged(e){const s=e.sessionKey??"";s&&(this.seenSessions.add(s),this.subscribeToSessionMessages(s))}send(e){if(this.ws)try{this.ws.send(JSON.stringify(e))}catch{}}scheduleReconnect(){this.destroyed||this.reconnectTimer||(l("OpenClaw reconnecting in",{ms:this.reconnectMs}),this.reconnectTimer=setTimeout(async()=>{this.reconnectTimer=null,this.connected=!1,this.seenSessions.clear(),this.subscribedSessions.clear(),this.pendingRequests.clear(),await this.connect()},this.reconnectMs),this.reconnectMs=Math.min(this.reconnectMs*2,T))}async getWebSocket(){return typeof globalThis.WebSocket<"u"?globalThis.WebSocket:(await import("ws")).default}}export{A as OpenClawConnector,E as resolveExecApprovalToken,R as resolveOpenClawToken};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aerostack/gateway",
3
- "version": "0.15.25",
3
+ "version": "0.15.26",
4
4
  "description": "stdio-to-HTTP bridge connecting any MCP client to Aerostack Workspaces",
5
5
  "author": "Aerostack",
6
6
  "license": "MIT",