@robota-sdk/agent-cli 3.0.0-beta.81 → 3.0.0-beta.82

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.
@@ -1,4 +1,4 @@
1
- import{B as e,Mt as t,T as n,et as r,o as i,st as a,yt as o}from"./node-CJnrbkAS.js";import{a as s,d as c,n as l,s as u,v as d}from"./bounded-output-DpjpS98g-DFgAppgl.js";import"./command-executor-DV-H2oD6-OKy8pwYH.js";import"./http-executor-cWzI2svn-TG_TMYKh.js";import{randomBytes as f,randomUUID as p}from"node:crypto";import{basename as m,dirname as h,isAbsolute as g,join as _,posix as v,relative as y,resolve as b,sep as ee}from"node:path";import{spawn as x,spawnSync as te}from"node:child_process";import{chmod as ne,mkdir as re,open as ie,readFile as ae,readdir as oe,rename as se,rm as ce,stat as S,writeFile as le}from"node:fs/promises";import{accessSync as ue,chmodSync as de,constants as fe,cpSync as pe,createReadStream as me,existsSync as he,lstatSync as ge,mkdirSync as C,readFileSync as _e,readdirSync as ve,readlinkSync as ye,realpathSync as w,renameSync as T,rmSync as be,statSync as E,symlinkSync as xe,unlinkSync as Se,writeFileSync as Ce}from"node:fs";import{homedir as we,tmpdir as Te}from"node:os";import{z as D}from"zod";import{lookup as Ee}from"node:dns/promises";import{isIP as De}from"node:net";import Oe from"fast-glob";import ke from"p-limit";import{EventEmitter as Ae}from"node:events";import{Worker as je}from"node:worker_threads";const Me=2e3,Ne=process.platform===`win32`;function O(e){return e.exitCode!==null||e.signalCode!==null}function Pe(e,t,n){if(n&&!Ne&&typeof e.pid==`number`)try{process.kill(-e.pid,t);return}catch{}try{e.kill(t)}catch{}}function Fe(e,t){if(Ne&&typeof e.pid==`number`){te(`taskkill`,[`/pid`,String(e.pid),`/T`,`/F`],{stdio:`ignore`});return}Pe(e,`SIGKILL`,t)}async function k(e,t={}){let n=t.graceMs??2e3,r=t.signal??`SIGTERM`,i=t.processGroup??!1;if(!O(e)){if(typeof e.pid!=`number`)throw Error(`[agent-process] killProcessTree called with an unspawned child (no pid)`);if(t.preKill){try{await t.preKill()}catch{}if(O(e))return}return new Promise(t=>{let a,o=()=>{a&&clearTimeout(a),t()};if(e.once(`exit`,o),O(e)){e.removeListener(`exit`,o),t();return}Pe(e,r,i),a=setTimeout(()=>{O(e)||Fe(e,i)},n),a.unref?.()})}}function Ie(e){if(typeof e!=`string`)throw TypeError(`executionRoot must be a string`);if(e.trim().length===0)throw TypeError(`executionRoot must be a non-empty string`);if(!g(e))throw TypeError(`executionRoot must be an absolute path`);let t;try{t=w(e)}catch{throw TypeError(`executionRoot must name an existing accessible directory`)}if(!E(t).isDirectory())throw TypeError(`executionRoot must name a directory`);try{ue(t,fe.R_OK|fe.X_OK)}catch{throw TypeError(`executionRoot directory must be readable and traversable`)}return t}function Le(e){let t=[],n=b(e);for(;;)try{return _(w(n),...t)}catch{let r=h(n);if(r===n)return b(e);t.unshift(m(n)),n=r}}function Re(e,t){let n=Le(e),r=Le(t);return r===n||r.startsWith(n+ee)}var ze=class extends Error{constructor(e){super(e),this.name=`OwnerOnlyModeError`}};function A(e=process.platform){return e===`win32`?`windows-acl`:`posix-mode`}function Be(e,t){let n=y(e,t);if(n.startsWith(`..`)||g(n))throw new ze(`withinRoot ${e} is not an ancestor of ${t}, so this call cannot own the path between them.`);let r=n.split(ee).filter(e=>e.length>0),i=[e],a=e;for(let e of r)a=_(a,e),i.push(a);return i}function j(e,t,n={}){if(A()!==`posix-mode`)return;let r=(n.readMode??(e=>E(e).mode&4095))(e);if(r&63)throw new ze(`${t} ${e} is mode 0${r.toString(8)} after being set owner-only; group or other permissions survived, so its contents are readable by another account.`)}function Ve(e,t={}){let n=t.makeDirectory??((e,t)=>{C(e,{recursive:!0,mode:t})}),r=t.setMode??((e,t)=>de(e,t));n(e,448);let i=t.withinRoot===void 0?[e]:Be(t.withinRoot,e);for(let e of i)A()===`posix-mode`&&r(e,448),j(e,`directory`,t)}function He(e,t){Ve(h(e));let n=`${e}.${process.pid}.tmp`;be(n,{force:!0}),Ce(n,t,{encoding:`utf8`,mode:384,flag:`wx`});try{j(n,`file`),T(n,e)}catch(e){try{Se(n)}catch{}throw e}j(e,`file`)}function Ue(e){if(A()!==`posix-mode`)return;let t;try{t=E(e).mode&4095}catch{return}t&63&&(de(e,384),j(e,`file`))}function We(e){let t=De(e);return t===4?Ge(e.split(`.`).map(Number)):t!==6||Ke(e)}function Ge(e){let[t=0,n=0,r=0]=e;return t===0||t===10||t===127||t===100&&n>=64&&n<=127||t===169&&n===254||t===172&&n>=16&&n<=31||t===192&&n===0&&r===0||t===192&&n===168||t===198&&(n===18||n===19)||t>=224}function Ke(e){let t=Je(e);if(t===void 0)return!0;let[n=0,r=0,i=0,a=0,o=0,s=0,c=0,l=0]=t;return n===0&&r===0&&i===0&&a===0&&o===0&&s===65535||n===100&&r===65435&&i===0&&a===0&&o===0&&s===0?Ge([c>>8,c&255,l>>8,l&255]):n===0&&r===0&&i===0&&a===0&&o===0&&s===0||(n&65024)==64512||(n&65472)==65152||(n&65472)==65216||(n&65280)==65280}function qe(e){let t=e.lastIndexOf(`:`),n=e.slice(t+1);if(!n.includes(`.`))return e;if(t<0||De(n)!==4)return;let[r=0,i=0,a=0,o=0]=n.split(`.`).map(Number),s=(r<<8|i).toString(16),c=(a<<8|o).toString(16);return`${e.slice(0,t+1)}${s}:${c}`}function Je(e){let t=qe(e.split(`%`)[0]??e);if(t===void 0)return;let n=t.split(`::`);if(n.length>2)return;let r=e=>e.length===0?[]:e.split(`:`).map(e=>Number.parseInt(e,16)),i=r(n[0]??``),a=n.length===2?r(n[1]??``):[],o=8-i.length-a.length;if(o<0||n.length===1&&o!==0)return;let s=[...i,...Array(o).fill(0),...a];return s.some(e=>Number.isNaN(e)||e<0||e>65535)?void 0:s}const Ye=3e4,Xe=5e6,Ze=new Set([301,302,303,307,308]),Qe=new Set([`localhost`,`metadata`,`metadata.google.internal`,`metadata.goog`,`instance-data`,`instance-data.ec2.internal`]),M=async e=>(await Ee(e,{all:!0,verbatim:!0})).map(e=>e.address);async function N(e,t={},n=M){let r=e.href;if(e.protocol!==`http:`&&e.protocol!==`https:`)return{reason:`unsupported_scheme`,url:r,message:`Only http(s) URLs may be fetched.`};if(t.allowPrivateAddresses===!0)return;let i=e.hostname.replace(/^\[|\]$/g,``).toLowerCase();if(t.allowedHosts?.includes(i))return;if(Qe.has(i)||i.endsWith(`.localhost`))return{reason:`metadata_host`,url:r,message:`Destination "${i}" is a loopback or cloud-metadata host and is not reachable from tools.`};let a=De(i)?[i]:await $e(i,n);if(a===void 0||a.length===0)return{reason:`unresolvable`,url:r,message:`Destination "${i}" did not resolve.`};let o=a.find(We);if(o!==void 0)return{reason:`private_destination`,url:r,message:`Destination "${i}" resolves to ${o}, a private, loopback or link-local address, and is not reachable from tools.`}}async function $e(e,t){try{return await t(e)}catch{return}}async function et(e,t={},n={},r={}){let i=r.fetch??((e,t)=>globalThis.fetch(e,t)),a=r.lookup??M,o=t.maxResponseBytes??Xe,s=n.maxRedirects??5,c=AbortSignal.timeout(t.timeoutMs??Ye),l=t.signal?AbortSignal.any([c,t.signal]):c,u=new URL(e),d={...t.headers??{}};for(let e=0;;e+=1){let t=await N(u,n,a);if(t!==void 0)return{ok:!1,rejection:t};let r=await i(u.href,{headers:d,signal:l,redirect:`manual`});if(!Ze.has(r.status))return rt(r,u.href,o,l);let c=r.headers.get(`location`);if(c===null)return{ok:!1,rejection:{reason:`redirect_without_location`,url:u.href,message:`HTTP ${r.status} without a Location header.`}};if(e>=s)return{ok:!1,rejection:{reason:`redirect_limit`,url:u.href,message:`More than ${s} redirects.`}};let f=new URL(c,u);f.origin!==u.origin&&(d=nt(d)),u=f}}async function tt(e,t,n={},r={}){let i=r.fetch??((e,t)=>globalThis.fetch(e,t)),a=t.maxResponseBytes??Xe,o=AbortSignal.timeout(t.timeoutMs??Ye),s=t.signal?AbortSignal.any([o,t.signal]):o,c=new URL(e),l=await N(c,n,r.lookup??M);if(l!==void 0)return{ok:!1,rejection:l};let u=await i(c.href,{method:`POST`,headers:{...t.headers??{}},body:t.body,signal:s,redirect:`manual`});return u.status>=300&&u.status<400?(await u.body?.cancel().catch(()=>void 0),{ok:!1,rejection:{reason:`redirect_refused`,url:c.href,message:`HTTP ${u.status}: a POST is never redirected.`}}):rt(u,c.href,a,s)}function nt(e){let t={};for(let[n,r]of Object.entries(e))n.toLowerCase()===`user-agent`&&(t[n]=r);return t}async function rt(e,t,n,r){let i=e=>({ok:!1,rejection:{reason:`response_too_large`,url:t,message:`Response exceeds ${n} bytes (${e} seen).`}}),a=Number(e.headers.get(`content-length`));if(Number.isFinite(a)&&a>n)return await e.body?.cancel(),i(a);let o=[],s=0;if(!e.body&&typeof e.arrayBuffer==`function`){let t=new Uint8Array(await e.arrayBuffer());if(t.byteLength>n)return i(t.byteLength);o.push(t),s=t.byteLength}else if(e.body){let t=e.body.getReader();for(;;){r.throwIfAborted();let{done:e,value:a}=await t.read();if(e)break;if(s+=a.byteLength,s>n)return await t.cancel(),i(s);o.push(a)}}let c=new Uint8Array(s),l=0;for(let e of o)c.set(e,l),l+=e.byteLength;return{ok:!0,status:e.status,statusText:e.statusText,headers:e.headers,body:c,finalUrl:t}}function it(e){return e===void 0?`host`:`sandbox-${e.filesystem??`separate`}`}function at(e){return it(e)===`sandbox-separate`}function ot(e){let t=[];e.environment&&Object.keys(e.environment).length>0&&t.push(`environment`);let n=e.permissions;if(n&&Object.values(n).some(e=>Array.isArray(e)?e.length>0:e!==void 0)&&t.push(`permissions`),t.length!==0)throw Error(`workspace manifest requests ${t.join(` and `)}, which this sandbox client cannot enforce. The built-in applicator applies entries only. Supply a sandbox client that implements applyManifest and honours these fields, or remove them from the manifest — they were previously accepted and silently ignored, which reported a sandbox policy that was never applied (issue #2027).`)}const st=/^[A-Za-z]:[\\/]/,ct=/'/g;async function lt(e,t,n={}){if(e.applyManifest)return e.applyManifest(t,n);ot(t);let r=bt(n.targetRoot??`/workspace`),i=[];for(let[a,o]of Object.entries(t.entries)){let t=ut(a),s=xt(r,t);i.push(await dt(e,t,s,r,o,n))}return{entries:i}}function ut(e){if(e.length===0)throw Error(`workspace manifest path must not be empty`);if(e.includes(`\0`))throw Error(`workspace manifest path must not contain NUL bytes`);if(e.startsWith(`/`)||e.startsWith(`\\`)||st.test(e))throw Error(`workspace manifest path must be workspace-relative`);let t=e.replace(/\\/g,`/`).split(`/`).filter(Boolean);if(t.length===0)throw Error(`workspace manifest path must not resolve to the workspace root`);if(t.some(e=>e===`..`))throw Error(`workspace manifest path cannot contain traversal segments`);let n=t.filter(e=>e!==`.`);if(n.length===0)throw Error(`workspace manifest path must not resolve to the workspace root`);return n.join(`/`)}async function dt(e,t,n,r,i,a){switch(i.type){case`file`:return await gt(e,n,r,i.content),P(t,i.type);case`dir`:return await F(e,n),P(t,i.type);case`localFile`:return await ft(e,i.src,n,r,a),P(t,i.type);case`localDir`:return await pt(e,i.src,n,a),P(t,i.type);case`gitRepo`:return await ht(e,i,n),P(t,i.type);case`s3Mount`:case`gcsMount`:case`r2Mount`:case`azureBlobMount`:return{path:t,type:i.type,status:`unsupported`,message:`${i.type} requires a provider-specific sandbox adapter.`};default:return St(i)}}function P(e,t){return{path:e,type:t,status:`applied`}}async function ft(e,t,n,r,i){await gt(e,n,r,await ae(vt(t,i.hostRoot),`utf8`))}async function pt(e,t,n,r){await mt(e,vt(t,r.hostRoot),n)}async function mt(e,t,n){await F(e,n);let r=await oe(t,{withFileTypes:!0});for(let i of r){let r=_(t,i.name),a=xt(n,i.name);if(i.isDirectory()){await mt(e,r,a);continue}if(i.isFile()){let t=await ae(r,`utf8`);await e.writeFile(a,t)}}}async function ht(e,t,n){await _t(e,`git clone${t.shallow===!1?``:` --depth 1`}${t.ref?` --branch ${I(t.ref)}`:``} ${I(t.url)} ${I(n)}`)}async function gt(e,t,n,r){let i=v.dirname(t);i!==n&&await F(e,i),await e.writeFile(t,r)}async function F(e,t){await _t(e,`mkdir -p ${I(t)}`)}async function _t(e,t){let n=await e.run(t);if(n.exitCode!==0)throw Error(`workspace manifest command failed: ${t}\n${n.stderr??n.stdout}`)}function vt(e,t){return g(e)?b(e):b(t??process.cwd(),e)}function yt(e){let t=e.length;for(;t>0&&e[t-1]===`/`;)--t;return e.slice(0,t)}function bt(e){let t=yt(e.replace(/\\/g,`/`));if(!t.startsWith(`/`))throw Error(`workspace manifest targetRoot must be an absolute sandbox path`);return t.length===0?`/`:t}function xt(e,t){let n=bt(e);return n===`/`?`/${t}`:`${n}/${t}`}function I(e){return`'${e.replace(ct,`'\\''`)}'`}function St(e){throw Error(`unsupported workspace manifest entry: ${JSON.stringify(e)}`)}const Ct=[`.robota/worktrees`,`.claude/worktrees`];function L(e,t){let n=e.length;for(;n>0&&e[n-1]===`/`;)--n;return`${e.slice(0,n)}/${t}`}function wt(){return[...a,...o]}function Tt(e){let{policy:t}=e,n=[`--ro-bind`,`/`,`/`,`--dev`,`/dev`,`--proc`,`/proc`];for(let e of[t.root,...t.tempDirectories,...t.allowWrite])n.push(`--bind-try`,e,e);for(let r of wt()){let i=L(t.root,r);e.exists(i)&&n.push(`--ro-bind`,i,i)}for(let r of Ct){let i=L(t.root,r);if(e.exists(i)){n.push(`--bind`,i,i);for(let t of e.listDirectory(i)){let r=L(i,`${t}/.git`);e.exists(r)&&n.push(`--ro-bind`,r,r)}}}for(let r of t.denyRead)e.exists(r.path)&&(r.directory?n.push(`--tmpfs`,r.path):n.push(`--ro-bind`,`/dev/null`,r.path));if(!t.network){if(e.seccompDescriptor===void 0)throw Error(`A sandbox without network needs the Unix-socket seccomp filter.`);n.push(`--unshare-net`,`--seccomp`,String(e.seccompDescriptor))}return n.push(`--unshare-pid`,`--die-with-parent`,`--new-session`,`--chdir`,e.cwd),n.push(`--`,e.command),[...n,...e.args]}function Et(e){return e.replace(/[\\^$.*+?()[\]{}|"]/g,e=>`\\${e}`)}function R(e){return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function Dt(e){let t=[e.root,...e.tempDirectories,...e.allowWrite].map(e=>`(subpath ${R(e)})`).join(` `),n=wt().map(t=>{let n=L(e.root,t);return o.includes(t)?`(literal ${R(n)})`:`(subpath ${R(n)})`}),r=Ct.map(t=>`(subpath ${R(L(e.root,t))})`),i=[`(literal ${R(L(e.root,`.git`))})`,...Ct.map(t=>`(regex #"^${Et(L(e.root,t))}/[^/]+/\\.git$")`)],a=[`(version 1)`,`(allow default)`,`(deny file-write*)`,`(allow file-write* ${t} (literal "/dev/null") (regex #"^/dev/tty") (regex #"^/dev/fd/"))`,`(deny file-write* ${n.join(` `)})`,`(allow file-write* ${r.join(` `)})`,`(deny file-write* ${i.join(` `)})`];if(e.denyRead.length>0){let t=e.denyRead.map(e=>e.directory?`(subpath ${R(e.path)})`:`(literal ${R(e.path)})`);a.push(`(deny file-read* ${t.join(` `)})`)}return e.network||a.push(`(deny network*)`),a.join(`
1
+ import{B as e,Mt as t,T as n,et as r,o as i,st as a,yt as o}from"./node-CQqDd5KI.js";import{a as s,d as c,n as l,s as u,v as d}from"./bounded-output-DpjpS98g-DFgAppgl.js";import"./command-executor-DV-H2oD6-OKy8pwYH.js";import"./http-executor-cWzI2svn-TG_TMYKh.js";import{randomBytes as f,randomUUID as p}from"node:crypto";import{basename as m,dirname as h,isAbsolute as g,join as _,posix as v,relative as y,resolve as b,sep as ee}from"node:path";import{spawn as x,spawnSync as te}from"node:child_process";import{chmod as ne,mkdir as re,open as ie,readFile as ae,readdir as oe,rename as se,rm as ce,stat as S,writeFile as le}from"node:fs/promises";import{accessSync as ue,chmodSync as de,constants as fe,cpSync as pe,createReadStream as me,existsSync as he,lstatSync as ge,mkdirSync as C,readFileSync as _e,readdirSync as ve,readlinkSync as ye,realpathSync as w,renameSync as T,rmSync as be,statSync as E,symlinkSync as xe,unlinkSync as Se,writeFileSync as Ce}from"node:fs";import{homedir as we,tmpdir as Te}from"node:os";import{z as D}from"zod";import{lookup as Ee}from"node:dns/promises";import{isIP as De}from"node:net";import Oe from"fast-glob";import ke from"p-limit";import{EventEmitter as Ae}from"node:events";import{Worker as je}from"node:worker_threads";const Me=2e3,Ne=process.platform===`win32`;function O(e){return e.exitCode!==null||e.signalCode!==null}function Pe(e,t,n){if(n&&!Ne&&typeof e.pid==`number`)try{process.kill(-e.pid,t);return}catch{}try{e.kill(t)}catch{}}function Fe(e,t){if(Ne&&typeof e.pid==`number`){te(`taskkill`,[`/pid`,String(e.pid),`/T`,`/F`],{stdio:`ignore`});return}Pe(e,`SIGKILL`,t)}async function k(e,t={}){let n=t.graceMs??2e3,r=t.signal??`SIGTERM`,i=t.processGroup??!1;if(!O(e)){if(typeof e.pid!=`number`)throw Error(`[agent-process] killProcessTree called with an unspawned child (no pid)`);if(t.preKill){try{await t.preKill()}catch{}if(O(e))return}return new Promise(t=>{let a,o=()=>{a&&clearTimeout(a),t()};if(e.once(`exit`,o),O(e)){e.removeListener(`exit`,o),t();return}Pe(e,r,i),a=setTimeout(()=>{O(e)||Fe(e,i)},n),a.unref?.()})}}function Ie(e){if(typeof e!=`string`)throw TypeError(`executionRoot must be a string`);if(e.trim().length===0)throw TypeError(`executionRoot must be a non-empty string`);if(!g(e))throw TypeError(`executionRoot must be an absolute path`);let t;try{t=w(e)}catch{throw TypeError(`executionRoot must name an existing accessible directory`)}if(!E(t).isDirectory())throw TypeError(`executionRoot must name a directory`);try{ue(t,fe.R_OK|fe.X_OK)}catch{throw TypeError(`executionRoot directory must be readable and traversable`)}return t}function Le(e){let t=[],n=b(e);for(;;)try{return _(w(n),...t)}catch{let r=h(n);if(r===n)return b(e);t.unshift(m(n)),n=r}}function Re(e,t){let n=Le(e),r=Le(t);return r===n||r.startsWith(n+ee)}var ze=class extends Error{constructor(e){super(e),this.name=`OwnerOnlyModeError`}};function A(e=process.platform){return e===`win32`?`windows-acl`:`posix-mode`}function Be(e,t){let n=y(e,t);if(n.startsWith(`..`)||g(n))throw new ze(`withinRoot ${e} is not an ancestor of ${t}, so this call cannot own the path between them.`);let r=n.split(ee).filter(e=>e.length>0),i=[e],a=e;for(let e of r)a=_(a,e),i.push(a);return i}function j(e,t,n={}){if(A()!==`posix-mode`)return;let r=(n.readMode??(e=>E(e).mode&4095))(e);if(r&63)throw new ze(`${t} ${e} is mode 0${r.toString(8)} after being set owner-only; group or other permissions survived, so its contents are readable by another account.`)}function Ve(e,t={}){let n=t.makeDirectory??((e,t)=>{C(e,{recursive:!0,mode:t})}),r=t.setMode??((e,t)=>de(e,t));n(e,448);let i=t.withinRoot===void 0?[e]:Be(t.withinRoot,e);for(let e of i)A()===`posix-mode`&&r(e,448),j(e,`directory`,t)}function He(e,t){Ve(h(e));let n=`${e}.${process.pid}.tmp`;be(n,{force:!0}),Ce(n,t,{encoding:`utf8`,mode:384,flag:`wx`});try{j(n,`file`),T(n,e)}catch(e){try{Se(n)}catch{}throw e}j(e,`file`)}function Ue(e){if(A()!==`posix-mode`)return;let t;try{t=E(e).mode&4095}catch{return}t&63&&(de(e,384),j(e,`file`))}function We(e){let t=De(e);return t===4?Ge(e.split(`.`).map(Number)):t!==6||Ke(e)}function Ge(e){let[t=0,n=0,r=0]=e;return t===0||t===10||t===127||t===100&&n>=64&&n<=127||t===169&&n===254||t===172&&n>=16&&n<=31||t===192&&n===0&&r===0||t===192&&n===168||t===198&&(n===18||n===19)||t>=224}function Ke(e){let t=Je(e);if(t===void 0)return!0;let[n=0,r=0,i=0,a=0,o=0,s=0,c=0,l=0]=t;return n===0&&r===0&&i===0&&a===0&&o===0&&s===65535||n===100&&r===65435&&i===0&&a===0&&o===0&&s===0?Ge([c>>8,c&255,l>>8,l&255]):n===0&&r===0&&i===0&&a===0&&o===0&&s===0||(n&65024)==64512||(n&65472)==65152||(n&65472)==65216||(n&65280)==65280}function qe(e){let t=e.lastIndexOf(`:`),n=e.slice(t+1);if(!n.includes(`.`))return e;if(t<0||De(n)!==4)return;let[r=0,i=0,a=0,o=0]=n.split(`.`).map(Number),s=(r<<8|i).toString(16),c=(a<<8|o).toString(16);return`${e.slice(0,t+1)}${s}:${c}`}function Je(e){let t=qe(e.split(`%`)[0]??e);if(t===void 0)return;let n=t.split(`::`);if(n.length>2)return;let r=e=>e.length===0?[]:e.split(`:`).map(e=>Number.parseInt(e,16)),i=r(n[0]??``),a=n.length===2?r(n[1]??``):[],o=8-i.length-a.length;if(o<0||n.length===1&&o!==0)return;let s=[...i,...Array(o).fill(0),...a];return s.some(e=>Number.isNaN(e)||e<0||e>65535)?void 0:s}const Ye=3e4,Xe=5e6,Ze=new Set([301,302,303,307,308]),Qe=new Set([`localhost`,`metadata`,`metadata.google.internal`,`metadata.goog`,`instance-data`,`instance-data.ec2.internal`]),M=async e=>(await Ee(e,{all:!0,verbatim:!0})).map(e=>e.address);async function N(e,t={},n=M){let r=e.href;if(e.protocol!==`http:`&&e.protocol!==`https:`)return{reason:`unsupported_scheme`,url:r,message:`Only http(s) URLs may be fetched.`};if(t.allowPrivateAddresses===!0)return;let i=e.hostname.replace(/^\[|\]$/g,``).toLowerCase();if(t.allowedHosts?.includes(i))return;if(Qe.has(i)||i.endsWith(`.localhost`))return{reason:`metadata_host`,url:r,message:`Destination "${i}" is a loopback or cloud-metadata host and is not reachable from tools.`};let a=De(i)?[i]:await $e(i,n);if(a===void 0||a.length===0)return{reason:`unresolvable`,url:r,message:`Destination "${i}" did not resolve.`};let o=a.find(We);if(o!==void 0)return{reason:`private_destination`,url:r,message:`Destination "${i}" resolves to ${o}, a private, loopback or link-local address, and is not reachable from tools.`}}async function $e(e,t){try{return await t(e)}catch{return}}async function et(e,t={},n={},r={}){let i=r.fetch??((e,t)=>globalThis.fetch(e,t)),a=r.lookup??M,o=t.maxResponseBytes??Xe,s=n.maxRedirects??5,c=AbortSignal.timeout(t.timeoutMs??Ye),l=t.signal?AbortSignal.any([c,t.signal]):c,u=new URL(e),d={...t.headers??{}};for(let e=0;;e+=1){let t=await N(u,n,a);if(t!==void 0)return{ok:!1,rejection:t};let r=await i(u.href,{headers:d,signal:l,redirect:`manual`});if(!Ze.has(r.status))return rt(r,u.href,o,l);let c=r.headers.get(`location`);if(c===null)return{ok:!1,rejection:{reason:`redirect_without_location`,url:u.href,message:`HTTP ${r.status} without a Location header.`}};if(e>=s)return{ok:!1,rejection:{reason:`redirect_limit`,url:u.href,message:`More than ${s} redirects.`}};let f=new URL(c,u);f.origin!==u.origin&&(d=nt(d)),u=f}}async function tt(e,t,n={},r={}){let i=r.fetch??((e,t)=>globalThis.fetch(e,t)),a=t.maxResponseBytes??Xe,o=AbortSignal.timeout(t.timeoutMs??Ye),s=t.signal?AbortSignal.any([o,t.signal]):o,c=new URL(e),l=await N(c,n,r.lookup??M);if(l!==void 0)return{ok:!1,rejection:l};let u=await i(c.href,{method:`POST`,headers:{...t.headers??{}},body:t.body,signal:s,redirect:`manual`});return u.status>=300&&u.status<400?(await u.body?.cancel().catch(()=>void 0),{ok:!1,rejection:{reason:`redirect_refused`,url:c.href,message:`HTTP ${u.status}: a POST is never redirected.`}}):rt(u,c.href,a,s)}function nt(e){let t={};for(let[n,r]of Object.entries(e))n.toLowerCase()===`user-agent`&&(t[n]=r);return t}async function rt(e,t,n,r){let i=e=>({ok:!1,rejection:{reason:`response_too_large`,url:t,message:`Response exceeds ${n} bytes (${e} seen).`}}),a=Number(e.headers.get(`content-length`));if(Number.isFinite(a)&&a>n)return await e.body?.cancel(),i(a);let o=[],s=0;if(!e.body&&typeof e.arrayBuffer==`function`){let t=new Uint8Array(await e.arrayBuffer());if(t.byteLength>n)return i(t.byteLength);o.push(t),s=t.byteLength}else if(e.body){let t=e.body.getReader();for(;;){r.throwIfAborted();let{done:e,value:a}=await t.read();if(e)break;if(s+=a.byteLength,s>n)return await t.cancel(),i(s);o.push(a)}}let c=new Uint8Array(s),l=0;for(let e of o)c.set(e,l),l+=e.byteLength;return{ok:!0,status:e.status,statusText:e.statusText,headers:e.headers,body:c,finalUrl:t}}function it(e){return e===void 0?`host`:`sandbox-${e.filesystem??`separate`}`}function at(e){return it(e)===`sandbox-separate`}function ot(e){let t=[];e.environment&&Object.keys(e.environment).length>0&&t.push(`environment`);let n=e.permissions;if(n&&Object.values(n).some(e=>Array.isArray(e)?e.length>0:e!==void 0)&&t.push(`permissions`),t.length!==0)throw Error(`workspace manifest requests ${t.join(` and `)}, which this sandbox client cannot enforce. The built-in applicator applies entries only. Supply a sandbox client that implements applyManifest and honours these fields, or remove them from the manifest — they were previously accepted and silently ignored, which reported a sandbox policy that was never applied (issue #2027).`)}const st=/^[A-Za-z]:[\\/]/,ct=/'/g;async function lt(e,t,n={}){if(e.applyManifest)return e.applyManifest(t,n);ot(t);let r=bt(n.targetRoot??`/workspace`),i=[];for(let[a,o]of Object.entries(t.entries)){let t=ut(a),s=xt(r,t);i.push(await dt(e,t,s,r,o,n))}return{entries:i}}function ut(e){if(e.length===0)throw Error(`workspace manifest path must not be empty`);if(e.includes(`\0`))throw Error(`workspace manifest path must not contain NUL bytes`);if(e.startsWith(`/`)||e.startsWith(`\\`)||st.test(e))throw Error(`workspace manifest path must be workspace-relative`);let t=e.replace(/\\/g,`/`).split(`/`).filter(Boolean);if(t.length===0)throw Error(`workspace manifest path must not resolve to the workspace root`);if(t.some(e=>e===`..`))throw Error(`workspace manifest path cannot contain traversal segments`);let n=t.filter(e=>e!==`.`);if(n.length===0)throw Error(`workspace manifest path must not resolve to the workspace root`);return n.join(`/`)}async function dt(e,t,n,r,i,a){switch(i.type){case`file`:return await gt(e,n,r,i.content),P(t,i.type);case`dir`:return await F(e,n),P(t,i.type);case`localFile`:return await ft(e,i.src,n,r,a),P(t,i.type);case`localDir`:return await pt(e,i.src,n,a),P(t,i.type);case`gitRepo`:return await ht(e,i,n),P(t,i.type);case`s3Mount`:case`gcsMount`:case`r2Mount`:case`azureBlobMount`:return{path:t,type:i.type,status:`unsupported`,message:`${i.type} requires a provider-specific sandbox adapter.`};default:return St(i)}}function P(e,t){return{path:e,type:t,status:`applied`}}async function ft(e,t,n,r,i){await gt(e,n,r,await ae(vt(t,i.hostRoot),`utf8`))}async function pt(e,t,n,r){await mt(e,vt(t,r.hostRoot),n)}async function mt(e,t,n){await F(e,n);let r=await oe(t,{withFileTypes:!0});for(let i of r){let r=_(t,i.name),a=xt(n,i.name);if(i.isDirectory()){await mt(e,r,a);continue}if(i.isFile()){let t=await ae(r,`utf8`);await e.writeFile(a,t)}}}async function ht(e,t,n){await _t(e,`git clone${t.shallow===!1?``:` --depth 1`}${t.ref?` --branch ${I(t.ref)}`:``} ${I(t.url)} ${I(n)}`)}async function gt(e,t,n,r){let i=v.dirname(t);i!==n&&await F(e,i),await e.writeFile(t,r)}async function F(e,t){await _t(e,`mkdir -p ${I(t)}`)}async function _t(e,t){let n=await e.run(t);if(n.exitCode!==0)throw Error(`workspace manifest command failed: ${t}\n${n.stderr??n.stdout}`)}function vt(e,t){return g(e)?b(e):b(t??process.cwd(),e)}function yt(e){let t=e.length;for(;t>0&&e[t-1]===`/`;)--t;return e.slice(0,t)}function bt(e){let t=yt(e.replace(/\\/g,`/`));if(!t.startsWith(`/`))throw Error(`workspace manifest targetRoot must be an absolute sandbox path`);return t.length===0?`/`:t}function xt(e,t){let n=bt(e);return n===`/`?`/${t}`:`${n}/${t}`}function I(e){return`'${e.replace(ct,`'\\''`)}'`}function St(e){throw Error(`unsupported workspace manifest entry: ${JSON.stringify(e)}`)}const Ct=[`.robota/worktrees`,`.claude/worktrees`];function L(e,t){let n=e.length;for(;n>0&&e[n-1]===`/`;)--n;return`${e.slice(0,n)}/${t}`}function wt(){return[...a,...o]}function Tt(e){let{policy:t}=e,n=[`--ro-bind`,`/`,`/`,`--dev`,`/dev`,`--proc`,`/proc`];for(let e of[t.root,...t.tempDirectories,...t.allowWrite])n.push(`--bind-try`,e,e);for(let r of wt()){let i=L(t.root,r);e.exists(i)&&n.push(`--ro-bind`,i,i)}for(let r of Ct){let i=L(t.root,r);if(e.exists(i)){n.push(`--bind`,i,i);for(let t of e.listDirectory(i)){let r=L(i,`${t}/.git`);e.exists(r)&&n.push(`--ro-bind`,r,r)}}}for(let r of t.denyRead)e.exists(r.path)&&(r.directory?n.push(`--tmpfs`,r.path):n.push(`--ro-bind`,`/dev/null`,r.path));if(!t.network){if(e.seccompDescriptor===void 0)throw Error(`A sandbox without network needs the Unix-socket seccomp filter.`);n.push(`--unshare-net`,`--seccomp`,String(e.seccompDescriptor))}return n.push(`--unshare-pid`,`--die-with-parent`,`--new-session`,`--chdir`,e.cwd),n.push(`--`,e.command),[...n,...e.args]}function Et(e){return e.replace(/[\\^$.*+?()[\]{}|"]/g,e=>`\\${e}`)}function R(e){return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function Dt(e){let t=[e.root,...e.tempDirectories,...e.allowWrite].map(e=>`(subpath ${R(e)})`).join(` `),n=wt().map(t=>{let n=L(e.root,t);return o.includes(t)?`(literal ${R(n)})`:`(subpath ${R(n)})`}),r=Ct.map(t=>`(subpath ${R(L(e.root,t))})`),i=[`(literal ${R(L(e.root,`.git`))})`,...Ct.map(t=>`(regex #"^${Et(L(e.root,t))}/[^/]+/\\.git$")`)],a=[`(version 1)`,`(allow default)`,`(deny file-write*)`,`(allow file-write* ${t} (literal "/dev/null") (regex #"^/dev/tty") (regex #"^/dev/fd/"))`,`(deny file-write* ${n.join(` `)})`,`(allow file-write* ${r.join(` `)})`,`(deny file-write* ${i.join(` `)})`];if(e.denyRead.length>0){let t=e.denyRead.map(e=>e.directory?`(subpath ${R(e.path)})`:`(literal ${R(e.path)})`);a.push(`(deny file-read* ${t.join(` `)})`)}return e.network||a.push(`(deny network*)`),a.join(`
2
2
  `)}const Ot={x64:{audit:3221225534,socket:41,ioUringSetup:425},arm64:{audit:3221225655,socket:198,ioUringSetup:425}};function z(e,t,n,r){return[e,t,n,r]}function kt(e=process.arch){let t=Ot[e];if(t===void 0)return;let n=e=>327680|e,r=[z(32,0,0,4),z(21,1,0,t.audit),z(6,0,0,n(1)),z(32,0,0,0),z(69,0,1,1073741824),z(6,0,0,n(1)),z(21,0,1,t.ioUringSetup),z(6,0,0,n(1)),z(21,0,3,t.socket),z(32,0,0,16),z(21,0,1,1),z(6,0,0,n(97)),z(6,0,0,2147418112)],i=new Uint8Array(r.length*8),a=new DataView(i.buffer);return r.forEach(([e,t,n,r],i)=>{a.setUint16(i*8,e,!0),a.setUint8(i*8+2,t),a.setUint8(i*8+3,n),a.setUint32(i*8+4,r>>>0,!0)}),i}const At=Object.freeze({enabled:!1,autoAllowBashIfSandboxed:!0,excludedCommands:[],allowWrite:[],denyRead:[],network:!1}),jt=`/usr/bin/sandbox-exec`;function Mt(e,t){let n=te(e,[...t],{timeout:5e3,encoding:`utf8`});if(n.error!==void 0)return{ok:!1,detail:n.error.message};let r=(n.stderr??``).trim().split(`
