@aerostack/gateway 0.15.26 → 0.15.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +20 -18
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,23 +1,23 @@
1
1
  #!/usr/bin/env node
2
2
 
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
3
+ import{Server as me}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as he}from"@modelcontextprotocol/sdk/server/stdio.js";import{ListToolsRequestSchema as fe,CallToolRequestSchema as ge,ListResourcesRequestSchema as ye,ReadResourceRequestSchema as _e,ListPromptsRequestSchema as we,GetPromptRequestSchema as Ae}from"@modelcontextprotocol/sdk/types.js";import{readFile as Ee,writeFile as Te}from"node:fs/promises";import{join as Se}from"node:path";import{homedir as ke}from"node:os";import{resolveApproval as J}from"./resolution.js";import{startHookServer as Re,installClaudeHook as Oe,stopHookServer as Ce}from"./hook-server.js";import{OpenClawConnector as ve,resolveOpenClawToken as $e}from"./openclaw-connector.js";import{info as u,warn as h,error as be}from"./logger.js";const se=Se(ke(),".openclaw","pre-authorized.json");async function Ne(e){try{let s={};try{s=JSON.parse(await Ee(se,"utf-8"))}catch{}s[e]=Date.now(),await Te(se,JSON.stringify(s))}catch{}}const Y=process.env.AEROSTACK_WORKSPACE_URL,l=process.env.AEROSTACK_TOKEN;function L(e,s,o){const t=parseInt(e??String(s),10);return Number.isFinite(t)&&t>=o?t:s}const X=L(process.env.AEROSTACK_APPROVAL_POLL_MS,3e3,500),Q=L(process.env.AEROSTACK_APPROVAL_TIMEOUT_MS,864e5,5e3),oe=L(process.env.AEROSTACK_REQUEST_TIMEOUT_MS,3e4,1e3),Pe=process.env.AEROSTACK_HOOK_SERVER!=="false",xe=L(process.env.AEROSTACK_HOOK_PORT,18321,1024),Ie=process.env.AEROSTACK_HOOK_AUTO_INSTALL!=="false",Ue=process.env.AEROSTACK_OPENCLAW_ENABLED!=="false",ne=L(process.env.AEROSTACK_OPENCLAW_PORT,18789,1024),Le=process.env.AEROSTACK_OPENCLAW_TOKEN;Y||(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 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(`
5
+ `),process.exit(1));let D;try{if(D=new URL(Y),D.protocol!=="https:"&&D.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)}D.protocol==="http:"&&!D.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=Y.replace(/\/+$/,""),re=crypto.randomUUID();function De(){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 ae=De();let C=null,v=Date.now();const je=3e4;async function E(e,s){const o={jsonrpc:"2.0",id:Date.now(),method:e,params:s??{}},t=new AbortController,r=setTimeout(()=>t.abort(),oe);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":re,"X-Agent-Type":ae},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 Ke(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 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 He=new Set(["aerostack__guardian_report","aerostack__check_approval","aerostack__guardian_check"]);function Me(e,s){if(He.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)"}E("tools/call",{name:"aerostack__guardian_report",arguments:{action:`${e}(${Object.keys(s).join(", ")})`,category:o,risk_level:"low",details:r}}).catch(()=>{})}const We=new Set(["aerostack__check_approval"]),ie=[{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"]}}],ze=new Set(ie.map(e=>e.name));function T(e){return e.replace(/[\r\n]+/g," ").replace(/\[/g,"(").replace(/\]/g,")").replace(/---/g,"\u2014")}const j=[],qe=100,k=new Map,ce=50,Be=100,le=10;let P=null;const ue=new Set,z=new Map;let x=null;function K(e,s,o){let t=k.get(e);if(!t){if(k.size>=Be){const r=k.keys().next().value;r&&k.delete(r)}t=[],k.set(e,t)}t.push({role:s,content:o,ts:Date.now()}),t.length>ce&&t.splice(0,t.length-ce)}async function Fe(e){if(!ue.has(e))try{const s=await S(`${d}/chat/history?limit=${le}`,{headers:{Authorization:`Bearer ${l}`}});if(!s.ok)return;const o=await s.json();o.session_id&&(P=o.session_id);for(const t of o.messages??[]){const r=t.sender_type==="agent"?"agent":"user",n=o.session_id||e;let a=k.get(n);a||(a=[],k.set(n,a)),a.push({role:r,content:t.content,ts:t.created_at})}ue.add(e),u("Thread history seeded from D1",{sessionId:o.session_id,count:o.messages?.length??0})}catch{}}function Z(e){const s=k.get(e);return!s||s.length===0?"":`Previous conversation:
9
+ ${s.slice(-le).map(r=>`[${r.role==="user"?"Admin":"You (Agent)"}] ${r.content}`).join(`
10
10
  `)}
11
11
 
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(`
12
+ `}async function S(e,s){const o=new AbortController,t=setTimeout(()=>o.abort(),oe);try{return await fetch(e,{...s,signal:o.signal})}finally{clearTimeout(t)}}async function Ge(){const e=P||"_default";if(await Fe(e),j.length>0){const s=j.splice(0);v=Date.now();const o=Z(e),t=s.map(r=>`${T(r.sender_name)}: ${T(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 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(`
16
+ ${t}`}]}try{const o=await S(`${d}/chat/pending?since=${v}`,{headers:{Authorization:`Bearer ${l}`}});if(!o.ok)return[{type:"text",text:"No new messages."}];const r=(await o.json()).messages??[];if(v=Date.now(),r.length===0)return[{type:"text",text:"No new messages from the workspace owner."}];for(const i of r)K(e,"user",i.content);const n=Z(e),a=r.map(i=>`${T(i.sender_name)}: ${T(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 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(`
20
+ ${a}`}]}catch{return[{type:"text",text:"Failed to check messages."}]}}async function Ve(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:P})});return o.ok?(K(P||"_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 Je(e,s){Me(e,s);const o=await E("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 J({approvalId:a,wsUrl:n?.ws_url,pollUrl:n?.polling_url??`${d}/approval-status/${a}`,pollIntervalMs:X,timeoutMs:Q,token:l});u("Tool gate resolved",{tool:e,status:i.status}),H({approvalId:a,toolName:e,toolArgs:s,sessionKey:null,gate:"tool_gate",pollUrl:"",authToken:l},i.status,!0);const p=ee({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 J({approvalId:n,wsUrl:r.ws_url,pollUrl:r.polling_url??`${d}/approval-status/${n}`,pollIntervalMs:X,timeoutMs:Q,token:l});u("Permission gate resolved",{tool:e,status:a.status}),H({approvalId:n,toolName:e,toolArgs:s,sessionKey:null,gate:"permission_gate",pollUrl:"",authToken:l},a.status,!0);const i=ee({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 ft(e){J({approvalId:e.approvalId,wsUrl:e.wsUrl,pollUrl:e.pollUrl,pollIntervalMs:X,timeoutMs:Q,token:e.authToken}).then(async s=>{u("Approval resolved",{tool:e.toolName,status:s.status,session:e.sessionKey});const o=ee(e,s),t=e.sessionKey??C?.getLastActiveSession()??null;if((s.status==="approved"||s.status==="executed")&&t&&Ne(t).catch(()=>{}),t&&C){if(await C.sendToSession(t,o)){u("Agent resumed via sessions.send",{session:t,status:s.status}),H(e,s.status,!0);return}h("sessions.send failed, falling back to channel notification",{session:t})}try{await R.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}),H(e,s.status,!0)}catch(r){h("Channel notification failed",{error:r instanceof Error?r.message:String(r)}),H(e,s.status,!1)}}).catch(s=>{h("Background approval resolver error",{error:s instanceof Error?s.message:String(s)})})}function H(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`,E("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 ee(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(`
@@ -50,12 +50,12 @@ 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(),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}
53
+ `.trim(),Ye=["delete","remove","drop","truncate","destroy","wipe","reset","deploy","publish","release","push","exec","shell","bash","run","command","terminal","install","uninstall","send","email","notify","webhook"];function Xe(e,s){const o=e.toLowerCase(),t=Ye.some(n=>o.includes(n)),r=s??"";return t?`[REQUIRES GUARDIAN APPROVAL] ${r}`.trim():r}let de=null;async function I(){if(de)return;const e=await E("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"aerostack-gateway",version:"0.15.14"}});if(e.result){const s=e.result,o=s.instructions??"";de={protocolVersion:s.protocolVersion??"2024-11-05",instructions:o?`${o}
54
54
 
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(`
55
+ ${q}`:q}}}const R=new me({name:"aerostack-gateway",version:"0.15.14"},{capabilities:{tools:{},resources:{},prompts:{},experimental:{"claude/channel":{}}},instructions:q});R.setRequestHandler(fe,async()=>{await I();const e=await E("tools/list");if(e.error)throw new Error(e.error.message);const o=(e.result.tools??[]).filter(t=>!We.has(t.name)).map(t=>({...t,description:Xe(t.name,t.description)}));return o.push(...ie),{tools:o}}),R.setRequestHandler(ge,async e=>{await I();const{name:s,arguments:o}=e.params;if(ze.has(s))return{content:(s==="aerostack__chat_check"?await Ge():await Ve(o??{})).map(i=>({...i,type:"text"}))};const t=await Je(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()-v>je)try{const i=await S(`${d}/chat/pending?since=${v}`,{headers:{Authorization:`Bearer ${l}`}});if(i.ok){const w=(await i.json()).messages??[];if(v=Date.now(),w.length>0){const A=w.map(y=>`${T(y.sender_name)}: ${T(y.content)}`).join(`
56
56
  `);n.unshift({type:"text",text:`--- WORKSPACE OWNER MESSAGE ---
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+`
57
+ ${A}
58
+ --- END MESSAGE \u2014 please acknowledge ---`})}}}catch{}return{content:n}});const Qe={uri:"aerostack://guardian/policy",name:"Aerostack Guardian Policy",description:"Mandatory workspace monitoring policy. Read this to understand required approval workflows.",mimeType:"text/plain"};R.setRequestHandler(ye,async()=>{await I();const e=await E("resources/list");if(e.error)throw new Error(e.error.message);const s=e.result;return{resources:[Qe,...s.resources??[]]}}),R.setRequestHandler(_e,async e=>{if(await I(),e.params.uri==="aerostack://guardian/policy")return{contents:[{uri:e.params.uri,text:q,mimeType:"text/plain"}]};const s=await E("resources/read",{uri:e.params.uri});if(s.error)throw new Error(s.error.message);return{contents:s.result.contents??[]}}),R.setRequestHandler(we,async()=>{await I();const e=await E("prompts/list");if(e.error)throw new Error(e.error.message);return{prompts:e.result.prompts??[]}}),R.setRequestHandler(Ae,async e=>{await I();const s=await E("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 Ze(){const e=s=>process.stderr.write(s+`
59
59
  `);e(`
60
60
  Aerostack Connection Check
61
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(`
@@ -69,11 +69,13 @@ ${T}
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 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?`
72
+ `)),process.exit(1)}}async function et(){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 tt(){u("Connecting to workspace",{url:d});const e=new he;await R.connect(e),u("Ready",{url:d}),et().catch(()=>{});const s=()=>{S(`${d}/chat/heartbeat`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},body:JSON.stringify({agent_type:ae,user_agent:"aerostack-gateway/0.15.14",bridge_id:re})}).catch(()=>{})};s();const o=setInterval(s,12e4);if(process.on("exit",()=>clearInterval(o)),Pe)try{const r=await Re(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}},xe);Ie&&await Oe(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(Ue)try{const t=Le??await $e();t?(C=new ve({port:ne,token:t,rpcCall:E,onToolEvent:n=>{const a=x;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(w=>w.name===n.toolName&&w.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 C.connect()?u("OpenClaw connector started",{port:ne}):(u("OpenClaw gateway not reachable, skipping connector"),C=null)):u("OpenClaw integration skipped (no token found)")}catch(t){h("OpenClaw connector failed (non-fatal)",{error:t instanceof Error?t.message:String(t)})}st()}let M=null;function st(){M&&M.abort(),M=new AbortController;const e=async()=>{try{const t=await fetch(d,{method:"GET",headers:{Authorization:`Bearer ${l}`,Accept:"text/event-stream"},signal:M.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 w=a.split(`
73
+ `);a=w.pop()??"";let A="",y="";for(const _ of w)_.startsWith("event: ")?A=_.slice(7).trim():_.startsWith("data: ")?y=_.slice(6):_===""&&A&&y&&(A==="aerostack_event"&&ot(y),A="",y="")}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 ot(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 U=Math.round(f.size/1024),B=U>=1024?`${(U/1024).toFixed(1)} MB`:`${U} KB`,F=T((f.filename||"file").slice(0,200)),G=T((f.mime_type||"application/octet-stream").slice(0,100)),V=a?`${d}/chat/media/${a}/${encodeURIComponent(f.filename)}`:"(unavailable)";return`[Attached: ${F} (${G}, ${B}) \u2014 ${V}]`}),p=i.length>0?`
74
74
  `+i.join(`
75
- `):"",y=t?s.content+(p?`
75
+ `):"",w=t?s.content+(p?`
76
76
  `+i.map(f=>f).join(`
77
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)});
78
+ `);n&&(P=n,K(n,"user",w)),j.length>=qe&&j.shift(),j.push({sender_name:s.sender_name??"Admin",content:t?s.content:i.join(", "),created_at:Date.now(),session_id:n}),v=Date.now();const A=T(s.sender_name??"Admin"),y=t?T(s.content):"",_=n||P||"_default",te=`aerostack-chat-${/^[a-zA-Z0-9_-]{1,64}$/.test(_)?_:"_default"}`,$=`turn-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,b=[];z.set($,b),x=$;try{const{execFile:f}=await import("child_process");u("Spawning full agent turn for chat",{sender:A,session:te});const U=y?y+p:p.trim(),B=Z(_),F=`You are chatting with ${A} via the Aerostack admin dashboard. Address them by name and be helpful.
79
+
80
+ `,G=`${B}${F}[${A}]: ${U}`;f("openclaw",["agent","--agent","main","--json","--session-id",te,"-m",G],{timeout:12e4},async(V,W)=>{let N=[];if(!V&&W)try{const c=JSON.parse(W.trim()),g=c?.result?.payloads;Array.isArray(g)&&g.length>0?N=g:(c.text||c.reply||c.message)&&(N=[{text:c.text||c.reply||c.message}])}catch{const c=W.trim().split(`
81
+ `).pop()||W.trim();c&&(N=[{text:c}])}N.length===0&&(N=[{text:`Message received. I'll process "${y.slice(0,100)}" shortly.`}]),await new Promise(c=>setTimeout(c,500));for(const c of b)c.status==="running"&&(c.status="timeout",c.ended_at=Date.now(),c.duration_ms=c.ended_at-c.started_at);if(b.length>0){const c=b.reduce((m,O)=>m+(O.duration_ms||0),0),g=b.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:b.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($),x===$&&(x=null);for(const c of N){const g=c.text?.trim()||"";if(c.mediaUrl){let m=!1;try{m=new URL(c.mediaUrl).protocol==="https:"}catch{}if(m)try{const O=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})});O.ok?u("Chat media sent to workspace",{mediaUrl:c.mediaUrl}):h("Chat media upload failed",{status:O.status})}catch(O){h("Failed to send chat media",{error:O?.message})}else h("Skipping invalid media URL",{mediaUrl:c.mediaUrl});K(_,"agent",g||`[media: ${c.mediaUrl}]`)}else if(g&&g.length>=2){K(_,"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($),x===$&&(x=null)}}catch{}}function pe(){M?.abort(),C?.stop(),Ce(),process.exit(0)}process.on("SIGTERM",()=>{pe()}),process.on("SIGINT",()=>{pe()}),process.argv.includes("--check")?Ze():tt().catch(e=>{be("Fatal error",{error:e instanceof Error?e.message:String(e)}),process.exit(1)});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aerostack/gateway",
3
- "version": "0.15.26",
3
+ "version": "0.15.27",
4
4
  "description": "stdio-to-HTTP bridge connecting any MCP client to Aerostack Workspaces",
5
5
  "author": "Aerostack",
6
6
  "license": "MIT",