@robota-sdk/agent-cli 3.0.0-beta.88 → 3.0.0-beta.90
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 +49 -0
- package/README.md +16 -5
- package/dist/node/bin.js +1 -1
- package/dist/node/{cli-core-CEWWF4d6.js → cli-core-YR-wNxJu.js} +324 -323
- package/dist/node/headless.js +1 -1
- package/dist/node/index.d.ts +6 -1
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +348 -347
- package/dist/node/index.js.map +1 -1
- package/dist/node/{node-CEI_VczS.js → node-B9M9cLfF.js} +1 -1
- package/dist/node/{node-CrspydTR.js → node-C1z7m4gZ.js} +2 -2
- package/dist/node/{node-CrspydTR.js.map → node-C1z7m4gZ.js.map} +1 -1
- package/dist/node/{node-BIdvEvlf.js → node-CHbqiARC.js} +1 -1
- package/package.json +35 -35
|
@@ -99,7 +99,7 @@ n.exports={WebsocketFrameSend:class{constructor(e){this.frameData=e}createFrame(
|
|
|
99
99
|
`).slice(1).join(`
|
|
100
100
|
`);e.stack=n?`${n}\n${a}`:i.stack}t.exports.fetch=function(e,n=void 0){return M(e,n).catch(e=>{throw N?P(e,N):e&&typeof e==`object`&&Error.captureStackTrace(e,t.exports.fetch),e})},t.exports.Headers=qt().Headers,t.exports.Response=Jt().Response,t.exports.Request=Yt().Request,t.exports.FormData=He().FormData;let{setGlobalOrigin:F,getGlobalOrigin:I}=Fe();t.exports.setGlobalOrigin=F,t.exports.getGlobalOrigin=I;let{CacheStorage:L}=en(),{kConstruct:R}=Z();t.exports.caches=new L(R);let{deleteCookie:z,getCookies:B,getSetCookies:V,setCookie:ee,parseCookie:H}=an();t.exports.deleteCookie=z,t.exports.getCookies=B,t.exports.getSetCookies=V,t.exports.setCookie=ee,t.exports.parseCookie=H;let{parseMIMEType:U,serializeAMimeType:te}=Re();t.exports.parseMIMEType=U,t.exports.serializeAMimeType=te;let{CloseEvent:ne,ErrorEvent:W,MessageEvent:re}=on(),{WebSocket:ie,ping:G}=mn();t.exports.WebSocket=ie,t.exports.CloseEvent=ne,t.exports.ErrorEvent=W,t.exports.MessageEvent=re,t.exports.ping=G,t.exports.WebSocketStream=gn().WebSocketStream,t.exports.WebSocketError=hn().WebSocketError,t.exports.request=j(g.request),t.exports.stream=j(g.stream),t.exports.pipeline=j(g.pipeline),t.exports.connect=j(g.connect),t.exports.upgrade=j(g.upgrade),t.exports.MockClient=v,t.exports.MockCallHistory=y,t.exports.MockCallHistoryLog=b,t.exports.MockPool=S,t.exports.MockAgent=x,t.exports.SnapshotAgent=C,t.exports.mockErrors=w;let{EventSource:ae}=yn();t.exports.EventSource=ae;function oe(){globalThis.fetch=t.exports.fetch,globalThis.Headers=t.exports.Headers,globalThis.Response=t.exports.Response,globalThis.Request=t.exports.Request,globalThis.FormData=t.exports.FormData,globalThis.WebSocket=t.exports.WebSocket,globalThis.CloseEvent=t.exports.CloseEvent,globalThis.ErrorEvent=t.exports.ErrorEvent,globalThis.MessageEvent=t.exports.MessageEvent,globalThis.EventSource=t.exports.EventSource}t.exports.install=oe}))();function xn(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(!I(e))throw TypeError(`executionRoot must be an absolute path`);let t;try{t=D(e)}catch{throw TypeError(`executionRoot must name an existing accessible directory`)}if(!A(t).isDirectory())throw TypeError(`executionRoot must name a directory`);try{g(t,v.R_OK|v.X_OK)}catch{throw TypeError(`executionRoot directory must be readable and traversable`)}return t}function Sn(e){let t=[],n=B(e);for(;;)try{return L(D(n),...t)}catch{let r=F(n);if(r===n)return B(e);t.unshift(P(n)),n=r}}function Cn(e,t){let n=Sn(e),r=Sn(t);return r===n||r.startsWith(n+V)}var wn=class extends Error{constructor(e){super(e),this.name=`OwnerOnlyModeError`}};function Tn(e=process.platform){return e===`win32`?`windows-acl`:`posix-mode`}function En(e,t){let n=z(e,t);if(n.startsWith(`..`)||I(n))throw new wn(`withinRoot ${e} is not an ancestor of ${t}, so this call cannot own the path between them.`);let r=n.split(V).filter(e=>e.length>0),i=[e],a=e;for(let e of r)a=L(a,e),i.push(a);return i}function Dn(e,t,n={}){if(Tn()!==`posix-mode`)return;let r=(n.readMode??(e=>A(e).mode&4095))(e);if(r&63)throw new wn(`${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 On(e,t={}){let n=t.makeDirectory??((e,t)=>{C(e,{recursive:!0,mode:t})}),r=t.setMode??((e,t)=>_(e,t));n(e,448);let i=t.withinRoot===void 0?[e]:En(t.withinRoot,e);for(let e of i)Tn()===`posix-mode`&&r(e,448),Dn(e,`directory`,t)}function kn(e,t){On(F(e));let n=`${e}.${process.pid}.tmp`;k(n,{force:!0}),N(n,t,{encoding:`utf8`,mode:384,flag:`wx`});try{Dn(n,`file`),O(n,e)}catch(e){try{M(n)}catch{}throw e}Dn(e,`file`)}function An(e){if(Tn()!==`posix-mode`)return;let t;try{t=A(e).mode&4095}catch{return}t&63&&(_(e,384),Dn(e,`file`))}function jn(e){let t=de(e);return t===4?Mn(e.split(`.`).map(Number)):t!==6||Nn(e)}function Mn(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 Nn(e){let t=Fn(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?Mn([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 Pn(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 Fn(e){let t=Pn(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 In=3e4,Ln=5e6,Rn=new Set([301,302,303,307,308]),zn=new Set([`localhost`,`metadata`,`metadata.google.internal`,`metadata.goog`,`instance-data`,`instance-data.ec2.internal`]),Bn=async e=>(await ue(e,{all:!0,verbatim:!0})).map(e=>e.address);async function Vn(e,t={},n=Bn){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(zn.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 Hn(i,n);if(a===void 0||a.length===0)return{reason:`unresolvable`,url:r,message:`Destination "${i}" did not resolve.`};let o=a.find(jn);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 Hn(e,t){try{return await t(e)}catch{return}}async function Un(e,t,n){n.throwIfAborted();let r;try{return await Promise.race([t(e),new Promise((e,t)=>{r=()=>t(n.reason),n.addEventListener(`abort`,r,{once:!0}),n.aborted&&r()})])}finally{r&&n.removeEventListener(`abort`,r)}}async function Wn(e,t,n,r,i){let a=e.hostname.replace(/^\[|\]$/g,``).toLowerCase(),o,s=async e=>{let t=await Un(e,r.lookup??Bn,i);if(t.length===0||t.some(e=>de(e)===0))throw Error(`Invalid DNS answer`);return o=Object.freeze([...t]),o},c=await Vn(e,n,s);if(i.throwIfAborted(),c)return c;if(r.fetch){let n=await r.fetch(e.href,{...t,signal:i,redirect:`manual`});return{response:n,close:async()=>{n.body&&!n.body.locked&&await n.body.cancel().catch(()=>void 0)}}}if(o??=de(a)?[a]:await Hn(a,s),i.throwIfAborted(),!o||o.length===0)return{reason:`unresolvable`,url:e.href,message:`Destination did not resolve to valid IP addresses.`};let l=o.map(e=>({address:e,family:de(e)})),u=new bn.Agent({connections:1,pipelining:0,connect:{lookup:(e,t,n)=>{if(e.toLowerCase()!==a||i.aborted){n(Error(`Connection authority unavailable`),``,4);return}let r=typeof t==`number`?t:t.family,o=l.filter(e=>!r||e.family===r);if(o.length===0){n(Error(`No validated address family`),``,4);return}typeof t==`object`&&t.all?n(null,o):n(null,o[0].address,o[0].family)}}});if(typeof u.dispatch!=`function`||typeof u.destroy!=`function`)throw Error(`Pinned HTTP transport is unavailable in this runtime`);try{return{response:await(0,bn.fetch)(e.href,{...t,signal:i,redirect:`manual`,dispatcher:u}),close:async()=>{await u.destroy()}}}catch(e){throw await u.destroy(),e}}async function Gn(e,t={},n={},r={}){let i=t.maxResponseBytes??Ln,a=n.maxRedirects??5,o=AbortSignal.timeout(t.timeoutMs??In),s=t.signal?AbortSignal.any([o,t.signal]):o,c=new URL(e),l={...t.headers??{}};for(let e=0;;e+=1){let t=await Wn(c,{headers:l,signal:s,redirect:`manual`},n,r,s);if(!(`response`in t))return{ok:!1,rejection:t};try{let n=t.response;if(!Rn.has(n.status))return await Jn(n,c.href,i,s);let r=n.headers.get(`location`);if(r===null)return{ok:!1,rejection:{reason:`redirect_without_location`,url:c.href,message:`HTTP ${n.status} without a Location header.`}};if(e>=a)return{ok:!1,rejection:{reason:`redirect_limit`,url:c.href,message:`More than ${a} redirects.`}};let o=new URL(r,c);o.origin!==c.origin&&(l=qn(l)),c=o}finally{await t.close()}}}async function Kn(e,t,n={},r={}){let i=t.maxResponseBytes??Ln,a=AbortSignal.timeout(t.timeoutMs??In),o=t.signal?AbortSignal.any([a,t.signal]):a,s=new URL(e),c=await Wn(s,{method:`POST`,headers:{...t.headers??{}},body:t.body,signal:o,redirect:`manual`},n,r,o);if(!(`response`in c))return{ok:!1,rejection:c};try{let e=c.response;return e.status>=300&&e.status<400?(await e.body?.cancel().catch(()=>void 0),{ok:!1,rejection:{reason:`redirect_refused`,url:s.href,message:`HTTP ${e.status}: a POST is never redirected.`}}):await Jn(e,s.href,i,o)}finally{await c.close()}}function qn(e){let t={};for(let[n,r]of Object.entries(e))n.toLowerCase()===`user-agent`&&(t[n]=r);return t}async function Jn(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 Yn(e){if(typeof e!=`string`||e.trim().length===0||e.length>1024||[...e].some(e=>{let t=e.codePointAt(0);return t<32||t===127||t>=55296&&t<=57343}))throw Error(`E2B resumable worker reference is invalid.`);return e}function Xn(e){if(typeof e!=`object`||!e||typeof e.commands?.run!=`function`||typeof e.files?.read!=`function`||typeof e.files?.write!=`function`)throw Error(`E2B worker adapter is invalid.`)}function Zn(e){if(typeof e!=`object`||!e)throw Error(`E2B command exit code is missing.`);let t=e.exitCode===void 0?e.exit_code:e.exitCode;if(!Number.isSafeInteger(t)||e.exitCode!==void 0&&e.exit_code!==void 0&&e.exitCode!==e.exit_code)throw Error(`E2B command exit code is missing, invalid or inconsistent.`);if(e.stdout!==void 0&&typeof e.stdout!=`string`||e.stderr!==void 0&&typeof e.stderr!=`string`)throw Error(`E2B command output is invalid.`);return{stdout:e.stdout??``,stderr:e.stderr??``,exitCode:t}}var Qn=class{sandbox;generation=0;restoring=!1;connectSandbox;createSandboxFromSnapshot;constructor(e){Xn(e.sandbox),this.sandbox=e.sandbox,this.connectSandbox=e.connectSandbox,this.createSandboxFromSnapshot=e.createSandboxFromSnapshot}async run(e,t){return Zn(await this.withWorker(n=>n.commands.run(e,{background:!1,timeoutMs:t?.timeoutMs,cwd:t?.workingDirectory})))}async readFile(e){let t=await this.withWorker(t=>t.files.read(e));if(typeof t!=`string`&&!(t instanceof Uint8Array))throw Error(`E2B file response is invalid.`);return typeof t==`string`?t:Buffer.from(t).toString(`utf8`)}async writeFile(e,t){await this.withWorker(n=>n.files.write(e,t))}async snapshot(){return this.withWorker(async e=>{if(e.createSnapshot){let t=await e.createSnapshot();if(typeof t!=`object`||!t||t.snapshotId!==void 0&&t.id!==void 0&&t.snapshotId!==t.id)throw Error(`E2B snapshot identity is invalid or inconsistent.`);return Yn(t.snapshotId??t.id)}let t=Yn(e.sandboxId);if(!e.pause)throw Error(`E2B sandbox adapter does not expose pause().`);return await e.pause(),t})}async restore(e){if(this.restoring)throw Error(`E2B worker restore is already in progress.`);let t=this.sandbox;this.sandbox=void 0,this.generation++,this.restoring=!0;try{Yn(e);let n;if(this.createSandboxFromSnapshot)n=await this.createSandboxFromSnapshot(e);else if(this.connectSandbox)n=await this.connectSandbox(e);else if(t?.sandboxId===e&&t.connect)n=await t.connect();else throw Error(`E2B sandbox restore requires connectSandbox(snapshotId) or sandbox.connect().`);if(Xn(n),!this.createSandboxFromSnapshot&&n.sandboxId!==e)throw Error(`E2B restored worker identity does not match the requested reference.`);this.sandbox=n}finally{this.restoring=!1}}async withWorker(e){let t=this.sandbox,n=this.generation;if(t===void 0||this.restoring)throw Error(`E2B worker is not available; a successful restore is required.`);let r=await e(t);if(n!==this.generation||t!==this.sandbox)throw Error(`E2B worker changed during the operation; the previous worker result is refused.`);return r}};function $n(e){return e===void 0?`host`:`sandbox-${e.filesystem??`separate`}`}function er(e){return $n(e)===`sandbox-separate`}function tr(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 nr=/^[A-Za-z]:[\\/]/,rr=/'/g;async function ir(e,t,n={}){if(e.applyManifest)return e.applyManifest(t,n);tr(t);let r=_r(n.targetRoot??`/workspace`),i=[];for(let[a,o]of Object.entries(t.entries)){let t=ar(a),s=vr(r,t);i.push(await or(e,t,s,r,o,n))}return{entries:i}}function ar(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(`\\`)||nr.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 or(e,t,n,r,i,a){switch(i.type){case`file`:return await fr(e,n,r,i.content),sr(t,i.type);case`dir`:return await pr(e,n),sr(t,i.type);case`localFile`:return await cr(e,i.src,n,r,a),sr(t,i.type);case`localDir`:return await lr(e,i.src,n,a),sr(t,i.type);case`gitRepo`:return await dr(e,i,n),sr(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 br(i)}}function sr(e,t){return{path:e,type:t,status:`applied`}}async function cr(e,t,n,r,i){await fr(e,n,r,await W(hr(t,i.hostRoot),`utf8`))}async function lr(e,t,n,r){await ur(e,hr(t,r.hostRoot),n)}async function ur(e,t,n){await pr(e,n);let r=await re(t,{withFileTypes:!0});for(let i of r){let r=L(t,i.name),a=vr(n,i.name);if(i.isDirectory()){await ur(e,r,a);continue}if(i.isFile()){let t=await W(r,`utf8`);await e.writeFile(a,t)}}}async function dr(e,t,n){await mr(e,`git clone${t.shallow===!1?``:` --depth 1`}${t.ref?` --branch ${yr(t.ref)}`:``} ${yr(t.url)} ${yr(n)}`)}async function fr(e,t,n,r){let i=R.dirname(t);i!==n&&await pr(e,i),await e.writeFile(t,r)}async function pr(e,t){await mr(e,`mkdir -p ${yr(t)}`)}async function mr(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 hr(e,t){return I(e)?B(e):B(t??process.cwd(),e)}function gr(e){let t=e.length;for(;t>0&&e[t-1]===`/`;)--t;return e.slice(0,t)}function _r(e){let t=gr(e.replace(/\\/g,`/`));if(!t.startsWith(`/`))throw Error(`workspace manifest targetRoot must be an absolute sandbox path`);return t.length===0?`/`:t}function vr(e,t){let n=_r(e);return n===`/`?`/${t}`:`${n}/${t}`}function yr(e){return`'${e.replace(rr,`'\\''`)}'`}function br(e){throw Error(`unsupported workspace manifest entry: ${JSON.stringify(e)}`)}function xr(e){return[...new Set([`.claude/worktrees`,...e?.writableWorktreeContainers??[]])]}function Sr(e,t){let n=e.length;for(;n>0&&e[n-1]===`/`;)--n;return`${e.slice(0,n)}/${t}`}function Cr(e){return[...new Set([...i,...e?.protectedDirectoryNames??[],...n])]}function wr(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 Cr(t.pathProtection)){let i=Sr(t.root,r);e.exists(i)&&n.push(`--ro-bind`,i,i)}for(let r of xr(t.pathProtection)){let i=Sr(t.root,r);if(e.exists(i)){n.push(`--bind`,i,i);for(let t of e.listDirectory(i)){let r=Sr(i,`${t}/.git`);e.exists(r)&&n.push(`--ro-bind`,r,r)}}}for(let r of t.pathProtection?.protectedPaths??[])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 Tr(e){return e.replace(/[\\^$.*+?()[\]{}|"]/g,e=>`\\${e}`)}function Er(e){return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function Dr(e){let t=[e.root,...e.tempDirectories,...e.allowWrite].map(e=>`(subpath ${Er(e)})`).join(` `),r=Cr(e.pathProtection).map(t=>{let r=Sr(e.root,t);return n.includes(t)?`(literal ${Er(r)})`:`(subpath ${Er(r)})`}),i=xr(e.pathProtection).map(t=>`(subpath ${Er(Sr(e.root,t))})`),a=[`(literal ${Er(Sr(e.root,`.git`))})`,...xr(e.pathProtection).map(t=>`(regex #"^${Tr(Sr(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* ${r.join(` `)})`,`(allow file-write* ${i.join(` `)})`,`(deny file-write* ${a.join(` `)})`,...(e.pathProtection?.protectedPaths.length??0)>0?[`(deny file-write* ${e.pathProtection.protectedPaths.map(e=>`(subpath ${Er(e)})`).join(` `)})`]:[]];if(e.denyRead.length>0){let t=e.denyRead.map(e=>e.directory?`(subpath ${Er(e.path)})`:`(literal ${Er(e.path)})`);o.push(`(deny file-read* ${t.join(` `)})`)}return e.network||o.push(`(deny network*)`),o.join(`
|
|
101
101
|
`)}const Or={x64:{audit:3221225534,socket:41,ioUringSetup:425},arm64:{audit:3221225655,socket:198,ioUringSetup:425}};function kr(e,t,n,r){return[e,t,n,r]}function Ar(e=process.arch){let t=Or[e];if(t===void 0)return;let n=e=>327680|e,r=[kr(32,0,0,4),kr(21,1,0,t.audit),kr(6,0,0,n(1)),kr(32,0,0,0),kr(69,0,1,1073741824),kr(6,0,0,n(1)),kr(21,0,1,t.ioUringSetup),kr(6,0,0,n(1)),kr(21,0,3,t.socket),kr(32,0,0,16),kr(21,0,1,1),kr(6,0,0,n(97)),kr(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 jr=Object.freeze({enabled:!1,autoAllowBashIfSandboxed:!0,excludedCommands:[],allowWrite:[],denyRead:[],network:!1}),Mr=`/usr/bin/sandbox-exec`;function Nr(e,t){let n=h(e,[...t],{timeout:5e3,encoding:`utf8`});if(n.error!==void 0)return{ok:!1,detail:n.error.message};let r=(n.stderr??``).trim().split(`
|
|
102
|
-
`)[0];return n.status===0?{ok:!0}:{ok:!1,...r?{detail:r}:{}}}function Pr(e={}){let t=e.platform??process.platform,n=e.probe??Nr;if(t===`linux`){if(Ar(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`,`--proc`,`/proc`,`--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(Mr,[`-p`,`(version 1)(allow default)`,`/usr/bin/true`]);return e.ok?{backend:`seatbelt`,executable:Mr,missing:[]}:{backend:`seatbelt`,missing:[`sandbox-exec cannot run${e.detail?`: ${e.detail}`:``}`]}}return{missing:[],unsupportedPlatform:t}}function Fr(e){try{return D(e)}catch{return e}}function Ir(e){try{return A(e).isDirectory()}catch{return!1}}function Lr(e){let t=S(e);if(!t.isSymbolicLink()&&(_(e,t.mode|448),t.isDirectory()))for(let t of T(e))Lr(`${e}/${t}`)}function Rr(e){try{return S(e).isSymbolicLink()}catch{return!1}}function zr(e){return e.trim().split(/\s+/)[0]}var Br=class{filesystem=`shared`;root;pathProtection;projectStateDirectory;userQuarantineDirectory;availability;homeDirectory;current;inFlight=0;baseline=[];unresolved=new Map;watchers=new Set;constructor(e){if(!/^[a-zA-Z0-9._-]+$/.test(e.projectStateDirectory)||[`.`,`..`].includes(e.projectStateDirectory))throw Error(`A safe project state directory is required`);if(!I(e.userQuarantineDirectory))throw Error(`An absolute quarantine directory is required`);this.projectStateDirectory=e.projectStateDirectory,this.userQuarantineDirectory=e.userQuarantineDirectory,this.pathProtection=Object.freeze({protectedDirectoryNames:Object.freeze([...new Set([e.projectStateDirectory,...e.pathProtection?.protectedDirectoryNames??[]])]),protectedPaths:Object.freeze([...e.pathProtection?.protectedPaths??[]]),writableWorktreeContainers:Object.freeze([...e.pathProtection?.writableWorktreeContainers??[]])}),this.root=Fr(e.root),this.availability=e.availability,this.homeDirectory=e.homeDirectory??ce(),this.current={...jr,...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(c(e).length!==1)return!0;let t=zr(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`,Dr(n),e.command,...e.args],cwd:e.cwd};let i=n.network?void 0:Ar();this.protectedEntryStates().some(e=>e.path===`${this.root}/${this.projectStateDirectory}`&&e.kind===`symlink`)||C(`${this.root}/${this.projectStateDirectory}`,{recursive:!0});let a=wr({policy:n,exists:e=>x(e)&&!Rr(e),listDirectory:e=>T(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 Cr(this.pathProtection).map(e=>{let t=`${this.root}/${e}`;try{return S(t).isSymbolicLink()?{path:t,kind:`symlink`,target:E(t)}:{path:t,kind:`present`}}catch{return{path:t,kind:`missing`}}})}resolvesOutsideWritableWorkspace(e){let t;try{t=D(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()}-${H()}`,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`&&j(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}/${this.projectStateDirectory}`;return e.some(e=>e.path===t&&e.kind===`present`)?`${t}/sandbox-quarantine`:this.userQuarantineDirectory}setAside(e,t){let n=`${t}/${P(e)}`;C(t,{recursive:!0});try{O(e,n)}catch(t){if(this.inFlight>0)throw t;Lr(e),t.code===`EXDEV`?(y(e,n,{recursive:!0,verbatimSymlinks:!0}),k(e,{recursive:!0,force:!0})):O(e,n)}return`moved ${e} to ${n}`}policy(){let e=e=>{let t=e===`~`||e.startsWith(`~/`)?`${this.homeDirectory}${e.slice(1)}`:e;return Fr(I(t)?t:B(this.root,t))},t=[...new Set([le(),`/tmp`].filter(x).map(Fr))];return{root:this.root,pathProtection:this.pathProtection,tempDirectories:t,allowWrite:this.current.allowWrite.map(e),denyRead:this.current.denyRead.map(t=>{let n=e(t);return{path:n,directory:Ir(n)}}),network:this.current.network}}run(e,t={}){let n=p(),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=m(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(w(e,`utf8`))}writeFile(e,t){return N(e,t,`utf8`),Promise.resolve()}};function Vr(e,t,n,i,a={}){return new s({name:e,description:t,parameters:r(n),...a.deferLoading!==void 0&&{deferLoading:a.deferLoading}},async(e,t)=>{let r=n.safeParse(e);if(!r.success)throw new l(`Zod validation failed: ${r.error}`);let a=await i(r.data,t);return typeof a==`string`?a:JSON.stringify(a)})}const Hr={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 Ur(){for(let[e,t]of Object.entries(Hr))a(e,t)}Ur();const Wr=1e3,Gr=q.object({activeFiles:q.array(q.string()).optional().describe(`Repo-relative files currently in focus; the map is ranked toward what they reference.`),mentionedIdentifiers:q.array(q.string()).optional().describe(`Symbol names to bias the map toward (e.g. identifiers named in the task).`),tokenBudget:q.number().int().positive().optional().describe(`Maximum tokens for the returned map (default ${Wr}).`)});function Kr(e){return e.map(e=>`${e.file}:${e.line} ${e.kind} ${e.name}`).join(`
|
|
102
|
+
`)[0];return n.status===0?{ok:!0}:{ok:!1,...r?{detail:r}:{}}}function Pr(e={}){let t=e.platform??process.platform,n=e.probe??Nr;if(t===`linux`){if(Ar(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`,`--proc`,`/proc`,`--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(Mr,[`-p`,`(version 1)(allow default)`,`/usr/bin/true`]);return e.ok?{backend:`seatbelt`,executable:Mr,missing:[]}:{backend:`seatbelt`,missing:[`sandbox-exec cannot run${e.detail?`: ${e.detail}`:``}`]}}return{missing:[],unsupportedPlatform:t}}function Fr(e){try{return D(e)}catch{return e}}function Ir(e){try{return A(e).isDirectory()}catch{return!1}}function Lr(e){let t=S(e);if(!t.isSymbolicLink()&&(_(e,t.mode|448),t.isDirectory()))for(let t of T(e))Lr(`${e}/${t}`)}function Rr(e){try{return S(e).isSymbolicLink()}catch{return!1}}function zr(e){return e.trim().split(/\s+/)[0]}var Br=class{filesystem=`shared`;root;pathProtection;projectStateDirectory;userQuarantineDirectory;availability;homeDirectory;hiddenPaths;current;inFlight=0;baseline=[];unresolved=new Map;watchers=new Set;constructor(e){if(!/^[a-zA-Z0-9._-]+$/.test(e.projectStateDirectory)||[`.`,`..`].includes(e.projectStateDirectory))throw Error(`A safe project state directory is required`);if(!I(e.userQuarantineDirectory))throw Error(`An absolute quarantine directory is required`);this.projectStateDirectory=e.projectStateDirectory,this.userQuarantineDirectory=e.userQuarantineDirectory,this.pathProtection=Object.freeze({protectedDirectoryNames:Object.freeze([...new Set([e.projectStateDirectory,...e.pathProtection?.protectedDirectoryNames??[]])]),protectedPaths:Object.freeze([...e.pathProtection?.protectedPaths??[]]),writableWorktreeContainers:Object.freeze([...e.pathProtection?.writableWorktreeContainers??[]])}),this.root=Fr(e.root),this.availability=e.availability,this.homeDirectory=e.homeDirectory??ce(),this.hiddenPaths=Object.freeze([...e.hiddenPaths??[]]),this.current={...jr,...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(c(e).length!==1)return!0;let t=zr(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`,Dr(n),e.command,...e.args],cwd:e.cwd};let i=n.network?void 0:Ar();this.protectedEntryStates().some(e=>e.path===`${this.root}/${this.projectStateDirectory}`&&e.kind===`symlink`)||C(`${this.root}/${this.projectStateDirectory}`,{recursive:!0});let a=wr({policy:n,exists:e=>x(e)&&!Rr(e),listDirectory:e=>T(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 Cr(this.pathProtection).map(e=>{let t=`${this.root}/${e}`;try{return S(t).isSymbolicLink()?{path:t,kind:`symlink`,target:E(t)}:{path:t,kind:`present`}}catch{return{path:t,kind:`missing`}}})}resolvesOutsideWritableWorkspace(e){let t;try{t=D(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()}-${H()}`,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`&&j(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}/${this.projectStateDirectory}`;return e.some(e=>e.path===t&&e.kind===`present`)?`${t}/sandbox-quarantine`:this.userQuarantineDirectory}setAside(e,t){let n=`${t}/${P(e)}`;C(t,{recursive:!0});try{O(e,n)}catch(t){if(this.inFlight>0)throw t;Lr(e),t.code===`EXDEV`?(y(e,n,{recursive:!0,verbatimSymlinks:!0}),k(e,{recursive:!0,force:!0})):O(e,n)}return`moved ${e} to ${n}`}policy(){let e=e=>{let t=e===`~`||e.startsWith(`~/`)?`${this.homeDirectory}${e.slice(1)}`:e;return Fr(I(t)?t:B(this.root,t))},t=[...new Set([le(),`/tmp`].filter(x).map(Fr))];return{root:this.root,pathProtection:this.pathProtection,tempDirectories:t,allowWrite:this.current.allowWrite.map(e),denyRead:[...new Set([...this.hiddenPaths,...this.current.denyRead])].map(t=>{let n=e(t);return{path:n,directory:Ir(n)}}),network:this.current.network}}run(e,t={}){let n=p(),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=m(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(w(e,`utf8`))}writeFile(e,t){return N(e,t,`utf8`),Promise.resolve()}};function Vr(e,t,n,i,a={}){return new s({name:e,description:t,parameters:r(n),...a.deferLoading!==void 0&&{deferLoading:a.deferLoading}},async(e,t)=>{let r=n.safeParse(e);if(!r.success)throw new l(`Zod validation failed: ${r.error}`);let a=await i(r.data,t);return typeof a==`string`?a:JSON.stringify(a)})}const Hr={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 Ur(){for(let[e,t]of Object.entries(Hr))a(e,t)}Ur();const Wr=1e3,Gr=q.object({activeFiles:q.array(q.string()).optional().describe(`Repo-relative files currently in focus; the map is ranked toward what they reference.`),mentionedIdentifiers:q.array(q.string()).optional().describe(`Symbol names to bias the map toward (e.g. identifiers named in the task).`),tokenBudget:q.number().int().positive().optional().describe(`Maximum tokens for the returned map (default ${Wr}).`)});function Kr(e){return e.map(e=>`${e.file}:${e.line} ${e.kind} ${e.name}`).join(`
|
|
103
103
|
`)}async function qr(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??Wr});return n.symbols.length===0?`No relevant symbols found within the token budget.`:`Most relevant symbols (~${n.totalTokens} tokens):\n${Kr(n.symbols)}`}function Jr(e={}){return Vr(`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.`,Gr,async t=>qr(t,e))}const Yr=`Computer use is not available in this session (no driver injected).`,Xr=q.enum([`left`,`right`,`middle`]),Zr=q.object({x:q.number(),y:q.number()}),Qr=q.object({type:q.enum([`click`,`double_click`,`type`,`keypress`,`scroll`,`drag`,`wait`,`takeover`]).describe(`Which action to perform.`),x:q.number().optional().describe(`X coordinate (click/double_click/scroll).`),y:q.number().optional().describe(`Y coordinate (click/double_click/scroll).`),button:Xr.optional().describe(`Mouse button (click/double_click/drag).`),text:q.string().optional().describe(`Text to type (type).`),keys:q.array(q.string()).optional().describe(`Keys to press as a chord (keypress).`),deltaX:q.number().optional().describe(`Horizontal wheel delta (scroll).`),deltaY:q.number().optional().describe(`Vertical wheel delta (scroll).`),path:q.array(Zr).optional().describe(`Points to drag through (drag).`),ms:q.number().optional().describe(`Milliseconds to wait (wait).`),reason:q.string().optional().describe(`Human-readable reason surfaced to the user (takeover).`)}),$r=q.object({action:Qr.describe(`The single mutating action to perform.`)}),ei=q.object({});var ti=class extends Error{};function ni(e,t,n){if(typeof e!=`number`)throw new ti(`Action '${n}' requires numeric '${t}'.`);return e}function ri(e){let t=e.button;switch(e.type){case`click`:return{type:`click`,x:ni(e.x,`x`,`click`),y:ni(e.y,`y`,`click`),...t?{button:t}:{}};case`double_click`:return{type:`double_click`,x:ni(e.x,`x`,`double_click`),y:ni(e.y,`y`,`double_click`),...t?{button:t}:{}};case`type`:if(typeof e.text!=`string`)throw new ti(`Action 'type' requires 'text'.`);return{type:`type`,text:e.text};case`keypress`:if(!e.keys||e.keys.length===0)throw new ti(`Action 'keypress' requires non-empty 'keys'.`);return{type:`keypress`,keys:e.keys};case`scroll`:return{type:`scroll`,x:ni(e.x,`x`,`scroll`),y:ni(e.y,`y`,`scroll`),deltaX:ni(e.deltaX,`deltaX`,`scroll`),deltaY:ni(e.deltaY,`deltaY`,`scroll`)};case`drag`:if(!e.path||e.path.length<2)throw new ti(`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 ti(`Unknown action type: ${String(t)}`)}}}async function ii(e){if(!e.driver)return JSON.stringify({success:!1,error:Yr});let t=await e.driver.screenshot();return JSON.stringify(t?{success:!0,screenshot:t}:{success:!0,takeover:!0})}async function ai(e,t){if(!t.driver)return JSON.stringify({success:!1,error:Yr});let n;try{n=ri(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 oi(e={}){return Vr(`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.`,ei,async()=>ii(e))}function si(e={}){return Vr(`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.",$r,async t=>ai(t,e))}function ci(e={}){return[oi(e),si(e)]}const li=[{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 ui(e,t){let n=t?li.filter(e=>t.includes(e.toolName)):li,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(`
|
|
104
104
|
`)}const di=process.platform!==`win32`,fi=2e6,pi=q.object({command:q.string().describe(`The shell command to execute`),timeout:q.number().optional().describe(`Optional timeout in milliseconds (max 600000). Default is 120000 (2 minutes)`),workingDirectory:q.string().optional().describe(`Working directory for the command. Defaults to the current working directory`)});async function mi(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 hi(e,t,n,r,i){let{command:a,timeout:o=12e4,workingDirectory:s}=e,c=Math.min(o,6e5),l=s??t.cwd;if(l===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 mi(a,c,s??t.cwd,t);let u={command:n.command,args:n.commandArgs(a),cwd:l},p=t.sandboxClient?.wrapCommand?.(u,a)??u,h=!1,g=()=>{if(!h){h=!0;try{return p.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=d({maxBytes:fi}),n=d({maxBytes:fi}),a=!1,o=!1,s;try{s=m(p.command,[...p.args],{cwd:p.cwd,env:i===void 0?process.env:f(process.env,i),stdio:[`pipe`,`pipe`,`pipe`,...(p.inputDescriptors??[]).map(()=>`pipe`)],detached:di})}catch(t){let n=g(),r=t instanceof Error?t.message:String(t);e(JSON.stringify({success:!1,output:n??``,error:r}));return}(p.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 l=setTimeout(()=>{a=!0,ve(s,{processGroup:di}),u({success:!1,output:t.toString(),error:`Command timed out after ${c}ms`})},c);function u(t){o||(o=!0,clearTimeout(l),r?.removeEventListener(`abort`,h),e(JSON.stringify(t)))}function h(){ve(s,{processGroup:di}),u({success:!1,output:t.toString(),error:`Aborted`})}r?.addEventListener(`abort`,h,{once:!0}),s.on(`error`,e=>{s.pid===void 0&&g(),u({success:!1,output:``,error:e.message})}),s.on(`close`,e=>{let r=g();if(a){u({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;u({success:!0,output:r===void 0?l:`${l}\n${r}`,exitCode:s})})})}function gi(e,t){let n=p({executable:t.shellExecutable});return Vr(e,t.description??ui(n,t.availableTools),pi,async(e,r)=>hi(e,t,n,r?.signal,r?.shellTraceEnv))}function _i(e){return gi(`Shell`,e)}function vi(e){return gi(`Bash`,e)}function yi(e,t){return t!==void 0&&Cn(t,e)}function bi(e,t){return t===void 0?e:B(t,e)}function xi(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(!yi(e,t)){let t={success:!1,output:``,error:`Access denied: "${e}" is outside the working directory`};return JSON.stringify(t)}}var Si=class extends Error{};function Ci(e,t){return t===e||t.startsWith(e+V)}async function wi(e,t,n){let r=()=>new Si(`Access denied: "${e}" is outside the working directory`);if(t===void 0)throw r();let i=await G(t);if(process.platform===`darwin`){let t=await G(e);if(!Ci(i,t))throw r();try{return await ne(t,n|536870912,384)}catch(e){throw e.code===`ELOOP`?r():e}}let a=await ne(e,n,384);if(process.platform!==`linux`)return a;let o;try{o=await ie(`/proc/self/fd/${a.fd}`)}catch{throw await a.close(),new Si(`Access denied: "${e}" cannot be confirmed inside the working directory without /proc`)}if(Ci(i,o))return a;throw await a.close(),r()}function Ti(e,t){if(t===void 0)return{root:``,error:xi(e??``,void 0)};let n=e?B(t,e):t;return{root:n,error:xi(n,t)}}const Ei=2e3,Di=4*1024*1024;var Oi=class extends u{boundary;constructor(e){super(`Read ${e} exceeds its UTF-8 byte limit`,`Read`),this.boundary=e}},ki=class extends u{constructor(){super(`Read cancelled`,`Read`)}};const Ai=q.object({filePath:q.string().describe(`The absolute path to the file to read`),offset:q.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:q.number().optional().describe(`The number of lines to read (default: ${Ei}). Only provide if the file is too large to read at once`)});function ji(e){let t=Math.min(e.length,8192);for(let n=0;n<t;n++)if(e[n]===0)return!0;return!1}function Mi(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(`
|
|
105
105
|
`)}function Ni(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(`
|
|
@@ -98,7 +98,7 @@ n.exports={WebsocketFrameSend:class{constructor(e){this.frameData=e}createFrame(
|
|
|
98
98
|
`).slice(1).join(`
|
|
99
99
|
`);e.stack=n?`${n}\n${a}`:i.stack}t.exports.fetch=function(e,n=void 0){return M(e,n).catch(e=>{throw N?P(e,N):e&&typeof e==`object`&&Error.captureStackTrace(e,t.exports.fetch),e})},t.exports.Headers=qt().Headers,t.exports.Response=Jt().Response,t.exports.Request=Yt().Request,t.exports.FormData=He().FormData;let{setGlobalOrigin:F,getGlobalOrigin:I}=Fe();t.exports.setGlobalOrigin=F,t.exports.getGlobalOrigin=I;let{CacheStorage:L}=en(),{kConstruct:R}=Z();t.exports.caches=new L(R);let{deleteCookie:z,getCookies:ee,getSetCookies:B,setCookie:V,parseCookie:H}=an();t.exports.deleteCookie=z,t.exports.getCookies=ee,t.exports.getSetCookies=B,t.exports.setCookie=V,t.exports.parseCookie=H;let{parseMIMEType:U,serializeAMimeType:te}=Re();t.exports.parseMIMEType=U,t.exports.serializeAMimeType=te;let{CloseEvent:ne,ErrorEvent:W,MessageEvent:re}=on(),{WebSocket:ie,ping:G}=mn();t.exports.WebSocket=ie,t.exports.CloseEvent=ne,t.exports.ErrorEvent=W,t.exports.MessageEvent=re,t.exports.ping=G,t.exports.WebSocketStream=gn().WebSocketStream,t.exports.WebSocketError=hn().WebSocketError,t.exports.request=j(g.request),t.exports.stream=j(g.stream),t.exports.pipeline=j(g.pipeline),t.exports.connect=j(g.connect),t.exports.upgrade=j(g.upgrade),t.exports.MockClient=v,t.exports.MockCallHistory=y,t.exports.MockCallHistoryLog=b,t.exports.MockPool=S,t.exports.MockAgent=x,t.exports.SnapshotAgent=C,t.exports.mockErrors=w;let{EventSource:ae}=yn();t.exports.EventSource=ae;function oe(){globalThis.fetch=t.exports.fetch,globalThis.Headers=t.exports.Headers,globalThis.Response=t.exports.Response,globalThis.Request=t.exports.Request,globalThis.FormData=t.exports.FormData,globalThis.WebSocket=t.exports.WebSocket,globalThis.CloseEvent=t.exports.CloseEvent,globalThis.ErrorEvent=t.exports.ErrorEvent,globalThis.MessageEvent=t.exports.MessageEvent,globalThis.EventSource=t.exports.EventSource}t.exports.install=oe}))();function xn(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(!v(e))throw TypeError(`executionRoot must be an absolute path`);let t;try{t=re(e)}catch{throw TypeError(`executionRoot must name an existing accessible directory`)}if(!ae(t).isDirectory())throw TypeError(`executionRoot must name a directory`);try{L(t,z.R_OK|z.X_OK)}catch{throw TypeError(`executionRoot directory must be readable and traversable`)}return t}function Sn(e){let t=[],n=S(e);for(;;)try{return y(re(n),...t)}catch{let r=_(n);if(r===n)return S(e);t.unshift(g(n)),n=r}}function Cn(e,t){let n=Sn(e),r=Sn(t);return r===n||r.startsWith(n+C)}var wn=class extends Error{constructor(e){super(e),this.name=`OwnerOnlyModeError`}};function Tn(e=process.platform){return e===`win32`?`windows-acl`:`posix-mode`}function En(e,t){let n=x(e,t);if(n.startsWith(`..`)||v(n))throw new wn(`withinRoot ${e} is not an ancestor of ${t}, so this call cannot own the path between them.`);let r=n.split(C).filter(e=>e.length>0),i=[e],a=e;for(let e of r)a=y(a,e),i.push(a);return i}function Dn(e,t,n={}){if(Tn()!==`posix-mode`)return;let r=(n.readMode??(e=>ae(e).mode&4095))(e);if(r&63)throw new wn(`${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 On(e,t={}){let n=t.makeDirectory??((e,t)=>{U(e,{recursive:!0,mode:t})}),r=t.setMode??((e,t)=>R(e,t));n(e,448);let i=t.withinRoot===void 0?[e]:En(t.withinRoot,e);for(let e of i)Tn()===`posix-mode`&&r(e,448),Dn(e,`directory`,t)}function kn(e,t){On(_(e));let n=`${e}.${process.pid}.tmp`;G(n,{force:!0}),K(n,t,{encoding:`utf8`,mode:384,flag:`wx`});try{Dn(n,`file`),ie(n,e)}catch(e){try{se(n)}catch{}throw e}Dn(e,`file`)}function An(e){if(Tn()!==`posix-mode`)return;let t;try{t=ae(e).mode&4095}catch{return}t&63&&(R(e,384),Dn(e,`file`))}function jn(e){let t=de(e);return t===4?Mn(e.split(`.`).map(Number)):t!==6||Nn(e)}function Mn(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 Nn(e){let t=Fn(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?Mn([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 Pn(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 Fn(e){let t=Pn(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 In=3e4,Ln=5e6,Rn=new Set([301,302,303,307,308]),zn=new Set([`localhost`,`metadata`,`metadata.google.internal`,`metadata.goog`,`instance-data`,`instance-data.ec2.internal`]),Bn=async e=>(await ue(e,{all:!0,verbatim:!0})).map(e=>e.address);async function Vn(e,t={},n=Bn){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(zn.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 Hn(i,n);if(a===void 0||a.length===0)return{reason:`unresolvable`,url:r,message:`Destination "${i}" did not resolve.`};let o=a.find(jn);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 Hn(e,t){try{return await t(e)}catch{return}}async function Un(e,t,n){n.throwIfAborted();let r;try{return await Promise.race([t(e),new Promise((e,t)=>{r=()=>t(n.reason),n.addEventListener(`abort`,r,{once:!0}),n.aborted&&r()})])}finally{r&&n.removeEventListener(`abort`,r)}}async function Wn(e,t,n,r,i){let a=e.hostname.replace(/^\[|\]$/g,``).toLowerCase(),o,s=async e=>{let t=await Un(e,r.lookup??Bn,i);if(t.length===0||t.some(e=>de(e)===0))throw Error(`Invalid DNS answer`);return o=Object.freeze([...t]),o},c=await Vn(e,n,s);if(i.throwIfAborted(),c)return c;if(r.fetch){let n=await r.fetch(e.href,{...t,signal:i,redirect:`manual`});return{response:n,close:async()=>{n.body&&!n.body.locked&&await n.body.cancel().catch(()=>void 0)}}}if(o??=de(a)?[a]:await Hn(a,s),i.throwIfAborted(),!o||o.length===0)return{reason:`unresolvable`,url:e.href,message:`Destination did not resolve to valid IP addresses.`};let l=o.map(e=>({address:e,family:de(e)})),u=new bn.Agent({connections:1,pipelining:0,connect:{lookup:(e,t,n)=>{if(e.toLowerCase()!==a||i.aborted){n(Error(`Connection authority unavailable`),``,4);return}let r=typeof t==`number`?t:t.family,o=l.filter(e=>!r||e.family===r);if(o.length===0){n(Error(`No validated address family`),``,4);return}typeof t==`object`&&t.all?n(null,o):n(null,o[0].address,o[0].family)}}});if(typeof u.dispatch!=`function`||typeof u.destroy!=`function`)throw Error(`Pinned HTTP transport is unavailable in this runtime`);try{return{response:await(0,bn.fetch)(e.href,{...t,signal:i,redirect:`manual`,dispatcher:u}),close:async()=>{await u.destroy()}}}catch(e){throw await u.destroy(),e}}async function Gn(e,t={},n={},r={}){let i=t.maxResponseBytes??Ln,a=n.maxRedirects??5,o=AbortSignal.timeout(t.timeoutMs??In),s=t.signal?AbortSignal.any([o,t.signal]):o,c=new URL(e),l={...t.headers??{}};for(let e=0;;e+=1){let t=await Wn(c,{headers:l,signal:s,redirect:`manual`},n,r,s);if(!(`response`in t))return{ok:!1,rejection:t};try{let n=t.response;if(!Rn.has(n.status))return await Jn(n,c.href,i,s);let r=n.headers.get(`location`);if(r===null)return{ok:!1,rejection:{reason:`redirect_without_location`,url:c.href,message:`HTTP ${n.status} without a Location header.`}};if(e>=a)return{ok:!1,rejection:{reason:`redirect_limit`,url:c.href,message:`More than ${a} redirects.`}};let o=new URL(r,c);o.origin!==c.origin&&(l=qn(l)),c=o}finally{await t.close()}}}async function Kn(e,t,n={},r={}){let i=t.maxResponseBytes??Ln,a=AbortSignal.timeout(t.timeoutMs??In),o=t.signal?AbortSignal.any([a,t.signal]):a,s=new URL(e),c=await Wn(s,{method:`POST`,headers:{...t.headers??{}},body:t.body,signal:o,redirect:`manual`},n,r,o);if(!(`response`in c))return{ok:!1,rejection:c};try{let e=c.response;return e.status>=300&&e.status<400?(await e.body?.cancel().catch(()=>void 0),{ok:!1,rejection:{reason:`redirect_refused`,url:s.href,message:`HTTP ${e.status}: a POST is never redirected.`}}):await Jn(e,s.href,i,o)}finally{await c.close()}}function qn(e){let t={};for(let[n,r]of Object.entries(e))n.toLowerCase()===`user-agent`&&(t[n]=r);return t}async function Jn(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 Yn(e){if(typeof e!=`string`||e.trim().length===0||e.length>1024||[...e].some(e=>{let t=e.codePointAt(0);return t<32||t===127||t>=55296&&t<=57343}))throw Error(`E2B resumable worker reference is invalid.`);return e}function Xn(e){if(typeof e!=`object`||!e||typeof e.commands?.run!=`function`||typeof e.files?.read!=`function`||typeof e.files?.write!=`function`)throw Error(`E2B worker adapter is invalid.`)}function Zn(e){if(typeof e!=`object`||!e)throw Error(`E2B command exit code is missing.`);let t=e.exitCode===void 0?e.exit_code:e.exitCode;if(!Number.isSafeInteger(t)||e.exitCode!==void 0&&e.exit_code!==void 0&&e.exitCode!==e.exit_code)throw Error(`E2B command exit code is missing, invalid or inconsistent.`);if(e.stdout!==void 0&&typeof e.stdout!=`string`||e.stderr!==void 0&&typeof e.stderr!=`string`)throw Error(`E2B command output is invalid.`);return{stdout:e.stdout??``,stderr:e.stderr??``,exitCode:t}}var Qn=class{sandbox;generation=0;restoring=!1;connectSandbox;createSandboxFromSnapshot;constructor(e){Xn(e.sandbox),this.sandbox=e.sandbox,this.connectSandbox=e.connectSandbox,this.createSandboxFromSnapshot=e.createSandboxFromSnapshot}async run(e,t){return Zn(await this.withWorker(n=>n.commands.run(e,{background:!1,timeoutMs:t?.timeoutMs,cwd:t?.workingDirectory})))}async readFile(e){let t=await this.withWorker(t=>t.files.read(e));if(typeof t!=`string`&&!(t instanceof Uint8Array))throw Error(`E2B file response is invalid.`);return typeof t==`string`?t:Buffer.from(t).toString(`utf8`)}async writeFile(e,t){await this.withWorker(n=>n.files.write(e,t))}async snapshot(){return this.withWorker(async e=>{if(e.createSnapshot){let t=await e.createSnapshot();if(typeof t!=`object`||!t||t.snapshotId!==void 0&&t.id!==void 0&&t.snapshotId!==t.id)throw Error(`E2B snapshot identity is invalid or inconsistent.`);return Yn(t.snapshotId??t.id)}let t=Yn(e.sandboxId);if(!e.pause)throw Error(`E2B sandbox adapter does not expose pause().`);return await e.pause(),t})}async restore(e){if(this.restoring)throw Error(`E2B worker restore is already in progress.`);let t=this.sandbox;this.sandbox=void 0,this.generation++,this.restoring=!0;try{Yn(e);let n;if(this.createSandboxFromSnapshot)n=await this.createSandboxFromSnapshot(e);else if(this.connectSandbox)n=await this.connectSandbox(e);else if(t?.sandboxId===e&&t.connect)n=await t.connect();else throw Error(`E2B sandbox restore requires connectSandbox(snapshotId) or sandbox.connect().`);if(Xn(n),!this.createSandboxFromSnapshot&&n.sandboxId!==e)throw Error(`E2B restored worker identity does not match the requested reference.`);this.sandbox=n}finally{this.restoring=!1}}async withWorker(e){let t=this.sandbox,n=this.generation;if(t===void 0||this.restoring)throw Error(`E2B worker is not available; a successful restore is required.`);let r=await e(t);if(n!==this.generation||t!==this.sandbox)throw Error(`E2B worker changed during the operation; the previous worker result is refused.`);return r}};function $n(e){return e===void 0?`host`:`sandbox-${e.filesystem??`separate`}`}function er(e){return $n(e)===`sandbox-separate`}function tr(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 nr=/^[A-Za-z]:[\\/]/,rr=/'/g;async function ir(e,t,n={}){if(e.applyManifest)return e.applyManifest(t,n);tr(t);let r=_r(n.targetRoot??`/workspace`),i=[];for(let[a,o]of Object.entries(t.entries)){let t=ar(a),s=vr(r,t);i.push(await or(e,t,s,r,o,n))}return{entries:i}}function ar(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(`\\`)||nr.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 or(e,t,n,r,i,a){switch(i.type){case`file`:return await fr(e,n,r,i.content),sr(t,i.type);case`dir`:return await pr(e,n),sr(t,i.type);case`localFile`:return await cr(e,i.src,n,r,a),sr(t,i.type);case`localDir`:return await lr(e,i.src,n,a),sr(t,i.type);case`gitRepo`:return await dr(e,i,n),sr(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 br(i)}}function sr(e,t){return{path:e,type:t,status:`applied`}}async function cr(e,t,n,r,i){await fr(e,n,r,await k(hr(t,i.hostRoot),`utf8`))}async function lr(e,t,n,r){await ur(e,hr(t,r.hostRoot),n)}async function ur(e,t,n){await pr(e,n);let r=await A(t,{withFileTypes:!0});for(let i of r){let r=y(t,i.name),a=vr(n,i.name);if(i.isDirectory()){await ur(e,r,a);continue}if(i.isFile()){let t=await k(r,`utf8`);await e.writeFile(a,t)}}}async function dr(e,t,n){await mr(e,`git clone${t.shallow===!1?``:` --depth 1`}${t.ref?` --branch ${yr(t.ref)}`:``} ${yr(t.url)} ${yr(n)}`)}async function fr(e,t,n,r){let i=b.dirname(t);i!==n&&await pr(e,i),await e.writeFile(t,r)}async function pr(e,t){await mr(e,`mkdir -p ${yr(t)}`)}async function mr(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 hr(e,t){return v(e)?S(e):S(t??process.cwd(),e)}function gr(e){let t=e.length;for(;t>0&&e[t-1]===`/`;)--t;return e.slice(0,t)}function _r(e){let t=gr(e.replace(/\\/g,`/`));if(!t.startsWith(`/`))throw Error(`workspace manifest targetRoot must be an absolute sandbox path`);return t.length===0?`/`:t}function vr(e,t){let n=_r(e);return n===`/`?`/${t}`:`${n}/${t}`}function yr(e){return`'${e.replace(rr,`'\\''`)}'`}function br(e){throw Error(`unsupported workspace manifest entry: ${JSON.stringify(e)}`)}function xr(e){return[...new Set([`.claude/worktrees`,...e?.writableWorktreeContainers??[]])]}function Sr(e,t){let n=e.length;for(;n>0&&e[n-1]===`/`;)--n;return`${e.slice(0,n)}/${t}`}function Cr(e){return[...new Set([...i,...e?.protectedDirectoryNames??[],...n])]}function wr(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 Cr(t.pathProtection)){let i=Sr(t.root,r);e.exists(i)&&n.push(`--ro-bind`,i,i)}for(let r of xr(t.pathProtection)){let i=Sr(t.root,r);if(e.exists(i)){n.push(`--bind`,i,i);for(let t of e.listDirectory(i)){let r=Sr(i,`${t}/.git`);e.exists(r)&&n.push(`--ro-bind`,r,r)}}}for(let r of t.pathProtection?.protectedPaths??[])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 Tr(e){return e.replace(/[\\^$.*+?()[\]{}|"]/g,e=>`\\${e}`)}function Er(e){return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function Dr(e){let t=[e.root,...e.tempDirectories,...e.allowWrite].map(e=>`(subpath ${Er(e)})`).join(` `),r=Cr(e.pathProtection).map(t=>{let r=Sr(e.root,t);return n.includes(t)?`(literal ${Er(r)})`:`(subpath ${Er(r)})`}),i=xr(e.pathProtection).map(t=>`(subpath ${Er(Sr(e.root,t))})`),a=[`(literal ${Er(Sr(e.root,`.git`))})`,...xr(e.pathProtection).map(t=>`(regex #"^${Tr(Sr(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* ${r.join(` `)})`,`(allow file-write* ${i.join(` `)})`,`(deny file-write* ${a.join(` `)})`,...(e.pathProtection?.protectedPaths.length??0)>0?[`(deny file-write* ${e.pathProtection.protectedPaths.map(e=>`(subpath ${Er(e)})`).join(` `)})`]:[]];if(e.denyRead.length>0){let t=e.denyRead.map(e=>e.directory?`(subpath ${Er(e.path)})`:`(literal ${Er(e.path)})`);o.push(`(deny file-read* ${t.join(` `)})`)}return e.network||o.push(`(deny network*)`),o.join(`
|
|
100
100
|
`)}const Or={x64:{audit:3221225534,socket:41,ioUringSetup:425},arm64:{audit:3221225655,socket:198,ioUringSetup:425}};function kr(e,t,n,r){return[e,t,n,r]}function Ar(e=process.arch){let t=Or[e];if(t===void 0)return;let n=e=>327680|e,r=[kr(32,0,0,4),kr(21,1,0,t.audit),kr(6,0,0,n(1)),kr(32,0,0,0),kr(69,0,1,1073741824),kr(6,0,0,n(1)),kr(21,0,1,t.ioUringSetup),kr(6,0,0,n(1)),kr(21,0,3,t.socket),kr(32,0,0,16),kr(21,0,1,1),kr(6,0,0,n(97)),kr(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 jr=Object.freeze({enabled:!1,autoAllowBashIfSandboxed:!0,excludedCommands:[],allowWrite:[],denyRead:[],network:!1}),Mr=`/usr/bin/sandbox-exec`;function Nr(e,t){let n=T(e,[...t],{timeout:5e3,encoding:`utf8`});if(n.error!==void 0)return{ok:!1,detail:n.error.message};let r=(n.stderr??``).trim().split(`
|
|
101
|
-
`)[0];return n.status===0?{ok:!0}:{ok:!1,...r?{detail:r}:{}}}function Pr(e={}){let t=e.platform??process.platform,n=e.probe??Nr;if(t===`linux`){if(Ar(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`,`--proc`,`/proc`,`--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(Mr,[`-p`,`(version 1)(allow default)`,`/usr/bin/true`]);return e.ok?{backend:`seatbelt`,executable:Mr,missing:[]}:{backend:`seatbelt`,missing:[`sandbox-exec cannot run${e.detail?`: ${e.detail}`:``}`]}}return{missing:[],unsupportedPlatform:t}}function Fr(e){try{return re(e)}catch{return e}}function Ir(e){try{return ae(e).isDirectory()}catch{return!1}}function Lr(e){let t=H(e);if(!t.isSymbolicLink()&&(R(e,t.mode|448),t.isDirectory()))for(let t of ne(e))Lr(`${e}/${t}`)}function Rr(e){try{return H(e).isSymbolicLink()}catch{return!1}}function zr(e){return e.trim().split(/\s+/)[0]}var Br=class{filesystem=`shared`;root;pathProtection;projectStateDirectory;userQuarantineDirectory;availability;homeDirectory;current;inFlight=0;baseline=[];unresolved=new Map;watchers=new Set;constructor(e){if(!/^[a-zA-Z0-9._-]+$/.test(e.projectStateDirectory)||[`.`,`..`].includes(e.projectStateDirectory))throw Error(`A safe project state directory is required`);if(!v(e.userQuarantineDirectory))throw Error(`An absolute quarantine directory is required`);this.projectStateDirectory=e.projectStateDirectory,this.userQuarantineDirectory=e.userQuarantineDirectory,this.pathProtection=Object.freeze({protectedDirectoryNames:Object.freeze([...new Set([e.projectStateDirectory,...e.pathProtection?.protectedDirectoryNames??[]])]),protectedPaths:Object.freeze([...e.pathProtection?.protectedPaths??[]]),writableWorktreeContainers:Object.freeze([...e.pathProtection?.writableWorktreeContainers??[]])}),this.root=Fr(e.root),this.availability=e.availability,this.homeDirectory=e.homeDirectory??ce(),this.current={...jr,...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(c(e).length!==1)return!0;let t=zr(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`,Dr(n),e.command,...e.args],cwd:e.cwd};let i=n.network?void 0:Ar();this.protectedEntryStates().some(e=>e.path===`${this.root}/${this.projectStateDirectory}`&&e.kind===`symlink`)||U(`${this.root}/${this.projectStateDirectory}`,{recursive:!0});let a=wr({policy:n,exists:e=>V(e)&&!Rr(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 Cr(this.pathProtection).map(e=>{let t=`${this.root}/${e}`;try{return H(t).isSymbolicLink()?{path:t,kind:`symlink`,target:W(t)}:{path:t,kind:`present`}}catch{return{path:t,kind:`missing`}}})}resolvesOutsideWritableWorkspace(e){let t;try{t=re(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()}-${h()}`,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}/${this.projectStateDirectory}`;return e.some(e=>e.path===t&&e.kind===`present`)?`${t}/sandbox-quarantine`:this.userQuarantineDirectory}setAside(e,t){let n=`${t}/${g(e)}`;U(t,{recursive:!0});try{ie(e,n)}catch(t){if(this.inFlight>0)throw t;Lr(e),t.code===`EXDEV`?(ee(e,n,{recursive:!0,verbatimSymlinks:!0}),G(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 Fr(v(t)?t:S(this.root,t))},t=[...new Set([le(),`/tmp`].filter(V).map(Fr))];return{root:this.root,pathProtection:this.pathProtection,tempDirectories:t,allowWrite:this.current.allowWrite.map(e),denyRead:this.current.denyRead.map(t=>{let n=e(t);return{path:n,directory:Ir(n)}}),network:this.current.network}}run(e,t={}){let n=p(),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=w(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 K(e,t,`utf8`),Promise.resolve()}};function Vr(e,t,n,i,a={}){return new s({name:e,description:t,parameters:r(n),...a.deferLoading!==void 0&&{deferLoading:a.deferLoading}},async(e,t)=>{let r=n.safeParse(e);if(!r.success)throw new l(`Zod validation failed: ${r.error}`);let a=await i(r.data,t);return typeof a==`string`?a:JSON.stringify(a)})}const Hr={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 Ur(){for(let[e,t]of Object.entries(Hr))a(e,t)}Ur();const Wr=1e3,Gr=q.object({activeFiles:q.array(q.string()).optional().describe(`Repo-relative files currently in focus; the map is ranked toward what they reference.`),mentionedIdentifiers:q.array(q.string()).optional().describe(`Symbol names to bias the map toward (e.g. identifiers named in the task).`),tokenBudget:q.number().int().positive().optional().describe(`Maximum tokens for the returned map (default ${Wr}).`)});function Kr(e){return e.map(e=>`${e.file}:${e.line} ${e.kind} ${e.name}`).join(`
|
|
101
|
+
`)[0];return n.status===0?{ok:!0}:{ok:!1,...r?{detail:r}:{}}}function Pr(e={}){let t=e.platform??process.platform,n=e.probe??Nr;if(t===`linux`){if(Ar(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`,`--proc`,`/proc`,`--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(Mr,[`-p`,`(version 1)(allow default)`,`/usr/bin/true`]);return e.ok?{backend:`seatbelt`,executable:Mr,missing:[]}:{backend:`seatbelt`,missing:[`sandbox-exec cannot run${e.detail?`: ${e.detail}`:``}`]}}return{missing:[],unsupportedPlatform:t}}function Fr(e){try{return re(e)}catch{return e}}function Ir(e){try{return ae(e).isDirectory()}catch{return!1}}function Lr(e){let t=H(e);if(!t.isSymbolicLink()&&(R(e,t.mode|448),t.isDirectory()))for(let t of ne(e))Lr(`${e}/${t}`)}function Rr(e){try{return H(e).isSymbolicLink()}catch{return!1}}function zr(e){return e.trim().split(/\s+/)[0]}var Br=class{filesystem=`shared`;root;pathProtection;projectStateDirectory;userQuarantineDirectory;availability;homeDirectory;hiddenPaths;current;inFlight=0;baseline=[];unresolved=new Map;watchers=new Set;constructor(e){if(!/^[a-zA-Z0-9._-]+$/.test(e.projectStateDirectory)||[`.`,`..`].includes(e.projectStateDirectory))throw Error(`A safe project state directory is required`);if(!v(e.userQuarantineDirectory))throw Error(`An absolute quarantine directory is required`);this.projectStateDirectory=e.projectStateDirectory,this.userQuarantineDirectory=e.userQuarantineDirectory,this.pathProtection=Object.freeze({protectedDirectoryNames:Object.freeze([...new Set([e.projectStateDirectory,...e.pathProtection?.protectedDirectoryNames??[]])]),protectedPaths:Object.freeze([...e.pathProtection?.protectedPaths??[]]),writableWorktreeContainers:Object.freeze([...e.pathProtection?.writableWorktreeContainers??[]])}),this.root=Fr(e.root),this.availability=e.availability,this.homeDirectory=e.homeDirectory??ce(),this.hiddenPaths=Object.freeze([...e.hiddenPaths??[]]),this.current={...jr,...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(c(e).length!==1)return!0;let t=zr(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`,Dr(n),e.command,...e.args],cwd:e.cwd};let i=n.network?void 0:Ar();this.protectedEntryStates().some(e=>e.path===`${this.root}/${this.projectStateDirectory}`&&e.kind===`symlink`)||U(`${this.root}/${this.projectStateDirectory}`,{recursive:!0});let a=wr({policy:n,exists:e=>V(e)&&!Rr(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 Cr(this.pathProtection).map(e=>{let t=`${this.root}/${e}`;try{return H(t).isSymbolicLink()?{path:t,kind:`symlink`,target:W(t)}:{path:t,kind:`present`}}catch{return{path:t,kind:`missing`}}})}resolvesOutsideWritableWorkspace(e){let t;try{t=re(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()}-${h()}`,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}/${this.projectStateDirectory}`;return e.some(e=>e.path===t&&e.kind===`present`)?`${t}/sandbox-quarantine`:this.userQuarantineDirectory}setAside(e,t){let n=`${t}/${g(e)}`;U(t,{recursive:!0});try{ie(e,n)}catch(t){if(this.inFlight>0)throw t;Lr(e),t.code===`EXDEV`?(ee(e,n,{recursive:!0,verbatimSymlinks:!0}),G(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 Fr(v(t)?t:S(this.root,t))},t=[...new Set([le(),`/tmp`].filter(V).map(Fr))];return{root:this.root,pathProtection:this.pathProtection,tempDirectories:t,allowWrite:this.current.allowWrite.map(e),denyRead:[...new Set([...this.hiddenPaths,...this.current.denyRead])].map(t=>{let n=e(t);return{path:n,directory:Ir(n)}}),network:this.current.network}}run(e,t={}){let n=p(),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=w(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 K(e,t,`utf8`),Promise.resolve()}};function Vr(e,t,n,i,a={}){return new s({name:e,description:t,parameters:r(n),...a.deferLoading!==void 0&&{deferLoading:a.deferLoading}},async(e,t)=>{let r=n.safeParse(e);if(!r.success)throw new l(`Zod validation failed: ${r.error}`);let a=await i(r.data,t);return typeof a==`string`?a:JSON.stringify(a)})}const Hr={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 Ur(){for(let[e,t]of Object.entries(Hr))a(e,t)}Ur();const Wr=1e3,Gr=q.object({activeFiles:q.array(q.string()).optional().describe(`Repo-relative files currently in focus; the map is ranked toward what they reference.`),mentionedIdentifiers:q.array(q.string()).optional().describe(`Symbol names to bias the map toward (e.g. identifiers named in the task).`),tokenBudget:q.number().int().positive().optional().describe(`Maximum tokens for the returned map (default ${Wr}).`)});function Kr(e){return e.map(e=>`${e.file}:${e.line} ${e.kind} ${e.name}`).join(`
|
|
102
102
|
`)}async function qr(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??Wr});return n.symbols.length===0?`No relevant symbols found within the token budget.`:`Most relevant symbols (~${n.totalTokens} tokens):\n${Kr(n.symbols)}`}function Jr(e={}){return Vr(`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.`,Gr,async t=>qr(t,e))}const Yr=`Computer use is not available in this session (no driver injected).`,Xr=q.enum([`left`,`right`,`middle`]),Zr=q.object({x:q.number(),y:q.number()}),Qr=q.object({type:q.enum([`click`,`double_click`,`type`,`keypress`,`scroll`,`drag`,`wait`,`takeover`]).describe(`Which action to perform.`),x:q.number().optional().describe(`X coordinate (click/double_click/scroll).`),y:q.number().optional().describe(`Y coordinate (click/double_click/scroll).`),button:Xr.optional().describe(`Mouse button (click/double_click/drag).`),text:q.string().optional().describe(`Text to type (type).`),keys:q.array(q.string()).optional().describe(`Keys to press as a chord (keypress).`),deltaX:q.number().optional().describe(`Horizontal wheel delta (scroll).`),deltaY:q.number().optional().describe(`Vertical wheel delta (scroll).`),path:q.array(Zr).optional().describe(`Points to drag through (drag).`),ms:q.number().optional().describe(`Milliseconds to wait (wait).`),reason:q.string().optional().describe(`Human-readable reason surfaced to the user (takeover).`)}),$r=q.object({action:Qr.describe(`The single mutating action to perform.`)}),ei=q.object({});var ti=class extends Error{};function ni(e,t,n){if(typeof e!=`number`)throw new ti(`Action '${n}' requires numeric '${t}'.`);return e}function ri(e){let t=e.button;switch(e.type){case`click`:return{type:`click`,x:ni(e.x,`x`,`click`),y:ni(e.y,`y`,`click`),...t?{button:t}:{}};case`double_click`:return{type:`double_click`,x:ni(e.x,`x`,`double_click`),y:ni(e.y,`y`,`double_click`),...t?{button:t}:{}};case`type`:if(typeof e.text!=`string`)throw new ti(`Action 'type' requires 'text'.`);return{type:`type`,text:e.text};case`keypress`:if(!e.keys||e.keys.length===0)throw new ti(`Action 'keypress' requires non-empty 'keys'.`);return{type:`keypress`,keys:e.keys};case`scroll`:return{type:`scroll`,x:ni(e.x,`x`,`scroll`),y:ni(e.y,`y`,`scroll`),deltaX:ni(e.deltaX,`deltaX`,`scroll`),deltaY:ni(e.deltaY,`deltaY`,`scroll`)};case`drag`:if(!e.path||e.path.length<2)throw new ti(`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 ti(`Unknown action type: ${String(t)}`)}}}async function ii(e){if(!e.driver)return JSON.stringify({success:!1,error:Yr});let t=await e.driver.screenshot();return JSON.stringify(t?{success:!0,screenshot:t}:{success:!0,takeover:!0})}async function ai(e,t){if(!t.driver)return JSON.stringify({success:!1,error:Yr});let n;try{n=ri(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 oi(e={}){return Vr(`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.`,ei,async()=>ii(e))}function si(e={}){return Vr(`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.",$r,async t=>ai(t,e))}function ci(e={}){return[oi(e),si(e)]}const li=[{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 ui(e,t){let n=t?li.filter(e=>t.includes(e.toolName)):li,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(`
|
|
103
103
|
`)}const di=process.platform!==`win32`,fi=2e6,pi=q.object({command:q.string().describe(`The shell command to execute`),timeout:q.number().optional().describe(`Optional timeout in milliseconds (max 600000). Default is 120000 (2 minutes)`),workingDirectory:q.string().optional().describe(`Working directory for the command. Defaults to the current working directory`)});async function mi(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 hi(e,t,n,r,i){let{command:a,timeout:o=12e4,workingDirectory:s}=e,c=Math.min(o,6e5),l=s??t.cwd;if(l===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 mi(a,c,s??t.cwd,t);let u={command:n.command,args:n.commandArgs(a),cwd:l},p=t.sandboxClient?.wrapCommand?.(u,a)??u,m=!1,h=()=>{if(!m){m=!0;try{return p.afterExit?.()}catch(e){return`[sandbox] clean-up failed: ${e instanceof Error?e.message:String(e)}`}}};return r?.aborted?(h(),JSON.stringify({success:!1,output:``,error:`Aborted before start`})):new Promise(e=>{let t=d({maxBytes:fi}),n=d({maxBytes:fi}),a=!1,o=!1,s;try{s=w(p.command,[...p.args],{cwd:p.cwd,env:i===void 0?process.env:f(process.env,i),stdio:[`pipe`,`pipe`,`pipe`,...(p.inputDescriptors??[]).map(()=>`pipe`)],detached:di})}catch(t){let n=h(),r=t instanceof Error?t.message:String(t);e(JSON.stringify({success:!1,output:n??``,error:r}));return}(p.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 l=setTimeout(()=>{a=!0,ve(s,{processGroup:di}),u({success:!1,output:t.toString(),error:`Command timed out after ${c}ms`})},c);function u(t){o||(o=!0,clearTimeout(l),r?.removeEventListener(`abort`,m),e(JSON.stringify(t)))}function m(){ve(s,{processGroup:di}),u({success:!1,output:t.toString(),error:`Aborted`})}r?.addEventListener(`abort`,m,{once:!0}),s.on(`error`,e=>{s.pid===void 0&&h(),u({success:!1,output:``,error:e.message})}),s.on(`close`,e=>{let r=h();if(a){u({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;u({success:!0,output:r===void 0?l:`${l}\n${r}`,exitCode:s})})})}function gi(e,t){let n=p({executable:t.shellExecutable});return Vr(e,t.description??ui(n,t.availableTools),pi,async(e,r)=>hi(e,t,n,r?.signal,r?.shellTraceEnv))}function _i(e){return gi(`Shell`,e)}function vi(e){return gi(`Bash`,e)}function yi(e,t){return t!==void 0&&Cn(t,e)}function bi(e,t){return t===void 0?e:S(t,e)}function xi(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(!yi(e,t)){let t={success:!1,output:``,error:`Access denied: "${e}" is outside the working directory`};return JSON.stringify(t)}}var Si=class extends Error{};function Ci(e,t){return t===e||t.startsWith(e+C)}async function wi(e,t,n){let r=()=>new Si(`Access denied: "${e}" is outside the working directory`);if(t===void 0)throw r();let i=await M(t);if(process.platform===`darwin`){let t=await M(e);if(!Ci(i,t))throw r();try{return await O(t,n|536870912,384)}catch(e){throw e.code===`ELOOP`?r():e}}let a=await O(e,n,384);if(process.platform!==`linux`)return a;let o;try{o=await j(`/proc/self/fd/${a.fd}`)}catch{throw await a.close(),new Si(`Access denied: "${e}" cannot be confirmed inside the working directory without /proc`)}if(Ci(i,o))return a;throw await a.close(),r()}function Ti(e,t){if(t===void 0)return{root:``,error:xi(e??``,void 0)};let n=e?S(t,e):t;return{root:n,error:xi(n,t)}}const Ei=2e3,Di=4*1024*1024;var Oi=class extends u{boundary;constructor(e){super(`Read ${e} exceeds its UTF-8 byte limit`,`Read`),this.boundary=e}},ki=class extends u{constructor(){super(`Read cancelled`,`Read`)}};const Ai=q.object({filePath:q.string().describe(`The absolute path to the file to read`),offset:q.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:q.number().optional().describe(`The number of lines to read (default: ${Ei}). Only provide if the file is too large to read at once`)});function ji(e){let t=Math.min(e.length,8192);for(let n=0;n<t;n++)if(e[n]===0)return!0;return!1}function Mi(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(`
|
|
104
104
|
`)}function Ni(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(`
|
|
@@ -162,4 +162,4 @@ readline.createInterface({ input: process.stdin }).on('line', line => {
|
|
|
162
162
|
`):`(no matches)`};return JSON.stringify(b)}function da(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 fa(e){return Vr(`Grep`,e.description??da(e.shellToolName??`Shell`),sa,async t=>ua(t,e))}const pa=3e4,ma=5e6,ha=q.object({url:q.string().describe(`The URL to fetch`),headers:q.record(q.string()).optional().describe(`Optional HTTP headers as key-value pairs`)});function ga(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 _a(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 va={"&":`&`,"<":`<`,">":`>`,""":`"`,"'":`'`," ":` `},ya=/&(?:amp|lt|gt|quot|nbsp|#39);/g;function ba(e){return _a(ga(ga(e,`script`),`style`)).replace(ya,e=>va[e]).replace(/\s+/g,` `).trim()}function xa(e){if(!(e instanceof Error))return String(e);if(e.name===`AbortError`)return`Request timed out after ${pa/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 Sa(e,t,n,r){let{url:i,headers:a}=e;try{new URL(i)}catch{let e={success:!1,output:``,error:`Invalid URL: "${i}". Fix the URL format before retrying.`};return JSON.stringify(e)}try{let e=await Gn(i,{headers:{...n===void 0?{}:{"User-Agent":n},...a??{}},signal:r,timeoutMs:pa,maxResponseBytes:ma},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 ${ma} 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 o=e.headers.get(`content-type`)??``,s=new TextDecoder().decode(e.body);return o.includes(`html`)&&(s=ba(s)),JSON.stringify({success:!0,output:s})}catch(e){let t={success:!1,output:``,error:xa(e)};return JSON.stringify(t)}}function Ca(e={}){let t=e.egress??{};return Vr(`WebFetch`,e.description??`Fetch a URL and return its content as text. HTML pages are converted to plain text.`,ha,async(n,r)=>Sa(n,t,e.userAgent,r?.signal))}const wa=Ca();function Ta(){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 Ea=q.object({query:q.string().describe(`The search query`),limit:q.number().optional().describe(`Maximum number of results to return (default: 10)`)});async function Da(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 Oa(e={}){let t=e.provider??Ta();return Vr(`WebSearch`,e.description??`Search the web and return results with title, URL, and snippet.`,Ea,async(e,n)=>Da(e,t,n?.signal))}const ka=Oa(),Aa=q.object({question:q.string().min(1).describe(`The complete question to ask the user.`),header:q.string().optional().describe(`Very short topic label for the question (e.g. "Auth method").`),options:q.array(q.union([q.string().min(1).describe(`Display text of this choice.`),q.object({label:q.string().min(1).describe(`Display text of this choice.`),description:q.string().optional().describe(`What choosing this option means.`)})])).optional().describe(`Predefined choices (strings or {label, description}). Omit for pure free text.`),multiSelect:q.boolean().optional().describe(`Allow selecting multiple options (default: single select).`),allowFreeText:q.boolean().optional().describe(`Allow a typed custom answer besides the options (default: true).`)}),ja=q.object({questions:q.array(Aa).min(1).max(4).describe(`Questions to ask the user (1-4), rendered one at a time.`)}),Ma=[`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(`
|
|
163
163
|
`);function Na(e){let t=(e.options??[]).map(e=>typeof e==`string`?{label:e}:e),n=e.multiSelect===!0&&t.length>1;return{id:`ask_${h()}`,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 Pa(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(Na(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 Fa(e={}){return Vr(`AskUserQuestion`,e.description??Ma,ja,async(e,t)=>{let n=e,r=t?.ask,i=r?await Pa(n,r):{unavailable:!0,reason:`no interactive user attached`},a={success:!0,output:JSON.stringify(i)};return JSON.stringify(a)})}Fa();const Ia=1/0;function La(e,t){e.description!==void 0&&t.push(e.description);for(let[n,r]of Object.entries(e.properties??{}))t.push(n),La(r,t);e.items!==void 0&&La(e.items,t);for(let n of e.anyOf??[])La(n,t)}function Ra(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 La(e.parameters,r),r.some(e=>e.toLowerCase().includes(t))?3:Ia}function za(e,t,n){let r=t.trim().toLowerCase();return r.length===0?[]:e.map(e=>({schema:e,rank:Ra(e,r)})).filter(e=>e.rank!==Ia).sort((e,t)=>e.rank-t.rank||(e.schema.name<t.schema.name?-1:1)).slice(0,n).map(e=>e.schema)}const Ba=o,Va=q.object({query:q.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:q.array(q.string().min(1)).optional().describe(`Exact tool names to load, skipping the search. An unknown name is an error naming it.`),limit:q.number().int().positive().optional().describe(`Maximum tools to load from a query match (default 5).`)}),Ha=[`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(`
|
|
164
164
|
`);function Ua(e){let t=e?.deferredTools;if(!t)throw Error(`${Ba} 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 Wa(e,t){if(e.names!==void 0)return t.loadDeferredTools(e.names);if(e.query===void 0)throw Error(`${Ba} needs either "query" to search for tools or "names" to load exact ones.`);let n=za(t.listDeferredTools(),e.query,e.limit??5);return t.loadDeferredTools(n.map(e=>e.name))}function Ga(e={}){return Vr(Ba,e.description??Ha,Va,async(e,t)=>{let n={loaded:Wa(e,Ua(t)).map(({name:e,description:t})=>({name:e,description:t})),unavailableSources:[]},r={success:!0,output:JSON.stringify(n)};return JSON.stringify(r)})}Ga();export{On as A,Pr as C,xn as D,ka as E,Gn as F,Tn as I,ve as L,An as M,Cn as N,Vn as O,Kn as P,pe as R,$n as S,wa as T,Ga as _,Oi as a,Hi as b,Fa as c,Ji as d,$i as f,_i as g,Jr as h,Br as i,kn as j,Wn as k,vi as l,Fi as m,Qn as n,ki as o,fa as p,la as r,ir as s,jr as t,ci as u,Ca as v,er as w,Vr as x,Oa as y};
|
|
165
|
-
//# sourceMappingURL=node-
|
|
165
|
+
//# sourceMappingURL=node-C1z7m4gZ.js.map
|