@aerostack/gateway 0.15.24 → 0.15.25
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 +13 -15
- 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
|
|
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
|
|
4
4
|
`),process.exit(1)),l||(process.stderr.write(`ERROR: AEROSTACK_TOKEN is required
|
|
5
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
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(/\/+$/,""),
|
|
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
|
|
9
|
-
${s.slice(-
|
|
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(`
|
|
10
10
|
`)}
|
|
11
11
|
|
|
12
|
-
`}async function
|
|
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(`
|
|
13
13
|
|
|
14
14
|
`);return[{type:"text",text:`${o}New messages from workspace owner:
|
|
15
15
|
|
|
16
|
-
${t}`}]}try{const o=await
|
|
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(`
|
|
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
|
|
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(`
|
|
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(),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
|
|
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}
|
|
54
54
|
|
|
55
|
-
${x}`:x}}}const
|
|
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(`
|
|
56
56
|
`);n.unshift({type:"text",text:`--- WORKSPACE OWNER MESSAGE ---
|
|
57
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"};
|
|
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+`
|
|
59
59
|
`);e(`
|
|
60
60
|
Aerostack Connection Check
|
|
61
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(`
|
|
@@ -69,8 +69,6 @@ ${m}
|
|
|
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
|
|
73
|
-
`);a=
|
|
74
|
-
|
|
75
|
-
Reply briefly and helpfully based on the conversation above. Do NOT call any tools \u2014 just respond with text.`:`The workspace owner (${t}) says: "${r}". Reply briefly and helpfully. Do NOT call any tools \u2014 just respond with text.`;i("openclaw",["agent","--agent","main","--json","-m",w],{timeout:6e4},async(A,m)=>{let p="";if(!A&&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(`
|
|
76
|
-
`).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 k(`${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 X(){$?.abort(),f?.stop(),de(),process.exit(0)}process.on("SIGTERM",()=>{X()}),process.on("SIGINT",()=>{X()}),process.argv.includes("--check")?De():Ke().catch(e=>{fe("Fatal error",{error:e instanceof Error?e.message:String(e)}),process.exit(1)});
|
|
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)});
|