3
3
  `)[0];return n.status===0?{ok:!0}:{ok:!1,...r?{detail:r}:{}}}function Nt(e={}){let t=e.platform??process.platform,n=e.probe??Mt;if(t===`linux`){if(kt(e.arch??process.arch)===void 0)return{backend:`bubblewrap`,missing:[`a seccomp filter for ${e.arch??process.arch} (x64 and arm64 are supported)`]};let t=n(`bwrap`,[`--ro-bind`,`/`,`/`,`--dev`,`/dev`,`--unshare-pid`,`true`]);return t.ok?{backend:`bubblewrap`,executable:`bwrap`,missing:[]}:{backend:`bubblewrap`,missing:[t.detail?.includes(`ENOENT`)?"bubblewrap (install the `bubblewrap` package)":`bubblewrap cannot create a sandbox here${t.detail?`: ${t.detail}`:``}`]}}if(t===`darwin`){let e=n(jt,[`-p`,`(version 1)(allow default)`,`/usr/bin/true`]);return e.ok?{backend:`seatbelt`,executable:jt,missing:[]}:{backend:`seatbelt`,missing:[`sandbox-exec cannot run${e.detail?`: ${e.detail}`:``}`]}}return{missing:[],unsupportedPlatform:t}}function B(e){try{return w(e)}catch{return e}}function Pt(e){try{return E(e).isDirectory()}catch{return!1}}function Ft(e){let t=ge(e);if(!t.isSymbolicLink()&&(de(e,t.mode|448),t.isDirectory()))for(let t of ve(e))Ft(`${e}/${t}`)}function It(e){try{return ge(e).isSymbolicLink()}catch{return!1}}function Lt(e){return e.trim().split(/\s+/)[0]}var Rt=class{filesystem=`shared`;root;availability;homeDirectory;current;inFlight=0;baseline=[];unresolved=new Map;constructor(e){this.root=B(e.root),this.availability=e.availability,this.homeDirectory=e.homeDirectory??we(),this.current={...At,...e.settings}}status(){return{settings:this.current,availability:this.availability,active:this.current.enabled&&this.availability.executable!==void 0}}configure(e){this.current={...this.current,...e}}confines(e){if(!this.status().active)return!1;if(i(e).length!==1)return!0;let t=Lt(e);return t===void 0||!this.current.excludedCommands.includes(t)}autoApproves(e){return!this.current.autoAllowBashIfSandboxed||!this.confines(e)||this.unresolved.size>0?!1:!this.protectedEntryStates().some(e=>e.kind===`symlink`&&!this.resolvesOutsideWritableWorkspace(e.path))}wrapCommand(e,t){if(!this.confines(t))return e;let n=this.policy(),r=this.availability.executable;if(this.availability.backend===`seatbelt`)return{command:r,args:[`-p`,Dt(n),e.command,...e.args],cwd:e.cwd};let i=n.network?void 0:kt();this.protectedEntryStates().some(e=>e.path.endsWith(`/.robota`)&&e.kind===`symlink`)||C(`${this.root}/.robota`,{recursive:!0});let a=Tt({policy:n,exists:e=>he(e)&&!It(e),listDirectory:e=>ve(e),cwd:e.cwd,command:e.command,args:e.args,...i===void 0?{}:{seccompDescriptor:3}});this.inFlight===0&&(this.baseline=this.protectedEntryStates().map(e=>this.unresolved.get(e.path)??e)),this.inFlight+=1;let o=!1;return{command:r,args:a,cwd:e.cwd,...i===void 0?{}:{inputDescriptors:[i]},afterExit:()=>{if(!o)return o=!0,--this.inFlight,this.restoreProtectedEntries(this.baseline)}}}protectedEntryStates(){return wt().map(e=>{let t=`${this.root}/${e}`;try{return ge(t).isSymbolicLink()?{path:t,kind:`symlink`,target:ye(t)}:{path:t,kind:`present`}}catch{return{path:t,kind:`missing`}}})}resolvesOutsideWritableWorkspace(e){let t;try{t=w(e)}catch{return!1}let n=this.policy();return![n.root,...n.tempDirectories,...n.allowWrite].some(e=>t===e||t.startsWith(`${e}/`))}restoreProtectedEntries(e){let t=`${this.quarantineRoot(e)}/${Date.now()}-${p()}`,n=[];for(let r of e)if(r.kind!==`present`)try{let e=this.protectedEntryStates().find(e=>e.path===r.path);if(r.kind===`missing`&&e.kind===`missing`){this.unresolved.delete(r.path);continue}if(r.kind===`symlink`&&e.kind===`symlink`&&e.target===r.target){this.unresolved.delete(r.path);continue}e.kind!==`missing`&&n.push(this.setAside(r.path,t)),r.kind===`symlink`&&xe(r.target,r.path),this.unresolved.delete(r.path)}catch(e){this.unresolved.set(r.path,r),n.push(`could not restore ${r.path} (${e instanceof Error?e.message:String(e)}); commands will ask until it is removed`)}if(n.length!==0)return`[sandbox] A confined command may not create or replace git, agent, MCP or shell configuration: ${n.join(`; `)}.`}quarantineRoot(e){let t=`${this.root}/.robota`;return e.some(e=>e.path===t&&e.kind===`present`)?`${t}/sandbox-quarantine`:`${this.homeDirectory}/.robota/sandbox-quarantine`}setAside(e,t){let n=`${t}/${m(e)}`;C(t,{recursive:!0});try{T(e,n)}catch(t){if(this.inFlight>0)throw t;Ft(e),t.code===`EXDEV`?(pe(e,n,{recursive:!0,verbatimSymlinks:!0}),be(e,{recursive:!0,force:!0})):T(e,n)}return`moved ${e} to ${n}`}policy(){let e=e=>{let t=e===`~`||e.startsWith(`~/`)?`${this.homeDirectory}${e.slice(1)}`:e;return B(g(t)?t:b(this.root,t))},t=[...new Set([Te(),`/tmp`].filter(he).map(B))];return{root:this.root,tempDirectories:t,allowWrite:this.current.allowWrite.map(e),denyRead:this.current.denyRead.map(t=>{let n=e(t);return{path:n,directory:Pt(n)}}),network:this.current.network}}run(e,t={}){let n=l(),r=t.workingDirectory??this.root,i=this.wrapCommand({command:n.command,args:n.commandArgs(e),cwd:r},e);return new Promise((e,n)=>{let r=i.inputDescriptors??[],a;try{a=x(i.command,[...i.args],{cwd:i.cwd,stdio:[`ignore`,`pipe`,`pipe`,...r.map(()=>`pipe`)],...t.timeoutMs===void 0?{}:{timeout:t.timeoutMs}})}catch(e){i.afterExit?.(),n(e instanceof Error?e:Error(String(e)));return}r.forEach((e,t)=>{let n=a.stdio[t+3];n?.on(`error`,()=>void 0),n?.end(Buffer.from(e))});let o=``,s=``;a.stdout?.on(`data`,e=>o+=e.toString()),a.stderr?.on(`data`,e=>s+=e.toString()),a.on(`error`,e=>{i.afterExit?.(),n(e)}),a.on(`close`,t=>{let n=i.afterExit?.();e({stdout:n===void 0?o:`${o}\n${n}`,...s?{stderr:s}:{},exitCode:t??1})})})}readFile(e){return Promise.resolve(_e(e,`utf8`))}writeFile(e,t){return Ce(e,t,`utf8`),Promise.resolve()}};function V(e,n,i,a,o={}){return new t({name:e,description:n,parameters:r(i),...o.deferLoading!==void 0&&{deferLoading:o.deferLoading}},async(e,t)=>{let n=i.safeParse(e);if(!n.success)throw new d(`Zod validation failed: ${n.error}`);let r=await a(n.data,t);return typeof r==`string`?r:JSON.stringify(r)})}const zt={Read:{argument:{key:`filePath`,kind:`path`},riskClass:`inspect`},Glob:{argument:{key:`pattern`,kind:`text`},riskClass:`inspect`},Grep:{argument:{key:`pattern`,kind:`text`},riskClass:`inspect`},WebFetch:{argument:{key:`url`,kind:`url`},riskClass:`inspect`},WebSearch:{argument:{key:`query`,kind:`text`},riskClass:`inspect`},CodebaseRetrieval:{riskClass:`inspect`},AskUserQuestion:{riskClass:`inspect`},ToolSearch:{argument:{key:`query`,kind:`text`},riskClass:`inspect`},ComputerView:{riskClass:`inspect`},Write:{argument:{key:`filePath`,kind:`path`},riskClass:`modify`},Edit:{argument:{key:`filePath`,kind:`path`},riskClass:`modify`},Shell:{argument:{key:`command`,kind:`command`},riskClass:`execute`,aliases:[`Bash`]},Bash:{argument:{key:`command`,kind:`command`},riskClass:`execute`,aliases:[`Shell`]},Computer:{riskClass:`execute`}};function Bt(){for(let[t,n]of Object.entries(zt))e(t,n)}Bt();const Vt=1e3,Ht=D.object({activeFiles:D.array(D.string()).optional().describe(`Repo-relative files currently in focus; the map is ranked toward what they reference.`),mentionedIdentifiers:D.array(D.string()).optional().describe(`Symbol names to bias the map toward (e.g. identifiers named in the task).`),tokenBudget:D.number().int().positive().optional().describe(`Maximum tokens for the returned map (default ${Vt}).`)});function Ut(e){return e.map(e=>`${e.file}:${e.line} ${e.kind} ${e.name}`).join(`
