@octavus/agent 0.3.0 → 0.3.1
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/README.md +7 -3
- package/dist/index.js +4 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -17,7 +17,7 @@ Then mint an agent API key from the agent's **Settings -> API** tab.
|
|
|
17
17
|
## Install
|
|
18
18
|
|
|
19
19
|
```bash
|
|
20
|
-
curl -fsSL https://octavus.ai/install/
|
|
20
|
+
curl -fsSL https://octavus.ai/install/agent-cli.sh | sh
|
|
21
21
|
```
|
|
22
22
|
|
|
23
23
|
The installer sets up the prerequisites a full computer needs on a standard Linux box (Node, a headless X display via Xvfb, the AT-SPI accessibility bus, Chrome for Testing) so "install and run" just works. A shell + filesystem only agent needs none of the display stack.
|
|
@@ -54,7 +54,11 @@ The working directory you launch in is the agent's workspace (override with `--w
|
|
|
54
54
|
- `octoagent config [--env <name>]` - show the current configuration.
|
|
55
55
|
- `octoagent version [--env <name>]` - show the CLI and platform-supported versions.
|
|
56
56
|
|
|
57
|
-
Exit codes: `0` completed, `1` failed, `2` bad usage, `3` update required.
|
|
57
|
+
Exit codes: `0` completed, `1` failed, `2` bad usage, `3` update required, `4` stopped from the dashboard.
|
|
58
|
+
|
|
59
|
+
### Stopping a run
|
|
60
|
+
|
|
61
|
+
A run has no live chat, but you can still stop it from the dashboard: open its thread and click **Stop**. The run is aborted on the machine and the CLI exits with code `4` (its `--json` output reports `"status": "cancelled"`). Useful when you fan out several runs from a server and want to halt some of them.
|
|
58
62
|
|
|
59
63
|
### Run configuration
|
|
60
64
|
|
|
@@ -81,7 +85,7 @@ Precedence: explicit flags > `--config` file > the agent's dashboard defaults. A
|
|
|
81
85
|
|
|
82
86
|
### Machine-readable output
|
|
83
87
|
|
|
84
|
-
`--json` prints exactly one JSON object to stdout - `{ "threadId", "sessionId", "status", "threadUrl" }` - with all human/progress output routed to stderr, so a benchmark harness can capture and correlate a run without scraping text. The exit code
|
|
88
|
+
`--json` prints exactly one JSON object to stdout - `{ "threadId", "sessionId", "status", "threadUrl" }` - with all human/progress output routed to stderr, so a benchmark harness can capture and correlate a run without scraping text. The exit code signals completed (`0`), failed (`1`), or stopped from the dashboard (`4`). Read the full transcript and a per-run cost/usage summary from `GET /api/v1/workforce/agents/{agentId}/threads/{threadId}` with the same agent key.
|
|
85
89
|
|
|
86
90
|
### Environments
|
|
87
91
|
|
package/dist/index.js
CHANGED
|
@@ -67,7 +67,7 @@ Caused by: ${e.cause.stack}`)}static isInstance(e){return typeof e=="object"&&e!
|
|
|
67
67
|
${e.slice(e.length-o)}`}function U8(e){let t=-1,r=-1;return e.forEach((o,n)=>{let i=D8(o);i>r&&(r=i,t=n)}),t}function L8(e){let t=e.result!==void 0,r=t?e1(e.result):e.error??"",o=Yi(r);if(o<=C8)return null;if(t&&e.outputVariable){let s=`Result omitted: it was ${Wb(o)}, too large to capture into variable "${e.outputVariable}" and send back. Reduce the output - add filters or a limit, request fewer fields, paginate, or write it to a file and return a reference instead of inline data.`;return e.result=void 0,e.error=s,{toolCallId:e.toolCallId,toolName:e.toolName,originalBytes:o,keptBytes:Yi(s),variableCapture:!0}}let i=`${`[Octavus: this tool result was too large to send (${Wb(o)}), so only the start and end are shown below. To use the full data, reduce the output - add filters or a limit, request fewer fields, paginate, or write it to a file and return a reference instead of inline data.]`}
|
|
68
68
|
|
|
69
69
|
${j8(r,A8)}`;return t?e.result=i:e.error=i,{toolCallId:e.toolCallId,toolName:e.toolName,originalBytes:o,keptBytes:Yi(i),variableCapture:!1}}function M8(e,t){if(!e||e.length===0)return{results:e,truncations:[],overflow:!1};if(qb(e)<=t)return{results:e,truncations:[],overflow:!1};let r=e.map(i=>({...i})),o=[],n=r.length;for(;n>0&&qb(r)>t;){n-=1;let i=U8(r);if(i<0)break;let s=L8(r[i]);if(!s)break;o.push(s)}return{results:r,truncations:o,overflow:qb(r)>t}}var Z8=2,F8=1e3,HP=8e3,q8=.25,B8=6e4;function V8(e){return e===408||e===429||e===502||e===503||e===504}function W8(e){return e instanceof TypeError}function H8(e){let t=Number(e);if(Number.isFinite(t))return Math.max(0,t*1e3);let r=Date.parse(e);return Number.isFinite(r)?Math.max(0,r-Date.now()):null}async function Bb(e,t,r){let o=t?.headers.get("retry-after"),n=o?H8(o):null,i;if(n!==null)i=Math.min(n,HP);else{let s=Math.min(F8*2**e,HP),a=s*q8*(Math.random()*2-1);i=s+a}r?.aborted||await new Promise((s,a)=>{let u={timer:null},c=()=>{u.timer!==null&&clearTimeout(u.timer),a(r.reason instanceof Error?r.reason:new Error("Aborted"))};u.timer=setTimeout(()=>{r?.removeEventListener("abort",c),s()},i),r?.addEventListener("abort",c,{once:!0})})}async function*Hb(e,t,r){let o=t.toolResults,n=t.executionId,i=!0,s=Math.max(0,e.config.streamIdleTimeoutMs??B8),a=e.config.maxContinuationBytes??O8,u=a-Math.min(R8,Math.floor(a/2));for(;i;){if(r?.aborted){yield{type:"finish",finishReason:"stop"};return}let c=M8(o,u);if(o=c.results,e.onToolResultTruncated)for(let v of c.truncations)e.onToolResultTruncated(v);let l=e.buildBody({executionId:n,toolResults:o});if(c.overflow||Yi(JSON.stringify(l))>a){yield $f(413,`${e.errorContext??"Request"}: the results are too large to send (over ${Wb(a)}) and could not be reduced enough. Return less data - filter, limit, or paginate the results, or write them to a file and return a reference.`);return}let f=Math.max(0,e.config.maxRetries??Z8),p,h=!1,m,g,_=null;try{for(let b=0;b<=f;b++){if(r?.aborted){yield{type:"finish",finishReason:"stop"};return}let T=new AbortController,C=()=>T.abort(r?.reason);r&&(r.aborted?T.abort(r.reason):r.addEventListener("abort",C,{once:!0}));let N=!1,I=s>0?setTimeout(()=>{N=!0,T.abort()},s):void 0,W=!1;try{let U=typeof e.url=="function"?e.url():e.url;if(p=await fetch(U,{method:"POST",headers:await e.config.getHeaders(),body:JSON.stringify(l),signal:T.signal}),V8(p.status)&&b<f){await p.body?.cancel().catch(()=>{}),await Bb(b,p,r);continue}h=!0,W=!0,m=T,g=C;break}catch(U){if(r?.aborted){yield{type:"finish",finishReason:"stop"};return}if(N){if(b<f){await Bb(b,null,r);continue}return}if(b<f&&W8(U)){await Bb(b,null,r);continue}throw U}finally{I&&clearTimeout(I),!W&&r&&r.removeEventListener("abort",C)}}if(!h)return;if(!p.ok){let{message:b}=await XP(p,e.errorContext??"Request failed");yield $f(p.status,b);return}if(!p.body){yield Gi("Response body is not readable");return}e.onResponse?.(p),o=void 0;let v=p.body.getReader(),w=new TextDecoder,k="",S=!1;for(;!S;){if(r?.aborted){v.releaseLock(),yield{type:"finish",finishReason:"stop"};return}let b=v.read(),T,C;try{if(s>0){let U=new Promise(De=>{T=setTimeout(()=>De("idle"),s)});C=await Promise.race([b,U])}else C=await b}catch(U){if(T&&clearTimeout(T),Ub(U)){v.releaseLock(),yield{type:"finish",finishReason:"stop"};return}if(Db(U)){await v.cancel().catch(()=>{});return}throw U}if(T&&clearTimeout(T),C==="idle"){b.then(()=>{},()=>{}),await v.cancel().catch(()=>{});return}let{done:N,value:I}=C;if(N){S=!0;continue}k+=w.decode(I,{stream:!0});let W=k.split(`
|
|
70
|
-
`);k=W.pop()??"";for(let U of W)if(U.startsWith("data: ")&&U!=="data: [DONE]")try{let De=Zb(JSON.parse(U.slice(6)));if(!De.success)continue;let xe=De.data;if(xe.type==="start"&&xe.executionId&&(n=xe.executionId),xe.type==="start"&&xe.sessionId&&e.onSessionId?.(xe.sessionId),xe.type==="tool-request"){_=xe.toolCalls;continue}if(xe.type==="finish"){if(xe.finishReason==="tool-calls"&&_)continue;yield xe,i=!1;continue}xe.type==="resource-update"&&e.onResourceUpdate&&e.onResourceUpdate(xe.name,xe.value),yield xe}catch{}}}finally{m&&g&&r&&r.removeEventListener("abort",g)}if(r?.aborted){yield{type:"finish",finishReason:"stop"};return}if(_&&_.length>0){let v=e.getToolHandlers(),w=_.filter(T=>v[T.toolName]),k=_.filter(T=>!v[T.toolName]),S=Promise.all(w.map(async T=>{let C=v[T.toolName];try{let N=await C(T.args);return{toolCallId:T.toolCallId,toolName:T.toolName,result:N,outputVariable:T.outputVariable,blockIndex:T.blockIndex,thread:T.thread,workerId:T.workerId}}catch(N){return{toolCallId:T.toolCallId,toolName:T.toolName,error:N instanceof Error?N.message:"Tool execution failed",outputVariable:T.outputVariable,blockIndex:T.blockIndex,thread:T.thread,workerId:T.workerId}}})),b;if(r&&!r.aborted){let T,C=new Promise(I=>{T=()=>I("aborted"),r.addEventListener("abort",T,{once:!0})}),N;try{N=await Promise.race([S,C])}finally{T&&r.removeEventListener("abort",T)}if(N==="aborted"){yield{type:"finish",finishReason:"stop"};return}b=N}else if(r?.aborted){yield{type:"finish",finishReason:"stop"};return}else b=await S;if(e.onToolResults&&b.length>0&&await e.onToolResults(b),r?.aborted){yield{type:"finish",finishReason:"stop"};return}for(let T of b)T.error?yield{type:"tool-output-error",toolCallId:T.toolCallId,error:T.error}:yield{type:"tool-output-available",toolCallId:T.toolCallId,output:T.result};if(k.length>0)if(e.rejectClientToolCalls){let T=k.map(C=>({toolCallId:C.toolCallId,toolName:C.toolName,error:`Tool "${C.toolName}" is not available. No handler is registered for this tool.`,outputVariable:C.outputVariable,blockIndex:C.blockIndex,thread:C.thread,workerId:C.workerId}));for(let C of T)yield{type:"tool-output-error",toolCallId:C.toolCallId,error:C.error};o=[...b,...T]}else{if(!n){yield Gi("Missing executionId for client-tool-request");return}yield{type:"client-tool-request",executionId:n,toolCalls:k,serverToolResults:b.length>0?b:void 0},yield{type:"finish",finishReason:"client-tool-calls",executionId:n},i=!1}else o=b}else i=!1}}function Jb(e,t,r){let o=new Set,n={...t},i=r?[...r]:[],s=new Set(i.map(a=>a.name));for(let a of e){if(o.has(a.namespace))throw new Error(`Duplicate MCP namespace "${a.namespace}". Each inline MCP server must have a unique namespace.`);o.add(a.namespace);let u=a.toolHandlers(),c=a.toolSchemas();for(let[l,f]of Object.entries(u)){if(n[l])throw new Error(`Tool name collision: "${l}" is already registered. Ensure no overlap between MCP-namespaced tools and static tool handlers.`);n[l]=f}for(let l of c){if(s.has(l.name))throw new Error(`Tool schema name collision: "${l.name}" is already registered as a dynamic tool schema.`);s.add(l.name),i.push(l)}}return{toolHandlers:n,dynamicToolSchemas:i}}function J8(e){let t=e.toolHandlers();return e.toolSchemas().filter(r=>t[r.name]).map(r=>({schema:r,handler:t[r.name]}))}var JP=class{sessionId;config;deferredStart;idempotencyKey;baseHandlers;toolHandlers;resourceMap;mcpToolSchemas=[];dynamicToolSchemas;socketAbortController=null;onToolResults;onToolResultTruncated;rejectClientToolCalls;constructor(e){if(this.sessionId=e.sessionId,this.config=e.config,this.deferredStart=e.deferredStart,this.idempotencyKey=e.deferredStart?e.deferredStart.idempotencyKey??uc():void 0,this.onToolResults=e.onToolResults,this.onToolResultTruncated=e.onToolResultTruncated,this.rejectClientToolCalls=e.rejectClientToolCalls??!1,this.resourceMap=new Map,e.mcpServers!==void 0&&e.mcpServers.length>0){let t=Jb(e.mcpServers,e.tools);this.baseHandlers=t.toolHandlers,this.mcpToolSchemas=t.dynamicToolSchemas}else this.baseHandlers=e.tools??{};this.toolHandlers={...this.baseHandlers};for(let t of e.resources??[])this.resourceMap.set(t.name,t)}async*execute(e,t){if(e.type==="continue"){if(!this.sessionId)throw new Error("Cannot continue a session before it exists. Run a trigger first to create the session.");yield*this.executeStream({executionId:e.executionId,toolResults:e.toolResults},t?.signal)}else yield*this.executeStream({triggerName:e.triggerName,input:e.input,rollbackAfterMessageId:e.rollbackAfterMessageId,sender:e.sender},t?.signal)}getSessionId(){return this.sessionId}setDynamicTools(e){let t=Array.isArray(e)?e:J8(e),r={...this.baseHandlers};for(let o of t)r[o.schema.name]=o.handler;this.toolHandlers=r,this.dynamicToolSchemas=t.map(o=>o.schema)}async handleSocketMessage(e,t){if(e.type==="stop"){this.socketAbortController?.abort();return}this.socketAbortController?.abort(),this.socketAbortController=new AbortController;let r=this.socketAbortController;try{let o=this.execute(e,{signal:r.signal});for await(let n of o){if(r.signal.aborted)break;t.onEvent(n)}!r.signal.aborted&&t.onFinish&&await t.onFinish()}catch(o){if(!r.signal.aborted){let n=Gi(o instanceof Error?o.message:"Unknown error");t.onEvent(n)}}}async*executeStream(e,t){yield*Hb({config:this.config,getToolHandlers:()=>this.toolHandlers,url:()=>this.sessionId?`${this.config.baseUrl}/api/agent-sessions/${this.sessionId}/trigger`:`${this.config.baseUrl}/api/agent-sessions/start`,buildBody:({executionId:r,toolResults:o})=>this.buildRequestBody(e,r,o),onResponse:this.deferredStart?r=>this.latchSessionIdFromHeader(r):void 0,onSessionId:this.deferredStart?r=>this.latchSessionId(r):void 0,onResourceUpdate:(r,o)=>this.handleResourceUpdate(r,o),onToolResults:this.onToolResults,onToolResultTruncated:this.onToolResultTruncated,rejectClientToolCalls:this.rejectClientToolCalls,errorContext:"Failed to trigger"},{executionId:e.executionId,toolResults:e.toolResults},t)}buildRequestBody(e,t,r){let o=this.collectDynamicSchemas();if(this.deferredStart&&this.sessionId===void 0&&t===void 0){let i={};e.triggerName!==void 0&&(i.triggerName=e.triggerName),e.input!==void 0&&(i.input=e.input),e.sender!==void 0&&(i.sender=e.sender),o!==void 0&&(i.dynamicToolSchemas=o);let s={agentId:this.deferredStart.agentId,trigger:i};return this.deferredStart.input!==void 0&&(s.input=this.deferredStart.input),this.idempotencyKey!==void 0&&(s.idempotencyKey=this.idempotencyKey),s}let n={};return e.triggerName!==void 0&&(n.triggerName=e.triggerName),e.input!==void 0&&(n.input=e.input),e.rollbackAfterMessageId!==void 0&&(n.rollbackAfterMessageId=e.rollbackAfterMessageId),e.sender!==void 0&&(n.sender=e.sender),t!==void 0&&(n.executionId=t),r!==void 0&&(n.toolResults=r),o!==void 0&&(n.dynamicToolSchemas=o),n}latchSessionId(e){this.sessionId||(this.sessionId=e,this.deferredStart?.onSessionCreated?.(e))}latchSessionIdFromHeader(e){if(this.sessionId)return;let t=e.headers.get("X-Octavus-Session-Id");t&&this.latchSessionId(t)}handleResourceUpdate(e,t){let r=this.resourceMap.get(e);r&&r.onUpdate(t)}collectDynamicSchemas(){return this.mcpToolSchemas.length===0?this.dynamicToolSchemas:[...this.mcpToolSchemas,...this.dynamicToolSchemas??[]]}},G8=d.object({sessionId:d.string()}),K8=d.object({id:d.string(),agentId:d.string(),input:d.record(d.string(),d.unknown()),variables:d.record(d.string(),d.unknown()),resources:d.record(d.string(),d.unknown()),messages:d.array(RP),status:d.literal("active").optional(),createdAt:d.string(),updatedAt:d.string()}),Y8=d.object({sessionId:d.string(),agentId:d.string(),messages:d.array(Ef),status:d.literal("active").optional()}),Vb=d.object({sessionId:d.string(),agentId:d.string(),status:d.literal("expired"),createdAt:d.string()}),X8=d.object({sessionId:d.string(),restored:d.boolean()}),Q8=d.object({sessionId:d.string(),cleared:d.boolean()}),eW=d.looseObject({id:d.string(),timestamp:d.string(),type:d.string()}),tW=d.object({sessionId:d.string(),entries:d.array(eW),total:d.number().optional(),truncated:d.boolean().optional()}),rW=class extends Xi{async create(e,t){return(await this.httpPost("/api/agent-sessions",{agentId:e,input:t},G8)).sessionId}async get(e){let t=await fetch(`${this.config.baseUrl}/api/agent-sessions/${e}`,{method:"GET",headers:await this.config.getHeaders()});t.ok||await ko(t,"Request failed");let r=await t.json(),o=Vb.safeParse(r);return o.success?o.data:K8.parse(r)}async getMessages(e){let t=await fetch(`${this.config.baseUrl}/api/agent-sessions/${e}?format=ui`,{method:"GET",headers:await this.config.getHeaders()});t.ok||await ko(t,"Request failed");let r=await t.json(),o=Vb.safeParse(r);return o.success?o.data:Y8.parse(r)}async restore(e,t,r){return await this.httpPost(`/api/agent-sessions/${e}/restore`,{messages:t,input:r},X8)}async clear(e){return await this.httpDelete(`/api/agent-sessions/${e}`,Q8)}async getLogs(e,t){let r=new URLSearchParams;t?.excludeModelRequests&&r.set("excludeModelRequests","true");let o=r.toString(),n=`${this.config.baseUrl}/api/agent-sessions/${e}/logs${o?`?${o}`:""}`,i=await fetch(n,{method:"GET",headers:await this.config.getHeaders()});i.ok||await ko(i,"Request failed");let s=await i.json(),a=Vb.safeParse(s);return a.success?a.data:tW.parse(s)}attach(e,t={}){return new JP({sessionId:e,config:this.config,tools:t.tools,resources:t.resources,mcpServers:t.mcpServers,onToolResults:t.onToolResults,onToolResultTruncated:t.onToolResultTruncated,rejectClientToolCalls:t.rejectClientToolCalls})}start(e){return new JP({config:this.config,deferredStart:{agentId:e.agentId,input:e.input,idempotencyKey:e.idempotencyKey,onSessionCreated:e.onSessionCreated},tools:e.tools,resources:e.resources,mcpServers:e.mcpServers,onToolResults:e.onToolResults,onToolResultTruncated:e.onToolResultTruncated,rejectClientToolCalls:e.rejectClientToolCalls})}},Epe=d.object({filename:d.string().min(1).max(255),mediaType:d.string().min(1),size:d.number().int().positive()}),nW=d.object({id:d.string(),uploadUrl:d.url(),downloadUrl:d.url()}),oW=d.object({files:d.array(nW)}),iW=class extends Xi{async getUploadUrls(e,t){return await this.httpPost("/api/files/upload-urls",{sessionId:e,files:t},oW)}},GP=class extends Error{constructor(e,t,r){super(e),this.sessionId=t,this.details=r,this.name="WorkerError"}},sW=class extends Xi{async*execute(e,t,r={}){let o=r.mcpServers,n=o!==void 0&&o.length>0?Jb(o,r.tools,r.dynamicToolSchemas):{toolHandlers:r.tools??{},dynamicToolSchemas:r.dynamicToolSchemas};yield*Hb({config:this.config,getToolHandlers:()=>n.toolHandlers,url:`${this.config.baseUrl}/api/agents/${e}/execute`,buildBody:({executionId:i,toolResults:s})=>i?{type:"continue",executionId:i,toolResults:s}:{type:"start",input:t,...n.dynamicToolSchemas!==void 0&&{dynamicToolSchemas:n.dynamicToolSchemas}},errorContext:"Failed to execute worker"},{},r.signal)}async generate(e,t,r={}){let o,n,i,s,a,u,c;for await(let l of this.execute(e,t,r))l.type==="start"&&l.executionId?o=l.executionId:l.type==="error"?(i=l.message,s={errorType:l.errorType,source:l.source,code:l.code,retryable:l.retryable,retryAfter:l.retryAfter,provider:l.provider}):l.type==="worker-result"?(a=l.workerId,l.error!==void 0?i=i??l.error:n={output:l.output,sessionId:o??l.workerId}):l.type==="usage"&&(u=l.cost,c=l.tokens);if(i!==void 0)throw new GP(i,o??a,s);if(n!==void 0)return u!==void 0&&(n.cost=u),c!==void 0&&(n.tokens=c),n;throw new GP("Worker completed without producing a result",o)}async*continue(e,t,r,o={}){let n=o.mcpServers,i=n!==void 0&&n.length>0?Jb(n,o.tools).toolHandlers:o.tools??{};yield*Hb({config:this.config,getToolHandlers:()=>i,url:`${this.config.baseUrl}/api/agents/${e}/execute`,buildBody:({executionId:s,toolResults:a})=>({type:"continue",executionId:s??t,toolResults:a??r}),errorContext:"Failed to continue worker"},{executionId:t,toolResults:r},o.signal)}},aW=new Set(["completed","failed","cancelled"]);function cW(e){return aW.has(e)}var t1=d.string().transform(e=>e),KP=d.object({threadId:d.string(),status:t1}),uW=d.object({threadId:d.string(),status:t1,failureReason:d.string().nullable(),messages:d.array(Ef)}),lW=3e3,dW=900*1e3,fW=class extends Xi{async dispatch(e,t,r={}){return await this.httpPost(`/api/v1/workforce/agents/${encodeURIComponent(e)}/threads`,{message:t,files:r.files},KP)}async getThread(e,t){return await this.httpGet(`/api/v1/workforce/agents/${encodeURIComponent(e)}/threads/${encodeURIComponent(t)}`,uW)}async followUp(e,t,r,o={}){return await this.httpPost(`/api/v1/workforce/agents/${encodeURIComponent(e)}/threads/${encodeURIComponent(t)}/messages`,{message:r,files:o.files},KP)}async waitForCompletion(e,t,r={}){let o=r.pollIntervalMs??lW,n=r.timeoutMs??dW,i=Date.now()+n;for(;;){let s=await this.getThread(e,t);if(cW(s.status))return s;if(Date.now()+o>=i)throw new Error(`Workforce thread ${t} did not finish within ${n}ms (last status: ${s.status})`);await pW(o,r.signal)}}async run(e,t,r={}){let{threadId:o}=await this.dispatch(e,t,{files:r.files});return await this.waitForCompletion(e,o,r)}};function pW(e,t){return new Promise((r,o)=>{if(t?.aborted){o(YP(t));return}let n=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e);function i(){clearTimeout(n),o(YP(t))}t?.addEventListener("abort",i,{once:!0})})}function YP(e){let t=e?.reason;return t instanceof Error?t:new Error("The wait was aborted")}var Ppe=d.object({agentId:d.string().min(1),sessionId:d.string().min(1).optional(),ttlSeconds:d.number().int().positive().optional()}),hW=d.object({token:d.string(),jti:d.string(),expiresAt:d.string()}),mW=class extends Xi{async mint(e){return await this.httpPost("/api/tokens",e,hW)}async revoke(e){return await this.httpPost("/api/tokens/revoke",{token:e},d.object({revoked:d.boolean(),jti:d.string().optional()}))}},gW="4",Gb=class{agents;agentSessions;files;workers;workforce;tokens;baseUrl;apiKey;traceModelRequests;constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.apiKey=e.apiKey,this.traceModelRequests=e.traceModelRequests??!1;let t={baseUrl:this.baseUrl,getHeaders:()=>this.getHeaders(),maxRetries:e.maxRetries,streamIdleTimeoutMs:e.streamIdleTimeoutMs};this.agents=new P8(t),this.agentSessions=new rW(t),this.files=new iW(t),this.workers=new sW(t),this.workforce=new fW(t),this.tokens=new mW(t)}getSessionUrl(e){return`${this.baseUrl}/platform/sessions/${e}`}getAgentUrl(e){return`${this.baseUrl}/platform/agents/${e}`}async getHeaders(){let e={"Content-Type":"application/json","X-Octavus-Sdk-Version":gW},t=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;return t&&(e.Authorization=`Bearer ${t}`),this.traceModelRequests&&(e["X-Octavus-Trace"]="true"),e}};function _W(e){let t=atob(e),r=new ArrayBuffer(t.length),o=new Uint8Array(r);for(let n=0;n<t.length;n++)o[n]=t.charCodeAt(n);return r}async function r1(e,t,r){for(let o of e){if(o.outputVariable)continue;let n=VP(o.result);if(!n)continue;let i=o.files?[...o.files]:[],s=[],a=[],u=[],c=[],l=[];if(n.parts.forEach((g,_)=>{if(!wf(g))return;let v=_W(g.data),w=g.type==="image"?qP(new Uint8Array(v)):void 0,k=g.type==="image"&&w!==void 0,S=w??FP(g);s.push(_),a.push(g.type),u.push(v),l.push(k),c.push({filename:`${g.type}-${uc()}.${WP(S)}`,mediaType:S,size:v.byteLength})}),c.length===0)continue;let f=null;try{f=(await t.getUploadUrls(r,c)).files}catch{f=null}let p=f===null?null:await Promise.allSettled(f.map((g,_)=>fetch(g.uploadUrl,{method:"PUT",body:u[_],headers:{"Content-Type":c[_].mediaType}}))),h=new Map;s.forEach((g,_)=>{let v=a[_],w=c[_].mediaType,k=c[_].filename,S=u[_].byteLength,b=f?.[_],T=p?.[_],C=T?.status==="fulfilled"&&T.value.ok&&b!==void 0,N=l[_];if(C){N&&i.push({id:b.id,mediaType:w,url:b.downloadUrl,filename:k,size:S});let I=v==="image"&&!N;h.set(g,{type:v,mediaType:w,size:S,url:b.downloadUrl,...I&&{error:BP}})}else h.set(g,{type:v,mediaType:w,size:S,error:"Upload failed"})});let m=n.parts.map((g,_)=>h.has(_)?h.get(_):g);o.files=i,o.result=n.rebuild(m)}}function n1(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vW(e){return n1(e)?typeof e.name=="string"&&(e.path===void 0||typeof e.path=="string")&&typeof e.mediaType=="string"&&typeof e.size=="number"&&typeof e.contentBase64=="string":!1}function yW(e){let t=atob(e),r=new ArrayBuffer(t.length),o=new Uint8Array(r);for(let n=0;n<t.length;n++)o[n]=t.charCodeAt(n);return r}async function o1(e,t,r){for(let o of e){if(o.outputVariable)continue;let n=o.result;if(!n1(n))continue;let i=n.outputFiles;if(!Array.isArray(i)||i.length===0)continue;let s=i.filter(vW);if(s.length===0)continue;let a=[],u=[];for(let h of s){let m=yW(h.contentBase64);a.push(m),u.push({filename:h.name,mediaType:h.mediaType,size:h.size})}let c;try{c=(await t.getUploadUrls(r,u)).files}catch{n.outputFiles=s.map(h=>({name:h.name,...h.path!==void 0?{path:h.path}:{},mediaType:h.mediaType,size:h.size,error:"Upload failed"}));continue}let l=await Promise.allSettled(c.map((h,m)=>fetch(h.uploadUrl,{method:"PUT",body:a[m],headers:{"Content-Type":u[m].mediaType}}))),f=o.files?[...o.files]:[],p=[];for(let h=0;h<s.length;h++){let m=l[h],g=c[h],_=u[h],v=s[h];m.status==="fulfilled"&&m.value.ok?(f.push({id:g.id,mediaType:_.mediaType,url:g.downloadUrl,filename:_.filename,size:_.size}),p.push({name:_.filename,...v.path!==void 0?{path:v.path}:{},mediaType:_.mediaType,size:_.size,url:g.downloadUrl})):p.push({name:_.filename,...v.path!==void 0?{path:v.path}:{},mediaType:_.mediaType,size:_.size,error:"Upload failed"})}o.files=f,n.outputFiles=p}}var OA=We(h1(),1);import{existsSync as Wc,mkdirSync as bp,readdirSync as vp,readFileSync as Fx,renameSync as aK,rmSync as yp,statSync as cK,writeFileSync as IA}from"fs";import{execFile as uK}from"child_process";import{dirname as lK,join as vt,normalize as dK,relative as PA,sep as fK}from"path";import{createHash as pK,randomBytes as zA}from"crypto";var hK={txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",yaml:"application/yaml",yml:"application/yaml",xml:"application/xml",html:"text/html",htm:"text/html",pdf:"application/pdf",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mp3:"audio/mpeg",wav:"audio/wav",py:"text/x-python",js:"text/javascript",ts:"text/typescript",zip:"application/zip"};function Vx(e){let t=e.lastIndexOf(".");if(t<0)return"application/octet-stream";let r=e.slice(t+1).toLowerCase();return hK[r]??"application/octet-stream"}var mK=3e5,gK=10*1024*1024,_K=20*1024*1024,vK=50*1024*1024,yK=20*1024*1024,TA=".octavus-skill.json",bK=new Set(["PATH","HOME","USER","LOGNAME","SHELL","TMPDIR","TEMP","TMP","LANG","LC_ALL","LC_CTYPE","TZ","APPDATA","LOCALAPPDATA","PROGRAMDATA","USERPROFILE","USERNAME","USERDOMAIN","HOMEDRIVE","HOMEPATH","SYSTEMROOT","SYSTEMDRIVE","WINDIR","COMSPEC","PATHEXT","PUBLIC","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMW6432","COMMONPROGRAMFILES","COMMONPROGRAMFILES(X86)","COMMONPROGRAMW6432","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","OS"]),Wx=class{skills=new Map;extracted=new Map;inflight=new Map;installedSha=new Map;installErrors=new Map;installLocks=new Map;skillsDir;pythonPath;bashPath;turnOutputDir=null;collectedFiles=new Map;constructor(e){this.skillsDir=e.skillsDir,this.pythonPath=e.pythonPath,this.bashPath=e.bashPath,bp(this.skillsDir,{recursive:!0}),this.sweepStagingDirs(),this.reconcileFromDisk();for(let t of e.skills)this.skills.set(t.slug,t)}setSkills(e){this.skills.clear();for(let t of e)this.skills.set(t.slug,t);for(let t of[...this.extracted.keys()]){let r=this.skills.get(t);if(!r){this.extracted.delete(t);continue}let o=this.installedSha.get(t);r.bundleSha256&&o!==r.bundleSha256&&this.extracted.delete(t)}for(let t of[...this.installErrors.keys()])this.skills.has(t)||this.installErrors.delete(t);this.reconcileFromDisk()}reconcileFromDisk(){let e;try{e=vp(this.skillsDir,{withFileTypes:!0})}catch{return}for(let t of e){if(!t.isDirectory())continue;let r=t.name;if(r.startsWith(".")||r.includes(".staging-"))continue;let o=vt(this.skillsDir,r);(Wc(vt(o,"SKILL.md"))||Wc(vt(o,"scripts")))&&(this.skills.has(r)||this.skills.set(r,{slug:r,secrets:{}}),this.installedSha.has(r)||this.installedSha.set(r,this.readInstalledMarker(o)))}}readInstalledMarker(e){try{let t=Fx(vt(e,TA),"utf-8"),r=JSON.parse(t);return typeof r.sha256=="string"?r.sha256:void 0}catch{return}}async setupSkill(e){this.skills.set(e.slug,e),this.extracted.delete(e.slug);try{let t=await this.downloadAndExtract(e.slug,{allowStaleFallback:!1});return t?{installed:!0,path:PA(vt(this.skillsDir,".."),t.dir)||t.dir}:{installed:!1,error:`Skill "${e.slug}" is not configured on this device`}}catch(t){let r=t instanceof Error?t.message:String(t);return this.installErrors.set(e.slug,r),{installed:!1,error:r}}}toolHandlers(){return{octavus_skill_read:e=>this.handleSkillRead(e),octavus_skill_list:e=>this.handleSkillList(e),octavus_skill_run:e=>this.handleSkillRun(e)}}async handleSkillRead(e){let t=Es(e,"skill");if(!t)return{error:"Missing required parameter: skill"};let r=await this.ensureExtracted(t);if(!r)return this.unavailableError(t);let o=Es(e,"file")??"SKILL.md",n=Bx(r.dir,o);if(!n)return{error:`Invalid file path: ${o}`};let i=qx(r);try{return{content:Fx(n,"utf-8"),path:o,...i?{warning:i}:{}}}catch{return{error:`File not found: ${o}`}}}async handleSkillList(e){let t=Es(e,"skill");if(!t)return{error:"Missing required parameter: skill"};let r=await this.ensureExtracted(t);if(!r)return this.unavailableError(t);let o=qx(r),n=vt(r.dir,"scripts");try{let s=vp(n,{withFileTypes:!0}).filter(a=>a.isFile()).map(a=>({name:a.name,path:`scripts/${a.name}`}));return{skill:t,scripts:s,...o?{warning:o}:{}}}catch{return{skill:t,scripts:[],...o?{warning:o}:{}}}}async handleSkillRun(e){let t=Es(e,"skill");if(!t)return{error:"Missing required parameter: skill"};let r=Es(e,"script");if(!r)return{error:"Missing required parameter: script"};let o=await this.ensureExtracted(t);if(!o)return this.unavailableError(t);let n=Bx(o.dir,r);if(!n||!Wc(n))return{error:`Script not found: ${r}`};let i=this.ensureTurnOutputDir(),s=Date.now(),a=wK(e.input)?e.input:void 0,u=this.skills.get(t)?.secrets??{},c={...kK(),...u,OUTPUT_DIR:i,PYTHONUTF8:"1",PYTHONIOENCODING:"utf-8"},l=xK(Es(e,"args"),c),{command:f,prefixArgs:p}=this.resolveInterpreter(n),h=await new Promise(_=>{let v=uK(f,[...p,n,...l],{cwd:o.dir,env:c,timeout:mK,maxBuffer:gK},(w,k,S)=>{_({stdout:k,stderr:S,exitCode:typeof w?.code=="number"?w.code:0,error:w?w.message:void 0})});a&&v.stdin&&(v.stdin.write(JSON.stringify(a)),v.stdin.end())}),m=this.readNewOutputFiles(s),g=qx(o);return{stdout:h.stdout||void 0,stderr:h.stderr||void 0,exitCode:h.exitCode,error:h.error,outputFiles:m.length>0?m:void 0,...g?{warning:g}:{}}}resolveInterpreter(e){return e.endsWith(".py")?{command:this.pythonPath??(process.platform==="win32"?"python":"python3"),prefixArgs:[]}:process.platform==="win32"&&e.endsWith(".ps1")?{command:"powershell.exe",prefixArgs:["-NoProfile","-ExecutionPolicy","Bypass","-File"]}:{command:this.bashPath??"bash",prefixArgs:[]}}unavailableError(e){let t=this.installErrors.get(e);return t?{error:`${t} (install failed - call octavus_skill_setup with skill "${e}" to retry)`}:{error:`Skill "${e}" is not available on this device`}}ensureTurnOutputDir(){if(!this.turnOutputDir){let e=zA(4).toString("hex");this.turnOutputDir=vt(this.skillsDir,".runs",e,"output"),bp(this.turnOutputDir,{recursive:!0})}return this.turnOutputDir}readNewOutputFiles(e){if(!this.turnOutputDir)return[];let t;try{t=vp(this.turnOutputDir,{withFileTypes:!0})}catch{return[]}let r=[],o=0;for(let n of t){if(!n.isFile())continue;let i=vt(this.turnOutputDir,n.name);try{let s=cK(i),a=this.collectedFiles.get(n.name),u=!a,c=a!==void 0&&s.mtimeMs>e;if(!u&&!c)continue;let l=Fx(i);if(l.byteLength>_K)continue;if(o+l.byteLength>vK)break;o+=l.byteLength,r.push({name:n.name,path:i,mediaType:Vx(n.name),size:l.byteLength,contentBase64:l.toString("base64")}),this.collectedFiles.set(n.name,{size:s.size,mtimeMs:s.mtimeMs})}catch{}}return r}cleanupRuns(){let e=vt(this.skillsDir,".runs");try{yp(e,{recursive:!0,force:!0})}catch{}this.turnOutputDir=null,this.collectedFiles.clear()}async ensureExtracted(e){let t=this.extracted.get(e);if(t)return t;let r=this.inflight.get(e);if(r)return await r;let o=this.downloadAndExtract(e,{allowStaleFallback:!0}).catch(n=>(this.installErrors.set(e,n instanceof Error?n.message:String(n)),null)).finally(()=>{this.inflight.delete(e)});return this.inflight.set(e,o),await o}async downloadAndExtract(e,t){let r=this.skills.get(e);if(!r)return null;let o=vt(this.skillsDir,e),n=Wc(vt(o,"SKILL.md"))||Wc(vt(o,"scripts")),i=this.installedSha.get(e),s=r.bundleSha256!==void 0&&i!==r.bundleSha256;if(n&&!s){let u={slug:e,dir:o};return this.extracted.set(e,u),u}try{await this.installBundle(r,o)}catch(u){let c=u instanceof Error?u.message:String(u);if(t.allowStaleFallback&&n){let l={slug:e,dir:o,staleReason:c};return this.extracted.set(e,l),l}throw new Error(`Skill "${e}" bundle error: ${c}`,{cause:u})}this.installedSha.set(e,r.bundleSha256),this.installErrors.delete(e);let a={slug:e,dir:o};return this.extracted.set(e,a),a}async installBundle(e,t){let o=(this.installLocks.get(e.slug)??Promise.resolve()).then(()=>this.performBundleInstall(e,t));this.installLocks.set(e.slug,o.then(()=>{},()=>{})),await o}async performBundleInstall(e,t){if(!e.bundleUrl)throw new Error(`No bundle URL for skill "${e.slug}" - call octavus_skill_setup to (re)install it`);let r=await fetch(e.bundleUrl);if(!r.ok)throw new Error(`Bundle download failed: HTTP ${r.status} ${r.statusText}`);let o=Buffer.from(await r.arrayBuffer());if(e.bundleSha256){let i=pK("sha256").update(o).digest("hex");if(i!==e.bundleSha256)throw new Error(`Bundle SHA-256 mismatch: expected ${e.bundleSha256.slice(0,12)}..., got ${i.slice(0,12)}...`)}let n=`${t}.staging-${zA(4).toString("hex")}`;try{bp(n,{recursive:!0}),await EK(o,n),IA(vt(n,TA),JSON.stringify({sha256:e.bundleSha256??null})),yp(t,{recursive:!0,force:!0}),aK(n,t)}catch(i){throw yp(n,{recursive:!0,force:!0}),i}}sweepStagingDirs(){let e;try{e=vp(this.skillsDir,{withFileTypes:!0})}catch{return}for(let t of e)if(!(!t.isDirectory()||!t.name.includes(".staging-")))try{yp(vt(this.skillsDir,t.name),{recursive:!0,force:!0})}catch{}}};function Es(e,t){let r=e[t];return typeof r=="string"&&r.length>0?r:void 0}function qx(e){return e.staleReason?`Using the previously installed version of "${e.slug}" - the latest bundle failed to install: ${e.staleReason}`:void 0}function wK(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Bx(e,t){let r=dK(vt(e,t)),o=PA(e,r);return o===".."||o.startsWith(`..${fK}`)?null:r}function xK(e,t){return e?process.platform==="win32"?SK(e,t):(0,OA.parse)(e,t).filter(r=>typeof r=="string"):[]}function SK(e,t){let r=[],o="",n=!1,i=!1;for(let s of e){if(s==='"'){n=!n,i=!0;continue}if(!n&&(s===" "||s===" ")){i&&(r.push(o),o="",i=!1);continue}o+=s,i=!0}return i&&r.push(o),r.map(s=>$K(s,t))}function $K(e,t){let r=e.replace(/%([A-Za-z_][A-Za-z0-9_()]*)%/g,(o,n)=>t[n]??o);return r=r.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(o,n)=>t[n]??""),r=r.replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(o,n)=>t[n]??""),r}function kK(){let e={};for(let t of bK){let r=process.env[t];typeof r=="string"&&(e[t]=r)}return e}async function EK(e,t){let o=await(await Promise.resolve().then(()=>We(EA(),1))).default.loadAsync(e),n=Object.keys(o.files).filter(s=>!o.files[s].dir);if(n.length===0)return;let i=zK(n);for(let s of n){if(s.includes("__MACOSX/"))continue;let a=i?s.slice(i.length):s;if(!a)continue;let u=Bx(t,a);if(!u)continue;let l=await o.files[s].async("nodebuffer");if(l.byteLength>yK)throw new Error(`Skill bundle entry too large: ${s}`);bp(lK(u),{recursive:!0}),IA(u,l)}}function zK(e){let t=null;for(let r of e){if(r.startsWith("__MACOSX/"))continue;let o=r.indexOf("/");if(o===-1)return null;let n=r.slice(0,o+1);if(t===null)t=n;else if(t!==n)return null}return t}import{stat as DK,readFile as jK}from"fs/promises";import{basename as UK,resolve as Hx,isAbsolute as jA,relative as LK,sep as MK}from"path";var wp={info(e,t){console.log(JSON.stringify({level:"info",message:e,...t,ts:new Date().toISOString()}))},warn(e,t){console.warn(JSON.stringify({level:"warn",message:e,...t,ts:new Date().toISOString()}))},error(e,t,r){let o=t instanceof Error?{error:t.message,stack:t.stack}:{error:t};console.error(JSON.stringify({level:"error",message:e,...o,...r,ts:new Date().toISOString()}))}},TK=1e3,IK=3e4,PK=.25,OK=60,RA=50,RK=6e4,CK=1e4,AK=45e3,NK=1e4,DA=class{config;log;ws=null;state="disconnected";reconnectAttempts=0;reconnectTimer=null;heartbeatTimer=null;livenessTimer=null;lastPingAt=0;intentionalClose=!1;hadDisconnect=!1;pendingLifecycle=[];constructor(e){this.config=e,this.log=e.logger??wp}getState(){return this.state}connect(){this.state==="connected"||this.state==="connecting"||(this.intentionalClose=!1,this.openWebSocket())}updateToken(e){this.config={...this.config,computerToken:e}}disconnect(){this.intentionalClose=!0,this.hadDisconnect=!1,this.clearTimers(),this.closeSocket("Client disconnect"),this.pendingLifecycle=[],this.setState("disconnected")}async closeGracefully(e=3e3){this.intentionalClose=!0,this.hadDisconnect=!1,this.clearTimers(),this.pendingLifecycle=[],this.setState("disconnected");let t=this.ws;this.ws=null,t&&await new Promise(r=>{let o=!1,n=null,i=()=>{o||(o=!0,n&&clearTimeout(n),r())};t.removeAllListeners(),t.on("close",i),t.on("error",i),t.readyState===kn.OPEN||t.readyState===kn.CONNECTING?(t.close(1e3,"Client disconnect"),n=setTimeout(()=>{try{t.terminate()}catch{}i()},e)):i()})}resetAndReconnect(){this.intentionalClose=!1,this.clearTimers(),this.closeSocket("Reset for reconnect"),this.reconnectAttempts=0,this.openWebSocket()}closeSocket(e){if(!this.ws)return;let t=this.ws;this.ws=null,t.removeAllListeners(),t.on("error",()=>{}),(t.readyState===kn.OPEN||t.readyState===kn.CONNECTING)&&t.close(1e3,e)}sendSessionEvent(e,t,r){this.send({type:"session-event",sessionId:e,event:t,seq:r})}sendSessionState(e,t,r){this.send({type:"session-state",sessionId:e,events:t,lastSeq:r})}sendSessionStarted(e){this.send({type:"session-started",sessionId:e})}sendSessionComplete(e,t,r,o,n){this.send({type:"session-complete",sessionId:e,status:t,error:r,errorType:o,title:n})}sendSessionTitle(e,t){this.send({type:"session-title",sessionId:e,title:t})}sendSessionRetry(e,t){this.send({type:"session-retry",sessionId:e,attempt:t.attempt,reason:t.reason,delayMs:t.delayMs})}sendDispatchAck(e){this.send({type:"dispatch-ack",sessionId:e})}openWebSocket(){this.setState("connecting");let e=new URL("/ws/computer",this.config.operatorWsUrl);e.searchParams.set("token",this.config.computerToken),this.ws=new kn(e.toString(),{handshakeTimeout:CK}),this.ws.on("open",()=>{let t=this.reconnectAttempts>0||this.hadDisconnect;this.reconnectAttempts=0,this.hadDisconnect=!1,this.setState("connected"),this.send({type:"sync",octoAgentIds:[this.config.octoAgentId],activeSessionIds:this.config.getActiveSessionIds?.()}),this.flushPendingLifecycle(),this.startHeartbeat(),this.startPingLiveness(),this.log.info("Connected to operator",{octoAgentId:this.config.octoAgentId,isReconnect:t}),t&&this.config.onReconnected?.()}),this.ws.on("message",t=>{let r=typeof t=="string"?t:Buffer.from(t).toString("utf8");this.handleMessage(r)}),this.ws.on("ping",()=>{this.lastPingAt=Date.now()}),this.ws.on("close",(t,r)=>{this.log.info("WebSocket closed",{octoAgentId:this.config.octoAgentId,code:t,reason:r?.toString()}),this.onDisconnect(t)}),this.ws.on("error",t=>{this.log.error("WebSocket error",t,{octoAgentId:this.config.octoAgentId})})}handleMessage(e){let t;try{t=vP.parse(JSON.parse(e))}catch{this.log.warn("Invalid message from operator",{octoAgentId:this.config.octoAgentId});return}switch(t.type){case"dispatch":this.config.onDispatch(t);break;case"stop":this.config.onStop(t.sessionId);break;case"request-session-state":this.config.onRequestSessionState(t.sessionId);break;case"start-screen-stream":case"device-reconnect":case"device-reconnect-agents":case"device-restart":case"start-voice-call":case"read-slack-prefs":this.config.onDeviceControl?.(t);break;case"heartbeat":break}}onDisconnect(e){if(this.clearTimers(),this.ws=null,this.intentionalClose){this.setState("disconnected");return}if(this.hadDisconnect=!0,e===bP){this.log.info("Connection revoked by operator, not reconnecting",{octoAgentId:this.config.octoAgentId}),this.config.onDisconnected?.({revoked:!0}),this.setState("disconnected");return}if(this.config.onDisconnected?.({revoked:!1}),this.reconnectAttempts>=OK){this.log.error("Max reconnect attempts reached",void 0,{octoAgentId:this.config.octoAgentId,attempts:this.reconnectAttempts}),this.setState("disconnected");return}this.setState("reconnecting"),this.scheduleReconnect()}scheduleReconnect(){let e=Math.min(TK*2**this.reconnectAttempts,IK),t=e*PK*(Math.random()*2-1),r=Math.max(0,e+t);this.reconnectAttempts+=1,this.log.info("Scheduling reconnect",{octoAgentId:this.config.octoAgentId,attempt:this.reconnectAttempts,delayMs:Math.round(r)}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.openWebSocket()},r)}startHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=setInterval(()=>{this.send({type:"heartbeat"})},yP)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}startPingLiveness(){this.stopPingLiveness(),this.lastPingAt=Date.now(),this.livenessTimer=setInterval(()=>{Date.now()-this.lastPingAt<=AK||(this.log.warn("No ping from operator - terminating stale socket",{octoAgentId:this.config.octoAgentId}),this.ws?.terminate())},NK)}stopPingLiveness(){this.livenessTimer&&(clearInterval(this.livenessTimer),this.livenessTimer=null)}clearTimers(){this.stopHeartbeat(),this.stopPingLiveness(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}send(e){this.ws?.readyState===kn.OPEN?this.ws.send(JSON.stringify(e)):(e.type==="session-started"||e.type==="session-complete"||e.type==="dispatch-ack")&&(this.pendingLifecycle.length<RA?(this.pendingLifecycle.push({msg:e,at:Date.now()}),this.log.info("Buffered lifecycle message for reconnect",{type:e.type,sessionId:"sessionId"in e?e.sessionId:void 0,buffered:this.pendingLifecycle.length})):this.log.warn("Lifecycle buffer full, dropping message",{type:e.type,sessionId:"sessionId"in e?e.sessionId:void 0,cap:RA}))}setState(e){this.state!==e&&(this.state=e,this.config.onStateChange?.(e))}flushPendingLifecycle(){if(this.pendingLifecycle.length===0)return;let e=Date.now(),t=this.pendingLifecycle.filter(({at:r})=>e-r<RK);if(this.pendingLifecycle=[],t.length!==0){this.log.info("Flushing buffered lifecycle messages",{count:t.length});for(let{msg:r}of t)this.ws?.readyState===kn.OPEN&&this.ws.send(JSON.stringify(r))}}},UA=1,Gx=600,ZK=d.object({seconds:d.number().min(UA).max(Gx)}),FK=Ab.length+1,qK=800*1e3,Jx=120*1e3,BK=qK+Gx*1e3+Jx+120*1e3,VK=class{config;client;abortController=null;agentSession=null;title=null;eventBuffer=[];nextSeq=0;stalledByWatchdog=!1;stallTimer=null;constructor(e){this.config=e,this.client=new Gb({baseUrl:e.platformUrl,apiKey:e.operatorToken,traceModelRequests:e.traceModelRequests})}get sessionId(){return this.config.sessionId}updateConfig(e){this.config=e,this.client=new Gb({baseUrl:e.platformUrl,apiKey:e.operatorToken,traceModelRequests:e.traceModelRequests}),this.title=null,this.eventBuffer=[],this.nextSeq=0}async execute(){this.abortController=new AbortController,this.stalledByWatchdog=!1;let e;for(let t=0;t<FK;t++){let r=await this.runOnce();if(r.kind==="completed"||r.kind==="hard-error")return r.sessionResult;r.kind==="provider-error"&&(e=r.sessionResult);let o=Ab[t];if(o===void 0||this.abortController.signal.aborted||(this.config.onRetry?.(t+1,r.kind,o),await this.sleepUnlessAborted(o),this.abortController.signal.aborted))break;this.resetForRetry()}return this.abortController.signal.aborted?{status:"completed",title:this.title??void 0}:e||{status:"failed",error:"Lost connection to platform after multiple retry attempts",errorType:"transport",title:this.title??void 0}}async runOnce(){let{sessionId:e,trigger:t,onEvent:r}=this.config;this.agentSession??=this.createAgentSession();try{let o=this.agentSession.execute({type:"trigger",triggerName:t.triggerName,input:t.input,sender:t.sender},{signal:this.abortController.signal}),n=null,i=!1;this.bumpStallWatchdog();for await(let s of o){if(this.abortController.signal.aborted)break;let a=this.nextSeq;this.nextSeq+=1;let u=s;this.eventBuffer.push({seq:a,event:u}),r(e,s,a),this.bumpStallWatchdog(),s.type==="finish"?(this.eventBuffer=[],i=!0):(i=!1,s.type==="error"&&(n=u))}if(i)return{kind:"completed",sessionResult:{status:"completed",title:this.title??void 0}};if(this.stalledByWatchdog)return{kind:"hard-error",sessionResult:this.stallResult()};if(n){let s=lP(n,this.title);return s.retryable?{kind:"provider-error",sessionResult:s}:{kind:"hard-error",sessionResult:s}}return{kind:"transport-drop"}}catch(o){if(this.stalledByWatchdog)return{kind:"hard-error",sessionResult:this.stallResult()};if(this.abortController.signal.aborted)return{kind:"completed",sessionResult:{status:"completed",title:this.title??void 0}};let n=bf(o);if(n==="transport")return{kind:"transport-drop"};let i=yf(o),s=xf.isInstance(o)?o:new xf({errorType:"internal_error",message:i,source:"platform",retryable:!1,cause:o}),a=Nb(s),u=this.nextSeq;return this.nextSeq+=1,this.eventBuffer.push({seq:u,event:a}),r(e,a,u),n==="network"||n==="timeout"?{kind:"network-error"}:{kind:"hard-error",sessionResult:{status:"failed",error:i,errorType:n,title:this.title??void 0}}}finally{this.clearStallWatchdog()}}bumpStallWatchdog(){this.clearStallWatchdog(),this.stallTimer=setTimeout(()=>{this.stallTimer=null,this.stalledByWatchdog=!0,this.abortController?.abort()},BK)}clearStallWatchdog(){this.stallTimer&&(clearTimeout(this.stallTimer),this.stallTimer=null)}stallResult(){return{status:"failed",error:"The run stopped making progress and was ended. Send a message to continue.",errorType:"transport",title:this.title??void 0}}getBufferedEvents(){return{events:this.eventBuffer.map(e=>e.event),lastSeq:this.nextSeq>0?this.nextSeq-1:-1}}stop(){this.abortController?.abort()}createAgentSession(){let{sessionId:e,computer:t,tools:r}=this.config,o=this.client.agentSessions.attach(e,{tools:this.buildStaticToolHandlers(r,t),onToolResults:n=>this.uploadToolResults(n,e),onToolResultTruncated:n=>{(this.config.logger??wp).warn("Tool result too large; reduced to a preview before sending",{sessionId:e,toolName:n.toolName,originalBytes:n.originalBytes,keptBytes:n.keptBytes,variableCapture:n.variableCapture})},rejectClientToolCalls:!0});return o.setDynamicTools(t),o}async uploadToolResults(e,t){this.stallTimer&&this.bumpStallWatchdog();let r=(async()=>{await r1(e,this.client.files,t),await o1(e,this.client.files,t)})(),o,n=new Promise(i=>{o=setTimeout(()=>i("timeout"),Jx)});try{await Promise.race([r.then(()=>"done"),n])==="timeout"&&((this.config.logger??wp).warn("Tool result upload exceeded its time budget; continuing without full offload",{sessionId:t,budgetMs:Jx}),r.catch(()=>{}))}finally{o&&clearTimeout(o)}}resetForRetry(){this.eventBuffer=[],this.agentSession=this.createAgentSession()}sleepUnlessAborted(e){return new Promise(t=>{let r=this.abortController?.signal;if(r?.aborted){t();return}let o=null,n=()=>{o!==null&&clearTimeout(o),t()};o=setTimeout(()=>{r?.removeEventListener("abort",n),t()},e),r?.addEventListener("abort",n,{once:!0})})}buildStaticToolHandlers(e,t){let r=d.object({title:d.string().min(1)}),o={"set-chat-title":n=>{let i=r.safeParse(n);return i.success?(this.title=i.data.title,this.config.onTitleChange?.(this.config.sessionId,i.data.title),Promise.resolve({success:!0,title:i.data.title})):Promise.resolve({success:!1,error:"Title must be a non-empty string"})},wait:n=>this.handleWait(n)};return t&&(o["computer-ensure-ready"]=()=>this.handleEnsureReady(),o["computer-get-status"]=()=>this.handleGetStatus(),o["computer-reset"]=()=>this.handleReset()),e&&Object.assign(o,e),o}async handleEnsureReady(){let e=this.config.computer,{environment:t}=this.config;if(lc(e))try{let r=await e.ensureReady();return this.agentSession?.setDynamicTools(e),{ready:r.healthy,tools:e.toolSchemas().map(o=>o.name),...(r.recovered?.length??0)>0&&{recovered:r.recovered},...(r.failedEntries?.length??0)>0&&{failedEntries:r.failedEntries},...t&&{environment:t}}}catch(r){return{ready:!1,error:r instanceof Error?r.message:String(r)}}return{ready:!0,tools:e.toolSchemas().map(r=>r.name),...t&&{environment:t}}}async handleGetStatus(){let e=this.config.computer;if(lc(e))try{let t=await e.getHealth();return{ready:t.healthy,tools:t.totalTools,entries:t.entries}}catch(t){return{ready:!1,error:t instanceof Error?t.message:String(t)}}return{ready:!0,schemasAvailable:!0,tools:e.toolSchemas().length}}async handleReset(){let{onComputerReset:e}=this.config;if(!e)return{ready:!1,error:"Reset not available"};try{let t=await e();return this.config.computer=t,this.agentSession?.setDynamicTools(t),{ready:lc(t)?(await t.getHealth()).healthy:!0,tools:t.toolSchemas().map(o=>o.name),reset:!0}}catch(t){return{ready:!1,error:t instanceof Error?t.message:String(t)}}}handleWait(e){let t=ZK.safeParse(e);if(!t.success)return Promise.resolve({success:!1,error:`seconds must be a number between ${UA} and ${Gx}`});let r=Math.round(t.data.seconds*1e3),o=this.abortController?.signal;return new Promise(n=>{if(o?.aborted){n({success:!0,waited_ms:0,aborted:!0});return}let i=setTimeout(()=>n({success:!0,waited_ms:r}),r);o?.addEventListener("abort",()=>{clearTimeout(i),n({success:!0,waited_ms:0,aborted:!0})},{once:!0})})}},WK=5e3,HK=10*6e4,JK=6e4,CA=20*1024*1024,AA=4e4;function GK(e){return new Promise(t=>{setTimeout(t,e)})}var KK=d.object({slug:d.string().min(1)}),YK=d.object({command:d.string().min(1),args:d.array(d.string()).optional(),env:d.record(d.string(),d.string()).optional(),connection:d.enum(["eager","lazy"]).optional()});function NA(e){return JSON.stringify({command:e.command,args:e.args,env:e.env,connection:e.connection})}var LA=class{config;log;activeExecutors=new Map;executorCache=new Map;cancelledSessions=new Map;terminalFailures=new Map;connectionLossTimer=null;idleCleanupTimer=null;afterSessionTimer=null;running=!1;resolvedComputer=null;computerPromise=null;currentDeviceMcpFingerprints=new Map;deviceSkillHandler=null;activeToolHandlers=null;oneShotResolvers=new Map;constructor(e){this.config=e,this.log=e.logger??wp}start(){this.running||(this.running=!0,this.idleCleanupTimer=setInterval(()=>this.cleanupIdleExecutors(),6e4))}async stop(){if(this.running=!1,this.cancelConnectionLossTimer(),this.idleCleanupTimer&&(clearInterval(this.idleCleanupTimer),this.idleCleanupTimer=null),this.afterSessionTimer&&(this.cancelAfterSessionTimer(),await this.fireAfterSession()),this.activeExecutors.size>0){for(let t of this.activeExecutors.values())t.stop();let e=Date.now()+WK;for(;this.activeExecutors.size>0&&Date.now()<e;)await GK(200);this.activeExecutors.size>0&&(this.log.warn("Drain timed out, forcing cleanup",{remaining:this.activeExecutors.size}),this.activeExecutors.clear(),this.notifyStateChange())}this.executorCache.clear(),this.cancelledSessions.clear()}getActiveSessions(){return[...this.activeExecutors.keys()].map(e=>({sessionId:e,octoAgentId:this.config.octoAgentId}))}isExecuting(){return this.activeExecutors.size>0}resetComputer(){this.resolvedComputer=null,this.computerPromise=null,this.currentDeviceMcpFingerprints.clear()}handleDispatch(e){return this.running?(this.cancelAfterSessionTimer(),this.activeExecutors.has(e.sessionId)?(this.log.warn("Ignoring duplicate dispatch for active session",{sessionId:e.sessionId}),this.config.connection.sendDispatchAck(e.sessionId),!0):(this.config.connection.sendDispatchAck(e.sessionId),this.executeSession(e).catch(t=>{this.log.error("Session execution threw outside its handler",t,{sessionId:e.sessionId})}),!0)):!1}async runLocalDispatch(e){let t=new Promise(r=>{this.oneShotResolvers.set(e.sessionId,r)});if(!this.handleDispatch(e))throw this.oneShotResolvers.delete(e.sessionId),new Error("SessionManager is not running");return await t}emitSessionComplete(e,t,r,o,n){this.config.connection.sendSessionComplete(e,t,r,o,n);let i=this.oneShotResolvers.get(e);i&&(this.oneShotResolvers.delete(e),i({status:t,error:r,errorType:o,title:n}))}handleStop(e){let t=this.activeExecutors.get(e);t?t.stop():this.cancelledSessions.set(e,Date.now())}handleConnectionLost(e){if(e.revoked){this.cancelConnectionLossTimer(),this.failActiveSessions("Operator connection revoked");return}this.activeExecutors.size!==0&&(this.connectionLossTimer||(this.log.warn("Operator connection lost with active sessions - starting grace window",{activeSessions:this.activeExecutors.size,graceMs:AA}),this.connectionLossTimer=setTimeout(()=>{this.connectionLossTimer=null,this.failActiveSessions("Operator connection lost",{report:!0})},AA)))}handleConnectionRestored(){this.connectionLossTimer&&(this.cancelConnectionLossTimer(),this.log.info("Operator connection restored within grace window - sessions continue"))}cancelConnectionLossTimer(){this.connectionLossTimer&&(clearTimeout(this.connectionLossTimer),this.connectionLossTimer=null)}failActiveSessions(e,t={}){if(this.activeExecutors.size!==0)for(let[r,o]of this.activeExecutors)this.terminalFailures.set(r,{reason:e,report:t.report??!1}),o.stop()}handleRequestSessionState(e){let t=this.activeExecutors.get(e);if(t){let{events:r,lastSeq:o}=t.getBufferedEvents();this.config.connection.sendSessionState(e,r,o)}else this.config.connection.sendSessionState(e,[],-1)}async getComputer(){if(this.resolvedComputer)return this.resolvedComputer;if(!this.computerPromise){let{computer:e}=this.config;this.computerPromise=typeof e=="function"?e():Promise.resolve(e)}return this.resolvedComputer=await this.computerPromise,this.resolvedComputer}consumeCancellation(e){return this.cancelledSessions.has(e)?(this.cancelledSessions.delete(e),this.log.info("Session was cancelled before execution started",{sessionId:e}),this.emitSessionComplete(e,"completed"),!0):!1}async executeSession(e){let{sessionId:t,operatorToken:r,trigger:o}=e;try{let n;try{n=await this.getComputer()}catch(a){let u=yf(a);this.log.error("Computer factory failed",a,{sessionId:t});let c=bf(a);this.emitSessionComplete(t,"failed",u,c==="transport"?"network":c);return}if(this.consumeCancellation(t))return;if(await this.reconcileDeviceMcps(n,e.deviceMcpConfigs),this.reconcileDeviceSkills(e.deviceSkillConfigs),this.config.onBeforeSession)try{await this.config.onBeforeSession()}catch(a){this.log.error("onBeforeSession failed",a)}if(this.consumeCancellation(t))return;let i=this.buildDeviceToolHandlers(n,e),s=this.getOrCreateExecutor(t,r,o,n,i);this.activeExecutors.set(t,s),this.notifyStateChange(),this.config.connection.sendSessionStarted(t);try{let a=await s.execute();if(this.consumeTerminalFailure(t))return;this.emitSessionComplete(t,a.status,a.error,a.errorType,a.title)}catch(a){if(this.consumeTerminalFailure(t))return;this.log.error("Session execution failed unexpectedly",a,{sessionId:t}),this.emitSessionComplete(t,"failed","Internal execution error","platform")}finally{this.deviceSkillHandler?.cleanupRuns(),this.terminalFailures.delete(t),this.activeExecutors.delete(t),this.notifyStateChange(),this.config.onAfterSession&&this.activeExecutors.size===0&&this.scheduleAfterSession()}}finally{let n=this.oneShotResolvers.get(t);n&&(this.oneShotResolvers.delete(t),n({status:"failed",error:"Run ended without completing",errorType:"network"})),this.config.onSessionSettled?.(t)}}consumeTerminalFailure(e){let t=this.terminalFailures.get(e);return t?(this.log.warn("Session aborted after operator disconnect",{sessionId:e,reason:t.reason}),t.report&&this.emitSessionComplete(e,"failed",t.reason,"network"),!0):!1}async reconcileDeviceMcps(e,t){if(!Ki(e)){t&&t.length>0&&this.log.warn("Device MCP configs provided but Computer does not support dynamic entries",{namespaces:t.map(o=>o.namespace)});return}let r=new Map;for(let o of t??[])r.set(o.namespace,o);for(let o of[...this.currentDeviceMcpFingerprints.keys()])if(!r.has(o))try{await e.removeEntry(o),this.currentDeviceMcpFingerprints.delete(o)}catch(n){this.log.warn("Failed to remove device MCP entry",{namespace:o,error:String(n)})}for(let[o,n]of r){let i=NA(n);if(this.currentDeviceMcpFingerprints.get(o)!==i){if(this.currentDeviceMcpFingerprints.has(o)){try{await e.removeEntry(o)}catch(s){this.log.warn("Failed to replace device MCP entry",{namespace:o,error:String(s)})}this.currentDeviceMcpFingerprints.delete(o)}try{await e.addEntry(o,{type:"stdio",command:n.command,args:n.args,env:n.env},{deferred:n.connection==="lazy"}),this.currentDeviceMcpFingerprints.set(o,i)}catch(s){this.log.warn("Failed to add device MCP entry",{namespace:o,error:String(s)})}}}}reconcileDeviceSkills(e){if(!e||e.length===0){this.deviceSkillHandler=null;return}if(!this.config.deviceSkillsDir){this.log.warn("Device skill configs provided but no deviceSkillsDir configured",{slugs:e.map(r=>r.slug)});return}let t=e.map(r=>({slug:r.slug,bundleUrl:r.bundleUrl,bundleSha256:r.bundleSha256,secrets:r.secrets}));this.deviceSkillHandler?this.deviceSkillHandler.setSkills(t):this.deviceSkillHandler=new Wx({skills:t,skillsDir:this.config.deviceSkillsDir,pythonPath:this.config.pythonPath})}buildDeviceToolHandlers(e,t){let r=!!(this.deviceSkillHandler&&(t.deviceSkillConfigs?.length??0)>0),o=(t.deviceMcpConfigs?.length??0)>0&&Ki(e),n=Ki(e),i=!!this.config.deviceSkillsDir,s=!!this.config.agentWorkspaceDir;if(!r&&!o&&!n&&!i&&!s)return this.activeToolHandlers=null,this.config.tools;let a={...this.config.tools??{}};if(this.activeToolHandlers=a,r){let u=this.deviceSkillHandler.toolHandlers();a[at.SKILL_READ]=u[at.SKILL_READ],a[at.SKILL_LIST]=u[at.SKILL_LIST],a[at.SKILL_RUN]=u[at.SKILL_RUN]}if(i&&(a[at.SKILL_SETUP]=u=>this.handleSkillSetup(u)),n&&(a[Fb.MCP_ACTIVATE]=u=>this.handleDeviceMcpActivate(e,u)),s){let u=this.config.agentWorkspaceDir;a[at.FILE_UPLOAD]=c=>this.handleFileUpload(c,u)}return a}async handleSkillSetup(e){let t=typeof e.skill=="string"?e.skill:void 0;if(!t)return{error:"Missing required parameter: skill"};let r=typeof e.bundleUrl=="string"?e.bundleUrl:void 0;if(!r)return{error:`Skill "${t}" could not be resolved - bundleUrl missing`};let o=typeof e.bundleSha256=="string"?e.bundleSha256:void 0,n=typeof e.secrets=="object"&&e.secrets!==null&&!Array.isArray(e.secrets)?e.secrets:{},i={slug:t,bundleUrl:r,bundleSha256:o,secrets:n};if(!this.deviceSkillHandler){if(!this.config.deviceSkillsDir)return{error:"Device skills are not configured on this device"};this.deviceSkillHandler=new Wx({skills:[i],skillsDir:this.config.deviceSkillsDir,pythonPath:this.config.pythonPath})}let s=await this.deviceSkillHandler.setupSkill(i);if(s.installed&&this.activeToolHandlers){let a=this.deviceSkillHandler.toolHandlers();this.activeToolHandlers[at.SKILL_READ]=a[at.SKILL_READ],this.activeToolHandlers[at.SKILL_LIST]=a[at.SKILL_LIST],this.activeToolHandlers[at.SKILL_RUN]=a[at.SKILL_RUN]}return s}async handleDeviceMcpActivate(e,t){let r=KK.safeParse(t);if(!r.success)return{error:"slug is required"};if(!Ki(e))return{error:"This computer does not support dynamic MCP activation"};let{slug:o}=r.data,n=YK.safeParse(t.deviceConfig);if(n.success&&!this.currentDeviceMcpFingerprints.has(o)){let a=n.data;try{let u=a.connection==="eager"?"eager":"lazy",c=a.args??[],l=a.env??{};await e.addEntry(o,{type:"stdio",command:a.command,args:c,env:l},{deferred:u==="lazy"}),this.currentDeviceMcpFingerprints.set(o,NA({namespace:o,name:o,description:"",command:a.command,args:c,env:l,connection:u}))}catch(u){return{error:u instanceof Error?u.message:String(u)}}}if(!this.currentDeviceMcpFingerprints.has(o))return{error:`MCP "${o}" is not registered on this device. Call computer-reset to refresh the device's MCP set.`};try{await e.restartEntry(o)}catch(a){return{error:a instanceof Error?a.message:String(a)}}let i=`${o}__`;return{activated:!0,tools:e.toolSchemas().filter(a=>a.name.startsWith(i))}}async handleFileUpload(e,t){let r=typeof e.path=="string"?e.path.trim():"";if(!r)return{error:"Missing required parameter: path"};let o=Hx(t),n=jA(r)?r:Hx(o,r),i=Hx(n);if(!XK(i,o))return{error:`Path is outside the agent workspace (${o}). Only files inside the workspace can be uploaded.`};let s;try{s=await DK(i)}catch{return{error:`File not found: ${i}`}}if(!s.isFile())return{error:`Path is not a file: ${i}`};if(s.size>CA)return{error:`File exceeds maximum upload size of ${CA/(1024*1024)}MB`};let a;try{a=await jK(i)}catch(l){return{error:l instanceof Error?l.message:"Failed to read file"}}let u=UK(i),c=Vx(u);return{outputFiles:[{name:u,path:i,mediaType:c,size:a.byteLength,contentBase64:a.toString("base64")}]}}getOrCreateExecutor(e,t,r,o,n){let i=(p,h,m)=>{this.config.connection.sendSessionEvent(e,h,m)},s=this.config.onComputerReset,a=s?async()=>{let p=await s();return this.resolvedComputer=p,this.currentDeviceMcpFingerprints.clear(),p}:void 0,u=(p,h)=>{this.config.connection.sendSessionTitle(e,h)},c={sessionId:e,operatorToken:t,trigger:r,platformUrl:this.config.platformUrl,computer:o,onEvent:i,onTitleChange:u,onRetry:(p,h,m)=>{this.log.warn("Retrying session execution",{sessionId:e,attempt:p,reason:h,delayMs:m}),this.config.connection.sendSessionRetry(e,{attempt:p,reason:h,delayMs:m})},tools:n??this.config.tools,onComputerReset:a,traceModelRequests:this.config.traceModelRequests,environment:this.config.environment,logger:this.log},l=this.executorCache.get(e);if(l)return l.lastActiveAt=Date.now(),l.executor.updateConfig(c),this.log.info("Reusing executor for session",{sessionId:e}),l.executor;let f=new VK(c);return this.executorCache.set(e,{executor:f,lastActiveAt:Date.now()}),f}cancelAfterSessionTimer(){this.afterSessionTimer&&(clearTimeout(this.afterSessionTimer),this.afterSessionTimer=null)}scheduleAfterSession(){if(this.cancelAfterSessionTimer(),!this.running)return;let e=this.config.idleTimeoutMs??0;if(e<=0){this.fireAfterSession();return}this.afterSessionTimer=setTimeout(()=>{this.afterSessionTimer=null,this.fireAfterSession()},e)}async fireAfterSession(){if(!(this.activeExecutors.size>0))try{await this.config.onAfterSession?.()}catch(e){this.log.error("onAfterSession failed",e)}}cleanupIdleExecutors(){let e=Date.now();for(let[t,r]of this.executorCache)e-r.lastActiveAt>HK&&!this.activeExecutors.has(t)&&(this.log.info("Removing idle executor cache for session",{sessionId:t}),this.executorCache.delete(t));for(let[t,r]of this.cancelledSessions)e-r>JK&&this.cancelledSessions.delete(t)}notifyStateChange(){this.config.onSessionStateChange?.(this.getActiveSessions())}};function XK(e,t){if(e===t)return!0;let r=LK(t,e);return r===""?!0:r.startsWith("..")||jA(r)?!1:!r.split(MK).includes("..")}import{homedir as QK}from"os";import{join as Hc}from"path";import{mkdirSync as MA,readFileSync as e7,writeFileSync as t7}from"fs";var r7="production",n7={production:"https://octavus.ai",local:"http://localhost:3000"};function Jc(e){let t=(e||process.env.OCTAVUS_ENV||r7).trim();if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(t))throw new Error(`Invalid environment "${t}": use letters, digits, dot, underscore, or hyphen (e.g. production, staging).`);return t}function zs(e){return process.env.OCTAVUS_HOME||Hc(QK(),".octavus",e)}function ZA(e){return Hc(zs(e),"config.json")}function Ts(e){try{let t=e7(ZA(e),"utf8"),r=JSON.parse(t);return typeof r=="object"&&r!==null?r:{}}catch{return{}}}function FA(e,t){let r=zs(e);MA(r,{recursive:!0,mode:448});let o={...Ts(e),...t};return t7(ZA(e),`${JSON.stringify(o,null,2)}
|
|
70
|
+
`);k=W.pop()??"";for(let U of W)if(U.startsWith("data: ")&&U!=="data: [DONE]")try{let De=Zb(JSON.parse(U.slice(6)));if(!De.success)continue;let xe=De.data;if(xe.type==="start"&&xe.executionId&&(n=xe.executionId),xe.type==="start"&&xe.sessionId&&e.onSessionId?.(xe.sessionId),xe.type==="tool-request"){_=xe.toolCalls;continue}if(xe.type==="finish"){if(xe.finishReason==="tool-calls"&&_)continue;yield xe,i=!1;continue}xe.type==="resource-update"&&e.onResourceUpdate&&e.onResourceUpdate(xe.name,xe.value),yield xe}catch{}}}finally{m&&g&&r&&r.removeEventListener("abort",g)}if(r?.aborted){yield{type:"finish",finishReason:"stop"};return}if(_&&_.length>0){let v=e.getToolHandlers(),w=_.filter(T=>v[T.toolName]),k=_.filter(T=>!v[T.toolName]),S=Promise.all(w.map(async T=>{let C=v[T.toolName];try{let N=await C(T.args);return{toolCallId:T.toolCallId,toolName:T.toolName,result:N,outputVariable:T.outputVariable,blockIndex:T.blockIndex,thread:T.thread,workerId:T.workerId}}catch(N){return{toolCallId:T.toolCallId,toolName:T.toolName,error:N instanceof Error?N.message:"Tool execution failed",outputVariable:T.outputVariable,blockIndex:T.blockIndex,thread:T.thread,workerId:T.workerId}}})),b;if(r&&!r.aborted){let T,C=new Promise(I=>{T=()=>I("aborted"),r.addEventListener("abort",T,{once:!0})}),N;try{N=await Promise.race([S,C])}finally{T&&r.removeEventListener("abort",T)}if(N==="aborted"){yield{type:"finish",finishReason:"stop"};return}b=N}else if(r?.aborted){yield{type:"finish",finishReason:"stop"};return}else b=await S;if(e.onToolResults&&b.length>0&&await e.onToolResults(b),r?.aborted){yield{type:"finish",finishReason:"stop"};return}for(let T of b)T.error?yield{type:"tool-output-error",toolCallId:T.toolCallId,error:T.error}:yield{type:"tool-output-available",toolCallId:T.toolCallId,output:T.result};if(k.length>0)if(e.rejectClientToolCalls){let T=k.map(C=>({toolCallId:C.toolCallId,toolName:C.toolName,error:`Tool "${C.toolName}" is not available. No handler is registered for this tool.`,outputVariable:C.outputVariable,blockIndex:C.blockIndex,thread:C.thread,workerId:C.workerId}));for(let C of T)yield{type:"tool-output-error",toolCallId:C.toolCallId,error:C.error};o=[...b,...T]}else{if(!n){yield Gi("Missing executionId for client-tool-request");return}yield{type:"client-tool-request",executionId:n,toolCalls:k,serverToolResults:b.length>0?b:void 0},yield{type:"finish",finishReason:"client-tool-calls",executionId:n},i=!1}else o=b}else i=!1}}function Jb(e,t,r){let o=new Set,n={...t},i=r?[...r]:[],s=new Set(i.map(a=>a.name));for(let a of e){if(o.has(a.namespace))throw new Error(`Duplicate MCP namespace "${a.namespace}". Each inline MCP server must have a unique namespace.`);o.add(a.namespace);let u=a.toolHandlers(),c=a.toolSchemas();for(let[l,f]of Object.entries(u)){if(n[l])throw new Error(`Tool name collision: "${l}" is already registered. Ensure no overlap between MCP-namespaced tools and static tool handlers.`);n[l]=f}for(let l of c){if(s.has(l.name))throw new Error(`Tool schema name collision: "${l.name}" is already registered as a dynamic tool schema.`);s.add(l.name),i.push(l)}}return{toolHandlers:n,dynamicToolSchemas:i}}function J8(e){let t=e.toolHandlers();return e.toolSchemas().filter(r=>t[r.name]).map(r=>({schema:r,handler:t[r.name]}))}var JP=class{sessionId;config;deferredStart;idempotencyKey;baseHandlers;toolHandlers;resourceMap;mcpToolSchemas=[];dynamicToolSchemas;socketAbortController=null;onToolResults;onToolResultTruncated;rejectClientToolCalls;constructor(e){if(this.sessionId=e.sessionId,this.config=e.config,this.deferredStart=e.deferredStart,this.idempotencyKey=e.deferredStart?e.deferredStart.idempotencyKey??uc():void 0,this.onToolResults=e.onToolResults,this.onToolResultTruncated=e.onToolResultTruncated,this.rejectClientToolCalls=e.rejectClientToolCalls??!1,this.resourceMap=new Map,e.mcpServers!==void 0&&e.mcpServers.length>0){let t=Jb(e.mcpServers,e.tools);this.baseHandlers=t.toolHandlers,this.mcpToolSchemas=t.dynamicToolSchemas}else this.baseHandlers=e.tools??{};this.toolHandlers={...this.baseHandlers};for(let t of e.resources??[])this.resourceMap.set(t.name,t)}async*execute(e,t){if(e.type==="continue"){if(!this.sessionId)throw new Error("Cannot continue a session before it exists. Run a trigger first to create the session.");yield*this.executeStream({executionId:e.executionId,toolResults:e.toolResults},t?.signal)}else yield*this.executeStream({triggerName:e.triggerName,input:e.input,rollbackAfterMessageId:e.rollbackAfterMessageId,sender:e.sender},t?.signal)}getSessionId(){return this.sessionId}setDynamicTools(e){let t=Array.isArray(e)?e:J8(e),r={...this.baseHandlers};for(let o of t)r[o.schema.name]=o.handler;this.toolHandlers=r,this.dynamicToolSchemas=t.map(o=>o.schema)}async handleSocketMessage(e,t){if(e.type==="stop"){this.socketAbortController?.abort();return}this.socketAbortController?.abort(),this.socketAbortController=new AbortController;let r=this.socketAbortController;try{let o=this.execute(e,{signal:r.signal});for await(let n of o){if(r.signal.aborted)break;t.onEvent(n)}!r.signal.aborted&&t.onFinish&&await t.onFinish()}catch(o){if(!r.signal.aborted){let n=Gi(o instanceof Error?o.message:"Unknown error");t.onEvent(n)}}}async*executeStream(e,t){yield*Hb({config:this.config,getToolHandlers:()=>this.toolHandlers,url:()=>this.sessionId?`${this.config.baseUrl}/api/agent-sessions/${this.sessionId}/trigger`:`${this.config.baseUrl}/api/agent-sessions/start`,buildBody:({executionId:r,toolResults:o})=>this.buildRequestBody(e,r,o),onResponse:this.deferredStart?r=>this.latchSessionIdFromHeader(r):void 0,onSessionId:this.deferredStart?r=>this.latchSessionId(r):void 0,onResourceUpdate:(r,o)=>this.handleResourceUpdate(r,o),onToolResults:this.onToolResults,onToolResultTruncated:this.onToolResultTruncated,rejectClientToolCalls:this.rejectClientToolCalls,errorContext:"Failed to trigger"},{executionId:e.executionId,toolResults:e.toolResults},t)}buildRequestBody(e,t,r){let o=this.collectDynamicSchemas();if(this.deferredStart&&this.sessionId===void 0&&t===void 0){let i={};e.triggerName!==void 0&&(i.triggerName=e.triggerName),e.input!==void 0&&(i.input=e.input),e.sender!==void 0&&(i.sender=e.sender),o!==void 0&&(i.dynamicToolSchemas=o);let s={agentId:this.deferredStart.agentId,trigger:i};return this.deferredStart.input!==void 0&&(s.input=this.deferredStart.input),this.idempotencyKey!==void 0&&(s.idempotencyKey=this.idempotencyKey),s}let n={};return e.triggerName!==void 0&&(n.triggerName=e.triggerName),e.input!==void 0&&(n.input=e.input),e.rollbackAfterMessageId!==void 0&&(n.rollbackAfterMessageId=e.rollbackAfterMessageId),e.sender!==void 0&&(n.sender=e.sender),t!==void 0&&(n.executionId=t),r!==void 0&&(n.toolResults=r),o!==void 0&&(n.dynamicToolSchemas=o),n}latchSessionId(e){this.sessionId||(this.sessionId=e,this.deferredStart?.onSessionCreated?.(e))}latchSessionIdFromHeader(e){if(this.sessionId)return;let t=e.headers.get("X-Octavus-Session-Id");t&&this.latchSessionId(t)}handleResourceUpdate(e,t){let r=this.resourceMap.get(e);r&&r.onUpdate(t)}collectDynamicSchemas(){return this.mcpToolSchemas.length===0?this.dynamicToolSchemas:[...this.mcpToolSchemas,...this.dynamicToolSchemas??[]]}},G8=d.object({sessionId:d.string()}),K8=d.object({id:d.string(),agentId:d.string(),input:d.record(d.string(),d.unknown()),variables:d.record(d.string(),d.unknown()),resources:d.record(d.string(),d.unknown()),messages:d.array(RP),status:d.literal("active").optional(),createdAt:d.string(),updatedAt:d.string()}),Y8=d.object({sessionId:d.string(),agentId:d.string(),messages:d.array(Ef),status:d.literal("active").optional()}),Vb=d.object({sessionId:d.string(),agentId:d.string(),status:d.literal("expired"),createdAt:d.string()}),X8=d.object({sessionId:d.string(),restored:d.boolean()}),Q8=d.object({sessionId:d.string(),cleared:d.boolean()}),eW=d.looseObject({id:d.string(),timestamp:d.string(),type:d.string()}),tW=d.object({sessionId:d.string(),entries:d.array(eW),total:d.number().optional(),truncated:d.boolean().optional()}),rW=class extends Xi{async create(e,t){return(await this.httpPost("/api/agent-sessions",{agentId:e,input:t},G8)).sessionId}async get(e){let t=await fetch(`${this.config.baseUrl}/api/agent-sessions/${e}`,{method:"GET",headers:await this.config.getHeaders()});t.ok||await ko(t,"Request failed");let r=await t.json(),o=Vb.safeParse(r);return o.success?o.data:K8.parse(r)}async getMessages(e){let t=await fetch(`${this.config.baseUrl}/api/agent-sessions/${e}?format=ui`,{method:"GET",headers:await this.config.getHeaders()});t.ok||await ko(t,"Request failed");let r=await t.json(),o=Vb.safeParse(r);return o.success?o.data:Y8.parse(r)}async restore(e,t,r){return await this.httpPost(`/api/agent-sessions/${e}/restore`,{messages:t,input:r},X8)}async clear(e){return await this.httpDelete(`/api/agent-sessions/${e}`,Q8)}async getLogs(e,t){let r=new URLSearchParams;t?.excludeModelRequests&&r.set("excludeModelRequests","true");let o=r.toString(),n=`${this.config.baseUrl}/api/agent-sessions/${e}/logs${o?`?${o}`:""}`,i=await fetch(n,{method:"GET",headers:await this.config.getHeaders()});i.ok||await ko(i,"Request failed");let s=await i.json(),a=Vb.safeParse(s);return a.success?a.data:tW.parse(s)}attach(e,t={}){return new JP({sessionId:e,config:this.config,tools:t.tools,resources:t.resources,mcpServers:t.mcpServers,onToolResults:t.onToolResults,onToolResultTruncated:t.onToolResultTruncated,rejectClientToolCalls:t.rejectClientToolCalls})}start(e){return new JP({config:this.config,deferredStart:{agentId:e.agentId,input:e.input,idempotencyKey:e.idempotencyKey,onSessionCreated:e.onSessionCreated},tools:e.tools,resources:e.resources,mcpServers:e.mcpServers,onToolResults:e.onToolResults,onToolResultTruncated:e.onToolResultTruncated,rejectClientToolCalls:e.rejectClientToolCalls})}},Epe=d.object({filename:d.string().min(1).max(255),mediaType:d.string().min(1),size:d.number().int().positive()}),nW=d.object({id:d.string(),uploadUrl:d.url(),downloadUrl:d.url()}),oW=d.object({files:d.array(nW)}),iW=class extends Xi{async getUploadUrls(e,t){return await this.httpPost("/api/files/upload-urls",{sessionId:e,files:t},oW)}},GP=class extends Error{constructor(e,t,r){super(e),this.sessionId=t,this.details=r,this.name="WorkerError"}},sW=class extends Xi{async*execute(e,t,r={}){let o=r.mcpServers,n=o!==void 0&&o.length>0?Jb(o,r.tools,r.dynamicToolSchemas):{toolHandlers:r.tools??{},dynamicToolSchemas:r.dynamicToolSchemas};yield*Hb({config:this.config,getToolHandlers:()=>n.toolHandlers,url:`${this.config.baseUrl}/api/agents/${e}/execute`,buildBody:({executionId:i,toolResults:s})=>i?{type:"continue",executionId:i,toolResults:s}:{type:"start",input:t,...n.dynamicToolSchemas!==void 0&&{dynamicToolSchemas:n.dynamicToolSchemas}},errorContext:"Failed to execute worker"},{},r.signal)}async generate(e,t,r={}){let o,n,i,s,a,u,c;for await(let l of this.execute(e,t,r))l.type==="start"&&l.executionId?o=l.executionId:l.type==="error"?(i=l.message,s={errorType:l.errorType,source:l.source,code:l.code,retryable:l.retryable,retryAfter:l.retryAfter,provider:l.provider}):l.type==="worker-result"?(a=l.workerId,l.error!==void 0?i=i??l.error:n={output:l.output,sessionId:o??l.workerId}):l.type==="usage"&&(u=l.cost,c=l.tokens);if(i!==void 0)throw new GP(i,o??a,s);if(n!==void 0)return u!==void 0&&(n.cost=u),c!==void 0&&(n.tokens=c),n;throw new GP("Worker completed without producing a result",o)}async*continue(e,t,r,o={}){let n=o.mcpServers,i=n!==void 0&&n.length>0?Jb(n,o.tools).toolHandlers:o.tools??{};yield*Hb({config:this.config,getToolHandlers:()=>i,url:`${this.config.baseUrl}/api/agents/${e}/execute`,buildBody:({executionId:s,toolResults:a})=>({type:"continue",executionId:s??t,toolResults:a??r}),errorContext:"Failed to continue worker"},{executionId:t,toolResults:r},o.signal)}},aW=new Set(["completed","failed","cancelled"]);function cW(e){return aW.has(e)}var t1=d.string().transform(e=>e),KP=d.object({threadId:d.string(),status:t1}),uW=d.object({threadId:d.string(),status:t1,failureReason:d.string().nullable(),messages:d.array(Ef)}),lW=3e3,dW=900*1e3,fW=class extends Xi{async dispatch(e,t,r={}){return await this.httpPost(`/api/v1/workforce/agents/${encodeURIComponent(e)}/threads`,{message:t,files:r.files},KP)}async getThread(e,t){return await this.httpGet(`/api/v1/workforce/agents/${encodeURIComponent(e)}/threads/${encodeURIComponent(t)}`,uW)}async followUp(e,t,r,o={}){return await this.httpPost(`/api/v1/workforce/agents/${encodeURIComponent(e)}/threads/${encodeURIComponent(t)}/messages`,{message:r,files:o.files},KP)}async waitForCompletion(e,t,r={}){let o=r.pollIntervalMs??lW,n=r.timeoutMs??dW,i=Date.now()+n;for(;;){let s=await this.getThread(e,t);if(cW(s.status))return s;if(Date.now()+o>=i)throw new Error(`Workforce thread ${t} did not finish within ${n}ms (last status: ${s.status})`);await pW(o,r.signal)}}async run(e,t,r={}){let{threadId:o}=await this.dispatch(e,t,{files:r.files});return await this.waitForCompletion(e,o,r)}};function pW(e,t){return new Promise((r,o)=>{if(t?.aborted){o(YP(t));return}let n=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e);function i(){clearTimeout(n),o(YP(t))}t?.addEventListener("abort",i,{once:!0})})}function YP(e){let t=e?.reason;return t instanceof Error?t:new Error("The wait was aborted")}var Ppe=d.object({agentId:d.string().min(1),sessionId:d.string().min(1).optional(),ttlSeconds:d.number().int().positive().optional()}),hW=d.object({token:d.string(),jti:d.string(),expiresAt:d.string()}),mW=class extends Xi{async mint(e){return await this.httpPost("/api/tokens",e,hW)}async revoke(e){return await this.httpPost("/api/tokens/revoke",{token:e},d.object({revoked:d.boolean(),jti:d.string().optional()}))}},gW="4",Gb=class{agents;agentSessions;files;workers;workforce;tokens;baseUrl;apiKey;traceModelRequests;constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.apiKey=e.apiKey,this.traceModelRequests=e.traceModelRequests??!1;let t={baseUrl:this.baseUrl,getHeaders:()=>this.getHeaders(),maxRetries:e.maxRetries,streamIdleTimeoutMs:e.streamIdleTimeoutMs};this.agents=new P8(t),this.agentSessions=new rW(t),this.files=new iW(t),this.workers=new sW(t),this.workforce=new fW(t),this.tokens=new mW(t)}getSessionUrl(e){return`${this.baseUrl}/platform/sessions/${e}`}getAgentUrl(e){return`${this.baseUrl}/platform/agents/${e}`}async getHeaders(){let e={"Content-Type":"application/json","X-Octavus-Sdk-Version":gW},t=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;return t&&(e.Authorization=`Bearer ${t}`),this.traceModelRequests&&(e["X-Octavus-Trace"]="true"),e}};function _W(e){let t=atob(e),r=new ArrayBuffer(t.length),o=new Uint8Array(r);for(let n=0;n<t.length;n++)o[n]=t.charCodeAt(n);return r}async function r1(e,t,r){for(let o of e){if(o.outputVariable)continue;let n=VP(o.result);if(!n)continue;let i=o.files?[...o.files]:[],s=[],a=[],u=[],c=[],l=[];if(n.parts.forEach((g,_)=>{if(!wf(g))return;let v=_W(g.data),w=g.type==="image"?qP(new Uint8Array(v)):void 0,k=g.type==="image"&&w!==void 0,S=w??FP(g);s.push(_),a.push(g.type),u.push(v),l.push(k),c.push({filename:`${g.type}-${uc()}.${WP(S)}`,mediaType:S,size:v.byteLength})}),c.length===0)continue;let f=null;try{f=(await t.getUploadUrls(r,c)).files}catch{f=null}let p=f===null?null:await Promise.allSettled(f.map((g,_)=>fetch(g.uploadUrl,{method:"PUT",body:u[_],headers:{"Content-Type":c[_].mediaType}}))),h=new Map;s.forEach((g,_)=>{let v=a[_],w=c[_].mediaType,k=c[_].filename,S=u[_].byteLength,b=f?.[_],T=p?.[_],C=T?.status==="fulfilled"&&T.value.ok&&b!==void 0,N=l[_];if(C){N&&i.push({id:b.id,mediaType:w,url:b.downloadUrl,filename:k,size:S});let I=v==="image"&&!N;h.set(g,{type:v,mediaType:w,size:S,url:b.downloadUrl,...I&&{error:BP}})}else h.set(g,{type:v,mediaType:w,size:S,error:"Upload failed"})});let m=n.parts.map((g,_)=>h.has(_)?h.get(_):g);o.files=i,o.result=n.rebuild(m)}}function n1(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vW(e){return n1(e)?typeof e.name=="string"&&(e.path===void 0||typeof e.path=="string")&&typeof e.mediaType=="string"&&typeof e.size=="number"&&typeof e.contentBase64=="string":!1}function yW(e){let t=atob(e),r=new ArrayBuffer(t.length),o=new Uint8Array(r);for(let n=0;n<t.length;n++)o[n]=t.charCodeAt(n);return r}async function o1(e,t,r){for(let o of e){if(o.outputVariable)continue;let n=o.result;if(!n1(n))continue;let i=n.outputFiles;if(!Array.isArray(i)||i.length===0)continue;let s=i.filter(vW);if(s.length===0)continue;let a=[],u=[];for(let h of s){let m=yW(h.contentBase64);a.push(m),u.push({filename:h.name,mediaType:h.mediaType,size:h.size})}let c;try{c=(await t.getUploadUrls(r,u)).files}catch{n.outputFiles=s.map(h=>({name:h.name,...h.path!==void 0?{path:h.path}:{},mediaType:h.mediaType,size:h.size,error:"Upload failed"}));continue}let l=await Promise.allSettled(c.map((h,m)=>fetch(h.uploadUrl,{method:"PUT",body:a[m],headers:{"Content-Type":u[m].mediaType}}))),f=o.files?[...o.files]:[],p=[];for(let h=0;h<s.length;h++){let m=l[h],g=c[h],_=u[h],v=s[h];m.status==="fulfilled"&&m.value.ok?(f.push({id:g.id,mediaType:_.mediaType,url:g.downloadUrl,filename:_.filename,size:_.size}),p.push({name:_.filename,...v.path!==void 0?{path:v.path}:{},mediaType:_.mediaType,size:_.size,url:g.downloadUrl})):p.push({name:_.filename,...v.path!==void 0?{path:v.path}:{},mediaType:_.mediaType,size:_.size,error:"Upload failed"})}o.files=f,n.outputFiles=p}}var OA=We(h1(),1);import{existsSync as Wc,mkdirSync as bp,readdirSync as vp,readFileSync as Fx,renameSync as aK,rmSync as yp,statSync as cK,writeFileSync as IA}from"fs";import{execFile as uK}from"child_process";import{dirname as lK,join as vt,normalize as dK,relative as PA,sep as fK}from"path";import{createHash as pK,randomBytes as zA}from"crypto";var hK={txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",yaml:"application/yaml",yml:"application/yaml",xml:"application/xml",html:"text/html",htm:"text/html",pdf:"application/pdf",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mp3:"audio/mpeg",wav:"audio/wav",py:"text/x-python",js:"text/javascript",ts:"text/typescript",zip:"application/zip"};function Vx(e){let t=e.lastIndexOf(".");if(t<0)return"application/octet-stream";let r=e.slice(t+1).toLowerCase();return hK[r]??"application/octet-stream"}var mK=3e5,gK=10*1024*1024,_K=20*1024*1024,vK=50*1024*1024,yK=20*1024*1024,TA=".octavus-skill.json",bK=new Set(["PATH","HOME","USER","LOGNAME","SHELL","TMPDIR","TEMP","TMP","LANG","LC_ALL","LC_CTYPE","TZ","APPDATA","LOCALAPPDATA","PROGRAMDATA","USERPROFILE","USERNAME","USERDOMAIN","HOMEDRIVE","HOMEPATH","SYSTEMROOT","SYSTEMDRIVE","WINDIR","COMSPEC","PATHEXT","PUBLIC","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMW6432","COMMONPROGRAMFILES","COMMONPROGRAMFILES(X86)","COMMONPROGRAMW6432","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","OS"]),Wx=class{skills=new Map;extracted=new Map;inflight=new Map;installedSha=new Map;installErrors=new Map;installLocks=new Map;skillsDir;pythonPath;bashPath;turnOutputDir=null;collectedFiles=new Map;constructor(e){this.skillsDir=e.skillsDir,this.pythonPath=e.pythonPath,this.bashPath=e.bashPath,bp(this.skillsDir,{recursive:!0}),this.sweepStagingDirs(),this.reconcileFromDisk();for(let t of e.skills)this.skills.set(t.slug,t)}setSkills(e){this.skills.clear();for(let t of e)this.skills.set(t.slug,t);for(let t of[...this.extracted.keys()]){let r=this.skills.get(t);if(!r){this.extracted.delete(t);continue}let o=this.installedSha.get(t);r.bundleSha256&&o!==r.bundleSha256&&this.extracted.delete(t)}for(let t of[...this.installErrors.keys()])this.skills.has(t)||this.installErrors.delete(t);this.reconcileFromDisk()}reconcileFromDisk(){let e;try{e=vp(this.skillsDir,{withFileTypes:!0})}catch{return}for(let t of e){if(!t.isDirectory())continue;let r=t.name;if(r.startsWith(".")||r.includes(".staging-"))continue;let o=vt(this.skillsDir,r);(Wc(vt(o,"SKILL.md"))||Wc(vt(o,"scripts")))&&(this.skills.has(r)||this.skills.set(r,{slug:r,secrets:{}}),this.installedSha.has(r)||this.installedSha.set(r,this.readInstalledMarker(o)))}}readInstalledMarker(e){try{let t=Fx(vt(e,TA),"utf-8"),r=JSON.parse(t);return typeof r.sha256=="string"?r.sha256:void 0}catch{return}}async setupSkill(e){this.skills.set(e.slug,e),this.extracted.delete(e.slug);try{let t=await this.downloadAndExtract(e.slug,{allowStaleFallback:!1});return t?{installed:!0,path:PA(vt(this.skillsDir,".."),t.dir)||t.dir}:{installed:!1,error:`Skill "${e.slug}" is not configured on this device`}}catch(t){let r=t instanceof Error?t.message:String(t);return this.installErrors.set(e.slug,r),{installed:!1,error:r}}}toolHandlers(){return{octavus_skill_read:e=>this.handleSkillRead(e),octavus_skill_list:e=>this.handleSkillList(e),octavus_skill_run:e=>this.handleSkillRun(e)}}async handleSkillRead(e){let t=Es(e,"skill");if(!t)return{error:"Missing required parameter: skill"};let r=await this.ensureExtracted(t);if(!r)return this.unavailableError(t);let o=Es(e,"file")??"SKILL.md",n=Bx(r.dir,o);if(!n)return{error:`Invalid file path: ${o}`};let i=qx(r);try{return{content:Fx(n,"utf-8"),path:o,...i?{warning:i}:{}}}catch{return{error:`File not found: ${o}`}}}async handleSkillList(e){let t=Es(e,"skill");if(!t)return{error:"Missing required parameter: skill"};let r=await this.ensureExtracted(t);if(!r)return this.unavailableError(t);let o=qx(r),n=vt(r.dir,"scripts");try{let s=vp(n,{withFileTypes:!0}).filter(a=>a.isFile()).map(a=>({name:a.name,path:`scripts/${a.name}`}));return{skill:t,scripts:s,...o?{warning:o}:{}}}catch{return{skill:t,scripts:[],...o?{warning:o}:{}}}}async handleSkillRun(e){let t=Es(e,"skill");if(!t)return{error:"Missing required parameter: skill"};let r=Es(e,"script");if(!r)return{error:"Missing required parameter: script"};let o=await this.ensureExtracted(t);if(!o)return this.unavailableError(t);let n=Bx(o.dir,r);if(!n||!Wc(n))return{error:`Script not found: ${r}`};let i=this.ensureTurnOutputDir(),s=Date.now(),a=wK(e.input)?e.input:void 0,u=this.skills.get(t)?.secrets??{},c={...kK(),...u,OUTPUT_DIR:i,PYTHONUTF8:"1",PYTHONIOENCODING:"utf-8"},l=xK(Es(e,"args"),c),{command:f,prefixArgs:p}=this.resolveInterpreter(n),h=await new Promise(_=>{let v=uK(f,[...p,n,...l],{cwd:o.dir,env:c,timeout:mK,maxBuffer:gK},(w,k,S)=>{_({stdout:k,stderr:S,exitCode:typeof w?.code=="number"?w.code:0,error:w?w.message:void 0})});a&&v.stdin&&(v.stdin.write(JSON.stringify(a)),v.stdin.end())}),m=this.readNewOutputFiles(s),g=qx(o);return{stdout:h.stdout||void 0,stderr:h.stderr||void 0,exitCode:h.exitCode,error:h.error,outputFiles:m.length>0?m:void 0,...g?{warning:g}:{}}}resolveInterpreter(e){return e.endsWith(".py")?{command:this.pythonPath??(process.platform==="win32"?"python":"python3"),prefixArgs:[]}:process.platform==="win32"&&e.endsWith(".ps1")?{command:"powershell.exe",prefixArgs:["-NoProfile","-ExecutionPolicy","Bypass","-File"]}:{command:this.bashPath??"bash",prefixArgs:[]}}unavailableError(e){let t=this.installErrors.get(e);return t?{error:`${t} (install failed - call octavus_skill_setup with skill "${e}" to retry)`}:{error:`Skill "${e}" is not available on this device`}}ensureTurnOutputDir(){if(!this.turnOutputDir){let e=zA(4).toString("hex");this.turnOutputDir=vt(this.skillsDir,".runs",e,"output"),bp(this.turnOutputDir,{recursive:!0})}return this.turnOutputDir}readNewOutputFiles(e){if(!this.turnOutputDir)return[];let t;try{t=vp(this.turnOutputDir,{withFileTypes:!0})}catch{return[]}let r=[],o=0;for(let n of t){if(!n.isFile())continue;let i=vt(this.turnOutputDir,n.name);try{let s=cK(i),a=this.collectedFiles.get(n.name),u=!a,c=a!==void 0&&s.mtimeMs>e;if(!u&&!c)continue;let l=Fx(i);if(l.byteLength>_K)continue;if(o+l.byteLength>vK)break;o+=l.byteLength,r.push({name:n.name,path:i,mediaType:Vx(n.name),size:l.byteLength,contentBase64:l.toString("base64")}),this.collectedFiles.set(n.name,{size:s.size,mtimeMs:s.mtimeMs})}catch{}}return r}cleanupRuns(){let e=vt(this.skillsDir,".runs");try{yp(e,{recursive:!0,force:!0})}catch{}this.turnOutputDir=null,this.collectedFiles.clear()}async ensureExtracted(e){let t=this.extracted.get(e);if(t)return t;let r=this.inflight.get(e);if(r)return await r;let o=this.downloadAndExtract(e,{allowStaleFallback:!0}).catch(n=>(this.installErrors.set(e,n instanceof Error?n.message:String(n)),null)).finally(()=>{this.inflight.delete(e)});return this.inflight.set(e,o),await o}async downloadAndExtract(e,t){let r=this.skills.get(e);if(!r)return null;let o=vt(this.skillsDir,e),n=Wc(vt(o,"SKILL.md"))||Wc(vt(o,"scripts")),i=this.installedSha.get(e),s=r.bundleSha256!==void 0&&i!==r.bundleSha256;if(n&&!s){let u={slug:e,dir:o};return this.extracted.set(e,u),u}try{await this.installBundle(r,o)}catch(u){let c=u instanceof Error?u.message:String(u);if(t.allowStaleFallback&&n){let l={slug:e,dir:o,staleReason:c};return this.extracted.set(e,l),l}throw new Error(`Skill "${e}" bundle error: ${c}`,{cause:u})}this.installedSha.set(e,r.bundleSha256),this.installErrors.delete(e);let a={slug:e,dir:o};return this.extracted.set(e,a),a}async installBundle(e,t){let o=(this.installLocks.get(e.slug)??Promise.resolve()).then(()=>this.performBundleInstall(e,t));this.installLocks.set(e.slug,o.then(()=>{},()=>{})),await o}async performBundleInstall(e,t){if(!e.bundleUrl)throw new Error(`No bundle URL for skill "${e.slug}" - call octavus_skill_setup to (re)install it`);let r=await fetch(e.bundleUrl);if(!r.ok)throw new Error(`Bundle download failed: HTTP ${r.status} ${r.statusText}`);let o=Buffer.from(await r.arrayBuffer());if(e.bundleSha256){let i=pK("sha256").update(o).digest("hex");if(i!==e.bundleSha256)throw new Error(`Bundle SHA-256 mismatch: expected ${e.bundleSha256.slice(0,12)}..., got ${i.slice(0,12)}...`)}let n=`${t}.staging-${zA(4).toString("hex")}`;try{bp(n,{recursive:!0}),await EK(o,n),IA(vt(n,TA),JSON.stringify({sha256:e.bundleSha256??null})),yp(t,{recursive:!0,force:!0}),aK(n,t)}catch(i){throw yp(n,{recursive:!0,force:!0}),i}}sweepStagingDirs(){let e;try{e=vp(this.skillsDir,{withFileTypes:!0})}catch{return}for(let t of e)if(!(!t.isDirectory()||!t.name.includes(".staging-")))try{yp(vt(this.skillsDir,t.name),{recursive:!0,force:!0})}catch{}}};function Es(e,t){let r=e[t];return typeof r=="string"&&r.length>0?r:void 0}function qx(e){return e.staleReason?`Using the previously installed version of "${e.slug}" - the latest bundle failed to install: ${e.staleReason}`:void 0}function wK(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Bx(e,t){let r=dK(vt(e,t)),o=PA(e,r);return o===".."||o.startsWith(`..${fK}`)?null:r}function xK(e,t){return e?process.platform==="win32"?SK(e,t):(0,OA.parse)(e,t).filter(r=>typeof r=="string"):[]}function SK(e,t){let r=[],o="",n=!1,i=!1;for(let s of e){if(s==='"'){n=!n,i=!0;continue}if(!n&&(s===" "||s===" ")){i&&(r.push(o),o="",i=!1);continue}o+=s,i=!0}return i&&r.push(o),r.map(s=>$K(s,t))}function $K(e,t){let r=e.replace(/%([A-Za-z_][A-Za-z0-9_()]*)%/g,(o,n)=>t[n]??o);return r=r.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(o,n)=>t[n]??""),r=r.replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g,(o,n)=>t[n]??""),r}function kK(){let e={};for(let t of bK){let r=process.env[t];typeof r=="string"&&(e[t]=r)}return e}async function EK(e,t){let o=await(await Promise.resolve().then(()=>We(EA(),1))).default.loadAsync(e),n=Object.keys(o.files).filter(s=>!o.files[s].dir);if(n.length===0)return;let i=zK(n);for(let s of n){if(s.includes("__MACOSX/"))continue;let a=i?s.slice(i.length):s;if(!a)continue;let u=Bx(t,a);if(!u)continue;let l=await o.files[s].async("nodebuffer");if(l.byteLength>yK)throw new Error(`Skill bundle entry too large: ${s}`);bp(lK(u),{recursive:!0}),IA(u,l)}}function zK(e){let t=null;for(let r of e){if(r.startsWith("__MACOSX/"))continue;let o=r.indexOf("/");if(o===-1)return null;let n=r.slice(0,o+1);if(t===null)t=n;else if(t!==n)return null}return t}import{stat as DK,readFile as jK}from"fs/promises";import{basename as UK,resolve as Hx,isAbsolute as jA,relative as LK,sep as MK}from"path";var wp={info(e,t){console.log(JSON.stringify({level:"info",message:e,...t,ts:new Date().toISOString()}))},warn(e,t){console.warn(JSON.stringify({level:"warn",message:e,...t,ts:new Date().toISOString()}))},error(e,t,r){let o=t instanceof Error?{error:t.message,stack:t.stack}:{error:t};console.error(JSON.stringify({level:"error",message:e,...o,...r,ts:new Date().toISOString()}))}},TK=1e3,IK=3e4,PK=.25,OK=60,RA=50,RK=6e4,CK=1e4,AK=45e3,NK=1e4,DA=class{config;log;ws=null;state="disconnected";reconnectAttempts=0;reconnectTimer=null;heartbeatTimer=null;livenessTimer=null;lastPingAt=0;intentionalClose=!1;hadDisconnect=!1;pendingLifecycle=[];constructor(e){this.config=e,this.log=e.logger??wp}getState(){return this.state}connect(){this.state==="connected"||this.state==="connecting"||(this.intentionalClose=!1,this.openWebSocket())}updateToken(e){this.config={...this.config,computerToken:e}}disconnect(){this.intentionalClose=!0,this.hadDisconnect=!1,this.clearTimers(),this.closeSocket("Client disconnect"),this.pendingLifecycle=[],this.setState("disconnected")}async closeGracefully(e=3e3){this.intentionalClose=!0,this.hadDisconnect=!1,this.clearTimers(),this.pendingLifecycle=[],this.setState("disconnected");let t=this.ws;this.ws=null,t&&await new Promise(r=>{let o=!1,n=null,i=()=>{o||(o=!0,n&&clearTimeout(n),r())};t.removeAllListeners(),t.on("close",i),t.on("error",i),t.readyState===kn.OPEN||t.readyState===kn.CONNECTING?(t.close(1e3,"Client disconnect"),n=setTimeout(()=>{try{t.terminate()}catch{}i()},e)):i()})}resetAndReconnect(){this.intentionalClose=!1,this.clearTimers(),this.closeSocket("Reset for reconnect"),this.reconnectAttempts=0,this.openWebSocket()}closeSocket(e){if(!this.ws)return;let t=this.ws;this.ws=null,t.removeAllListeners(),t.on("error",()=>{}),(t.readyState===kn.OPEN||t.readyState===kn.CONNECTING)&&t.close(1e3,e)}sendSessionEvent(e,t,r){this.send({type:"session-event",sessionId:e,event:t,seq:r})}sendSessionState(e,t,r){this.send({type:"session-state",sessionId:e,events:t,lastSeq:r})}sendSessionStarted(e){this.send({type:"session-started",sessionId:e})}sendSessionComplete(e,t,r,o,n){this.send({type:"session-complete",sessionId:e,status:t,error:r,errorType:o,title:n})}sendSessionTitle(e,t){this.send({type:"session-title",sessionId:e,title:t})}sendSessionRetry(e,t){this.send({type:"session-retry",sessionId:e,attempt:t.attempt,reason:t.reason,delayMs:t.delayMs})}sendDispatchAck(e){this.send({type:"dispatch-ack",sessionId:e})}openWebSocket(){this.setState("connecting");let e=new URL("/ws/computer",this.config.operatorWsUrl);e.searchParams.set("token",this.config.computerToken),this.ws=new kn(e.toString(),{handshakeTimeout:CK}),this.ws.on("open",()=>{let t=this.reconnectAttempts>0||this.hadDisconnect;this.reconnectAttempts=0,this.hadDisconnect=!1,this.setState("connected"),this.send({type:"sync",octoAgentIds:[this.config.octoAgentId],activeSessionIds:this.config.getActiveSessionIds?.()}),this.flushPendingLifecycle(),this.startHeartbeat(),this.startPingLiveness(),this.log.info("Connected to operator",{octoAgentId:this.config.octoAgentId,isReconnect:t}),t&&this.config.onReconnected?.()}),this.ws.on("message",t=>{let r=typeof t=="string"?t:Buffer.from(t).toString("utf8");this.handleMessage(r)}),this.ws.on("ping",()=>{this.lastPingAt=Date.now()}),this.ws.on("close",(t,r)=>{this.log.info("WebSocket closed",{octoAgentId:this.config.octoAgentId,code:t,reason:r?.toString()}),this.onDisconnect(t)}),this.ws.on("error",t=>{this.log.error("WebSocket error",t,{octoAgentId:this.config.octoAgentId})})}handleMessage(e){let t;try{t=vP.parse(JSON.parse(e))}catch{this.log.warn("Invalid message from operator",{octoAgentId:this.config.octoAgentId});return}switch(t.type){case"dispatch":this.config.onDispatch(t);break;case"stop":this.config.onStop(t.sessionId);break;case"request-session-state":this.config.onRequestSessionState(t.sessionId);break;case"start-screen-stream":case"device-reconnect":case"device-reconnect-agents":case"device-restart":case"start-voice-call":case"read-slack-prefs":this.config.onDeviceControl?.(t);break;case"heartbeat":break}}onDisconnect(e){if(this.clearTimers(),this.ws=null,this.intentionalClose){this.setState("disconnected");return}if(this.hadDisconnect=!0,e===bP){this.log.info("Connection revoked by operator, not reconnecting",{octoAgentId:this.config.octoAgentId}),this.config.onDisconnected?.({revoked:!0}),this.setState("disconnected");return}if(this.config.onDisconnected?.({revoked:!1}),this.reconnectAttempts>=OK){this.log.error("Max reconnect attempts reached",void 0,{octoAgentId:this.config.octoAgentId,attempts:this.reconnectAttempts}),this.setState("disconnected");return}this.setState("reconnecting"),this.scheduleReconnect()}scheduleReconnect(){let e=Math.min(TK*2**this.reconnectAttempts,IK),t=e*PK*(Math.random()*2-1),r=Math.max(0,e+t);this.reconnectAttempts+=1,this.log.info("Scheduling reconnect",{octoAgentId:this.config.octoAgentId,attempt:this.reconnectAttempts,delayMs:Math.round(r)}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.openWebSocket()},r)}startHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=setInterval(()=>{this.send({type:"heartbeat"})},yP)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}startPingLiveness(){this.stopPingLiveness(),this.lastPingAt=Date.now(),this.livenessTimer=setInterval(()=>{Date.now()-this.lastPingAt<=AK||(this.log.warn("No ping from operator - terminating stale socket",{octoAgentId:this.config.octoAgentId}),this.ws?.terminate())},NK)}stopPingLiveness(){this.livenessTimer&&(clearInterval(this.livenessTimer),this.livenessTimer=null)}clearTimers(){this.stopHeartbeat(),this.stopPingLiveness(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}send(e){this.ws?.readyState===kn.OPEN?this.ws.send(JSON.stringify(e)):(e.type==="session-started"||e.type==="session-complete"||e.type==="dispatch-ack")&&(this.pendingLifecycle.length<RA?(this.pendingLifecycle.push({msg:e,at:Date.now()}),this.log.info("Buffered lifecycle message for reconnect",{type:e.type,sessionId:"sessionId"in e?e.sessionId:void 0,buffered:this.pendingLifecycle.length})):this.log.warn("Lifecycle buffer full, dropping message",{type:e.type,sessionId:"sessionId"in e?e.sessionId:void 0,cap:RA}))}setState(e){this.state!==e&&(this.state=e,this.config.onStateChange?.(e))}flushPendingLifecycle(){if(this.pendingLifecycle.length===0)return;let e=Date.now(),t=this.pendingLifecycle.filter(({at:r})=>e-r<RK);if(this.pendingLifecycle=[],t.length!==0){this.log.info("Flushing buffered lifecycle messages",{count:t.length});for(let{msg:r}of t)this.ws?.readyState===kn.OPEN&&this.ws.send(JSON.stringify(r))}}},UA=1,Gx=600,ZK=d.object({seconds:d.number().min(UA).max(Gx)}),FK=Ab.length+1,qK=800*1e3,Jx=120*1e3,BK=qK+Gx*1e3+Jx+120*1e3,VK=class{config;client;abortController=null;agentSession=null;title=null;eventBuffer=[];nextSeq=0;stalledByWatchdog=!1;stallTimer=null;constructor(e){this.config=e,this.client=new Gb({baseUrl:e.platformUrl,apiKey:e.operatorToken,traceModelRequests:e.traceModelRequests})}get sessionId(){return this.config.sessionId}updateConfig(e){this.config=e,this.client=new Gb({baseUrl:e.platformUrl,apiKey:e.operatorToken,traceModelRequests:e.traceModelRequests}),this.title=null,this.eventBuffer=[],this.nextSeq=0}async execute(){this.abortController=new AbortController,this.stalledByWatchdog=!1;let e;for(let t=0;t<FK;t++){let r=await this.runOnce();if(r.kind==="completed"||r.kind==="hard-error")return r.sessionResult;r.kind==="provider-error"&&(e=r.sessionResult);let o=Ab[t];if(o===void 0||this.abortController.signal.aborted||(this.config.onRetry?.(t+1,r.kind,o),await this.sleepUnlessAborted(o),this.abortController.signal.aborted))break;this.resetForRetry()}return this.abortController.signal.aborted?{status:"completed",title:this.title??void 0}:e||{status:"failed",error:"Lost connection to platform after multiple retry attempts",errorType:"transport",title:this.title??void 0}}async runOnce(){let{sessionId:e,trigger:t,onEvent:r}=this.config;this.agentSession??=this.createAgentSession();try{let o=this.agentSession.execute({type:"trigger",triggerName:t.triggerName,input:t.input,sender:t.sender},{signal:this.abortController.signal}),n=null,i=!1;this.bumpStallWatchdog();for await(let s of o){if(this.abortController.signal.aborted)break;let a=this.nextSeq;this.nextSeq+=1;let u=s;this.eventBuffer.push({seq:a,event:u}),r(e,s,a),this.bumpStallWatchdog(),s.type==="finish"?(this.eventBuffer=[],i=!0):(i=!1,s.type==="error"&&(n=u))}if(i)return{kind:"completed",sessionResult:{status:"completed",title:this.title??void 0}};if(this.stalledByWatchdog)return{kind:"hard-error",sessionResult:this.stallResult()};if(n){let s=lP(n,this.title);return s.retryable?{kind:"provider-error",sessionResult:s}:{kind:"hard-error",sessionResult:s}}return{kind:"transport-drop"}}catch(o){if(this.stalledByWatchdog)return{kind:"hard-error",sessionResult:this.stallResult()};if(this.abortController.signal.aborted)return{kind:"completed",sessionResult:{status:"completed",title:this.title??void 0}};let n=bf(o);if(n==="transport")return{kind:"transport-drop"};let i=yf(o),s=xf.isInstance(o)?o:new xf({errorType:"internal_error",message:i,source:"platform",retryable:!1,cause:o}),a=Nb(s),u=this.nextSeq;return this.nextSeq+=1,this.eventBuffer.push({seq:u,event:a}),r(e,a,u),n==="network"||n==="timeout"?{kind:"network-error"}:{kind:"hard-error",sessionResult:{status:"failed",error:i,errorType:n,title:this.title??void 0}}}finally{this.clearStallWatchdog()}}bumpStallWatchdog(){this.clearStallWatchdog(),this.stallTimer=setTimeout(()=>{this.stallTimer=null,this.stalledByWatchdog=!0,this.abortController?.abort()},BK)}clearStallWatchdog(){this.stallTimer&&(clearTimeout(this.stallTimer),this.stallTimer=null)}stallResult(){return{status:"failed",error:"The run stopped making progress and was ended. Send a message to continue.",errorType:"transport",title:this.title??void 0}}getBufferedEvents(){return{events:this.eventBuffer.map(e=>e.event),lastSeq:this.nextSeq>0?this.nextSeq-1:-1}}stop(){this.abortController?.abort()}createAgentSession(){let{sessionId:e,computer:t,tools:r}=this.config,o=this.client.agentSessions.attach(e,{tools:this.buildStaticToolHandlers(r,t),onToolResults:n=>this.uploadToolResults(n,e),onToolResultTruncated:n=>{(this.config.logger??wp).warn("Tool result too large; reduced to a preview before sending",{sessionId:e,toolName:n.toolName,originalBytes:n.originalBytes,keptBytes:n.keptBytes,variableCapture:n.variableCapture})},rejectClientToolCalls:!0});return o.setDynamicTools(t),o}async uploadToolResults(e,t){this.stallTimer&&this.bumpStallWatchdog();let r=(async()=>{await r1(e,this.client.files,t),await o1(e,this.client.files,t)})(),o,n=new Promise(i=>{o=setTimeout(()=>i("timeout"),Jx)});try{await Promise.race([r.then(()=>"done"),n])==="timeout"&&((this.config.logger??wp).warn("Tool result upload exceeded its time budget; continuing without full offload",{sessionId:t,budgetMs:Jx}),r.catch(()=>{}))}finally{o&&clearTimeout(o)}}resetForRetry(){this.eventBuffer=[],this.agentSession=this.createAgentSession()}sleepUnlessAborted(e){return new Promise(t=>{let r=this.abortController?.signal;if(r?.aborted){t();return}let o=null,n=()=>{o!==null&&clearTimeout(o),t()};o=setTimeout(()=>{r?.removeEventListener("abort",n),t()},e),r?.addEventListener("abort",n,{once:!0})})}buildStaticToolHandlers(e,t){let r=d.object({title:d.string().min(1)}),o={"set-chat-title":n=>{let i=r.safeParse(n);return i.success?(this.title=i.data.title,this.config.onTitleChange?.(this.config.sessionId,i.data.title),Promise.resolve({success:!0,title:i.data.title})):Promise.resolve({success:!1,error:"Title must be a non-empty string"})},wait:n=>this.handleWait(n)};return t&&(o["computer-ensure-ready"]=()=>this.handleEnsureReady(),o["computer-get-status"]=()=>this.handleGetStatus(),o["computer-reset"]=()=>this.handleReset()),e&&Object.assign(o,e),o}async handleEnsureReady(){let e=this.config.computer,{environment:t}=this.config;if(lc(e))try{let r=await e.ensureReady();return this.agentSession?.setDynamicTools(e),{ready:r.healthy,tools:e.toolSchemas().map(o=>o.name),...(r.recovered?.length??0)>0&&{recovered:r.recovered},...(r.failedEntries?.length??0)>0&&{failedEntries:r.failedEntries},...t&&{environment:t}}}catch(r){return{ready:!1,error:r instanceof Error?r.message:String(r)}}return{ready:!0,tools:e.toolSchemas().map(r=>r.name),...t&&{environment:t}}}async handleGetStatus(){let e=this.config.computer;if(lc(e))try{let t=await e.getHealth();return{ready:t.healthy,tools:t.totalTools,entries:t.entries}}catch(t){return{ready:!1,error:t instanceof Error?t.message:String(t)}}return{ready:!0,schemasAvailable:!0,tools:e.toolSchemas().length}}async handleReset(){let{onComputerReset:e}=this.config;if(!e)return{ready:!1,error:"Reset not available"};try{let t=await e();return this.config.computer=t,this.agentSession?.setDynamicTools(t),{ready:lc(t)?(await t.getHealth()).healthy:!0,tools:t.toolSchemas().map(o=>o.name),reset:!0}}catch(t){return{ready:!1,error:t instanceof Error?t.message:String(t)}}}handleWait(e){let t=ZK.safeParse(e);if(!t.success)return Promise.resolve({success:!1,error:`seconds must be a number between ${UA} and ${Gx}`});let r=Math.round(t.data.seconds*1e3),o=this.abortController?.signal;return new Promise(n=>{if(o?.aborted){n({success:!0,waited_ms:0,aborted:!0});return}let i=setTimeout(()=>n({success:!0,waited_ms:r}),r);o?.addEventListener("abort",()=>{clearTimeout(i),n({success:!0,waited_ms:0,aborted:!0})},{once:!0})})}},WK=5e3,HK=10*6e4,JK=6e4,CA=20*1024*1024,AA=4e4;function GK(e){return new Promise(t=>{setTimeout(t,e)})}var KK=d.object({slug:d.string().min(1)}),YK=d.object({command:d.string().min(1),args:d.array(d.string()).optional(),env:d.record(d.string(),d.string()).optional(),connection:d.enum(["eager","lazy"]).optional()});function NA(e){return JSON.stringify({command:e.command,args:e.args,env:e.env,connection:e.connection})}var LA=class{config;log;activeExecutors=new Map;executorCache=new Map;cancelledSessions=new Map;stoppedSessions=new Set;terminalFailures=new Map;connectionLossTimer=null;idleCleanupTimer=null;afterSessionTimer=null;running=!1;resolvedComputer=null;computerPromise=null;currentDeviceMcpFingerprints=new Map;deviceSkillHandler=null;activeToolHandlers=null;oneShotResolvers=new Map;constructor(e){this.config=e,this.log=e.logger??wp}start(){this.running||(this.running=!0,this.idleCleanupTimer=setInterval(()=>this.cleanupIdleExecutors(),6e4))}async stop(){if(this.running=!1,this.cancelConnectionLossTimer(),this.idleCleanupTimer&&(clearInterval(this.idleCleanupTimer),this.idleCleanupTimer=null),this.afterSessionTimer&&(this.cancelAfterSessionTimer(),await this.fireAfterSession()),this.activeExecutors.size>0){for(let t of this.activeExecutors.values())t.stop();let e=Date.now()+WK;for(;this.activeExecutors.size>0&&Date.now()<e;)await GK(200);this.activeExecutors.size>0&&(this.log.warn("Drain timed out, forcing cleanup",{remaining:this.activeExecutors.size}),this.activeExecutors.clear(),this.notifyStateChange())}this.executorCache.clear(),this.cancelledSessions.clear(),this.stoppedSessions.clear()}getActiveSessions(){return[...this.activeExecutors.keys()].map(e=>({sessionId:e,octoAgentId:this.config.octoAgentId}))}isExecuting(){return this.activeExecutors.size>0}resetComputer(){this.resolvedComputer=null,this.computerPromise=null,this.currentDeviceMcpFingerprints.clear()}handleDispatch(e){return this.running?(this.cancelAfterSessionTimer(),this.activeExecutors.has(e.sessionId)?(this.log.warn("Ignoring duplicate dispatch for active session",{sessionId:e.sessionId}),this.config.connection.sendDispatchAck(e.sessionId),!0):(this.config.connection.sendDispatchAck(e.sessionId),this.executeSession(e).catch(t=>{this.log.error("Session execution threw outside its handler",t,{sessionId:e.sessionId})}),!0)):!1}async runLocalDispatch(e){let t=new Promise(r=>{this.oneShotResolvers.set(e.sessionId,r)});if(!this.handleDispatch(e))throw this.oneShotResolvers.delete(e.sessionId),new Error("SessionManager is not running");return await t}emitSessionComplete(e,t,r,o,n){this.config.connection.sendSessionComplete(e,t,r,o,n);let i=this.stoppedSessions.delete(e),s=this.oneShotResolvers.get(e);s&&(this.oneShotResolvers.delete(e),s(i&&t==="completed"?{status:"cancelled",title:n}:{status:t,error:r,errorType:o,title:n}))}handleStop(e){this.stoppedSessions.add(e);let t=this.activeExecutors.get(e);t?t.stop():this.cancelledSessions.set(e,Date.now())}handleConnectionLost(e){if(e.revoked){this.cancelConnectionLossTimer(),this.failActiveSessions("Operator connection revoked");return}this.activeExecutors.size!==0&&(this.connectionLossTimer||(this.log.warn("Operator connection lost with active sessions - starting grace window",{activeSessions:this.activeExecutors.size,graceMs:AA}),this.connectionLossTimer=setTimeout(()=>{this.connectionLossTimer=null,this.failActiveSessions("Operator connection lost",{report:!0})},AA)))}handleConnectionRestored(){this.connectionLossTimer&&(this.cancelConnectionLossTimer(),this.log.info("Operator connection restored within grace window - sessions continue"))}cancelConnectionLossTimer(){this.connectionLossTimer&&(clearTimeout(this.connectionLossTimer),this.connectionLossTimer=null)}failActiveSessions(e,t={}){if(this.activeExecutors.size!==0)for(let[r,o]of this.activeExecutors)this.terminalFailures.set(r,{reason:e,report:t.report??!1}),o.stop()}handleRequestSessionState(e){let t=this.activeExecutors.get(e);if(t){let{events:r,lastSeq:o}=t.getBufferedEvents();this.config.connection.sendSessionState(e,r,o)}else this.config.connection.sendSessionState(e,[],-1)}async getComputer(){if(this.resolvedComputer)return this.resolvedComputer;if(!this.computerPromise){let{computer:e}=this.config;this.computerPromise=typeof e=="function"?e():Promise.resolve(e)}return this.resolvedComputer=await this.computerPromise,this.resolvedComputer}consumeCancellation(e){return this.cancelledSessions.has(e)?(this.cancelledSessions.delete(e),this.log.info("Session was cancelled before execution started",{sessionId:e}),this.emitSessionComplete(e,"completed"),!0):!1}async executeSession(e){let{sessionId:t,operatorToken:r,trigger:o}=e;try{let n;try{n=await this.getComputer()}catch(a){let u=yf(a);this.log.error("Computer factory failed",a,{sessionId:t});let c=bf(a);this.emitSessionComplete(t,"failed",u,c==="transport"?"network":c);return}if(this.consumeCancellation(t))return;if(await this.reconcileDeviceMcps(n,e.deviceMcpConfigs),this.reconcileDeviceSkills(e.deviceSkillConfigs),this.config.onBeforeSession)try{await this.config.onBeforeSession()}catch(a){this.log.error("onBeforeSession failed",a)}if(this.consumeCancellation(t))return;let i=this.buildDeviceToolHandlers(n,e),s=this.getOrCreateExecutor(t,r,o,n,i);this.activeExecutors.set(t,s),this.notifyStateChange(),this.config.connection.sendSessionStarted(t);try{let a=await s.execute();if(this.consumeTerminalFailure(t))return;this.emitSessionComplete(t,a.status,a.error,a.errorType,a.title)}catch(a){if(this.consumeTerminalFailure(t))return;this.log.error("Session execution failed unexpectedly",a,{sessionId:t}),this.emitSessionComplete(t,"failed","Internal execution error","platform")}finally{this.deviceSkillHandler?.cleanupRuns(),this.terminalFailures.delete(t),this.activeExecutors.delete(t),this.notifyStateChange(),this.config.onAfterSession&&this.activeExecutors.size===0&&this.scheduleAfterSession()}}finally{let n=this.oneShotResolvers.get(t);n&&(this.oneShotResolvers.delete(t),n({status:"failed",error:"Run ended without completing",errorType:"network"})),this.stoppedSessions.delete(t),this.config.onSessionSettled?.(t)}}consumeTerminalFailure(e){let t=this.terminalFailures.get(e);return t?(this.log.warn("Session aborted after operator disconnect",{sessionId:e,reason:t.reason}),t.report&&this.emitSessionComplete(e,"failed",t.reason,"network"),!0):!1}async reconcileDeviceMcps(e,t){if(!Ki(e)){t&&t.length>0&&this.log.warn("Device MCP configs provided but Computer does not support dynamic entries",{namespaces:t.map(o=>o.namespace)});return}let r=new Map;for(let o of t??[])r.set(o.namespace,o);for(let o of[...this.currentDeviceMcpFingerprints.keys()])if(!r.has(o))try{await e.removeEntry(o),this.currentDeviceMcpFingerprints.delete(o)}catch(n){this.log.warn("Failed to remove device MCP entry",{namespace:o,error:String(n)})}for(let[o,n]of r){let i=NA(n);if(this.currentDeviceMcpFingerprints.get(o)!==i){if(this.currentDeviceMcpFingerprints.has(o)){try{await e.removeEntry(o)}catch(s){this.log.warn("Failed to replace device MCP entry",{namespace:o,error:String(s)})}this.currentDeviceMcpFingerprints.delete(o)}try{await e.addEntry(o,{type:"stdio",command:n.command,args:n.args,env:n.env},{deferred:n.connection==="lazy"}),this.currentDeviceMcpFingerprints.set(o,i)}catch(s){this.log.warn("Failed to add device MCP entry",{namespace:o,error:String(s)})}}}}reconcileDeviceSkills(e){if(!e||e.length===0){this.deviceSkillHandler=null;return}if(!this.config.deviceSkillsDir){this.log.warn("Device skill configs provided but no deviceSkillsDir configured",{slugs:e.map(r=>r.slug)});return}let t=e.map(r=>({slug:r.slug,bundleUrl:r.bundleUrl,bundleSha256:r.bundleSha256,secrets:r.secrets}));this.deviceSkillHandler?this.deviceSkillHandler.setSkills(t):this.deviceSkillHandler=new Wx({skills:t,skillsDir:this.config.deviceSkillsDir,pythonPath:this.config.pythonPath})}buildDeviceToolHandlers(e,t){let r=!!(this.deviceSkillHandler&&(t.deviceSkillConfigs?.length??0)>0),o=(t.deviceMcpConfigs?.length??0)>0&&Ki(e),n=Ki(e),i=!!this.config.deviceSkillsDir,s=!!this.config.agentWorkspaceDir;if(!r&&!o&&!n&&!i&&!s)return this.activeToolHandlers=null,this.config.tools;let a={...this.config.tools??{}};if(this.activeToolHandlers=a,r){let u=this.deviceSkillHandler.toolHandlers();a[at.SKILL_READ]=u[at.SKILL_READ],a[at.SKILL_LIST]=u[at.SKILL_LIST],a[at.SKILL_RUN]=u[at.SKILL_RUN]}if(i&&(a[at.SKILL_SETUP]=u=>this.handleSkillSetup(u)),n&&(a[Fb.MCP_ACTIVATE]=u=>this.handleDeviceMcpActivate(e,u)),s){let u=this.config.agentWorkspaceDir;a[at.FILE_UPLOAD]=c=>this.handleFileUpload(c,u)}return a}async handleSkillSetup(e){let t=typeof e.skill=="string"?e.skill:void 0;if(!t)return{error:"Missing required parameter: skill"};let r=typeof e.bundleUrl=="string"?e.bundleUrl:void 0;if(!r)return{error:`Skill "${t}" could not be resolved - bundleUrl missing`};let o=typeof e.bundleSha256=="string"?e.bundleSha256:void 0,n=typeof e.secrets=="object"&&e.secrets!==null&&!Array.isArray(e.secrets)?e.secrets:{},i={slug:t,bundleUrl:r,bundleSha256:o,secrets:n};if(!this.deviceSkillHandler){if(!this.config.deviceSkillsDir)return{error:"Device skills are not configured on this device"};this.deviceSkillHandler=new Wx({skills:[i],skillsDir:this.config.deviceSkillsDir,pythonPath:this.config.pythonPath})}let s=await this.deviceSkillHandler.setupSkill(i);if(s.installed&&this.activeToolHandlers){let a=this.deviceSkillHandler.toolHandlers();this.activeToolHandlers[at.SKILL_READ]=a[at.SKILL_READ],this.activeToolHandlers[at.SKILL_LIST]=a[at.SKILL_LIST],this.activeToolHandlers[at.SKILL_RUN]=a[at.SKILL_RUN]}return s}async handleDeviceMcpActivate(e,t){let r=KK.safeParse(t);if(!r.success)return{error:"slug is required"};if(!Ki(e))return{error:"This computer does not support dynamic MCP activation"};let{slug:o}=r.data,n=YK.safeParse(t.deviceConfig);if(n.success&&!this.currentDeviceMcpFingerprints.has(o)){let a=n.data;try{let u=a.connection==="eager"?"eager":"lazy",c=a.args??[],l=a.env??{};await e.addEntry(o,{type:"stdio",command:a.command,args:c,env:l},{deferred:u==="lazy"}),this.currentDeviceMcpFingerprints.set(o,NA({namespace:o,name:o,description:"",command:a.command,args:c,env:l,connection:u}))}catch(u){return{error:u instanceof Error?u.message:String(u)}}}if(!this.currentDeviceMcpFingerprints.has(o))return{error:`MCP "${o}" is not registered on this device. Call computer-reset to refresh the device's MCP set.`};try{await e.restartEntry(o)}catch(a){return{error:a instanceof Error?a.message:String(a)}}let i=`${o}__`;return{activated:!0,tools:e.toolSchemas().filter(a=>a.name.startsWith(i))}}async handleFileUpload(e,t){let r=typeof e.path=="string"?e.path.trim():"";if(!r)return{error:"Missing required parameter: path"};let o=Hx(t),n=jA(r)?r:Hx(o,r),i=Hx(n);if(!XK(i,o))return{error:`Path is outside the agent workspace (${o}). Only files inside the workspace can be uploaded.`};let s;try{s=await DK(i)}catch{return{error:`File not found: ${i}`}}if(!s.isFile())return{error:`Path is not a file: ${i}`};if(s.size>CA)return{error:`File exceeds maximum upload size of ${CA/(1024*1024)}MB`};let a;try{a=await jK(i)}catch(l){return{error:l instanceof Error?l.message:"Failed to read file"}}let u=UK(i),c=Vx(u);return{outputFiles:[{name:u,path:i,mediaType:c,size:a.byteLength,contentBase64:a.toString("base64")}]}}getOrCreateExecutor(e,t,r,o,n){let i=(p,h,m)=>{this.config.connection.sendSessionEvent(e,h,m)},s=this.config.onComputerReset,a=s?async()=>{let p=await s();return this.resolvedComputer=p,this.currentDeviceMcpFingerprints.clear(),p}:void 0,u=(p,h)=>{this.config.connection.sendSessionTitle(e,h)},c={sessionId:e,operatorToken:t,trigger:r,platformUrl:this.config.platformUrl,computer:o,onEvent:i,onTitleChange:u,onRetry:(p,h,m)=>{this.log.warn("Retrying session execution",{sessionId:e,attempt:p,reason:h,delayMs:m}),this.config.connection.sendSessionRetry(e,{attempt:p,reason:h,delayMs:m})},tools:n??this.config.tools,onComputerReset:a,traceModelRequests:this.config.traceModelRequests,environment:this.config.environment,logger:this.log},l=this.executorCache.get(e);if(l)return l.lastActiveAt=Date.now(),l.executor.updateConfig(c),this.log.info("Reusing executor for session",{sessionId:e}),l.executor;let f=new VK(c);return this.executorCache.set(e,{executor:f,lastActiveAt:Date.now()}),f}cancelAfterSessionTimer(){this.afterSessionTimer&&(clearTimeout(this.afterSessionTimer),this.afterSessionTimer=null)}scheduleAfterSession(){if(this.cancelAfterSessionTimer(),!this.running)return;let e=this.config.idleTimeoutMs??0;if(e<=0){this.fireAfterSession();return}this.afterSessionTimer=setTimeout(()=>{this.afterSessionTimer=null,this.fireAfterSession()},e)}async fireAfterSession(){if(!(this.activeExecutors.size>0))try{await this.config.onAfterSession?.()}catch(e){this.log.error("onAfterSession failed",e)}}cleanupIdleExecutors(){let e=Date.now();for(let[t,r]of this.executorCache)e-r.lastActiveAt>HK&&!this.activeExecutors.has(t)&&(this.log.info("Removing idle executor cache for session",{sessionId:t}),this.executorCache.delete(t));for(let[t,r]of this.cancelledSessions)e-r>JK&&(this.cancelledSessions.delete(t),this.stoppedSessions.delete(t))}notifyStateChange(){this.config.onSessionStateChange?.(this.getActiveSessions())}};function XK(e,t){if(e===t)return!0;let r=LK(t,e);return r===""?!0:r.startsWith("..")||jA(r)?!1:!r.split(MK).includes("..")}import{homedir as QK}from"os";import{join as Hc}from"path";import{mkdirSync as MA,readFileSync as e7,writeFileSync as t7}from"fs";var r7="production",n7={production:"https://octavus.ai",local:"http://localhost:3000"};function Jc(e){let t=(e||process.env.OCTAVUS_ENV||r7).trim();if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(t))throw new Error(`Invalid environment "${t}": use letters, digits, dot, underscore, or hyphen (e.g. production, staging).`);return t}function zs(e){return process.env.OCTAVUS_HOME||Hc(QK(),".octavus",e)}function ZA(e){return Hc(zs(e),"config.json")}function Ts(e){try{let t=e7(ZA(e),"utf8"),r=JSON.parse(t);return typeof r=="object"&&r!==null?r:{}}catch{return{}}}function FA(e,t){let r=zs(e);MA(r,{recursive:!0,mode:448});let o={...Ts(e),...t};return t7(ZA(e),`${JSON.stringify(o,null,2)}
|
|
71
71
|
`,{mode:384}),o}function qA(e,t){return t||process.env.OCTAVUS_API_KEY||Ts(e).apiKey}function Gc(e,t){let r=t||process.env.OCTAVUS_PLATFORM_URL||Ts(e).platformUrl||n7[e];return r?r.replace(/\/+$/,""):void 0}function xp(e,t){let r=t||process.env.OCTAVUS_OPERATOR_WS_URL||Ts(e).operatorWsUrl;return r?r.replace(/\/+$/,""):void 0}function BA(e,t){let r=Hc(zs(e),t),o=Hc(r,"browser-profile"),n=Hc(r,"skills");for(let i of[r,o,n])MA(i,{recursive:!0,mode:448});return{base:r,browserProfileDir:o,skillsDir:n}}function o7(e){return e instanceof Error?e.message:String(e)}function VA(e){let t=(r,o,n)=>{let i=n&&Object.keys(n).length>0?` ${JSON.stringify(n)}`:"";process.stderr.write(`[${r}] ${o}${i}
|
|
72
72
|
`)};return{info:(r,o)=>{e&&t("info",r,o)},warn:(r,o)=>t("warn",r,o),error:(r,o,n)=>t("error",r,{...n,...o==null?{}:{error:o7(o)}})}}import{createRequire as Wce}from"module";import{existsSync as Hce}from"fs";import{dirname as B6,join as wa}from"path";import{fileURLToPath as Jce}from"url";var WA,Kx=Object.freeze({status:"aborted"});function z(e,t,r){function o(a,u){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:u,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,u);let c=s.prototype,l=Object.keys(c);for(let f=0;f<l.length;f++){let p=l[f];p in a||(a[p]=c[p].bind(a))}}let n=r?.Parent??Object;class i extends n{}Object.defineProperty(i,"name",{value:e});function s(a){var u;let c=r?.Parent?new i:this;o(c,a),(u=c._zod).deferred??(u.deferred=[]);for(let l of c._zod.deferred)l();return c}return Object.defineProperty(s,"init",{value:o}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}var i7=Symbol("zod_brand"),Nr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Is=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(WA=globalThis).__zod_globalConfig??(WA.__zod_globalConfig={});var Ps=globalThis.__zod_globalConfig;function Et(e){return e&&Object.assign(Ps,e),Ps}var re={};Zt(re,{BIGINT_FORMAT_RANGES:()=>KA,Class:()=>Xx,NUMBER_FORMAT_RANGES:()=>o0,aborted:()=>Gn,allowsEval:()=>t0,assert:()=>l7,assertEqual:()=>s7,assertIs:()=>c7,assertNever:()=>u7,assertNotEqual:()=>a7,assignProp:()=>Hn,base64ToUint8Array:()=>XA,base64urlToUint8Array:()=>z7,cached:()=>Rs,captureStackTrace:()=>kp,cleanEnum:()=>E7,cleanRegex:()=>Qc,clone:()=>Yt,cloneDef:()=>f7,createTransparentProxy:()=>v7,defineLazy:()=>le,esc:()=>$p,escapeRegex:()=>cn,explicitlyAborted:()=>i0,extend:()=>w7,finalizeIssue:()=>Xt,floatSafeRemainder:()=>Qx,getElementAtPath:()=>p7,getEnumValues:()=>Yc,getLengthableOrigin:()=>eu,getParsedType:()=>_7,getSizableOrigin:()=>YA,hexToUint8Array:()=>I7,isObject:()=>Zo,isPlainObject:()=>Jn,issue:()=>Cs,joinValues:()=>Sp,jsonStringifyReplacer:()=>Os,merge:()=>S7,mergeDefs:()=>an,normalizeParams:()=>q,nullish:()=>Xc,numKeys:()=>g7,objectClone:()=>d7,omit:()=>b7,optionalKeys:()=>n0,parsedType:()=>s0,partial:()=>$7,pick:()=>y7,prefixIssues:()=>un,primitiveTypes:()=>GA,promiseAllObject:()=>h7,propertyKeyTypes:()=>r0,randomString:()=>m7,required:()=>k7,safeExtend:()=>x7,shallowClone:()=>JA,slugify:()=>e0,stringifyPrimitive:()=>Ep,uint8ArrayToBase64:()=>QA,uint8ArrayToBase64url:()=>T7,uint8ArrayToHex:()=>P7,unwrapMessage:()=>Kc});function s7(e){return e}function a7(e){return e}function c7(e){}function u7(e){throw new Error("Unexpected value in exhaustive check")}function l7(e){}function Yc(e){let t=Object.values(e).filter(o=>typeof o=="number");return Object.entries(e).filter(([o,n])=>t.indexOf(+o)===-1).map(([o,n])=>n)}function Sp(e,t="|"){return e.map(r=>Ep(r)).join(t)}function Os(e,t){return typeof t=="bigint"?t.toString():t}function Rs(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Xc(e){return e==null}function Qc(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Qx(e,t){let r=e/t,o=Math.round(r),n=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-o)<n?0:r-o}var HA=Symbol("evaluating");function le(e,t,r){let o;Object.defineProperty(e,t,{get(){if(o!==HA)return o===void 0&&(o=HA,o=r()),o},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function d7(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function Hn(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function an(...e){let t={};for(let r of e){let o=Object.getOwnPropertyDescriptors(r);Object.assign(t,o)}return Object.defineProperties({},t)}function f7(e){return an(e._zod.def)}function p7(e,t){return t?t.reduce((r,o)=>r?.[o],e):e}function h7(e){let t=Object.keys(e),r=t.map(o=>e[o]);return Promise.all(r).then(o=>{let n={};for(let i=0;i<t.length;i++)n[t[i]]=o[i];return n})}function m7(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let o=0;o<e;o++)r+=t[Math.floor(Math.random()*t.length)];return r}function $p(e){return JSON.stringify(e)}function e0(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var kp="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Zo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var t0=Rs(()=>{if(Ps.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function Jn(e){if(Zo(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(Zo(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function JA(e){return Jn(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function g7(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var _7=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},r0=new Set(["string","number","symbol"]),GA=new Set(["string","number","bigint","boolean","symbol","undefined"]);function cn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Yt(e,t,r){let o=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(o._zod.parent=e),o}function q(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function v7(e){let t;return new Proxy({},{get(r,o,n){return t??(t=e()),Reflect.get(t,o,n)},set(r,o,n,i){return t??(t=e()),Reflect.set(t,o,n,i)},has(r,o){return t??(t=e()),Reflect.has(t,o)},deleteProperty(r,o){return t??(t=e()),Reflect.deleteProperty(t,o)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,o){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,o)},defineProperty(r,o,n){return t??(t=e()),Reflect.defineProperty(t,o,n)}})}function Ep(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function n0(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var o0={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},KA={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function y7(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i=an(e._zod.def,{get shape(){let s={};for(let a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(s[a]=r.shape[a])}return Hn(this,"shape",s),s},checks:[]});return Yt(e,i)}function b7(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=an(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete s[a]}return Hn(this,"shape",s),s},checks:[]});return Yt(e,i)}function w7(e,t){if(!Jn(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let i=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let n=an(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return Hn(this,"shape",i),i}});return Yt(e,n)}function x7(e,t){if(!Jn(t))throw new Error("Invalid input to safeExtend: expected a plain object");let r=an(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return Hn(this,"shape",o),o}});return Yt(e,r)}function S7(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=an(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t._zod.def.shape};return Hn(this,"shape",o),o},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Yt(e,r)}function $7(e,t,r){let n=t._zod.def.checks;if(n&&n.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=an(t._zod.def,{get shape(){let a=t._zod.def.shape,u={...a};if(r)for(let c in r){if(!(c in a))throw new Error(`Unrecognized key: "${c}"`);r[c]&&(u[c]=e?new e({type:"optional",innerType:a[c]}):a[c])}else for(let c in a)u[c]=e?new e({type:"optional",innerType:a[c]}):a[c];return Hn(this,"shape",u),u},checks:[]});return Yt(t,s)}function k7(e,t,r){let o=an(t._zod.def,{get shape(){let n=t._zod.def.shape,i={...n};if(r)for(let s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=new e({type:"nonoptional",innerType:n[s]}))}else for(let s in n)i[s]=new e({type:"nonoptional",innerType:n[s]});return Hn(this,"shape",i),i}});return Yt(t,o)}function Gn(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function i0(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function un(e,t){return t.map(r=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function Kc(e){return typeof e=="string"?e:e?.message}function Xt(e,t,r){let o=e.message?e.message:Kc(e.inst?._zod.def?.error?.(e))??Kc(t?.error?.(e))??Kc(r.customError?.(e))??Kc(r.localeError?.(e))??"Invalid input",{inst:n,continue:i,input:s,...a}=e;return a.path??(a.path=[]),a.message=o,t?.reportInput&&(a.input=s),a}function YA(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function eu(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function s0(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function Cs(...e){let[t,r,o]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:o}:{...t}}function E7(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function XA(e){let t=atob(e),r=new Uint8Array(t.length);for(let o=0;o<t.length;o++)r[o]=t.charCodeAt(o);return r}function QA(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function z7(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return XA(t+r)}function T7(e){return QA(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function I7(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let o=0;o<t.length;o+=2)r[o/2]=Number.parseInt(t.slice(o,o+2),16);return r}function P7(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var Xx=class{constructor(...t){}};var eN=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Os,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},zp=z("$ZodError",eN),a0=z("$ZodError",eN,{Parent:Error});function c0(e,t=r=>r.message){let r={},o=[];for(let n of e.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n))):o.push(t(n));return{formErrors:o,fieldErrors:r}}function u0(e,t=r=>r.message){let r={_errors:[]},o=(n,i=[])=>{for(let s of n.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>o({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")o({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")o({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)r._errors.push(t(s));else{let u=r,c=0;for(;c<a.length;){let l=a[c];c===a.length-1?(u[l]=u[l]||{_errors:[]},u[l]._errors.push(t(s))):u[l]=u[l]||{_errors:[]},u=u[l],c++}}}};return o(e),r}var Tp=e=>(t,r,o,n)=>{let i=o?{...o,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new Nr;if(s.issues.length){let a=new(n?.Err??e)(s.issues.map(u=>Xt(u,i,Et())));throw kp(a,n?.callee),a}return s.value};var Ip=e=>async(t,r,o,n)=>{let i=o?{...o,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(n?.Err??e)(s.issues.map(u=>Xt(u,i,Et())));throw kp(a,n?.callee),a}return s.value};var tu=e=>(t,r,o)=>{let n=o?{...o,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},n);if(i instanceof Promise)throw new Nr;return i.issues.length?{success:!1,error:new(e??zp)(i.issues.map(s=>Xt(s,n,Et())))}:{success:!0,data:i.value}},ru=tu(a0),nu=e=>async(t,r,o)=>{let n=o?{...o,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},n);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>Xt(s,n,Et())))}:{success:!0,data:i.value}},Pp=nu(a0),tN=e=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Tp(e)(t,r,n)};var rN=e=>(t,r,o)=>Tp(e)(t,r,o);var nN=e=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Ip(e)(t,r,n)};var oN=e=>async(t,r,o)=>Ip(e)(t,r,o);var iN=e=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return tu(e)(t,r,n)};var sN=e=>(t,r,o)=>tu(e)(t,r,o);var aN=e=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return nu(e)(t,r,n)};var cN=e=>async(t,r,o)=>nu(e)(t,r,o);var uN=/^[cC][0-9a-z]{6,}$/,lN=/^[0-9a-z]+$/,dN=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,fN=/^[0-9a-vA-V]{20}$/,pN=/^[A-Za-z0-9]{27}$/,hN=/^[a-zA-Z0-9_-]{21}$/,mN=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var gN=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,l0=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;var _N=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var R7="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function vN(){return new RegExp(R7,"u")}var yN=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,bN=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var wN=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,xN=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,SN=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,d0=/^[A-Za-z0-9_-]*$/;var $N=/^https?$/,kN=/^\+[1-9]\d{6,14}$/,EN="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",zN=new RegExp(`^${EN}$`);function TN(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function IN(e){return new RegExp(`^${TN(e)}$`)}function PN(e){let t=TN({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let o=`${t}(?:${r.join("|")})`;return new RegExp(`^${EN}T(?:${o})$`)}var ON=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},RN=/^-?\d+n?$/,CN=/^-?\d+$/,f0=/^-?\d+(?:\.\d+)?$/,AN=/^(?:true|false)$/i,NN=/^null$/i;var DN=/^[^A-Z]*$/,jN=/^[^a-z]*$/;var Xe=z("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),UN={number:"number",bigint:"bigint",object:"date"},p0=z("$ZodCheckLessThan",(e,t)=>{Xe.init(e,t);let r=UN[typeof t.value];e._zod.onattach.push(o=>{let n=o._zod.bag,i=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=o=>{(t.inclusive?o.value<=t.value:o.value<t.value)||o.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),h0=z("$ZodCheckGreaterThan",(e,t)=>{Xe.init(e,t);let r=UN[typeof t.value];e._zod.onattach.push(o=>{let n=o._zod.bag,i=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=o=>{(t.inclusive?o.value>=t.value:o.value>t.value)||o.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),LN=z("$ZodCheckMultipleOf",(e,t)=>{Xe.init(e,t),e._zod.onattach.push(r=>{var o;(o=r._zod.bag).multipleOf??(o.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):Qx(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),MN=z("$ZodCheckNumberFormat",(e,t)=>{Xe.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),o=r?"int":"number",[n,i]=o0[t.format];e._zod.onattach.push(s=>{let a=s._zod.bag;a.format=t.format,a.minimum=n,a.maximum=i,r&&(a.pattern=CN)}),e._zod.check=s=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});return}}a<n&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}});var ZN=z("$ZodCheckMaxLength",(e,t)=>{var r;Xe.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!Xc(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(o._zod.bag.maximum=t.maximum)}),e._zod.check=o=>{let n=o.value;if(n.length<=t.maximum)return;let s=eu(n);o.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),FN=z("$ZodCheckMinLength",(e,t)=>{var r;Xe.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!Xc(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(o._zod.bag.minimum=t.minimum)}),e._zod.check=o=>{let n=o.value;if(n.length>=t.minimum)return;let s=eu(n);o.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),qN=z("$ZodCheckLengthEquals",(e,t)=>{var r;Xe.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!Xc(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=o=>{let n=o.value,i=n.length;if(i===t.length)return;let s=eu(n),a=i>t.length;o.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),iu=z("$ZodCheckStringFormat",(e,t)=>{var r,o;Xe.init(e,t),e._zod.onattach.push(n=>{let i=n._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(o=e._zod).check??(o.check=()=>{})}),BN=z("$ZodCheckRegex",(e,t)=>{iu.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),VN=z("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=DN),iu.init(e,t)}),WN=z("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=jN),iu.init(e,t)}),HN=z("$ZodCheckIncludes",(e,t)=>{Xe.init(e,t);let r=cn(t.includes),o=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=o,e._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(o)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),JN=z("$ZodCheckStartsWith",(e,t)=>{Xe.init(e,t);let r=new RegExp(`^${cn(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(o=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=o=>{o.value.startsWith(t.prefix)||o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:o.value,inst:e,continue:!t.abort})}}),GN=z("$ZodCheckEndsWith",(e,t)=>{Xe.init(e,t);let r=new RegExp(`.*${cn(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(o=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=o=>{o.value.endsWith(t.suffix)||o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:o.value,inst:e,continue:!t.abort})}});var KN=z("$ZodCheckOverwrite",(e,t)=>{Xe.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Op=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let o=t.split(`
|
|
73
73
|
`).filter(s=>s),n=Math.min(...o.map(s=>s.length-s.trimStart().length)),i=o.map(s=>s.slice(n)).map(s=>" ".repeat(this.indent*2)+s);for(let s of i)this.content.push(s)}compile(){let t=Function,r=this?.args,n=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...r,n.join(`
|
|
@@ -151,8 +151,9 @@ ${o.join(`
|
|
|
151
151
|
`),r&&process.stdout.write(`${JSON.stringify({status:"failed",error:I,...U})}
|
|
152
152
|
`),W),n=Gc(e.env,e.platformUrl),i=qA(e.env,e.apiKey),s=xp(e.env,e.operatorUrl);if(!n)return o(`No platform URL for environment "${e.env}". Configure it once with \`octoagent auth --env ${e.env} --platform-url <url> --api-key <oct_agt_...>\`, or pass --platform-url / set OCTAVUS_PLATFORM_URL.`,2);if(!i)return o("No API key configured. Run `octoagent auth --api-key <oct_agt_...>` or pass --api-key.",2);let a=wue(e.workdir??process.cwd());if(!e.force&&(a===Q6()||a==="/"))return o(`Refusing to run with the workspace at ${a}. cd into a project directory, pass --workdir <dir>, or --force to override.`,2);let u;try{u=X6({configFile:e.configFile,model:e.model,backupModel:e.backupModel,capabilityFlags:e.capabilities})}catch(I){return o(I instanceof Error?I.message:String(I),2)}try{let I=await fm(n);if(xue(li,I.minVersion)<0)return o(`This Octavus Agent CLI (${li}) is out of date. Update to ${I.minVersion} or newer to run.`,3)}catch(I){t.warn("Could not check the supported CLI version; continuing",{error:String(I)})}let c;try{c=await Y6(n,i,{prompt:e.prompt,config:u})}catch(I){return I instanceof gl?o(I.message,I.status===426?3:1):o(`Failed to start the run: ${String(I)}`,1)}let l=`${n}/agents/${c.octoAgentId}/chat/${c.threadId}`,f=`Started run. Watch it live: ${l}
|
|
153
153
|
`;r?process.stderr.write(f):process.stdout.write(f);let p=BA(e.env,c.octoAgentId),h=bue(a,"downloads");yue(h,{recursive:!0});let m=await J6(t),g=new dm(t),_={os:vue(),arch:_ue(),workingDirectory:a,homeDirectory:Q6(),skillsDirectory:p.skillsDir,downloadsDirectory:h,...m.dimensions?{display:m.dimensions}:{}},v=async()=>{let I=V6({workspaceDir:a,skillsDir:p.skillsDir,browserProfileDir:p.browserProfileDir,downloadsDir:h,chromePath:e.chromePath,display:m.display,fillWindowSize:m.ownsDisplay?m.dimensions:void 0}),{errors:W}=await I.start();return W.length>0&&t.warn("Some computer tools failed to start",{errors:W}),I},w=null,k,S=new Promise(I=>{k=I}),b=new DA({operatorWsUrl:s??c.operator.wsUrl,computerToken:c.operator.computerToken,octoAgentId:c.octoAgentId,onDispatch:()=>{},onDeviceControl:I=>{I.type==="start-screen-stream"&&g.start({livekitUrl:I.livekitUrl,token:I.token,roomName:I.roomName,display:m.display,dimensions:m.dimensions})},onStop:I=>w?.handleStop(I),onRequestSessionState:I=>w?.handleRequestSessionState(I),getActiveSessionIds:()=>w?.getActiveSessions().map(I=>I.sessionId)??[],onDisconnected:I=>w?.handleConnectionLost(I),onReconnected:()=>w?.handleConnectionRestored(),onStateChange:I=>{I==="connected"&&k()},logger:t}),T=new LA({octoAgentId:c.octoAgentId,connection:b,computer:v,platformUrl:n,deviceSkillsDir:p.skillsDir,agentWorkspaceDir:a,environment:_,logger:t,onComputerReset:v});w=T,T.start(),b.connect(),await Promise.race([S,new Promise(I=>{setTimeout(I,2e4)})]),b.getState()!=="connected"&&t.warn("Operator relay not connected; the run still completes, but its live view may lag");let C={type:"dispatch",sessionId:c.sessionId,operatorToken:c.driverToken,trigger:c.trigger,deviceMcpConfigs:c.deviceMcpConfigs,deviceSkillConfigs:c.deviceSkillConfigs},N;try{N=await T.runLocalDispatch(C)}finally{g.stop(),await T.stop(),await b.closeGracefully(),m.cleanup()}return r?(process.stdout.write(`${JSON.stringify({threadId:c.threadId,sessionId:c.sessionId,status:N.status,threadUrl:l,...N.error?{error:N.error}:{}})}
|
|
154
|
-
`),N.status==="completed"?0:1):N.status==="completed"?(process.stdout.write(`Run completed. View: ${l}
|
|
155
|
-
`),0):(process.
|
|
154
|
+
`),N.status==="completed"?0:N.status==="cancelled"?4:1):N.status==="completed"?(process.stdout.write(`Run completed. View: ${l}
|
|
155
|
+
`),0):N.status==="cancelled"?(process.stdout.write(`Run stopped from the dashboard. View: ${l}
|
|
156
|
+
`),4):(process.stderr.write(`Error: Run ${N.status}${N.error?`: ${N.error}`:""}. View: ${l}
|
|
156
157
|
`),1)}var Sue=new Set(["json","force","verbose"]);function $ue(e){let t=[],r={};for(let o=0;o<e.length;o++){let n=e[o];if(n.startsWith("--")){let i=n.slice(2),s=i.indexOf("=");if(s>=0)r[i.slice(0,s)]=i.slice(s+1);else if(Sue.has(i))r[i]=!0;else{let a=e[o+1];a!==void 0&&!a.startsWith("--")?(r[i]=a,o+=1):r[i]=!0}}else t.push(n)}return{positionals:t,flags:r}}function it(e){return typeof e=="string"?e:void 0}function kue(e,t){let r=[];for(let o=0;o<e.length;o+=1){let n=e[o];if(n===`--${t}`){let i=e[o+1];i!==void 0&&!i.startsWith("--")&&(r.push(i),o+=1)}else n.startsWith(`--${t}=`)&&r.push(n.slice(t.length+3))}return r}var tF=`octoagent - run your cloud Octavus Agent on a machine you control
|
|
157
158
|
|
|
158
159
|
Usage:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@octavus/agent",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"description": "Octavus Agent CLI - run one of your cloud Octavus Agents on a machine you control, using that machine as the agent's computer. The agent lives in the cloud (fully configured and observable); the local machine only supplies the computer and the trigger.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"octavus",
|