@aerostack/gateway 0.15.20 → 0.15.22
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 +25 -18
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,24 +1,28 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
import{Server as
|
|
3
|
+
import{Server as Q}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as Z}from"@modelcontextprotocol/sdk/server/stdio.js";import{ListToolsRequestSchema as ee,CallToolRequestSchema as te,ListResourcesRequestSchema as se,ReadResourceRequestSchema as oe,ListPromptsRequestSchema as re,GetPromptRequestSchema as ne}from"@modelcontextprotocol/sdk/types.js";import{readFile as ae,writeFile as ie}from"node:fs/promises";import{join as ce}from"node:path";import{homedir as le}from"node:os";import{resolveApproval as x}from"./resolution.js";import{startHookServer as ue,installClaudeHook as pe,stopHookServer as de}from"./hook-server.js";import{OpenClawConnector as me,resolveOpenClawToken as he}from"./openclaw-connector.js";import{info as c,warn as h,error as fe}from"./logger.js";const H=ce(le(),".openclaw","pre-authorized.json");async function ge(t){try{let s={};try{s=JSON.parse(await ae(H,"utf-8"))}catch{}s[t]=Date.now(),await ie(H,JSON.stringify(s))}catch{}}const L=process.env.AEROSTACK_WORKSPACE_URL,u=process.env.AEROSTACK_TOKEN;function S(t,s,o){const e=parseInt(t??String(s),10);return Number.isFinite(e)&&e>=o?e:s}const D=S(process.env.AEROSTACK_APPROVAL_POLL_MS,3e3,500),U=S(process.env.AEROSTACK_APPROVAL_TIMEOUT_MS,864e5,5e3),M=S(process.env.AEROSTACK_REQUEST_TIMEOUT_MS,3e4,1e3),we=process.env.AEROSTACK_HOOK_SERVER!=="false",ye=S(process.env.AEROSTACK_HOOK_PORT,18321,1024),_e=process.env.AEROSTACK_HOOK_AUTO_INSTALL!=="false",Ae=process.env.AEROSTACK_OPENCLAW_ENABLED!=="false",q=S(process.env.AEROSTACK_OPENCLAW_PORT,18789,1024),Ee=process.env.AEROSTACK_OPENCLAW_TOKEN;L||(process.stderr.write(`ERROR: AEROSTACK_WORKSPACE_URL is required
|
|
4
4
|
`),process.exit(1)),u||(process.stderr.write(`ERROR: AEROSTACK_TOKEN is required
|
|
5
|
-
`),process.exit(1));let
|
|
6
|
-
`),process.exit(1)}
|
|
7
|
-
`);const
|
|
8
|
-
`);let e=null;for(const
|
|
5
|
+
`),process.exit(1));let v;try{if(v=new URL(L),v.protocol!=="https:"&&v.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)}v.protocol==="http:"&&!v.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=L.replace(/\/+$/,""),W=crypto.randomUUID();function Te(){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 G=Te();let f=null,E=Date.now();const Re=3e4;async function g(t,s){const o={jsonrpc:"2.0",id:Date.now(),method:t,params:s??{}},e=new AbortController,r=setTimeout(()=>e.abort(),M);try{const n=await fetch(d,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`,"User-Agent":"aerostack-gateway/0.15.14","X-Agent-Id":"aerostack-gateway","X-Bridge-Id":W,"X-Agent-Type":G},body:JSON.stringify(o),signal:e.signal});if(clearTimeout(r),(n.headers.get("content-type")??"").includes("text/event-stream")){const w=await n.text();return Oe(w,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 Oe(t,s){const o=t.split(`
|
|
8
|
+
`);let e=null;for(const r of o)if(r.startsWith("data: "))try{e=JSON.parse(r.slice(6))}catch{}return e??{jsonrpc:"2.0",id:s,error:{code:-32603,message:"Empty SSE response"}}}const Se=new Set(["aerostack__guardian_report","aerostack__check_approval","aerostack__guardian_check"]);function ve(t,s){if(Se.has(t))return;let o="other";const e=t.toLowerCase();e.includes("exec")||e.includes("bash")||e.includes("shell")||e.includes("command")||e.includes("run")?o="exec_command":e.includes("write")||e.includes("edit")||e.includes("create")||e.includes("patch")?o="file_write":e.includes("delete")||e.includes("remove")||e.includes("trash")||e.includes("unlink")?o="file_delete":e.includes("fetch")||e.includes("http")||e.includes("request")||e.includes("api")||e.includes("get")||e.includes("post")?o="api_call":e.includes("install")||e.includes("package")||e.includes("npm")||e.includes("pip")?o="package_install":e.includes("config")||e.includes("setting")||e.includes("env")?o="config_change":e.includes("deploy")||e.includes("publish")||e.includes("release")?o="deploy":e.includes("send")||e.includes("message")||e.includes("email")||e.includes("notify")||e.includes("slack")||e.includes("telegram")?o="message_send":(e.includes("read")||e.includes("query")||e.includes("search")||e.includes("list")||e.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)"}g("tools/call",{name:"aerostack__guardian_report",arguments:{action:`${t}(${Object.keys(s).join(", ")})`,category:o,risk_level:"low",details:r}}).catch(()=>{})}const ke=new Set(["aerostack__check_approval"]),V=[{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"]}}],Ce=new Set(V.map(t=>t.name));function y(t){return t.replace(/\[/g,"(").replace(/\]/g,")")}const k=[],Ne=100,T=new Map,Y=50,z=10;let C=null,B=!1;function P(t,s,o){let e=T.get(t);e||(e=[],T.set(t,e)),e.push({role:s,content:o,ts:Date.now()}),e.length>Y&&e.splice(0,e.length-Y)}async function F(t){if(!B)try{const s=await R(`${d}/chat/history?limit=${z}`,{headers:{Authorization:`Bearer ${u}`}});if(!s.ok)return;const o=await s.json();o.session_id&&(C=o.session_id);for(const e of o.messages??[]){const r=e.sender_type==="agent"?"agent":"user",n=o.session_id||t;let a=T.get(n);a||(a=[],T.set(n,a)),a.push({role:r,content:e.content,ts:e.created_at})}B=!0,c("Thread history seeded from D1",{sessionId:o.session_id,count:o.messages?.length??0})}catch{}}function K(t){const s=T.get(t);return!s||s.length===0?"":`Previous conversation:
|
|
9
|
+
${s.slice(-z).map(r=>`[${r.role==="user"?"Admin":"You (Agent)"}] ${r.content}`).join(`
|
|
10
|
+
`)}
|
|
9
11
|
|
|
10
|
-
|
|
12
|
+
`}async function R(t,s){const o=new AbortController,e=setTimeout(()=>o.abort(),M);try{return await fetch(t,{...s,signal:o.signal})}finally{clearTimeout(e)}}async function be(){const t=C||"_default";if(await F(t),k.length>0){const s=k.splice(0);E=Date.now();const o=K(t),e=s.map(r=>`${y(r.sender_name)}: ${y(r.content)}`).join(`
|
|
11
13
|
|
|
12
|
-
`)
|
|
14
|
+
`);return[{type:"text",text:`${o}New messages from workspace owner:
|
|
13
15
|
|
|
14
|
-
${e.map(
|
|
16
|
+
${e}`}]}try{const o=await R(`${d}/chat/pending?since=${E}`,{headers:{Authorization:`Bearer ${u}`}});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(t,"user",i.content);const n=K(t),a=r.map(i=>`${y(i.sender_name)}: ${y(i.content)}`).join(`
|
|
15
17
|
|
|
16
|
-
`)
|
|
17
|
-
|
|
18
|
-
`)
|
|
19
|
-
`)
|
|
18
|
+
`);return[{type:"text",text:`${n}New messages from workspace owner:
|
|
19
|
+
|
|
20
|
+
${a}`}]}catch{return[{type:"text",text:"Failed to check messages."}]}}async function $e(t){const s=typeof t.message=="string"?t.message.trim().slice(0,1e4):"";if(!s)return[{type:"text",text:"Error: message is required."}];try{const o=await R(`${d}/chat/messages`,{method:"POST",headers:{Authorization:`Bearer ${u}`,"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(t,s){ve(t,s);const o=await g("tools/call",{name:t,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:t,approvalId:a});const i=await x({approvalId:a,wsUrl:n?.ws_url,pollUrl:n?.polling_url??`${d}/approval-status/${a}`,pollIntervalMs:D,timeoutMs:U,token:u});c("Tool gate resolved",{tool:t,status:i.status}),N({approvalId:a,toolName:t,toolArgs:s,sessionKey:null,gate:"tool_gate",pollUrl:"",authToken:u},i.status,!0);const w=j({approvalId:a,toolName:t,toolArgs:s,sessionKey:null,gate:"tool_gate",pollUrl:"",authToken:u},i);return{jsonrpc:"2.0",id:o.id,result:{content:[{type:"text",text:w}]}}}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:t,approvalId:n});const a=await x({approvalId:n,wsUrl:r.ws_url,pollUrl:r.polling_url??`${d}/approval-status/${n}`,pollIntervalMs:D,timeoutMs:U,token:u});c("Permission gate resolved",{tool:t,status:a.status}),N({approvalId:n,toolName:t,toolArgs:s,sessionKey:null,gate:"permission_gate",pollUrl:"",authToken:u},a.status,!0);const i=j({approvalId:n,toolName:t,toolArgs:s,sessionKey:null,gate:"permission_gate",pollUrl:"",authToken:u},a);return{jsonrpc:"2.0",id:o.id,result:{content:[{type:"text",text:i}]}}}return o}function Fe(t){x({approvalId:t.approvalId,wsUrl:t.wsUrl,pollUrl:t.pollUrl,pollIntervalMs:D,timeoutMs:U,token:t.authToken}).then(async s=>{c("Approval resolved",{tool:t.toolName,status:s.status,session:t.sessionKey});const o=j(t,s),e=t.sessionKey??f?.getLastActiveSession()??null;if((s.status==="approved"||s.status==="executed")&&e&&ge(e).catch(()=>{}),e&&f){if(await f.sendToSession(e,o)){c("Agent resumed via sessions.send",{session:e,status:s.status}),N(t,s.status,!0);return}h("sessions.send failed, falling back to channel notification",{session:e})}try{await _.notification({method:"notifications/claude/channel",params:{content:o,meta:{tool_name:t.toolName,approval_id:t.approvalId,status:s.status,gate:t.gate}}}),c("Agent resumed via channel notification",{tool:t.toolName,status:s.status}),N(t,s.status,!0)}catch(r){h("Channel notification failed",{error:r instanceof Error?r.message:String(r)}),N(t,s.status,!1)}}).catch(s=>{h("Background approval resolver error",{error:s instanceof Error?s.message:String(s)})})}function N(t,s,o){const e=typeof t.toolArgs.action=="string"?t.toolArgs.action:null,r=e??t.toolName.replace(/^(?:\w+__)*aerostack__/,"")??t.toolName,n=e?`${r}`:`${r}(${Object.keys(t.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`,g("tools/call",{name:"aerostack__guardian_report",arguments:{action:i.slice(0,500),category:"approval",risk_level:"low",details:JSON.stringify({tool:t.toolName,approvalId:t.approvalId,status:s,delivered:o,session:t.sessionKey}).slice(0,500)}}).catch(()=>{})}function j(t,s){const o=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}`,o?`Reviewer note: "${o}"`:null,"",`Please now execute this action: call ${t.toolName} with the same parameters as before.`].filter(r=>r!==null).join(`
|
|
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
|
+
`);case"changes_requested":return["[CHANGES REQUESTED] The workspace owner reviewed your action and requested changes.","",`Original action: ${e}`,`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
|
+
`);case"rejected":return["[REJECTED] The workspace owner denied this action.","",`Action: ${e}`,o?`Reason: "${o}"`:"No reason provided.","","Do not retry this action. If you believe this was a mistake, inform the user."].join(`
|
|
20
24
|
`);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(`
|
|
21
|
-
`);default:return`[APPROVAL UPDATE] Status for "${e}": ${s.status}.`}}const
|
|
25
|
+
`);default:return`[APPROVAL UPDATE] Status for "${e}": ${s.status}.`}}const I=`
|
|
22
26
|
=== AEROSTACK GUARDIAN POLICY (MANDATORY) ===
|
|
23
27
|
|
|
24
28
|
You are operating under Aerostack workspace monitoring. These rules apply to ALL actions:
|
|
@@ -46,10 +50,13 @@ or before starting a new one, call aerostack__chat_check to see if the owner sen
|
|
|
46
50
|
If there are messages, read them carefully and respond using aerostack__chat_reply. This keeps
|
|
47
51
|
the owner informed and allows them to steer your work in real time.
|
|
48
52
|
=== END WORKSPACE CHAT ===
|
|
49
|
-
`.trim(),
|
|
53
|
+
`.trim(),Ie=["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(t,s){const o=t.toLowerCase(),e=Ie.some(n=>o.includes(n)),r=s??"";return e?`[REQUIRES GUARDIAN APPROVAL] ${r}`.trim():r}let J=null;async function O(){if(J)return;const t=await g("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"aerostack-gateway",version:"0.15.14"}});if(t.result){const s=t.result,o=s.instructions??"";J={protocolVersion:s.protocolVersion??"2024-11-05",instructions:o?`${o}
|
|
50
54
|
|
|
51
|
-
${
|
|
55
|
+
${I}`:I}}}const _=new Q({name:"aerostack-gateway",version:"0.15.14"},{capabilities:{tools:{},resources:{},prompts:{},experimental:{"claude/channel":{}}},instructions:I});_.setRequestHandler(ee,async()=>{await O();const t=await g("tools/list");if(t.error)throw new Error(t.error.message);const o=(t.result.tools??[]).filter(e=>!ke.has(e.name)).map(e=>({...e,description:xe(e.name,e.description)}));return o.push(...V),{tools:o}}),_.setRequestHandler(te,async t=>{await O();const{name:s,arguments:o}=t.params;if(Ce.has(s))return{content:(s==="aerostack__chat_check"?await be():await $e(o??{})).map(i=>({...i,type:"text"}))};const e=await Pe(s,o??{});if(e.error)return{content:[{type:"text",text:`Error: ${e.error.message}`}],isError:!0};const n=e.result.content??[{type:"text",text:JSON.stringify(e.result)}];if(Date.now()-E>Re)try{const i=await R(`${d}/chat/pending?since=${E}`,{headers:{Authorization:`Bearer ${u}`}});if(i.ok){const A=(await i.json()).messages??[];if(E=Date.now(),A.length>0){const m=A.map(l=>`${y(l.sender_name)}: ${y(l.content)}`).join(`
|
|
52
56
|
`);n.unshift({type:"text",text:`--- WORKSPACE OWNER MESSAGE ---
|
|
53
|
-
${
|
|
54
|
-
--- END MESSAGE \u2014 please acknowledge ---`})}}}catch{}return{content:n}});const
|
|
55
|
-
`);a=
|
|
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"};_.setRequestHandler(se,async()=>{await O();const t=await g("resources/list");if(t.error)throw new Error(t.error.message);const s=t.result;return{resources:[Le,...s.resources??[]]}}),_.setRequestHandler(oe,async t=>{if(await O(),t.params.uri==="aerostack://guardian/policy")return{contents:[{uri:t.params.uri,text:I,mimeType:"text/plain"}]};const s=await g("resources/read",{uri:t.params.uri});if(s.error)throw new Error(s.error.message);return{contents:s.result.contents??[]}}),_.setRequestHandler(re,async()=>{await O();const t=await g("prompts/list");if(t.error)throw new Error(t.error.message);return{prompts:t.result.prompts??[]}}),_.setRequestHandler(ne,async t=>{await O();const s=await g("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 De(){c("Connecting to workspace",{url:d});const t=new Z;await _.connect(t),c("Ready",{url:d});const s=()=>{R(`${d}/chat/heartbeat`,{method:"POST",headers:{Authorization:`Bearer ${u}`,"Content-Type":"application/json"},body:JSON.stringify({agent_type:G,user_agent:"aerostack-gateway/0.15.14",bridge_id:W})}).catch(()=>{})};s();const o=setInterval(s,12e4);if(process.on("exit",()=>clearInterval(o)),we)try{const r=await ue(async n=>{try{const a=await fetch(`${d}/guardian-batch`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`,"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}},ye);_e&&await pe(r)&&c("Claude Code hook auto-installed",{port:r})}catch(e){h("Hook server failed to start (non-fatal)",{error:e instanceof Error?e.message:String(e)})}if(Ae)try{const e=Ee??await he();e?(f=new me({port:q,token:e,rpcCall:g}),await f.connect()?c("OpenClaw connector started",{port:q}):(c("OpenClaw gateway not reachable, skipping connector"),f=null)):c("OpenClaw integration skipped (no token found)")}catch(e){h("OpenClaw connector failed (non-fatal)",{error:e instanceof Error?e.message:String(e)})}Ue()}let b=null;function Ue(){b&&b.abort(),b=new AbortController;const t=async()=>{try{const e=await fetch(d,{method:"GET",headers:{Authorization:`Bearer ${u}`,Accept:"text/event-stream"},signal:b.signal});if(!e.ok||!e.body){h("Chat event listener: failed to connect",{status:e.status}),o();return}c("Chat event listener connected");const r=e.body.getReader(),n=new TextDecoder;let a="";for(;;){const{done:i,value:w}=await r.read();if(i)break;a+=n.decode(w,{stream:!0});const A=a.split(`
|
|
59
|
+
`);a=A.pop()??"";let m="",l="";for(const p of A)p.startsWith("event: ")?m=p.slice(7).trim():p.startsWith("data: ")?l=p.slice(6):p===""&&m&&l&&(m==="aerostack_event"&&Ke(l),m="",l="")}c("Chat event listener: stream ended, reconnecting"),o()}catch(e){if(e?.name==="AbortError")return;h("Chat event listener error",{error:e?.message}),o()}};let s=null;const o=()=>{s||(s=setTimeout(()=>{s=null,t()},5e3))};t()}async function Ke(t){try{const s=JSON.parse(t);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)),k.length>=Ne&&k.shift(),k.push({sender_name:s.sender_name??"Admin",content:s.content,created_at:Date.now(),session_id:o}),E=Date.now();const e=y(s.sender_name??"Admin"),r=y(s.content);if(f){const i=f.getLastActiveSession()||"agent:main:main";f.sendToSession(i,`[Workspace Owner \u2014 ${e}]: ${r}`).catch(()=>{})}const n=o||C||"_default";await F(n);const a=K(n);try{const{execFile:i}=await import("child_process");c("Spawning agent turn for chat response",{sender:e,historyLen:T.get(n)?.length??0});const w=a?`${a}New message from workspace owner (${e}): "${r}"
|
|
60
|
+
|
|
61
|
+
Reply briefly and helpfully based on the conversation above. Do NOT call any tools \u2014 just respond with text.`:`The workspace owner (${e}) 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 l="";if(!A&&m)try{const p=JSON.parse(m.trim()),$=p?.result?.payloads;Array.isArray($)&&$.length>0&&$[0].text?l=$[0].text:l=p.text||p.reply||p.message||""}catch{l=m.trim().split(`
|
|
62
|
+
`).pop()||m.trim()}(!l||l.length<2)&&(l=`Message received. I'll process "${r.slice(0,100)}" shortly.`),P(n,"agent",l);try{const p=await R(`${d}/chat/messages`,{method:"POST",headers:{Authorization:`Bearer ${u}`,"Content-Type":"application/json"},body:JSON.stringify({content:l.slice(0,1e4)})});p.ok?c("Chat reply sent to workspace"):h("Chat reply failed",{status:p.status})}catch(p){h("Failed to send chat reply",{error:p?.message})}})}catch(i){h("Failed to spawn agent turn",{error:i?.message})}}catch{}}function X(){b?.abort(),f?.stop(),de(),process.exit(0)}process.on("SIGTERM",()=>{X()}),process.on("SIGINT",()=>{X()}),De().catch(t=>{fe("Fatal error",{error:t instanceof Error?t.message:String(t)}),process.exit(1)});
|