4
4
  `)}async function Wt(e,t={}){if(!t.adapter)return`Codebase retrieval is not available in this session.`;let n=await t.adapter.retrieve({...e.activeFiles?{activeFiles:e.activeFiles}:{},...e.mentionedIdentifiers?{mentionedIdentifiers:e.mentionedIdentifiers}:{},tokenBudget:e.tokenBudget??Vt});return n.symbols.length===0?`No relevant symbols found within the token budget.`:`Most relevant symbols (~${n.totalTokens} tokens):\n${Ut(n.symbols)}`}function Gt(e={}){return V(`CodebaseRetrieval`,`Retrieve the most relevant slice of the codebase (a ranked repo map of symbols) for the current task, within a token budget. Provide the files you are focused on and/or identifiers named in the task; returns the highest-centrality definitions first.`,Ht,async t=>Wt(t,e))}const Kt=`Computer use is not available in this session (no driver injected).`,qt=D.enum([`left`,`right`,`middle`]),Jt=D.object({x:D.number(),y:D.number()}),Yt=D.object({type:D.enum([`click`,`double_click`,`type`,`keypress`,`scroll`,`drag`,`wait`,`takeover`]).describe(`Which action to perform.`),x:D.number().optional().describe(`X coordinate (click/double_click/scroll).`),y:D.number().optional().describe(`Y coordinate (click/double_click/scroll).`),button:qt.optional().describe(`Mouse button (click/double_click/drag).`),text:D.string().optional().describe(`Text to type (type).`),keys:D.array(D.string()).optional().describe(`Keys to press as a chord (keypress).`),deltaX:D.number().optional().describe(`Horizontal wheel delta (scroll).`),deltaY:D.number().optional().describe(`Vertical wheel delta (scroll).`),path:D.array(Jt).optional().describe(`Points to drag through (drag).`),ms:D.number().optional().describe(`Milliseconds to wait (wait).`),reason:D.string().optional().describe(`Human-readable reason surfaced to the user (takeover).`)}),Xt=D.object({action:Yt.describe(`The single mutating action to perform.`)}),Zt=D.object({});var H=class extends Error{};function U(e,t,n){if(typeof e!=`number`)throw new H(`Action '${n}' requires numeric '${t}'.`);return e}function Qt(e){let t=e.button;switch(e.type){case`click`:return{type:`click`,x:U(e.x,`x`,`click`),y:U(e.y,`y`,`click`),...t?{button:t}:{}};case`double_click`:return{type:`double_click`,x:U(e.x,`x`,`double_click`),y:U(e.y,`y`,`double_click`),...t?{button:t}:{}};case`type`:if(typeof e.text!=`string`)throw new H(`Action 'type' requires 'text'.`);return{type:`type`,text:e.text};case`keypress`:if(!e.keys||e.keys.length===0)throw new H(`Action 'keypress' requires non-empty 'keys'.`);return{type:`keypress`,keys:e.keys};case`scroll`:return{type:`scroll`,x:U(e.x,`x`,`scroll`),y:U(e.y,`y`,`scroll`),deltaX:U(e.deltaX,`deltaX`,`scroll`),deltaY:U(e.deltaY,`deltaY`,`scroll`)};case`drag`:if(!e.path||e.path.length<2)throw new H(`Action 'drag' requires a 'path' of at least two points.`);return{type:`drag`,path:e.path,...t?{button:t}:{}};case`wait`:return{type:`wait`,...typeof e.ms==`number`?{ms:e.ms}:{}};case`takeover`:return{type:`takeover`,...e.reason?{reason:e.reason}:{}};default:{let t=e.type;throw new H(`Unknown action type: ${String(t)}`)}}}async function $t(e){if(!e.driver)return JSON.stringify({success:!1,error:Kt});let t=await e.driver.screenshot();return JSON.stringify(t?{success:!0,screenshot:t}:{success:!0,takeover:!0})}async function en(e,t){if(!t.driver)return JSON.stringify({success:!1,error:Kt});let n;try{n=Qt(e.action)}catch(e){return JSON.stringify({success:!1,error:e instanceof Error?e.message:String(e)})}let r=await t.driver.act(n),i={success:!0,...r.screenshot?{screenshot:r.screenshot}:{},...r.takeover?{takeover:!0}:{}};return JSON.stringify(i)}function tn(e={}){return V(`ComputerView`,`Perceive the computer/browser surface: capture and return a screenshot of the current screen so you can reason about what to do next. Read-only — it never changes anything.`,Zt,async()=>$t(e))}function nn(e={}){return V(`Computer`,"Perform one mutating action on the computer/browser surface (click, double_click, type, keypress, scroll, drag, wait, or takeover) and return the resulting screenshot. Use `takeover` to hand control to the human for sensitive input (credentials/payment); perception is paused during a takeover.",Xt,async t=>en(t,e))}function rn(e={}){return[tn(e),nn(e)]}const an=[{toolName:`Glob`,hint:` - File search: Use Glob (NOT find or ls)`},{toolName:`Grep`,hint:` - Content search: Use Grep (NOT grep or rg)`},{toolName:`Read`,hint:` - Read files: Use Read (NOT cat/head/tail)`},{toolName:`Edit`,hint:` - Edit files: Use Edit (NOT sed/awk)`}];function on(e,t){let n=t?an.filter(e=>t.includes(e.toolName)):an,r=n.length>0?["IMPORTANT: Avoid using this tool to run `find`, `grep`, `cat`, `head`, `tail`, `sed`, `awk`, or `echo` commands. Instead, use the appropriate dedicated tool:",...n.map(e=>e.hint)]:[];return[`Executes a command in the host shell and returns its output.`,``,`Active shell: ${e.label}. ${e.syntaxHint}`,``,`Each command runs in a fresh shell in workingDirectory (default: the configured working directory); no shell state carries over between calls.`,``,...r].join(`
