@aerostack/gateway 0.15.7 → 0.15.9
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.
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import{join as p}from"node:path";import{homedir as f}from"node:os";import{readFile as u}from"node:fs/promises";import{info as i,warn as l,error as S}from"./logger.js";import{startExecApprovalServer as x}from"./exec-approval-server.js";const d=process.env.AEROSTACK_WORKSPACE_URL,v=process.env.AEROSTACK_TOKEN;(!d||!v)&&(process.stderr.write(`ERROR: AEROSTACK_WORKSPACE_URL and AEROSTACK_TOKEN are required
|
|
4
|
+
`),process.exit(1));const m=d.replace(/\/+$/,"");async function O(t,a){const n={jsonrpc:"2.0",id:Date.now(),method:t,params:a??{}};try{const e=await fetch(m,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${v}`,"User-Agent":"aerostack-exec-daemon/0.15.8","X-Agent-Id":"aerostack-exec-daemon"},body:JSON.stringify(n),signal:AbortSignal.timeout(15e3)});if((e.headers.get("content-type")??"").includes("text/event-stream")){const o=(await e.text()).split(`
|
|
5
|
+
`).reverse().find(s=>s.startsWith("data: "));return o?JSON.parse(o.slice(6)):null}return await e.json()}catch(e){return l("rpcCall failed",{method:t,error:e instanceof Error?e.message:String(e)}),null}}async function g(){i("Aerostack exec approval daemon starting",{workspace:m});const t=p(f(),".openclaw","exec-approvals.json");let a={};try{a=JSON.parse(await u(t,"utf-8"))}catch{l("exec-approvals.json not found, will retry on interval",{path:t})}const n=async()=>{try{const w=await u(t,"utf-8");a=JSON.parse(w)}catch{return null}const o=a?.socket?.path??p(f(),".openclaw","exec-approvals.sock"),s=a?.socket?.token;return s?(i("Starting exec approval socket server",{path:o}),x({socketPath:o,token:s,rpcCall:O})):(l("No socket token in exec-approvals.json, waiting for OpenClaw to write it"),null)};let e=await n(),r=null;e||(r=setInterval(async()=>{e=await n(),e&&r&&(clearInterval(r),r=null)},3e4)),i("Exec approval daemon ready \u2014 waiting for OpenClaw approval requests");const c=()=>{r&&(clearInterval(r),r=null),e?.stop(),process.exit(0)};process.on("SIGTERM",c),process.on("SIGINT",c)}g().catch(t=>{S("Fatal",{error:t instanceof Error?t.message:String(t)}),process.exit(1)});
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createServer as
|
|
2
|
-
`);if(i===-1)return;const c=a.slice(0,i).trim();a=a.slice(i+1),clearTimeout(n);try{const s=JSON.parse(c)
|
|
3
|
-
`),e.end()}catch{}}export{
|
|
1
|
+
import{createServer as h}from"node:net";import{unlink as m,mkdir as y}from"node:fs/promises";import{timingSafeEqual as v}from"node:crypto";import{dirname as E}from"node:path";import{info as f,warn as d,debug as b,error as g}from"./logger.js";import{addToBatch as w}from"./hook-server.js";function x(e){const t=e.toLowerCase();return/\brm\s+-rf?\b|\bdrop\s|\bdelete\s|\btruncate\s|\bformat\b/.test(t)?"critical":/\brm\b|\bgit\s+push\b|\bgit\s+reset\b|\bdeploy\b|\bkill\b/.test(t)?"high":/\binstall\b|\bpip\b|\bnpm\b|\bcurl\b|\bwget\b/.test(t)?"medium":"low"}function k(e){const t=e.toLowerCase();return/\brm\b|\bunlink\b|\brmdir\b/.test(t)?"file_delete":/\bgit\s+push\b|\bdeploy\b|\bwrangler\b/.test(t)?"deploy":/\binstall\b|\bpip\b|\bnpm\b|\byarn\b/.test(t)?"package_install":/\bcurl\b|\bwget\b|\bfetch\b/.test(t)?"api_call":/\bwrite\b|\btee\b|\b>\b|\bcat\s.*>/.test(t)?"file_write":"exec_command"}function q(e){let t=null,a=!1;return(async()=>{await y(E(e.socketPath),{recursive:!0}).catch(()=>{}),await m(e.socketPath).catch(()=>{}),t=h(r=>{_(r,e)}),t.on("error",r=>{r.code==="EADDRINUSE"?d("Exec approval socket in use, skipping",{path:e.socketPath}):g("Exec approval server error",{error:r.message})}),t.listen(e.socketPath,()=>{f("Exec approval server started",{path:e.socketPath})})})().catch(r=>{d("Exec approval server failed to start",{error:r instanceof Error?r.message:String(r)})}),{stop:()=>{a||(a=!0,t&&(t.close(),t=null),m(e.socketPath).catch(()=>{}))}}}function _(e,t){let a="";const n=setTimeout(()=>{b("Exec approval timeout, denying"),o(e,"deny")},14e3);e.on("data",r=>{a+=r.toString("utf-8");const i=a.indexOf(`
|
|
2
|
+
`);if(i===-1)return;const c=a.slice(0,i).trim();a=a.slice(i+1),clearTimeout(n);try{const s=JSON.parse(c),u=Buffer.from(s.token??""),p=Buffer.from(t.token);if(u.length!==p.length||!v(u,p)){b("Exec approval token mismatch"),o(e,"deny");return}S(s,e,t).catch(l=>{g("Exec approval processing error",{error:l instanceof Error?l.message:String(l)}),o(e,"deny")})}catch{o(e,"deny")}}),e.on("error",()=>{clearTimeout(n)})}async function S(e,t,a){const n=e.request.command??e.request.args?.join(" ")??"unknown",r=x(n),i=k(n),c=e.request.sessionKey??"",s=e.request.agentId??"";w({action:`[exec-approval] ${n}`.slice(0,500),category:i,risk_level:r,details:JSON.stringify({command:n,host:e.request.host,agent:s,session:c,security:e.request.security}).slice(0,500),agent_name:"OpenClaw"}),a.rpcCall("tools/call",{name:"aerostack__guardian_report",arguments:{action:`OpenClaw exec: ${n}`.slice(0,500),category:i,risk_level:r,details:JSON.stringify({command:n,agent:s,session:c}).slice(0,500)}}).catch(()=>{}),r==="critical"||r==="high"?(f("Exec approval DENIED (high risk)",{command:n.slice(0,100),risk:r}),a.rpcCall("tools/call",{name:"aerostack__local_guardian",arguments:{action:n.slice(0,500),category:i,risk_level:r,details:`OpenClaw agent ${s} wants to execute: ${n}`}}).catch(()=>{}),o(t,"deny")):(b("Exec approval ALLOWED",{command:n.slice(0,100),risk:r}),o(t,"allow-once"))}function o(e,t){try{e.write(JSON.stringify({type:"decision",decision:t})+`
|
|
3
|
+
`),e.end()}catch{}}export{q as startExecApprovalServer};
|
package/dist/index.js
CHANGED
|
@@ -1,17 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
import{Server as
|
|
4
|
-
`),process.exit(1)),
|
|
5
|
-
`),process.exit(1));let
|
|
6
|
-
`),process.exit(1)}
|
|
7
|
-
`);const p=
|
|
8
|
-
`);let e=null;for(const n of
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
3
|
+
import{Server as S}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as k}from"@modelcontextprotocol/sdk/server/stdio.js";import{ListToolsRequestSchema as P,CallToolRequestSchema as C,ListResourcesRequestSchema as I,ReadResourceRequestSchema as N,ListPromptsRequestSchema as b,GetPromptRequestSchema as L}from"@modelcontextprotocol/sdk/types.js";import{resolveApproval as U}from"./resolution.js";import{startHookServer as K,installClaudeHook as $,stopHookServer as D}from"./hook-server.js";import{OpenClawConnector as x,resolveOpenClawToken as j}from"./openclaw-connector.js";import{info as i,warn as m,error as q}from"./logger.js";const R=process.env.AEROSTACK_WORKSPACE_URL,w=process.env.AEROSTACK_TOKEN;function h(t,s,r){const e=parseInt(t??String(s),10);return Number.isFinite(e)&&e>=r?e:s}const H=h(process.env.AEROSTACK_APPROVAL_POLL_MS,3e3,500),V=h(process.env.AEROSTACK_APPROVAL_TIMEOUT_MS,864e5,5e3),M=h(process.env.AEROSTACK_REQUEST_TIMEOUT_MS,3e4,1e3),G=process.env.AEROSTACK_HOOK_SERVER!=="false",W=h(process.env.AEROSTACK_HOOK_PORT,18321,1024),Y=process.env.AEROSTACK_HOOK_AUTO_INSTALL!=="false",B=process.env.AEROSTACK_OPENCLAW_ENABLED!=="false",_=h(process.env.AEROSTACK_OPENCLAW_PORT,18789,1024),J=process.env.AEROSTACK_OPENCLAW_TOKEN;R||(process.stderr.write(`ERROR: AEROSTACK_WORKSPACE_URL is required
|
|
4
|
+
`),process.exit(1)),w||(process.stderr.write(`ERROR: AEROSTACK_TOKEN is required
|
|
5
|
+
`),process.exit(1));let E;try{if(E=new URL(R),E.protocol!=="https:"&&E.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)}E.protocol==="http:"&&!E.hostname.match(/^(localhost|127\.0\.0\.1)$/)&&process.stderr.write(`WARNING: Using HTTP (not HTTPS) \u2014 token will be sent in plaintext
|
|
7
|
+
`);const p=R.replace(/\/+$/,""),z=crypto.randomUUID(),F=process.env.AEROSTACK_AGENT_TYPE||"unknown";let l=null;async function c(t,s){const r={jsonrpc:"2.0",id:Date.now(),method:t,params:s??{}},e=new AbortController,n=setTimeout(()=>e.abort(),M);try{const o=await fetch(p,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${w}`,"User-Agent":"aerostack-gateway/0.15.8","X-Agent-Id":"aerostack-gateway","X-Bridge-Id":z,"X-Agent-Type":F},body:JSON.stringify(r),signal:e.signal});if(clearTimeout(n),(o.headers.get("content-type")??"").includes("text/event-stream")){const v=await o.text();return Q(v,r.id)}return await o.json()}catch(o){clearTimeout(n);const a=o instanceof Error?o.message:"Unknown error";return o instanceof Error&&o.name==="AbortError"?{jsonrpc:"2.0",id:r.id,error:{code:-32603,message:"Request timed out"}}:{jsonrpc:"2.0",id:r.id,error:{code:-32603,message:`HTTP error: ${a}`}}}}function Q(t,s){const r=t.split(`
|
|
8
|
+
`);let e=null;for(const n of r)if(n.startsWith("data: "))try{e=JSON.parse(n.slice(6))}catch{}return e??{jsonrpc:"2.0",id:s,error:{code:-32603,message:"Empty SSE response"}}}const X=new Set(["aerostack__guardian_report","aerostack__check_approval","aerostack__guardian_check"]);function Z(t,s){if(X.has(t))return;let r="other";const e=t.toLowerCase();e.includes("exec")||e.includes("bash")||e.includes("shell")||e.includes("command")||e.includes("run")?r="exec_command":e.includes("write")||e.includes("edit")||e.includes("create")||e.includes("patch")?r="file_write":e.includes("delete")||e.includes("remove")||e.includes("trash")||e.includes("unlink")?r="file_delete":e.includes("fetch")||e.includes("http")||e.includes("request")||e.includes("api")||e.includes("get")||e.includes("post")?r="api_call":e.includes("install")||e.includes("package")||e.includes("npm")||e.includes("pip")?r="package_install":e.includes("config")||e.includes("setting")||e.includes("env")?r="config_change":e.includes("deploy")||e.includes("publish")||e.includes("release")?r="deploy":e.includes("send")||e.includes("message")||e.includes("email")||e.includes("notify")||e.includes("slack")||e.includes("telegram")?r="message_send":(e.includes("read")||e.includes("query")||e.includes("search")||e.includes("list")||e.includes("get"))&&(r="data_access");let n;try{const o=JSON.stringify(s);n=o.length>500?o.slice(0,500)+"...":o}catch{n="(unable to serialize)"}c("tools/call",{name:"aerostack__guardian_report",arguments:{action:`${t}(${Object.keys(s).join(", ")})`,category:r,risk_level:"low",details:n}}).catch(()=>{})}const ee=new Set(["aerostack__check_approval"]);async function te(t,s){Z(t,s);const r=await c("tools/call",{name:t,arguments:s});if(r.error?.code===-32050){const o=r.error.data,a=o?.approval_id;if(!a||!/^[a-zA-Z0-9_-]{4,128}$/.test(a))return{jsonrpc:"2.0",id:r.id,error:{code:-32603,message:"Approval required but no approval_id returned"}};const A=l?.getLastActiveSession()??null;return i("Tool gate: returning pending, background resolver started",{tool:t,approvalId:a,sessionKey:A}),y({approvalId:a,toolName:t,toolArgs:s,sessionKey:A,gate:"tool_gate",wsUrl:o?.ws_url,pollUrl:o?.polling_url??`${p}/approval-status/${a}`,authToken:w}),{jsonrpc:"2.0",id:r.id,result:{content:[{type:"text",text:`This action requires workspace approval.
|
|
9
|
+
|
|
10
|
+
Tool: ${t}
|
|
11
|
+
Status: Pending review by workspace owner
|
|
12
|
+
|
|
13
|
+
The gateway will resume this task automatically once a decision is made. You may continue with other tasks in the meantime.`}]}}}const n=r.result?._meta;if(n?.approval_id&&n?.status==="pending"){const o=n.approval_id;if(!/^[a-zA-Z0-9_-]{4,128}$/.test(o))return r;const a=l?.getLastActiveSession()??null;return i("Permission gate: returning pending, background resolver started",{tool:t,approvalId:o,sessionKey:a}),y({approvalId:o,toolName:t,toolArgs:s,sessionKey:a,gate:"permission_gate",wsUrl:n.ws_url,pollUrl:n.polling_url??`${p}/approval-status/${o}`,authToken:w}),{jsonrpc:"2.0",id:r.id,result:{content:[{type:"text",text:`Permission request submitted for workspace review.
|
|
14
|
+
|
|
15
|
+
Action: ${t}
|
|
16
|
+
Status: Pending
|
|
17
|
+
|
|
18
|
+
I'll be notified when the workspace owner decides. You may continue with other tasks.`}]}}}return r}function y(t){U({approvalId:t.approvalId,wsUrl:t.wsUrl,pollUrl:t.pollUrl,pollIntervalMs:H,timeoutMs:V,token:t.authToken}).then(async s=>{i("Approval resolved",{tool:t.toolName,status:s.status,session:t.sessionKey});const r=se(t,s);if(t.sessionKey&&l){if(await l.sendToSession(t.sessionKey,r)){i("Agent resumed via sessions.send",{session:t.sessionKey,status:s.status}),g(t,s.status,!0);return}m("sessions.send failed, session may have ended",{session:t.sessionKey}),g(t,s.status,!1)}else m("No session key available for resume",{tool:t.toolName,approvalId:t.approvalId}),g(t,s.status,!1)}).catch(s=>{m("Background approval resolver error",{error:s instanceof Error?s.message:String(s)})})}function g(t,s,r){const e=`${t.toolName}(${Object.keys(t.toolArgs).join(", ")})`,n=r?"resume sent to agent":"session unavailable \u2014 resume not delivered";let o;s==="approved"||s==="executed"?o=r?`[RESUMED] ${e} \u2014 ${n}`:`[RESUME FAILED] ${e} \u2014 ${n}`:s==="rejected"?o=`[REJECTED] ${e} \u2014 rejection sent to agent`:s==="changes_requested"?o=`[CHANGES REQUESTED] ${e} \u2014 feedback sent to agent`:o=`[EXPIRED] ${e} \u2014 approval timed out, expiry sent to agent`,c("tools/call",{name:"aerostack__guardian_report",arguments:{action:o.slice(0,500),category:"approval",risk_level:"low",details:JSON.stringify({tool:t.toolName,approvalId:t.approvalId,status:s,delivered:r,session:t.sessionKey}).slice(0,500)}}).catch(()=>{})}function se(t,s){const r=s.reviewer_note?.trim()||null,e=`${t.toolName}(${Object.keys(t.toolArgs).join(", ")})`;switch(s.status){case"approved":case"executed":return t.gate==="tool_gate"?["[APPROVAL RECEIVED] Your pending action has been approved.","",`Action: ${e}`,r?`Reviewer note: "${r}"`:null,"",`Please now execute this action: call ${t.toolName} with the same parameters as before.`].filter(n=>n!==null).join(`
|
|
19
|
+
`):["[APPROVAL RECEIVED] Your request has been approved by the workspace owner.",r?`Reviewer note: "${r}"`:null,"","You may now proceed with the action you requested approval for."].filter(n=>n!==null).join(`
|
|
20
|
+
`);case"changes_requested":return["[CHANGES REQUESTED] The workspace owner reviewed your action and requested changes.","",`Original action: ${e}`,`Reviewer feedback: "${r??"No details provided"}"`,"","Please revise your approach based on this feedback and try again.","Do NOT proceed with the original plan."].join(`
|
|
21
|
+
`);case"rejected":return["[REJECTED] The workspace owner denied this action.","",`Action: ${e}`,r?`Reason: "${r}"`:"No reason provided.","","Do not retry this action. If you believe this was a mistake, inform the user."].join(`
|
|
22
|
+
`);case"expired":return[`[EXPIRED] The approval request for "${e}" timed out \u2014 no decision was made.`,"","You may resubmit the request if the action is still needed."].join(`
|
|
23
|
+
`);default:return`[APPROVAL UPDATE] Status for "${e}": ${s.status}.`}}const f=`
|
|
15
24
|
=== AEROSTACK GUARDIAN POLICY (MANDATORY) ===
|
|
16
25
|
|
|
17
26
|
You are operating under Aerostack workspace monitoring. These rules apply to ALL actions:
|
|
@@ -32,6 +41,6 @@ the result once the workspace owner approves. Simply wait; do not retry or proce
|
|
|
32
41
|
These rules exist to protect the workspace owner. Violating them may result in your session
|
|
33
42
|
being terminated. Compliance is non-negotiable.
|
|
34
43
|
=== END GUARDIAN POLICY ===
|
|
35
|
-
`.trim(),
|
|
44
|
+
`.trim(),re=["delete","remove","drop","truncate","destroy","wipe","reset","deploy","publish","release","push","exec","shell","bash","run","command","terminal","install","uninstall","send","email","notify","webhook"];function oe(t,s){const r=t.toLowerCase(),e=re.some(o=>r.includes(o)),n=s??"";return e?`[REQUIRES GUARDIAN APPROVAL] ${n}`.trim():n}let O=null;async function d(){if(O)return;const t=await c("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"aerostack-gateway",version:"0.15.8"}});if(t.result){const s=t.result,r=s.instructions??"";O={protocolVersion:s.protocolVersion??"2024-11-05",instructions:r?`${r}
|
|
36
45
|
|
|
37
|
-
${
|
|
46
|
+
${f}`:f}}}const u=new S({name:"aerostack-gateway",version:"0.15.8"},{capabilities:{tools:{},resources:{},prompts:{}},instructions:f});u.setRequestHandler(P,async()=>{await d();const t=await c("tools/list");if(t.error)throw new Error(t.error.message);return{tools:(t.result.tools??[]).filter(e=>!ee.has(e.name)).map(e=>({...e,description:oe(e.name,e.description)}))}}),u.setRequestHandler(C,async t=>{await d();const{name:s,arguments:r}=t.params,e=await te(s,r??{});return e.error?{content:[{type:"text",text:`Error: ${e.error.message}`}],isError:!0}:{content:e.result.content??[{type:"text",text:JSON.stringify(e.result)}]}});const ne={uri:"aerostack://guardian/policy",name:"Aerostack Guardian Policy",description:"Mandatory workspace monitoring policy. Read this to understand required approval workflows.",mimeType:"text/plain"};u.setRequestHandler(I,async()=>{await d();const t=await c("resources/list");if(t.error)throw new Error(t.error.message);const s=t.result;return{resources:[ne,...s.resources??[]]}}),u.setRequestHandler(N,async t=>{if(await d(),t.params.uri==="aerostack://guardian/policy")return{contents:[{uri:t.params.uri,text:f,mimeType:"text/plain"}]};const s=await c("resources/read",{uri:t.params.uri});if(s.error)throw new Error(s.error.message);return{contents:s.result.contents??[]}}),u.setRequestHandler(b,async()=>{await d();const t=await c("prompts/list");if(t.error)throw new Error(t.error.message);return{prompts:t.result.prompts??[]}}),u.setRequestHandler(L,async t=>{await d();const s=await c("prompts/get",{name:t.params.name,arguments:t.params.arguments});if(s.error)throw new Error(s.error.message);return{messages:s.result.messages??[]}});async function ae(){i("Connecting to workspace",{url:p});const t=new k;if(await u.connect(t),i("Ready",{url:p}),G)try{const r=await K(async e=>{try{const n=await fetch(`${p}/guardian-batch`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${w}`,"User-Agent":"aerostack-gateway/0.15.8","X-Agent-Id":"aerostack-gateway"},body:JSON.stringify({events:e})});return n.ok?(await n.json()).config?.hook_tracking??null:null}catch{return null}},W);Y&&await $(r)&&i("Claude Code hook auto-installed",{port:r})}catch(s){m("Hook server failed to start (non-fatal)",{error:s instanceof Error?s.message:String(s)})}if(B)try{const s=J??await j();s?(l=new x({port:_,token:s,rpcCall:c}),await l.connect()?i("OpenClaw connector started",{port:_}):(i("OpenClaw gateway not reachable, skipping connector"),l=null)):i("OpenClaw integration skipped (no token found)")}catch(s){m("OpenClaw connector failed (non-fatal)",{error:s instanceof Error?s.message:String(s)})}}function T(){l?.stop(),D(),process.exit(0)}process.on("SIGTERM",()=>{T()}),process.on("SIGINT",()=>{T()}),ae().catch(t=>{q("Fatal error",{error:t instanceof Error?t.message:String(t)}),process.exit(1)});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFile as m}from"node:fs/promises";import{join as g}from"node:path";import{homedir as
|
|
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 a,debug as c}from"./logger.js";import{addToBatch as p,detectCategory as b,summarizeToolInput as w}from"./hook-server.js";async function _(){try{const d=g(f(),".openclaw","openclaw.json"),e=await m(d,"utf-8");return JSON.parse(e)?.gateway?.auth?.token??null}catch{return null}}async function N(){try{const d=g(f(),".openclaw","exec-approvals.json"),e=await m(d,"utf-8");return JSON.parse(e)?.socket?.token??null}catch{return null}}const y=1e3,k=3e4;class R{opts;ws=null;destroyed=!1;reconnectMs=y;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(()=>{c("OpenClaw connect timeout");try{n.close()}catch{}t(!1)},1e4);n.onopen=()=>{clearTimeout(o),c("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||a("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=y,u("OpenClaw connector connected",{port:this.opts.port}),s?.(!0),this.subscribeAllSessions().catch(t=>a("subscribeAllSessions failed",{error:t?.message}))):(a("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){a("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?c("OpenClaw subscribed to session messages",{key:e}):a("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)"):a("OpenClaw sessions.subscribe failed",{error:e.error?.message});const s=await this.sendRequest("sessions.list",{limit:50});if(!s.ok){a("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:l,risk:h}=b(o,r),S=w(o,r);p({action:`OpenClaw ${o}: ${S}`.slice(0,500),category:l,risk_level:h,details:JSON.stringify({tool:o,session:n,...r}).slice(0,500),agent_name:"OpenClaw"}),c("OpenClaw agent tool event",{tool:o,category:l,risk:h})}}if(s==="lifecycle"&&t){const o=t.phase??"";(o==="start"||o==="end")&&c("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:l}=b(t,o),h=w(t,o);p({action:`OpenClaw ${t}: ${h}`.slice(0,500),category:r,risk_level:l,details:JSON.stringify({tool:t,session:i,...o}).slice(0,500),agent_name:"OpenClaw"}),c("OpenClaw tool event",{tool:t,category:r,risk:l,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||(c("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,k))}async getWebSocket(){return typeof globalThis.WebSocket<"u"?globalThis.WebSocket:(await import("ws")).default}}export{R as OpenClawConnector,N as resolveExecApprovalToken,_ as resolveOpenClawToken};
|
package/dist/resolution.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{info as
|
|
1
|
+
import{info as y,warn as _,debug as h}from"./logger.js";function J(e,o){const{approvalId:n}=e;let a=!1,s=null,r=null,g=null;const v=()=>{if(a=!0,r&&(clearInterval(r),r=null),g&&(clearTimeout(g),g=null),s){try{s.close(1e3)}catch{}s=null}},c=f=>{a||(o.resolve(n,f.status,f.reviewer_note),y("Background resolver: approval resolved",{approvalId:n,status:f.status}),v())};return(async()=>{if(e.wsUrl)try{const d=await O(),l=new d(e.wsUrl);s=l,l.onmessage=S=>{try{const i=typeof S.data=="string"?JSON.parse(S.data):JSON.parse(String(S.data)),p=i?.status;(p==="executed"||p==="approved"||p==="rejected"||p==="expired"||p==="changes_requested")&&c({status:p,reviewer_note:i?.reviewer_note})}catch{}},l.onerror=()=>{h("Background resolver WS error",{approvalId:n})},l.onclose=()=>{s=null},typeof l.on=="function"&&l.on("unexpected-response",async(S,i)=>{try{const p=[];for await(const w of i)p.push(w);const k=Buffer.concat(p).toString(),t=JSON.parse(k);t?.status&&t.status!=="pending"&&c({status:t.status,reviewer_note:t?.reviewer_note})}catch{}})}catch{h("Background resolver WS connect failed, using polling only",{approvalId:n})}r=setInterval(async()=>{if(!a)try{const d=await W(e.pollUrl);d&&c(d)}catch{}},3e4);try{const d=await W(e.pollUrl);if(d){c(d);return}}catch{}const m=e.timeoutMs??2*60*60*1e3;g=setTimeout(()=>{a||(o.resolve(n,"expired"),v())},m)})().catch(()=>{}),{cancel:v}}async function N(e){const{approvalId:o,wsUrl:n,pollUrl:a,pollIntervalMs:s,timeoutMs:r,token:g}=e,v=Date.now()+r;if(n)try{return await L(o,n,a,v,g)}catch(c){const f=c instanceof Error?c.message:"Unknown WS error";_("WebSocket resolution failed, falling back to polling",{approvalId:o,error:f})}return P(o,a,s,v,g)}async function L(e,o,n,a,s){const r=await O();return new Promise((g,v)=>{let c=!1,f=null,m=null;const d=()=>{c=!0,f&&clearInterval(f),m&&clearTimeout(m)},l=t=>{c||(d(),g(t))},S=t=>{c||(d(),v(t))};h("Connecting WebSocket",{approvalId:e,wsUrl:o});const i=new r(o);i.onopen=()=>{y("WebSocket connected, waiting for resolution",{approvalId:e})},i.onmessage=t=>{try{const w=typeof t.data=="string"?JSON.parse(t.data):JSON.parse(String(t.data)),u=w?.status;if(h("WebSocket message received",{approvalId:e,status:u}),u==="executed"||u==="approved"||u==="rejected"||u==="expired"||u==="changes_requested"){y("Approval resolved via WebSocket",{approvalId:e,status:u}),l({status:u,reviewer_note:w?.reviewer_note});try{i.close(1e3)}catch{}}}catch{_("Failed to parse WebSocket message",{approvalId:e})}},i.onerror=t=>{const w=t instanceof Error?t.message:"WebSocket error";h("WebSocket error",{approvalId:e,error:w}),S(new Error(`WebSocket error: ${w}`))},i.onclose=t=>{c||(h("WebSocket closed without resolution",{approvalId:e,code:t.code}),S(new Error(`WebSocket closed unexpectedly (code ${t.code})`)))},typeof i.on=="function"&&i.on("unexpected-response",async(t,w)=>{try{const u=[];for await(const A of w)u.push(A);const T=Buffer.concat(u).toString(),x=JSON.parse(T),b=x?.status;if(b&&b!=="pending"){y("Approval already resolved (WS endpoint returned JSON)",{approvalId:e,status:b}),l({status:b,reviewer_note:x?.reviewer_note});return}}catch{}S(new Error("WebSocket upgrade rejected by server"))}),f=setInterval(async()=>{if(!c)try{const t=await W(n,s);if(t){y("Approval resolved via safety-net poll",{approvalId:e,status:t.status}),l(t);try{i.close(1e3)}catch{}}}catch{}},3e4);const k=a-Date.now();if(k<=0){S(new Error("Approval timeout"));return}m=setTimeout(()=>{if(!c){_("Approval timed out",{approvalId:e}),l({status:"expired"});try{i.close(1e3)}catch{}}},k)})}async function P(e,o,n,a,s){for(y("Polling for approval resolution",{approvalId:e,intervalMs:n});Date.now()<a;){await B(n);try{const r=await W(o,s);if(r)return y("Approval resolved via polling",{approvalId:e,status:r.status}),r}catch{}}return _("Approval polling timed out",{approvalId:e}),{status:"expired"}}async function W(e,o){const n={"User-Agent":"aerostack-gateway/0.15.8"};o&&(n.Authorization=`Bearer ${o}`);const a=await fetch(e,{headers:n});if(!a.ok)return null;const s=await a.json(),r=s.status;return r==="executed"||r==="approved"?{status:r,reviewer_note:s.reviewer_note}:r==="rejected"?{status:"rejected",reviewer_note:s.reviewer_note}:r==="changes_requested"?{status:"changes_requested",reviewer_note:s.reviewer_note}:r==="expired"?{status:"expired"}:null}async function O(){if(typeof globalThis.WebSocket<"u")return globalThis.WebSocket;try{return(await import("ws")).default}catch{throw new Error('WebSocket not available. Install the "ws" package: npm install ws')}}function B(e){return new Promise(o=>setTimeout(o,e))}export{N as resolveApproval,J as startBackgroundResolver};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aerostack/gateway",
|
|
3
|
-
"version": "0.15.
|
|
3
|
+
"version": "0.15.9",
|
|
4
4
|
"description": "stdio-to-HTTP bridge connecting any MCP client to Aerostack Workspaces",
|
|
5
5
|
"author": "Aerostack",
|
|
6
6
|
"license": "MIT",
|
|
@@ -8,10 +8,12 @@
|
|
|
8
8
|
"main": "dist/index.js",
|
|
9
9
|
"types": "dist/index.d.ts",
|
|
10
10
|
"bin": {
|
|
11
|
-
"aerostack-gateway": "dist/index.js"
|
|
11
|
+
"aerostack-gateway": "dist/index.js",
|
|
12
|
+
"aerostack-exec-daemon": "dist/exec-approval-daemon.js"
|
|
12
13
|
},
|
|
13
14
|
"files": [
|
|
14
15
|
"dist/**/*.js",
|
|
16
|
+
"scripts/install-exec-daemon.sh",
|
|
15
17
|
"README.md"
|
|
16
18
|
],
|
|
17
19
|
"scripts": {
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
#!/bin/bash
|
|
2
|
+
# Install aerostack-exec-daemon as a macOS LaunchAgent.
|
|
3
|
+
# Run after: npm install -g @aerostack/gateway
|
|
4
|
+
# Usage: AEROSTACK_WORKSPACE_URL=https://... AEROSTACK_TOKEN=mwt_... install-exec-daemon.sh
|
|
5
|
+
|
|
6
|
+
set -e
|
|
7
|
+
|
|
8
|
+
WORKSPACE_URL="${AEROSTACK_WORKSPACE_URL:-}"
|
|
9
|
+
TOKEN="${AEROSTACK_TOKEN:-}"
|
|
10
|
+
|
|
11
|
+
if [ -z "$WORKSPACE_URL" ] || [ -z "$TOKEN" ]; then
|
|
12
|
+
# Try to read from OpenClaw MCP config
|
|
13
|
+
OPENCLAW_CONFIG="$HOME/.openclaw/openclaw.json"
|
|
14
|
+
if [ -f "$OPENCLAW_CONFIG" ]; then
|
|
15
|
+
WORKSPACE_URL=$(python3 -c "import json,sys; c=json.load(open('$OPENCLAW_CONFIG')); print(c.get('mcp',{}).get('servers',{}).get('notification',{}).get('env',{}).get('AEROSTACK_WORKSPACE_URL',''))" 2>/dev/null)
|
|
16
|
+
TOKEN=$(python3 -c "import json,sys; c=json.load(open('$OPENCLAW_CONFIG')); print(c.get('mcp',{}).get('servers',{}).get('notification',{}).get('env',{}).get('AEROSTACK_TOKEN',''))" 2>/dev/null)
|
|
17
|
+
fi
|
|
18
|
+
fi
|
|
19
|
+
|
|
20
|
+
if [ -z "$WORKSPACE_URL" ] || [ -z "$TOKEN" ]; then
|
|
21
|
+
echo "ERROR: AEROSTACK_WORKSPACE_URL and AEROSTACK_TOKEN must be set (or configured in OpenClaw)"
|
|
22
|
+
exit 1
|
|
23
|
+
fi
|
|
24
|
+
|
|
25
|
+
NODE_BIN="$(which node)"
|
|
26
|
+
DAEMON_BIN="$(which aerostack-exec-daemon)"
|
|
27
|
+
PLIST_PATH="$HOME/Library/LaunchAgents/dev.aerostack.exec-daemon.plist"
|
|
28
|
+
LOG_DIR="$HOME/.aerostack/logs"
|
|
29
|
+
|
|
30
|
+
mkdir -p "$LOG_DIR"
|
|
31
|
+
|
|
32
|
+
cat > "$PLIST_PATH" << EOF
|
|
33
|
+
<?xml version="1.0" encoding="UTF-8"?>
|
|
34
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
35
|
+
<plist version="1.0">
|
|
36
|
+
<dict>
|
|
37
|
+
<key>Label</key>
|
|
38
|
+
<string>dev.aerostack.exec-daemon</string>
|
|
39
|
+
<key>RunAtLoad</key>
|
|
40
|
+
<true/>
|
|
41
|
+
<key>KeepAlive</key>
|
|
42
|
+
<true/>
|
|
43
|
+
<key>ThrottleInterval</key>
|
|
44
|
+
<integer>5</integer>
|
|
45
|
+
<key>ProgramArguments</key>
|
|
46
|
+
<array>
|
|
47
|
+
<string>$NODE_BIN</string>
|
|
48
|
+
<string>$DAEMON_BIN</string>
|
|
49
|
+
</array>
|
|
50
|
+
<key>EnvironmentVariables</key>
|
|
51
|
+
<dict>
|
|
52
|
+
<key>AEROSTACK_WORKSPACE_URL</key>
|
|
53
|
+
<string>$WORKSPACE_URL</string>
|
|
54
|
+
<key>AEROSTACK_TOKEN</key>
|
|
55
|
+
<string>$TOKEN</string>
|
|
56
|
+
<key>HOME</key>
|
|
57
|
+
<string>$HOME</string>
|
|
58
|
+
<key>PATH</key>
|
|
59
|
+
<string>$(dirname "$NODE_BIN"):/usr/local/bin:/usr/bin:/bin</string>
|
|
60
|
+
</dict>
|
|
61
|
+
<key>StandardOutPath</key>
|
|
62
|
+
<string>$LOG_DIR/exec-daemon.log</string>
|
|
63
|
+
<key>StandardErrorPath</key>
|
|
64
|
+
<string>$LOG_DIR/exec-daemon.err.log</string>
|
|
65
|
+
</dict>
|
|
66
|
+
</plist>
|
|
67
|
+
EOF
|
|
68
|
+
|
|
69
|
+
# Load / reload
|
|
70
|
+
launchctl unload "$PLIST_PATH" 2>/dev/null || true
|
|
71
|
+
launchctl load "$PLIST_PATH"
|
|
72
|
+
|
|
73
|
+
echo "Installed: dev.aerostack.exec-daemon"
|
|
74
|
+
echo "Logs: $LOG_DIR/exec-daemon.log"
|
|
75
|
+
echo "Status: launchctl list dev.aerostack.exec-daemon"
|