@robota-sdk/agent-cli 3.0.0-beta.84 → 3.0.0-beta.86
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/CHANGELOG.md +28 -0
- package/README.md +9 -5
- package/dist/node/bin.js +10 -10
- package/dist/node/bounded-output-Bgx2Cgkx-28em7iHq.js +2 -0
- package/dist/node/bounded-output-Bgx2Cgkx-28em7iHq.js.map +1 -0
- package/dist/node/bounded-output-Bgx2Cgkx-C4ucXwLR.js +2 -0
- package/dist/node/cli-core-DOdGt9XE.js +2891 -0
- package/dist/node/command-executor-d6DdfUTD-3KEnsTnN.js +2 -0
- package/dist/node/command-executor-d6DdfUTD-DhFSDHvb.js +2 -0
- package/dist/node/{command-executor-BdE1zg3q-Br7z38P6.js.map → command-executor-d6DdfUTD-DhFSDHvb.js.map} +1 -1
- package/dist/node/headless.js +1 -1
- package/dist/node/{http-executor-cWzI2svn-TG_TMYKh.js → http-executor-ADn4locH-D-8crzF8.js} +2 -2
- package/dist/node/{http-executor-cWzI2svn-TG_TMYKh.js.map → http-executor-ADn4locH-D-8crzF8.js.map} +1 -1
- package/dist/node/{http-executor-cWzI2svn-Ype0naht.js → http-executor-ADn4locH-uz5KV6N-.js} +1 -1
- package/dist/node/index.d.ts +11 -4
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +353 -352
- package/dist/node/index.js.map +1 -1
- package/dist/node/node-B48couEE.js +14 -0
- package/dist/node/node-B48couEE.js.map +1 -0
- package/dist/node/{node-D_fk2mK2.js → node-BfqR16CD.js} +1 -1
- package/dist/node/{node-BhEYLQDQ.js → node-CgLYctGm.js} +5 -5
- package/dist/node/{node-BhEYLQDQ.js.map → node-CgLYctGm.js.map} +1 -1
- package/dist/node/{node-B_3rSS2i.js → node-DAOCaE6N.js} +4 -4
- package/dist/node/node-DlLm_kxn.js +14 -0
- package/dist/node/{verdict-decoder-Dk_w2NG9-Bka7Cldj.js → verdict-decoder-Dz_rjoIZ-DA8BKB83.js} +2 -2
- package/dist/node/{verdict-decoder-Dk_w2NG9-Bka7Cldj.js.map → verdict-decoder-Dz_rjoIZ-DA8BKB83.js.map} +1 -1
- package/dist/node/{verdict-decoder-Dk_w2NG9-BKWMtxp8.js → verdict-decoder-Dz_rjoIZ-qM0jJVsB.js} +1 -1
- package/package.json +33 -33
- package/dist/node/bounded-output-D3cgiOrh-C5ywb_Yg.js +0 -2
- package/dist/node/bounded-output-D3cgiOrh-C5ywb_Yg.js.map +0 -1
- package/dist/node/bounded-output-D3cgiOrh-kO7zrx1P.js +0 -2
- package/dist/node/cli-core-BloQpWhd.js +0 -2891
- package/dist/node/command-executor-BdE1zg3q-BGQmze1E.js +0 -2
- package/dist/node/command-executor-BdE1zg3q-Br7z38P6.js +0 -2
- package/dist/node/node-A7RJeEyA.js +0 -14
- package/dist/node/node-A7RJeEyA.js.map +0 -1
- package/dist/node/node-CCe6GM9V.js +0 -14
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
;(function(){var v=parseInt(process.versions.node.split('.')[0],10);if(v<22){process.stderr.write('\n✗ Node.js 22+ is required (current: '+process.version+')\n\nUpgrade:\n nvm: nvm install 22 && nvm use 22\n Volta: volta install node@22\n Download: https://nodejs.org/en/download\n\n');process.exit(1);}})();
|
|
2
|
-
import{At as e,C as t,T as n,c as r,ct as i,n as a,tt as o}from"./node-CCe6GM9V.js";import{a as s,d as c,n as l,s as u,v as d}from"./bounded-output-D3cgiOrh-kO7zrx1P.js";import"./command-executor-BdE1zg3q-BGQmze1E.js";import"./http-executor-cWzI2svn-Ype0naht.js";import{spawn as f,spawnSync as p}from"node:child_process";import{accessSync as m,chmodSync as h,constants as g,cpSync as _,createReadStream as ee,existsSync as v,lstatSync as y,mkdirSync as b,readFileSync as te,readdirSync as ne,readlinkSync as re,realpathSync as x,renameSync as ie,rmSync as ae,statSync as S,symlinkSync as oe,unlinkSync as se,writeFileSync as ce}from"node:fs";import{basename as le,dirname as C,isAbsolute as w,join as T,posix as ue,relative as de,resolve as E,sep as fe}from"node:path";import{randomBytes as pe,randomUUID as me}from"node:crypto";import{chmod as he,mkdir as ge,open as _e,readFile as ve,readdir as ye,readlink as be,realpath as xe,rename as Se,rm as Ce,stat as D,writeFile as we}from"node:fs/promises";import{homedir as Te,tmpdir as Ee}from"node:os";import{z as O}from"zod";import{lookup as De}from"node:dns/promises";import{isIP as k}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 A(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`){p(`taskkill`,[`/pid`,String(e.pid),`/T`,`/F`],{stdio:`ignore`});return}Pe(e,`SIGKILL`,t)}async function Ie(e,t={}){let n=t.graceMs??2e3,r=t.signal??`SIGTERM`,i=t.processGroup??!1;if(!A(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(A(e))return}return new Promise(t=>{let a,o=()=>{a&&clearTimeout(a),t()};if(e.once(`exit`,o),A(e)){e.removeListener(`exit`,o),t();return}Pe(e,r,i),a=setTimeout(()=>{A(e)||Fe(e,i)},n),a.unref?.()})}}function Le(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(!w(e))throw TypeError(`executionRoot must be an absolute path`);let t;try{t=x(e)}catch{throw TypeError(`executionRoot must name an existing accessible directory`)}if(!S(t).isDirectory())throw TypeError(`executionRoot must name a directory`);try{m(t,g.R_OK|g.X_OK)}catch{throw TypeError(`executionRoot directory must be readable and traversable`)}return t}function Re(e){let t=[],n=E(e);for(;;)try{return T(x(n),...t)}catch{let r=C(n);if(r===n)return E(e);t.unshift(le(n)),n=r}}function ze(e,t){let n=Re(e),r=Re(t);return r===n||r.startsWith(n+fe)}var Be=class extends Error{constructor(e){super(e),this.name=`OwnerOnlyModeError`}};function j(e=process.platform){return e===`win32`?`windows-acl`:`posix-mode`}function Ve(e,t){let n=de(e,t);if(n.startsWith(`..`)||w(n))throw new Be(`withinRoot ${e} is not an ancestor of ${t}, so this call cannot own the path between them.`);let r=n.split(fe).filter(e=>e.length>0),i=[e],a=e;for(let e of r)a=T(a,e),i.push(a);return i}function M(e,t,n={}){if(j()!==`posix-mode`)return;let r=(n.readMode??(e=>S(e).mode&4095))(e);if(r&63)throw new Be(`${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 He(e,t={}){let n=t.makeDirectory??((e,t)=>{b(e,{recursive:!0,mode:t})}),r=t.setMode??((e,t)=>h(e,t));n(e,448);let i=t.withinRoot===void 0?[e]:Ve(t.withinRoot,e);for(let e of i)j()===`posix-mode`&&r(e,448),M(e,`directory`,t)}function Ue(e,t){He(C(e));let n=`${e}.${process.pid}.tmp`;ae(n,{force:!0}),ce(n,t,{encoding:`utf8`,mode:384,flag:`wx`});try{M(n,`file`),ie(n,e)}catch(e){try{se(n)}catch{}throw e}M(e,`file`)}function We(e){if(j()!==`posix-mode`)return;let t;try{t=S(e).mode&4095}catch{return}t&63&&(h(e,384),M(e,`file`))}function Ge(e){let t=k(e);return t===4?Ke(e.split(`.`).map(Number)):t!==6||qe(e)}function Ke(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 qe(e){let t=Ye(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?Ke([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 Je(e){let t=e.lastIndexOf(`:`),n=e.slice(t+1);if(!n.includes(`.`))return e;if(t<0||k(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 Ye(e){let t=Je(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 Xe=3e4,Ze=5e6,Qe=new Set([301,302,303,307,308]),$e=new Set([`localhost`,`metadata`,`metadata.google.internal`,`metadata.goog`,`instance-data`,`instance-data.ec2.internal`]),N=async e=>(await De(e,{all:!0,verbatim:!0})).map(e=>e.address);async function P(e,t={},n=N){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($e.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=k(i)?[i]:await et(i,n);if(a===void 0||a.length===0)return{reason:`unresolvable`,url:r,message:`Destination "${i}" did not resolve.`};let o=a.find(Ge);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 et(e,t){try{return await t(e)}catch{return}}async function tt(e,t={},n={},r={}){let i=r.fetch??((e,t)=>globalThis.fetch(e,t)),a=r.lookup??N,o=t.maxResponseBytes??Ze,s=n.maxRedirects??5,c=AbortSignal.timeout(t.timeoutMs??Xe),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 P(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(!Qe.has(r.status))return it(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=rt(d)),u=f}}async function nt(e,t,n={},r={}){let i=r.fetch??((e,t)=>globalThis.fetch(e,t)),a=t.maxResponseBytes??Ze,o=AbortSignal.timeout(t.timeoutMs??Xe),s=t.signal?AbortSignal.any([o,t.signal]):o,c=new URL(e),l=await P(c,n,r.lookup??N);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.`}}):it(u,c.href,a,s)}function rt(e){let t={};for(let[n,r]of Object.entries(e))n.toLowerCase()===`user-agent`&&(t[n]=r);return t}async function it(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 at(e){return e===void 0?`host`:`sandbox-${e.filesystem??`separate`}`}function ot(e){return at(e)===`sandbox-separate`}function st(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 ct=/^[A-Za-z]:[\\/]/,lt=/'/g;async function ut(e,t,n={}){if(e.applyManifest)return e.applyManifest(t,n);st(t);let r=St(n.targetRoot??`/workspace`),i=[];for(let[a,o]of Object.entries(t.entries)){let t=dt(a),s=Ct(r,t);i.push(await ft(e,t,s,r,o,n))}return{entries:i}}function dt(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(`\\`)||ct.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 ft(e,t,n,r,i,a){switch(i.type){case`file`:return await _t(e,n,r,i.content),F(t,i.type);case`dir`:return await vt(e,n),F(t,i.type);case`localFile`:return await pt(e,i.src,n,r,a),F(t,i.type);case`localDir`:return await mt(e,i.src,n,a),F(t,i.type);case`gitRepo`:return await gt(e,i,n),F(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 wt(i)}}function F(e,t){return{path:e,type:t,status:`applied`}}async function pt(e,t,n,r,i){await _t(e,n,r,await ve(bt(t,i.hostRoot),`utf8`))}async function mt(e,t,n,r){await ht(e,bt(t,r.hostRoot),n)}async function ht(e,t,n){await vt(e,n);let r=await ye(t,{withFileTypes:!0});for(let i of r){let r=T(t,i.name),a=Ct(n,i.name);if(i.isDirectory()){await ht(e,r,a);continue}if(i.isFile()){let t=await ve(r,`utf8`);await e.writeFile(a,t)}}}async function gt(e,t,n){await yt(e,`git clone${t.shallow===!1?``:` --depth 1`}${t.ref?` --branch ${I(t.ref)}`:``} ${I(t.url)} ${I(n)}`)}async function _t(e,t,n,r){let i=ue.dirname(t);i!==n&&await vt(e,i),await e.writeFile(t,r)}async function vt(e,t){await yt(e,`mkdir -p ${I(t)}`)}async function yt(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 bt(e,t){return w(e)?E(e):E(t??process.cwd(),e)}function xt(e){let t=e.length;for(;t>0&&e[t-1]===`/`;)--t;return e.slice(0,t)}function St(e){let t=xt(e.replace(/\\/g,`/`));if(!t.startsWith(`/`))throw Error(`workspace manifest targetRoot must be an absolute sandbox path`);return t.length===0?`/`:t}function Ct(e,t){let n=St(e);return n===`/`?`/${t}`:`${n}/${t}`}function I(e){return`'${e.replace(lt,`'\\''`)}'`}function wt(e){throw Error(`unsupported workspace manifest entry: ${JSON.stringify(e)}`)}const Tt=[`.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 Et(){return[...o,...e]}function Dt(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 Et()){let i=L(t.root,r);e.exists(i)&&n.push(`--ro-bind`,i,i)}for(let r of Tt){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 Ot(e){return e.replace(/[\\^$.*+?()[\]{}|"]/g,e=>`\\${e}`)}function R(e){return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function kt(t){let n=[t.root,...t.tempDirectories,...t.allowWrite].map(e=>`(subpath ${R(e)})`).join(` `),r=Et().map(n=>{let r=L(t.root,n);return e.includes(n)?`(literal ${R(r)})`:`(subpath ${R(r)})`}),i=Tt.map(e=>`(subpath ${R(L(t.root,e))})`),a=[`(literal ${R(L(t.root,`.git`))})`,...Tt.map(e=>`(regex #"^${Ot(L(t.root,e))}/[^/]+/\\.git$")`)],o=[`(version 1)`,`(allow default)`,`(deny file-write*)`,`(allow file-write* ${n} (literal "/dev/null") (regex #"^/dev/tty") (regex #"^/dev/fd/"))`,`(deny file-write* ${r.join(` `)})`,`(allow file-write* ${i.join(` `)})`,`(deny file-write* ${a.join(` `)})`];if(t.denyRead.length>0){let e=t.denyRead.map(e=>e.directory?`(subpath ${R(e.path)})`:`(literal ${R(e.path)})`);o.push(`(deny file-read* ${e.join(` `)})`)}return t.network||o.push(`(deny network*)`),o.join(`
|
|
2
|
+
import{D as e,K as t,V as n,h as r,jt as i,mt as a,u as o}from"./node-DlLm_kxn.js";import{_ as s,l as c,r as l,s as u,w as d}from"./bounded-output-Bgx2Cgkx-C4ucXwLR.js";import"./command-executor-d6DdfUTD-3KEnsTnN.js";import"./http-executor-ADn4locH-uz5KV6N-.js";import{spawn as f,spawnSync as p}from"node:child_process";import{accessSync as m,chmodSync as h,constants as g,cpSync as _,createReadStream as ee,existsSync as v,lstatSync as y,mkdirSync as b,readFileSync as te,readdirSync as ne,readlinkSync as re,realpathSync as x,renameSync as ie,rmSync as ae,statSync as S,symlinkSync as oe,unlinkSync as se,writeFileSync as ce}from"node:fs";import{basename as le,dirname as C,isAbsolute as w,join as T,posix as ue,relative as de,resolve as E,sep as fe}from"node:path";import{randomBytes as pe,randomUUID as me}from"node:crypto";import{chmod as he,mkdir as ge,open as _e,readFile as ve,readdir as ye,readlink as be,realpath as xe,rename as Se,rm as Ce,stat as D,writeFile as we}from"node:fs/promises";import{homedir as Te,tmpdir as Ee}from"node:os";import{z as O}from"zod";import{lookup as De}from"node:dns/promises";import{isIP as k}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 A(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`){p(`taskkill`,[`/pid`,String(e.pid),`/T`,`/F`],{stdio:`ignore`});return}Pe(e,`SIGKILL`,t)}async function Ie(e,t={}){let n=t.graceMs??2e3,r=t.signal??`SIGTERM`,i=t.processGroup??!1;if(!A(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(A(e))return}return new Promise(t=>{let a,o=()=>{a&&clearTimeout(a),t()};if(e.once(`exit`,o),A(e)){e.removeListener(`exit`,o),t();return}Pe(e,r,i),a=setTimeout(()=>{A(e)||Fe(e,i)},n),a.unref?.()})}}function Le(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(!w(e))throw TypeError(`executionRoot must be an absolute path`);let t;try{t=x(e)}catch{throw TypeError(`executionRoot must name an existing accessible directory`)}if(!S(t).isDirectory())throw TypeError(`executionRoot must name a directory`);try{m(t,g.R_OK|g.X_OK)}catch{throw TypeError(`executionRoot directory must be readable and traversable`)}return t}function Re(e){let t=[],n=E(e);for(;;)try{return T(x(n),...t)}catch{let r=C(n);if(r===n)return E(e);t.unshift(le(n)),n=r}}function ze(e,t){let n=Re(e),r=Re(t);return r===n||r.startsWith(n+fe)}var Be=class extends Error{constructor(e){super(e),this.name=`OwnerOnlyModeError`}};function j(e=process.platform){return e===`win32`?`windows-acl`:`posix-mode`}function Ve(e,t){let n=de(e,t);if(n.startsWith(`..`)||w(n))throw new Be(`withinRoot ${e} is not an ancestor of ${t}, so this call cannot own the path between them.`);let r=n.split(fe).filter(e=>e.length>0),i=[e],a=e;for(let e of r)a=T(a,e),i.push(a);return i}function M(e,t,n={}){if(j()!==`posix-mode`)return;let r=(n.readMode??(e=>S(e).mode&4095))(e);if(r&63)throw new Be(`${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 He(e,t={}){let n=t.makeDirectory??((e,t)=>{b(e,{recursive:!0,mode:t})}),r=t.setMode??((e,t)=>h(e,t));n(e,448);let i=t.withinRoot===void 0?[e]:Ve(t.withinRoot,e);for(let e of i)j()===`posix-mode`&&r(e,448),M(e,`directory`,t)}function Ue(e,t){He(C(e));let n=`${e}.${process.pid}.tmp`;ae(n,{force:!0}),ce(n,t,{encoding:`utf8`,mode:384,flag:`wx`});try{M(n,`file`),ie(n,e)}catch(e){try{se(n)}catch{}throw e}M(e,`file`)}function We(e){if(j()!==`posix-mode`)return;let t;try{t=S(e).mode&4095}catch{return}t&63&&(h(e,384),M(e,`file`))}function Ge(e){let t=k(e);return t===4?Ke(e.split(`.`).map(Number)):t!==6||qe(e)}function Ke(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 qe(e){let t=Ye(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?Ke([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 Je(e){let t=e.lastIndexOf(`:`),n=e.slice(t+1);if(!n.includes(`.`))return e;if(t<0||k(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 Ye(e){let t=Je(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 Xe=3e4,Ze=5e6,Qe=new Set([301,302,303,307,308]),$e=new Set([`localhost`,`metadata`,`metadata.google.internal`,`metadata.goog`,`instance-data`,`instance-data.ec2.internal`]),N=async e=>(await De(e,{all:!0,verbatim:!0})).map(e=>e.address);async function P(e,t={},n=N){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($e.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=k(i)?[i]:await et(i,n);if(a===void 0||a.length===0)return{reason:`unresolvable`,url:r,message:`Destination "${i}" did not resolve.`};let o=a.find(Ge);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 et(e,t){try{return await t(e)}catch{return}}async function tt(e,t={},n={},r={}){let i=r.fetch??((e,t)=>globalThis.fetch(e,t)),a=r.lookup??N,o=t.maxResponseBytes??Ze,s=n.maxRedirects??5,c=AbortSignal.timeout(t.timeoutMs??Xe),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 P(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(!Qe.has(r.status))return it(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=rt(d)),u=f}}async function nt(e,t,n={},r={}){let i=r.fetch??((e,t)=>globalThis.fetch(e,t)),a=t.maxResponseBytes??Ze,o=AbortSignal.timeout(t.timeoutMs??Xe),s=t.signal?AbortSignal.any([o,t.signal]):o,c=new URL(e),l=await P(c,n,r.lookup??N);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.`}}):it(u,c.href,a,s)}function rt(e){let t={};for(let[n,r]of Object.entries(e))n.toLowerCase()===`user-agent`&&(t[n]=r);return t}async function it(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 at(e){return e===void 0?`host`:`sandbox-${e.filesystem??`separate`}`}function ot(e){return at(e)===`sandbox-separate`}function st(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 ct=/^[A-Za-z]:[\\/]/,lt=/'/g;async function ut(e,t,n={}){if(e.applyManifest)return e.applyManifest(t,n);st(t);let r=St(n.targetRoot??`/workspace`),i=[];for(let[a,o]of Object.entries(t.entries)){let t=dt(a),s=Ct(r,t);i.push(await ft(e,t,s,r,o,n))}return{entries:i}}function dt(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(`\\`)||ct.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 ft(e,t,n,r,i,a){switch(i.type){case`file`:return await _t(e,n,r,i.content),F(t,i.type);case`dir`:return await vt(e,n),F(t,i.type);case`localFile`:return await pt(e,i.src,n,r,a),F(t,i.type);case`localDir`:return await mt(e,i.src,n,a),F(t,i.type);case`gitRepo`:return await gt(e,i,n),F(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 wt(i)}}function F(e,t){return{path:e,type:t,status:`applied`}}async function pt(e,t,n,r,i){await _t(e,n,r,await ve(bt(t,i.hostRoot),`utf8`))}async function mt(e,t,n,r){await ht(e,bt(t,r.hostRoot),n)}async function ht(e,t,n){await vt(e,n);let r=await ye(t,{withFileTypes:!0});for(let i of r){let r=T(t,i.name),a=Ct(n,i.name);if(i.isDirectory()){await ht(e,r,a);continue}if(i.isFile()){let t=await ve(r,`utf8`);await e.writeFile(a,t)}}}async function gt(e,t,n){await yt(e,`git clone${t.shallow===!1?``:` --depth 1`}${t.ref?` --branch ${I(t.ref)}`:``} ${I(t.url)} ${I(n)}`)}async function _t(e,t,n,r){let i=ue.dirname(t);i!==n&&await vt(e,i),await e.writeFile(t,r)}async function vt(e,t){await yt(e,`mkdir -p ${I(t)}`)}async function yt(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 bt(e,t){return w(e)?E(e):E(t??process.cwd(),e)}function xt(e){let t=e.length;for(;t>0&&e[t-1]===`/`;)--t;return e.slice(0,t)}function St(e){let t=xt(e.replace(/\\/g,`/`));if(!t.startsWith(`/`))throw Error(`workspace manifest targetRoot must be an absolute sandbox path`);return t.length===0?`/`:t}function Ct(e,t){let n=St(e);return n===`/`?`/${t}`:`${n}/${t}`}function I(e){return`'${e.replace(lt,`'\\''`)}'`}function wt(e){throw Error(`unsupported workspace manifest entry: ${JSON.stringify(e)}`)}const Tt=[`.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 Et(){return[...i,...a]}function Dt(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 Et()){let i=L(t.root,r);e.exists(i)&&n.push(`--ro-bind`,i,i)}for(let r of Tt){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 Ot(e){return e.replace(/[\\^$.*+?()[\]{}|"]/g,e=>`\\${e}`)}function R(e){return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function kt(e){let t=[e.root,...e.tempDirectories,...e.allowWrite].map(e=>`(subpath ${R(e)})`).join(` `),n=Et().map(t=>{let n=L(e.root,t);return a.includes(t)?`(literal ${R(n)})`:`(subpath ${R(n)})`}),r=Tt.map(t=>`(subpath ${R(L(e.root,t))})`),i=[`(literal ${R(L(e.root,`.git`))})`,...Tt.map(t=>`(regex #"^${Ot(L(e.root,t))}/[^/]+/\\.git$")`)],o=[`(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)})`);o.push(`(deny file-read* ${t.join(` `)})`)}return e.network||o.push(`(deny network*)`),o.join(`
|
|
3
3
|
`)}const At={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 jt(e=process.arch){let t=At[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 Mt=Object.freeze({enabled:!1,autoAllowBashIfSandboxed:!0,excludedCommands:[],allowWrite:[],denyRead:[],network:!1}),Nt=`/usr/bin/sandbox-exec`;function Pt(e,t){let n=p(e,[...t],{timeout:5e3,encoding:`utf8`});if(n.error!==void 0)return{ok:!1,detail:n.error.message};let r=(n.stderr??``).trim().split(`
|
|
4
|
-
`)[0];return n.status===0?{ok:!0}:{ok:!1,...r?{detail:r}:{}}}function Ft(e={}){let t=e.platform??process.platform,n=e.probe??Pt;if(t===`linux`){if(jt(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(Nt,[`-p`,`(version 1)(allow default)`,`/usr/bin/true`]);return e.ok?{backend:`seatbelt`,executable:Nt,missing:[]}:{backend:`seatbelt`,missing:[`sandbox-exec cannot run${e.detail?`: ${e.detail}`:``}`]}}return{missing:[],unsupportedPlatform:t}}function It(e){try{return x(e)}catch{return e}}function Lt(e){try{return S(e).isDirectory()}catch{return!1}}function Rt(e){let t=y(e);if(!t.isSymbolicLink()&&(h(e,t.mode|448),t.isDirectory()))for(let t of ne(e))Rt(`${e}/${t}`)}function zt(e){try{return y(e).isSymbolicLink()}catch{return!1}}function Bt(e){return e.trim().split(/\s+/)[0]}var Vt=class{filesystem=`shared`;root;availability;homeDirectory;current;inFlight=0;baseline=[];unresolved=new Map;watchers=new Set;constructor(e){this.root=It(e.root),this.availability=e.availability,this.homeDirectory=e.homeDirectory??Te(),this.current={...Mt,...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};for(let e of this.watchers)e(this.current)}watchSettings(e){return this.watchers.add(e),()=>{this.watchers.delete(e)}}confines(e){if(!this.status().active)return!1;if(
|
|
4
|
+
`)[0];return n.status===0?{ok:!0}:{ok:!1,...r?{detail:r}:{}}}function Ft(e={}){let t=e.platform??process.platform,n=e.probe??Pt;if(t===`linux`){if(jt(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(Nt,[`-p`,`(version 1)(allow default)`,`/usr/bin/true`]);return e.ok?{backend:`seatbelt`,executable:Nt,missing:[]}:{backend:`seatbelt`,missing:[`sandbox-exec cannot run${e.detail?`: ${e.detail}`:``}`]}}return{missing:[],unsupportedPlatform:t}}function It(e){try{return x(e)}catch{return e}}function Lt(e){try{return S(e).isDirectory()}catch{return!1}}function Rt(e){let t=y(e);if(!t.isSymbolicLink()&&(h(e,t.mode|448),t.isDirectory()))for(let t of ne(e))Rt(`${e}/${t}`)}function zt(e){try{return y(e).isSymbolicLink()}catch{return!1}}function Bt(e){return e.trim().split(/\s+/)[0]}var Vt=class{filesystem=`shared`;root;availability;homeDirectory;current;inFlight=0;baseline=[];unresolved=new Map;watchers=new Set;constructor(e){this.root=It(e.root),this.availability=e.availability,this.homeDirectory=e.homeDirectory??Te(),this.current={...Mt,...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};for(let e of this.watchers)e(this.current)}watchSettings(e){return this.watchers.add(e),()=>{this.watchers.delete(e)}}confines(e){if(!this.status().active)return!1;if(o(e).length!==1)return!0;let t=Bt(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`,kt(n),e.command,...e.args],cwd:e.cwd};let i=n.network?void 0:jt();this.protectedEntryStates().some(e=>e.path.endsWith(`/.robota`)&&e.kind===`symlink`)||b(`${this.root}/.robota`,{recursive:!0});let a=Dt({policy:n,exists:e=>v(e)&&!zt(e),listDirectory:e=>ne(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 Et().map(e=>{let t=`${this.root}/${e}`;try{return y(t).isSymbolicLink()?{path:t,kind:`symlink`,target:re(t)}:{path:t,kind:`present`}}catch{return{path:t,kind:`missing`}}})}resolvesOutsideWritableWorkspace(e){let t;try{t=x(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()}-${me()}`,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`&&oe(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}/${le(e)}`;b(t,{recursive:!0});try{ie(e,n)}catch(t){if(this.inFlight>0)throw t;Rt(e),t.code===`EXDEV`?(_(e,n,{recursive:!0,verbatimSymlinks:!0}),ae(e,{recursive:!0,force:!0})):ie(e,n)}return`moved ${e} to ${n}`}policy(){let e=e=>{let t=e===`~`||e.startsWith(`~/`)?`${this.homeDirectory}${e.slice(1)}`:e;return It(w(t)?t:E(this.root,t))},t=[...new Set([Ee(),`/tmp`].filter(v).map(It))];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:Lt(n)}}),network:this.current.network}}run(e,t={}){let n=d(),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=f(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(te(e,`utf8`))}writeFile(e,t){return ce(e,t,`utf8`),Promise.resolve()}};function B(n,r,i,a,o={}){return new t({name:n,description:r,parameters:e(i),...o.deferLoading!==void 0&&{deferLoading:o.deferLoading}},async(e,t)=>{let n=i.safeParse(e);if(!n.success)throw new s(`Zod validation failed: ${n.error}`);let r=await a(n.data,t);return typeof r==`string`?r:JSON.stringify(r)})}const Ht={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 Ut(){for(let[e,t]of Object.entries(Ht))n(e,t)}Ut();const Wt=1e3,Gt=O.object({activeFiles:O.array(O.string()).optional().describe(`Repo-relative files currently in focus; the map is ranked toward what they reference.`),mentionedIdentifiers:O.array(O.string()).optional().describe(`Symbol names to bias the map toward (e.g. identifiers named in the task).`),tokenBudget:O.number().int().positive().optional().describe(`Maximum tokens for the returned map (default ${Wt}).`)});function Kt(e){return e.map(e=>`${e.file}:${e.line} ${e.kind} ${e.name}`).join(`
|
|
5
5
|
`)}async function qt(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??Wt});return n.symbols.length===0?`No relevant symbols found within the token budget.`:`Most relevant symbols (~${n.totalTokens} tokens):\n${Kt(n.symbols)}`}function Jt(e={}){return B(`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.`,Gt,async t=>qt(t,e))}const Yt=`Computer use is not available in this session (no driver injected).`,Xt=O.enum([`left`,`right`,`middle`]),Zt=O.object({x:O.number(),y:O.number()}),Qt=O.object({type:O.enum([`click`,`double_click`,`type`,`keypress`,`scroll`,`drag`,`wait`,`takeover`]).describe(`Which action to perform.`),x:O.number().optional().describe(`X coordinate (click/double_click/scroll).`),y:O.number().optional().describe(`Y coordinate (click/double_click/scroll).`),button:Xt.optional().describe(`Mouse button (click/double_click/drag).`),text:O.string().optional().describe(`Text to type (type).`),keys:O.array(O.string()).optional().describe(`Keys to press as a chord (keypress).`),deltaX:O.number().optional().describe(`Horizontal wheel delta (scroll).`),deltaY:O.number().optional().describe(`Vertical wheel delta (scroll).`),path:O.array(Zt).optional().describe(`Points to drag through (drag).`),ms:O.number().optional().describe(`Milliseconds to wait (wait).`),reason:O.string().optional().describe(`Human-readable reason surfaced to the user (takeover).`)}),$t=O.object({action:Qt.describe(`The single mutating action to perform.`)}),en=O.object({});var V=class extends Error{};function H(e,t,n){if(typeof e!=`number`)throw new V(`Action '${n}' requires numeric '${t}'.`);return e}function tn(e){let t=e.button;switch(e.type){case`click`:return{type:`click`,x:H(e.x,`x`,`click`),y:H(e.y,`y`,`click`),...t?{button:t}:{}};case`double_click`:return{type:`double_click`,x:H(e.x,`x`,`double_click`),y:H(e.y,`y`,`double_click`),...t?{button:t}:{}};case`type`:if(typeof e.text!=`string`)throw new V(`Action 'type' requires 'text'.`);return{type:`type`,text:e.text};case`keypress`:if(!e.keys||e.keys.length===0)throw new V(`Action 'keypress' requires non-empty 'keys'.`);return{type:`keypress`,keys:e.keys};case`scroll`:return{type:`scroll`,x:H(e.x,`x`,`scroll`),y:H(e.y,`y`,`scroll`),deltaX:H(e.deltaX,`deltaX`,`scroll`),deltaY:H(e.deltaY,`deltaY`,`scroll`)};case`drag`:if(!e.path||e.path.length<2)throw new V(`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 V(`Unknown action type: ${String(t)}`)}}}async function nn(e){if(!e.driver)return JSON.stringify({success:!1,error:Yt});let t=await e.driver.screenshot();return JSON.stringify(t?{success:!0,screenshot:t}:{success:!0,takeover:!0})}async function rn(e,t){if(!t.driver)return JSON.stringify({success:!1,error:Yt});let n;try{n=tn(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 an(e={}){return B(`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.`,en,async()=>nn(e))}function on(e={}){return B(`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.",$t,async t=>rn(t,e))}function sn(e={}){return[an(e),on(e)]}const cn=[{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 ln(e,t){let n=t?cn.filter(e=>t.includes(e.toolName)):cn,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(`
|
|
6
|
-
`)}const U=process.platform!==`win32`,un=2e6,dn=O.object({command:O.string().describe(`The shell command to execute`),timeout:O.number().optional().describe(`Optional timeout in milliseconds (max 600000). Default is 120000 (2 minutes)`),workingDirectory:O.string().optional().describe(`Working directory for the command. Defaults to the current working directory`)});async function fn(e,t,n,r){try{let i=await r.sandboxClient.run(e,{timeoutMs:t,workingDirectory:n}),a={success:!0,output:i.stderr?`${i.stdout}\nstderr:\n${i.stderr}`:i.stdout,exitCode:i.exitCode};return JSON.stringify(a)}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}}async function pn(e,t,n,r,i){let{command:a,timeout:o=12e4,workingDirectory:
|
|
6
|
+
`)}const U=process.platform!==`win32`,un=2e6,dn=O.object({command:O.string().describe(`The shell command to execute`),timeout:O.number().optional().describe(`Optional timeout in milliseconds (max 600000). Default is 120000 (2 minutes)`),workingDirectory:O.string().optional().describe(`Working directory for the command. Defaults to the current working directory`)});async function fn(e,t,n,r){try{let i=await r.sandboxClient.run(e,{timeoutMs:t,workingDirectory:n}),a={success:!0,output:i.stderr?`${i.stdout}\nstderr:\n${i.stderr}`:i.stdout,exitCode:i.exitCode};return JSON.stringify(a)}catch(e){let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}}async function pn(e,t,n,r,i){let{command:a,timeout:o=12e4,workingDirectory:s}=e,c=Math.min(o,6e5),d=s??t.cwd;if(d===void 0)return JSON.stringify({success:!1,output:``,error:"Shell tool has no working directory: it was constructed without a `cwd` (ARCH-010). This is an assembly bug — the tool would otherwise run in whatever directory the host process was started in."});if(t.sandboxClient&&t.sandboxClient.wrapCommand===void 0)return fn(a,c,s??t.cwd,t);let p={command:n.command,args:n.commandArgs(a),cwd:d},m=t.sandboxClient?.wrapCommand?.(p,a)??p,h=!1,g=()=>{if(!h){h=!0;try{return m.afterExit?.()}catch(e){return`[sandbox] clean-up failed: ${e instanceof Error?e.message:String(e)}`}}};return r?.aborted?(g(),JSON.stringify({success:!1,output:``,error:`Aborted before start`})):new Promise(e=>{let t=l({maxBytes:un}),n=l({maxBytes:un}),a=!1,o=!1,s;try{s=f(m.command,[...m.args],{cwd:m.cwd,env:i===void 0?process.env:u(process.env,i),stdio:[`pipe`,`pipe`,`pipe`,...(m.inputDescriptors??[]).map(()=>`pipe`)],detached:U})}catch(t){let n=g(),r=t instanceof Error?t.message:String(t);e(JSON.stringify({success:!1,output:n??``,error:r}));return}(m.inputDescriptors??[]).forEach((e,t)=>{let n=s.stdio[t+3];n?.on(`error`,()=>void 0),n?.end(Buffer.from(e))}),s.stdin?.end(),s.stdout?.on(`data`,e=>{t.append(e)}),s.stderr?.on(`data`,e=>{n.append(e)});let d=setTimeout(()=>{a=!0,Ie(s,{processGroup:U}),p({success:!1,output:t.toString(),error:`Command timed out after ${c}ms`})},c);function p(t){o||(o=!0,clearTimeout(d),r?.removeEventListener(`abort`,h),e(JSON.stringify(t)))}function h(){Ie(s,{processGroup:U}),p({success:!1,output:t.toString(),error:`Aborted`})}r?.addEventListener(`abort`,h,{once:!0}),s.on(`error`,e=>{s.pid===void 0&&g(),p({success:!1,output:``,error:e.message})}),s.on(`close`,e=>{let r=g();if(a){p({success:!1,output:t.toString(),error:`Command timed out after ${c}ms`,exitCode:e??void 0});return}let i=t.toString(),o=n.toString(),s=e??0,l=o?`${i}\nstderr:\n${o}`:i;p({success:!0,output:r===void 0?l:`${l}\n${r}`,exitCode:s})})})}function mn(e,t){let n=d({executable:t.shellExecutable});return B(e,t.description??ln(n,t.availableTools),dn,async(e,r)=>pn(e,t,n,r?.signal,r?.shellTraceEnv))}function hn(e){return mn(`Shell`,e)}function gn(e){return mn(`Bash`,e)}function W(e,t){return t!==void 0&&ze(t,e)}function G(e,t){return t===void 0?e:E(t,e)}function K(e,t){if(t===void 0){let t={success:!1,output:``,error:`Access denied: "${e}" cannot be checked because no containment root is configured for this tool. This is an assembly bug, not a path problem — the tool was constructed without a \`cwd\`, so it has no boundary to enforce (ARCH-010).`};return JSON.stringify(t)}if(!W(e,t)){let t={success:!1,output:``,error:`Access denied: "${e}" is outside the working directory`};return JSON.stringify(t)}}var q=class extends Error{};function _n(e,t){return t===e||t.startsWith(e+fe)}async function vn(e,t,n){let r=()=>new q(`Access denied: "${e}" is outside the working directory`);if(t===void 0)throw r();let i=await xe(t);if(process.platform===`darwin`){let t=await xe(e);if(!_n(i,t))throw r();try{return await _e(t,n|536870912,384)}catch(e){throw e.code===`ELOOP`?r():e}}let a=await _e(e,n,384);if(process.platform!==`linux`)return a;let o;try{o=await be(`/proc/self/fd/${a.fd}`)}catch{throw await a.close(),new q(`Access denied: "${e}" cannot be confirmed inside the working directory without /proc`)}if(_n(i,o))return a;throw await a.close(),r()}function yn(e,t){if(t===void 0)return{root:``,error:K(e??``,void 0)};let n=e?E(t,e):t;return{root:n,error:K(n,t)}}const bn=2e3,J=4*1024*1024;var Y=class extends c{boundary;constructor(e){super(`Read ${e} exceeds its UTF-8 byte limit`,`Read`),this.boundary=e}},X=class extends c{constructor(){super(`Read cancelled`,`Read`)}};const xn=O.object({filePath:O.string().describe(`The absolute path to the file to read`),offset:O.number().optional().describe(`The line number to start reading from (1-based). Only provide if the file is too large to read at once`),limit:O.number().optional().describe(`The number of lines to read (default: ${bn}). Only provide if the file is too large to read at once`)});function Sn(e){let t=Math.min(e.length,8192);for(let n=0;n<t;n++)if(e[n]===0)return!0;return!1}function Cn(e,t){let n=t+e.length-1,r=String(n).length;return e.map((e,n)=>`${String(t+n).padStart(r,` `)}\t${e}`).join(`
|
|
7
7
|
`)}function wn(e,t,n,r){let i=[],a=0,o=0,s=0,c=Math.trunc(n-1),l=Math.trunc(n-1+r);for(;s<t.length;){let e=t.indexOf(`
|
|
8
8
|
`,s),r=e===-1?t.length:e;if(o++,o>c&&o<=l){let e=t.slice(s,r);if(a+=Buffer.byteLength(e,`utf8`)+String(n+i.length).length+1,a>J)throw new Y(`output`);i.push(e)}if(e===-1)break;s=e+1}let u=i.length,d=u<o?`[File: ${e} (lines ${n}-${n+u-1} of ${o})]\n`:`[File: ${e} (${o} lines)]\n`,f=String(n+u-1).length,p=Buffer.byteLength(d,`utf8`)+Math.max(0,u-1);for(let e of i)p+=f+1+Buffer.byteLength(e,`utf8`);if(p>J)throw new Y(`output`);let m={success:!0,output:d+Cn(i,n)};return JSON.stringify(m)}async function Tn(e,t){if(t.signal?.aborted)throw new X;let{offset:n,limit:r=bn}=e,i=t.sandboxClient?e.filePath:G(e.filePath,t.cwd),a=n!==void 0&&n>0?n:1;if(t.sandboxClient)try{let e=await t.sandboxClient.readFile(i);if(t.signal?.aborted)throw new X;if(Buffer.byteLength(e,`utf8`)>J)throw new Y(`input`);return wn(i,e,a,r)}catch(e){if(e instanceof Y||e instanceof X)throw e;let t={success:!1,output:``,error:e instanceof Error?e.message:String(e)};return JSON.stringify(t)}let o=K(i,t.cwd);if(o!==void 0)return o;let s=e=>JSON.stringify({success:!1,output:``,error:e}),c;try{c=await vn(i,t.cwd,g.O_RDONLY|g.O_NONBLOCK)}catch(e){if(e instanceof q)return s(e.message);let t=await D(i).catch(()=>void 0);return t===void 0?s(`File not found: ${i}`):t.isFile()?s(e instanceof Error?e.message:String(e)):s(`Path is not a file: ${i}`)}let l=Buffer.alloc(0),u=!1;try{if(!(await c.stat()).isFile())return s(`Path is not a file: ${i}`);let e=[],n=Buffer.allocUnsafe(65536),r=0,a=0;for(;r<=J;){if(t.signal?.aborted)throw new X;let{bytesRead:i}=await c.read(n,0,Math.min(n.length,4194305-r),null);if(i===0)break;let o=Math.min(i,8192-a);if(o>0&&Sn(n.subarray(0,o))){u=!0;break}if(a+=o,r+=i,r>J)throw new Y(`input`);e.push(Buffer.from(n.subarray(0,i)))}u||(l=Buffer.concat(e,r))}catch(e){if(e instanceof Y||e instanceof X)throw e;return s(e instanceof Error?e.message:String(e))}finally{await c.close()}if(t.signal?.aborted)throw new X;if(u){let e={success:!1,output:``,error:`Binary file not supported: ${i}`};return JSON.stringify(e)}return wn(i,l.toString(`utf8`),a,r)}function En(e){return B(`Read`,e.description??`Reads a file from the local filesystem.
|
|
9
9
|
|
|
@@ -63,5 +63,5 @@ readline.createInterface({ input: process.stdin }).on('line', line => {
|
|
|
63
63
|
`))>=0;){let t=e.slice(0,n);e=e.slice(n+1);try{this.emit(`message`,JSON.parse(t))}catch{this.emit(`error`)}}}),this.child.stderr.resume(),this.child.on(`error`,()=>this.emit(`error`)),this.child.stdin.on(`error`,()=>this.emit(`error`)),this.closed=new Promise(e=>{this.child.once(`close`,()=>{this.emit(`exit`),e()})})}postMessage(e){this.child.stdin.write(JSON.stringify(e)+`
|
|
64
64
|
`)}async terminate(){this.child.exitCode===null&&this.child.signalCode===null&&this.child.kill(`SIGKILL`),await this.closed}},Xn=class{pattern;signal;worker=process.versions.bun?new Yn:new je(Jn,{eval:!0,execArgv:[],resourceLimits:{maxOldGenerationSizeMb:128,maxYoungGenerationSizeMb:32}});pending=new Map;nextId=0;stopped=!1;termination;timer;abort=()=>{this.stop(Error(`Grep search cancelled`))};constructor(e,t){this.pattern=e,this.signal=t,this.worker.on(`message`,e=>{let t=this.pending.get(e.id);!t||this.stopped||(this.pending.delete(e.id),Array.isArray(e.matches)&&e.matches.every(e=>typeof e==`string`)?t.resolve(e.matches):t.reject(Error(e.error??`Invalid grep worker response`)))}),this.worker.on(`error`,()=>{this.stop(Error(`Grep search worker failed`))}),this.worker.once(`exit`,()=>{this.stop(Error(`Grep search worker exited`))}),this.timer=setTimeout(()=>{this.stop(Error(`Grep search timed out`))},2e3),t?.addEventListener(`abort`,this.abort,{once:!0}),t?.aborted&&this.abort()}search(e,t,n,r){if(this.stopped)return Promise.reject(Error(this.signal?.aborted?`Grep search cancelled`:`Grep search timed out`));let i=this.nextId++;return new Promise((a,o)=>{this.pending.set(i,{resolve:a,reject:o});try{this.worker.postMessage({id:i,content:e,filePath:t,pattern:this.pattern,contextLines:n,outputMode:r})}catch{this.stop(Error(`Grep search worker failed`))}})}async stop(e){return this.termination?this.termination:(this.stopped=!0,clearTimeout(this.timer),this.signal?.removeEventListener(`abort`,this.abort),this.termination=(async()=>{try{await this.worker.terminate()}catch{}for(let t of this.pending.values())t.reject(e??Error(`Grep search stopped`));this.pending.clear()})(),this.termination)}};const Zn=O.object({pattern:O.string().describe(`The regular expression pattern to search for in file contents`),path:O.string().optional().describe(`File or directory to search in. Defaults to the current working directory`),glob:O.string().optional().describe(`Glob pattern to filter files (e.g. "*.ts", "*.{ts,tsx}"). Only files matching this pattern will be searched`),contextLines:O.number().optional().describe(`Number of context lines to show before and after each match. Only applies when outputMode is "content". Default: 0`),outputMode:O.enum([`files_with_matches`,`content`,`count`]).optional().describe(`Output mode: "files_with_matches" shows only file paths (default), "content" shows matching lines with context, "count" shows per-file match counts`),headLimit:O.number().int().positive().optional().describe(`Maximum number of result lines (file paths, content lines, or count rows) to return. Excess results are truncated with a marker line`)}),Qn=4*1024*1024;var Q=class extends c{reason;constructor(e){super(`Grep search ${e===`timeout`?`timed out`:e===`cancelled`?`cancelled`:e===`limit`?`exceeded its byte limit`:`worker failed`}`,`Grep`),this.reason=e}};async function $n(e,t){let{pattern:n,path:r,glob:i,contextLines:a=0,outputMode:o=`files_with_matches`,headLimit:s}=e,c=t.cwd,{root:l,error:u}=yn(r,c);if(u)return u;try{new RegExp(n)}catch{let e={success:!1,output:``,error:`Invalid regex pattern: ${n}`};return JSON.stringify(e)}let d;try{d=await D(l)}catch{let e={success:!1,output:``,error:`Path not found: ${l}`};return JSON.stringify(e)}let f,p=!1;if(d.isFile())f=[l];else{let e=await Kn(l,i,c);f=e.files,p=e.truncated}let m=new Xn(n,t.signal),h=new AbortController,g=()=>h.abort();t.signal?.addEventListener(`abort`,g,{once:!0}),t.signal?.aborted&&g();let _;try{if(h.signal.aborted)throw new Q(`cancelled`);let e=Array(f.length),t=0,n,r=async e=>{let t;try{if((await D(e)).size>Qn)throw new Q(`limit`);let n=ee(e,{highWaterMark:65536,signal:h.signal}),r=[],i=0;try{for await(let e of n){if(h.signal.aborted)throw new Q(`cancelled`);let t=Buffer.isBuffer(e)?e:Buffer.from(e);if(i+=t.length,i>Qn)throw new Q(`limit`);r.push(t)}}finally{n.destroy()}let a=Buffer.concat(r,i),o=Math.min(a.length,8192),s=!1;for(let e=0;e<o;e++)if(a[e]===0){s=!0;break}if(s)return[];t=a.toString(`utf8`)}catch(e){if(e instanceof Q)throw e;if(h.signal.aborted)throw new Q(`cancelled`);return[]}return m.search(t,e,a,o)};if(await Promise.all(Array.from({length:Math.min(8,f.length)},async()=>{for(;n===void 0&&t<f.length;){let i=t++;try{e[i]=await r(f[i])}catch(e){n===void 0&&(n=e,h.abort(),m.stop(e instanceof Error?e:Error(`Grep search failed`)))}}})),n!==void 0)throw n;_=e}catch(e){let t=e instanceof Error?e.message:``;throw e instanceof Q?e:new Q(t.includes(`timed out`)?`timeout`:t.includes(`cancelled`)?`cancelled`:t.includes(`byte limit`)?`limit`:`failed`)}finally{t.signal?.removeEventListener(`abort`,g),await m.stop()}let v=0;for(let e of _)for(let t of e)if(v+=Buffer.byteLength(t,`utf8`)+1,v>4*1024*1024)throw new Q(`limit`);let y=_.flat();if(s!==void 0&&y.length>s){let e=y.length-s;y=[...y.slice(0,s),`(+${e} more results truncated by headLimit)`]}p&&(y=[...y,`[File enumeration stopped early; the search tree has more files than this tool scans in one call. Results may be incomplete — narrow the path or glob.]`]);let b={success:!0,output:y.length>0?y.join(`
|
|
65
65
|
`):`(no matches)`};return JSON.stringify(b)}function er(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 tr(e){return B(`Grep`,e.description??er(e.shellToolName??`Shell`),Zn,async t=>$n(t,e))}const nr=3e4,rr=5e6,ir=O.object({url:O.string().describe(`The URL to fetch`),headers:O.record(O.string()).optional().describe(`Optional HTTP headers as key-value pairs`)});function ar(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 or(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 sr={"&":`&`,"<":`<`,">":`>`,""":`"`,"'":`'`," ":` `},cr=/&(?:amp|lt|gt|quot|nbsp|#39);/g;function lr(e){return or(ar(ar(e,`script`),`style`)).replace(cr,e=>sr[e]).replace(/\s+/g,` `).trim()}function ur(e){if(!(e instanceof Error))return String(e);if(e.name===`AbortError`)return`Request timed out after ${nr/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 dr(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 tt(r,{headers:{"User-Agent":`Robota-CLI/3.0`,...i??{}},signal:n,timeoutMs:nr,maxResponseBytes:rr},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 ${rr} 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=lr(o)),JSON.stringify({success:!0,output:o})}catch(e){let t={success:!1,output:``,error:ur(e)};return JSON.stringify(t)}}function fr(e={}){let t=e.egress??{};return B(`WebFetch`,e.description??`Fetch a URL and return its content as text. HTML pages are converted to plain text.`,ir,async(e,n)=>dr(e,t,n?.signal))}const pr=fr();function mr(){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 hr=O.object({query:O.string().describe(`The search query`),limit:O.number().optional().describe(`Maximum number of results to return (default: 10)`)});async function gr(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 _r(e={}){let t=e.provider??mr();return B(`WebSearch`,e.description??`Search the web and return results with title, URL, and snippet.`,hr,async(e,n)=>gr(e,t,n?.signal))}const vr=_r(),yr=O.object({question:O.string().min(1).describe(`The complete question to ask the user.`),header:O.string().optional().describe(`Very short topic label for the question (e.g. "Auth method").`),options:O.array(O.union([O.string().min(1).describe(`Display text of this choice.`),O.object({label:O.string().min(1).describe(`Display text of this choice.`),description:O.string().optional().describe(`What choosing this option means.`)})])).optional().describe(`Predefined choices (strings or {label, description}). Omit for pure free text.`),multiSelect:O.boolean().optional().describe(`Allow selecting multiple options (default: single select).`),allowFreeText:O.boolean().optional().describe(`Allow a typed custom answer besides the options (default: true).`)}),br=O.object({questions:O.array(yr).min(1).max(4).describe(`Questions to ask the user (1-4), rendered one at a time.`)}),xr=[`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(`
|
|
66
|
-
`);function Sr(e){let t=(e.options??[]).map(e=>typeof e==`string`?{label:e}:e),n=e.multiSelect===!0&&t.length>1;return{id:`ask_${me()}`,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 Cr(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(Sr(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 wr(e={}){return B(`AskUserQuestion`,e.description??xr,br,async(e,t)=>{let n=e,r=t?.ask,i=r?await Cr(n,r):{unavailable:!0,reason:`no interactive user attached`},a={success:!0,output:JSON.stringify(i)};return JSON.stringify(a)})}wr();const Tr=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 Er(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:Tr}function Dr(e,t,n){let r=t.trim().toLowerCase();return r.length===0?[]:e.map(e=>({schema:e,rank:Er(e,r)})).filter(e=>e.rank!==Tr).sort((e,t)=>e.rank-t.rank||(e.schema.name<t.schema.name?-1:1)).slice(0,n).map(e=>e.schema)}const Or=
|
|
66
|
+
`);function Sr(e){let t=(e.options??[]).map(e=>typeof e==`string`?{label:e}:e),n=e.multiSelect===!0&&t.length>1;return{id:`ask_${me()}`,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 Cr(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(Sr(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 wr(e={}){return B(`AskUserQuestion`,e.description??xr,br,async(e,t)=>{let n=e,r=t?.ask,i=r?await Cr(n,r):{unavailable:!0,reason:`no interactive user attached`},a={success:!0,output:JSON.stringify(i)};return JSON.stringify(a)})}wr();const Tr=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 Er(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:Tr}function Dr(e,t,n){let r=t.trim().toLowerCase();return r.length===0?[]:e.map(e=>({schema:e,rank:Er(e,r)})).filter(e=>e.rank!==Tr).sort((e,t)=>e.rank-t.rank||(e.schema.name<t.schema.name?-1:1)).slice(0,n).map(e=>e.schema)}const Or=r,kr=O.object({query:O.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:O.array(O.string().min(1)).optional().describe(`Exact tool names to load, skipping the search. An unknown name is an error naming it.`),limit:O.number().int().positive().optional().describe(`Maximum tools to load from a query match (default 5).`)}),Ar=[`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(`
|
|
67
67
|
`);function jr(e){let t=e?.deferredTools;if(!t)throw Error(`${Or} 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 Mr(e,t){if(e.names!==void 0)return t.loadDeferredTools(e.names);if(e.query===void 0)throw Error(`${Or} needs either "query" to search for tools or "names" to load exact ones.`);let n=Dr(t.listDeferredTools(),e.query,e.limit??5);return t.loadDeferredTools(n.map(e=>e.name))}function Nr(e={}){return B(Or,e.description??Ar,kr,async(e,t)=>{let n={loaded:Mr(e,jr(t)).map(({name:e,description:t})=>({name:e,description:t})),unavailableSources:[]},r={success:!0,output:JSON.stringify(n)};return JSON.stringify(r)})}Nr();export{nt as A,ot as C,ze as D,He as E,Ie as F,Me as I,P as M,Ue as N,j as O,Le as P,Ft as S,vr as T,fr as _,X as a,B as b,gn as c,Un as d,tr as f,Nr as g,hn as h,Y as i,We as j,tt as k,sn as l,Jt as m,Q as n,ut as o,En as p,Vt as r,wr as s,Mt as t,Rn as u,_r as v,pr as w,at as x,Nn as y};
|