@@ -64,4 +64,4 @@ readline.createInterface({ input: process.stdin }).on('line', line => {
64
64
  `):`(no matches)`};return JSON.stringify(b)}function Yn(e){return`A powerful search tool built on regex matching.\n\nSupports full regex syntax (e.g., 'log.*Error', 'function\\\\s+\\\\w+'). Filter files with glob parameter (e.g., '*.js', '**/*.tsx').\n\nOutput modes: 'content' shows matching lines with context, 'files_with_matches' shows only file paths (default), 'count' shows per-file match counts.\n\nPrefer this tool over running grep or rg through the ${e} tool — it returns structured results directly.\n\nUse headLimit to control result size and save context space.`}function Xn(e){return V(`Grep`,e.description??Yn(e.shellToolName??`Shell`),Kn,async t=>Jn(t,e))}const Zn=3e4,Qn=5e6,$n=D.object({url:D.string().describe(`The URL to fetch`),headers:D.record(D.string()).optional().describe(`Optional HTTP headers as key-value pairs`)});function er(e,t){let n=`<${t}`,r=`</${t}>`,i=e.replace(/[A-Z]/g,e=>e.toLowerCase()),a=[],o=0;for(;;){let t=i.indexOf(n,o);if(t<0)break;let s=i.indexOf(r,t+n.length);if(s<0)break;a.push(e.slice(o,t)),o=s+r.length}return a.push(e.slice(o)),a.join(``)}function tr(e){let t=[],n=0;for(;;){let r=e.indexOf(`<`,n);if(r<0)break;let i=e.indexOf(`>`,r+1);if(i<0)break;if(i===r+1){t.push(e.slice(n,r+1)),n=r+1;continue}t.push(e.slice(n,r),` `),n=i+1}return t.push(e.slice(n)),t.join(``)}const nr={"&amp;":`&`,"&lt;":`<`,"&gt;":`>`,"&quot;":`"`,"&#39;":`'`,"&nbsp;":` `},rr=/&(?:amp|lt|gt|quot|nbsp|#39);/g;function ir(e){return tr(er(er(e,`script`),`style`)).replace(rr,e=>nr[e]).replace(/\s+/g,` `).trim()}function ar(e){if(!(e instanceof Error))return String(e);if(e.name===`AbortError`)return`Request timed out after ${Zn/1e3}s. The server did not respond in time.`;let t=e.code;return t===`ENOTFOUND`||t===`EAI_AGAIN`?`Network error: DNS resolution failed for this host. The URL may be incorrect or the host does not exist. Do not retry with the same URL.`:t===`ECONNREFUSED`?`Network error: Connection refused. The server is not accepting connections at this address. Do not retry with the same URL.`:t===`ECONNRESET`?`Network error: Connection was reset by the server. The server may be temporarily unavailable.`:t===`ETIMEDOUT`?`Network error: Connection timed out. The server is not reachable within the expected time.`:t===`CERT_HAS_EXPIRED`||t===`UNABLE_TO_VERIFY_LEAF_SIGNATURE`?`Network error: SSL certificate error (${t}). The server's certificate is invalid. Do not retry with the same URL.`:`Network error: ${e.message} Check that the URL is correct and the server is reachable.`}async function or(e,t,n){let{url:r,headers:i}=e;try{new URL(r)}catch{let e={success:!1,output:``,error:`Invalid URL: "${r}". Fix the URL format before retrying.`};return JSON.stringify(e)}try{let e=await et(r,{headers:{"User-Agent":`Robota-CLI/3.0`,...i??{}},signal:n,timeoutMs:Zn,maxResponseBytes:Qn},t.policy,t.deps);if(!e.ok){let{rejection:t}=e,n={success:!1,output:``,error:t.reason===`response_too_large`?`Response too large (max ${Qn} bytes). Consider fetching a more specific URL or a paginated endpoint.`:`Blocked by egress policy: ${t.message} Do not retry with the same URL.`};return JSON.stringify(n)}if(e.status<200||e.status>=300){let t=e.status>=500?` The server is temporarily unavailable — retrying may help.`:` Do not retry with the same URL.`,n={success:!1,output:``,error:`HTTP ${e.status} ${e.statusText}.${t}`};return JSON.stringify(n)}let a=e.headers.get(`content-type`)??``,o=new TextDecoder().decode(e.body);return a.includes(`html`)&&(o=ir(o)),JSON.stringify({success:!0,output:o})}catch(e){let t={success:!1,output:``,error:ar(e)};return JSON.stringify(t)}}function sr(e={}){let t=e.egress??{};return V(`WebFetch`,e.description??`Fetch a URL and return its content as text. HTML pages are converted to plain text.`,$n,async(e,n)=>or(e,t,n?.signal))}const cr=sr();function lr(){return{async search({query:e,limit:t},n){let r=process.env.BRAVE_API_KEY;if(!r)throw Error(`Web search requires BRAVE_API_KEY environment variable for the default Brave Search provider, or inject a custom search provider at the composition root.`);let i=new URLSearchParams({q:e,count:String(Math.min(t,20))}),a=await fetch(`https://api.search.brave.com/res/v1/web/search?${i}`,{headers:{Accept:`application/json`,"Accept-Encoding":`gzip`,"X-Subscription-Token":r},...n?{signal:n}:{}});if(!a.ok)throw Error(`Brave Search API error: HTTP ${a.status} ${a.statusText}`);return((await a.json()).web?.results??[]).map(e=>({title:e.title,url:e.url,snippet:e.description}))}}}const ur=D.object({query:D.string().describe(`The search query`),limit:D.number().optional().describe(`Maximum number of results to return (default: 10)`)});async function dr(e,t,n){let{query:r,limit:i=10}=e;try{let e=new AbortController,a=setTimeout(()=>e.abort(),15e3),o=n?AbortSignal.any([e.signal,n]):e.signal;try{let e=await t.search({query:r,limit:i},o),n={success:!0,output:JSON.stringify(e,null,2)};return JSON.stringify(n)}finally{clearTimeout(a)}}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}}function fr(e={}){let t=e.provider??lr();return V(`WebSearch`,e.description??`Search the web and return results with title, URL, and snippet.`,ur,async(e,n)=>dr(e,t,n?.signal))}const pr=fr(),mr=D.object({question:D.string().min(1).describe(`The complete question to ask the user.`),header:D.string().optional().describe(`Very short topic label for the question (e.g. "Auth method").`),options:D.array(D.union([D.string().min(1).describe(`Display text of this choice.`),D.object({label:D.string().min(1).describe(`Display text of this choice.`),description:D.string().optional().describe(`What choosing this option means.`)})])).optional().describe(`Predefined choices (strings or {label, description}). Omit for pure free text.`),multiSelect:D.boolean().optional().describe(`Allow selecting multiple options (default: single select).`),allowFreeText:D.boolean().optional().describe(`Allow a typed custom answer besides the options (default: true).`)}),hr=D.object({questions:D.array(mr).min(1).max(4).describe(`Questions to ask the user (1-4), rendered one at a time.`)}),gr=[`Ask the user one or more structured questions and wait for their answers.`,``,`Use this when you are blocked on a decision only the user can make — ambiguous requirements,`,`mutually exclusive approaches, or choices with real trade-offs. Do not use it for decisions with`,`a conventional default or facts you can verify yourself.`,``,`Provide 1-4 questions. Each question offers predefined options and/or free text:`,` - options + default: user picks one option (or types a custom answer unless allowFreeText: false)`,` - multiSelect: true: user may pick several options`,` - no options: pure free-text entry`,``,"The result is a JSON array with one entry per question: the selected option labels in `values`","and/or the typed answer in `text`, or `cancelled: true` if the user dismissed the question.","If no interactive user is attached (headless run), the result is `{ unavailable: true }` —",`continue autonomously with your best judgment and say what you assumed.`].join(`
65
65
  `);function _r(e){let t=(e.options??[]).map(e=>typeof e==`string`?{label:e}:e),n=e.multiSelect===!0&&t.length>1;return{id:`ask_${p()}`,title:e.question,...e.header===void 0?{}:{description:e.header},...t.length>0?{options:t.map(e=>({value:e.label,label:e.label,...e.description===void 0?{}:{description:e.description}}))}:{},minSelect:+(t.length>0),maxSelect:n?t.length:1,allowFreeText:e.allowFreeText!==!1||t.length===0}}async function vr(e,t){let n=[],r=!1;for(let i of e.questions){if(r){n.push({question:i.question,cancelled:!0});continue}let e=await t(_r(i));if(e.type===`cancelled`){r=!0,n.push({question:i.question,cancelled:!0});continue}n.push({question:i.question,values:[...e.values],...e.text===void 0?{}:{text:e.text}})}return{answers:n}}function yr(e={}){return V(`AskUserQuestion`,e.description??gr,hr,async(e,t)=>{let n=e,r=t?.ask,i=r?await vr(n,r):{unavailable:!0,reason:`no interactive user attached`},a={success:!0,output:JSON.stringify(i)};return JSON.stringify(a)})}yr();const br=1/0;function $(e,t){e.description!==void 0&&t.push(e.description);for(let[n,r]of Object.entries(e.properties??{}))t.push(n),$(r,t);e.items!==void 0&&$(e.items,t);for(let n of e.anyOf??[])$(n,t)}function xr(e,t){let n=e.name.toLowerCase();if(n===t)return 0;if(n.includes(t))return 1;if(e.description.toLowerCase().includes(t))return 2;let r=[];return $(e.parameters,r),r.some(e=>e.toLowerCase().includes(t))?3:br}function Sr(e,t,n){let r=t.trim().toLowerCase();return r.length===0?[]:e.map(e=>({schema:e,rank:xr(e,r)})).filter(e=>e.rank!==br).sort((e,t)=>e.rank-t.rank||(e.schema.name<t.schema.name?-1:1)).slice(0,n).map(e=>e.schema)}const Cr=n,wr=D.object({query:D.string().optional().describe(`Text matched case-insensitively against each withheld tool's name, description, and its parameters' names and descriptions. An exact tool name is a valid query.`),names:D.array(D.string().min(1)).optional().describe(`Exact tool names to load, skipping the search. An unknown name is an error naming it.`),limit:D.number().int().positive().optional().describe(`Maximum tools to load from a query match (default 5).`)}),Tr=[`Load tools whose definitions are withheld from your tool list, so you can call them.`,``,`Some tools are deferred: they exist and are callable, but their schemas are not sent to you until`,`you load them here. If a capability you need is not in your tool list, search for it before`,`concluding it is unavailable — and if a tool call fails as "deferred and not yet loaded", load it`,`with this tool and call it again.`,``,` - query: what you are trying to do (e.g. "read a spreadsheet", "postgres"). Matched against tool`,` names, descriptions, and parameter names and descriptions. An exact tool name works too.`,` - names: load exactly these tools, skipping the search. Unknown names are an error.`,` - limit: how many matches to load (default 5).`,``,`The result lists what is now loaded; those tools appear in your tool list from your next turn and`,`stay available. A query that matches nothing returns an empty list — that is a normal answer, not`,"a failure. `unavailableSources` names any tool source that could not be consulted."].join(`
66
66
  `);function Er(e){let t=e?.deferredTools;if(!t)throw Error(`${Cr} requires the deferred-tool catalog, which the execution runtime injects; it was not present, so this tool was called outside the agent execution loop.`);return t}function Dr(e,t){if(e.names!==void 0)return t.loadDeferredTools(e.names);if(e.query===void 0)throw Error(`${Cr} needs either "query" to search for tools or "names" to load exact ones.`);let n=Sr(t.listDeferredTools(),e.query,e.limit??5);return t.loadDeferredTools(n.map(e=>e.name))}function Or(e={}){return V(Cr,e.description??Tr,wr,async(e,t)=>{let n={loaded:Dr(e,Er(t)).map(({name:e,description:t})=>({name:e,description:t})),unavailableSources:[]},r={success:!0,output:JSON.stringify(n)};return JSON.stringify(r)})}Or();export{N as A,pr as C,et as D,A as E,Ie as M,k as N,tt as O,Me as P,cr as S,Re as T,On as _,X as a,Nt as b,pn as c,Rn as d,Xn as f,Or as g,fn as h,Y as i,He as j,Ue as k,rn as l,Gt as m,Q as n,lt as o,xn as p,Rt as r,yr as s,At as t,Nn as u,V as v,Ve as w,at as x,it as y};
67
- //# sourceMappingURL=node-DIRGC_1P.js.map
67
+ //# sourceMappingURL=node-hHzxDyjn.js.map