@robota-sdk/agent-cli 3.0.0 → 3.0.2
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 +11 -0
- package/dist/node/bin.js +5 -5
- package/dist/node/{cli-core-Bz_5Fzj0.js → cli-core-Cg4H6FH2.js} +315 -315
- package/dist/node/desktop-host.js +1 -1
- package/dist/node/headless.js +1 -1
- package/dist/node/host.js +1 -1
- package/dist/node/index.js +1 -1
- package/dist/node/node-DdB-oeq6.js.map +1 -1
- package/dist/node/{node-oHeP4vDn.js → node-DwQY2ITL.js} +3 -3
- package/dist/node/node-DwQY2ITL.js.map +1 -0
- package/dist/node/{node-BsDZQcvi.js → node-TUI6iwZA.js} +2 -2
- package/dist/node/{product-host-BPPyJk9w.js → product-host-BsT1Xq4C.js} +358 -358
- package/dist/node/product-host-BsT1Xq4C.js.map +1 -0
- package/dist/node/{src-B9UMvThT-B-MlnUJH.js → src-B9UMvThT-B4p8y1ba.js} +1 -1
- package/dist/node/{src-B9UMvThT-Cvs0M0_E.js → src-B9UMvThT-DInbihOf.js} +2 -2
- package/dist/node/{src-B9UMvThT-Cvs0M0_E.js.map → src-B9UMvThT-DInbihOf.js.map} +1 -1
- package/dist/node/{src-BzaNFPZx-DAgH-EaI.js → src-BzaNFPZx-E-faT9I-.js} +2 -2
- package/dist/node/{src-BzaNFPZx-DAgH-EaI.js.map → src-BzaNFPZx-E-faT9I-.js.map} +1 -1
- package/dist/node/{src-BzaNFPZx-CIKPBZac.js → src-BzaNFPZx-PaYEuPZc.js} +1 -1
- package/dist/node/{src-DwAfU-9z-DOErKivb.js → src-DwAfU-9z-DLr4gyAc.js} +2 -2
- package/dist/node/{src-DwAfU-9z-DOErKivb.js.map → src-DwAfU-9z-DLr4gyAc.js.map} +1 -1
- package/dist/node/{src-DwAfU-9z-CalH1ynp.js → src-DwAfU-9z-YAG_fVg1.js} +1 -1
- package/dist/node/{src-UPsd6jNY-CgN4wopU.js → src-UPsd6jNY-BT0Qq67D.js} +2 -2
- package/dist/node/{src-UPsd6jNY-CgN4wopU.js.map → src-UPsd6jNY-BT0Qq67D.js.map} +1 -1
- package/dist/node/{src-UPsd6jNY-CUahgEdL.js → src-UPsd6jNY-CPmh5JTO.js} +1 -1
- package/package.json +38 -38
- package/dist/node/node-oHeP4vDn.js.map +0 -1
- package/dist/node/product-host-BPPyJk9w.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Bt as e,N as t,U as n,b as r,jt as i,p as a,rt as o}from"./node-Ct446qHg.js";import{_ as s,l as c,r as l,s as u,w as d}from"./bounded-output-BdWv9SX3-28em7iHq.js";import{l as f,s as p}from"./node-DdB-oeq6.js";import{randomBytes as m,randomUUID as h}from"node:crypto";import{basename as g,dirname as _,isAbsolute as v,join as y,posix as ee,relative as te,resolve as b,sep as ne}from"node:path";import{spawn as re,spawnSync as ie}from"node:child_process";import{open as ae,readFile as oe,readdir as se,readlink as ce,realpath as le,stat as x}from"node:fs/promises";import{chmodSync as ue,closeSync as de,constants as S,cpSync as fe,createReadStream as pe,existsSync as me,fstatSync as he,fsyncSync as ge,lstatSync as _e,mkdirSync as ve,readFileSync as ye,readSync as be,readdirSync as xe,readlinkSync as Se,realpathSync as Ce,renameSync as we,rmSync as Te,statSync as Ee,symlinkSync as De,writeFileSync as Oe}from"node:fs";import{homedir as ke,tmpdir as Ae}from"node:os";import{z as C}from"zod";import{EventEmitter as je}from"node:events";import{Worker as Me}from"node:worker_threads";import*as w from"koffi";import Ne from"fast-glob";import Pe from"p-limit";const Fe=2e3,Ie=process.platform===`win32`;function Le(e){return e.exitCode!==null||e.signalCode!==null}function Re(e,t,n){if(n&&!Ie&&typeof e.pid==`number`)try{process.kill(-e.pid,t);return}catch{}try{e.kill(t)}catch{}}function ze(e,t){if(Ie&&typeof e.pid==`number`){ie(`taskkill`,[`/pid`,String(e.pid),`/T`,`/F`],{stdio:`ignore`});return}Re(e,`SIGKILL`,t)}async function Be(e,t={}){let n=t.graceMs??2e3,r=t.signal??`SIGTERM`,i=t.processGroup??!1;if(!Le(e)){if(typeof e.pid!=`number`)throw Error(`[agent-process] killProcessTree called with an unspawned child (no pid)`);if(t.preKill){try{await t.preKill()}catch{}if(Le(e))return}return new Promise(t=>{let a,o=()=>{a&&clearTimeout(a),t()};if(e.once(`exit`,o),Le(e)){e.removeListener(`exit`,o),t();return}Re(e,r,i),a=setTimeout(()=>{Le(e)||ze(e,i)},n),a.unref?.()})}}const Ve={INVALID_PATH:`The requested root-relative file operation is invalid.`,UNSAFE_ENTRY:`The requested entry cannot be opened without following an unsafe object.`,UNSUPPORTED_BACKEND:`This host cannot provide stable root-relative file operations.`,AUTHORITY_CLOSED:`The stable rooted file authority is closed.`,ROOT_CHANGED:`The retained root identity changed during the operation.`,FILE_CHANGED:`The file identity or contents changed during the bounded read.`,OVER_BUDGET:`The file exceeds the supplied byte budget.`,HOST_IO:`The host could not complete the stable root-relative file operation.`};var T=class extends Error{code;context;constructor(e,t){super(Ve[e]),this.name=`StableFileAuthorityError`,this.code=e,this.context=Object.freeze({...t})}};function E(e,t,n={}){return new T(e,{operation:t,...n})}const He=16777216,Ue=524288;function D(e){return{device:e.dev,inode:e.ino,mode:e.mode}}function We(e){return{...D(e),size:e.size,modified:e.mtimeNs,changed:e.ctimeNs}}function Ge(e,t){return e.device===t.device&&e.inode===t.inode&&e.mode===t.mode}function O(e,t){return e.device===t.device&&e.inode===t.inode}function Ke(e,t){return Ge(e,t)&&e.size===t.size&&e.modified===t.modified&&e.changed===t.changed}function k(e){for(let[t,n]of Object.entries(w.os.errno))if(n===e)return t;return`ERRNO_${e}`}function A(e){let t=S.O_CLOEXEC??(process.platform===`darwin`?He:Ue);return S.O_RDONLY|S.O_NOFOLLOW|S.O_NONBLOCK|t|(e?S.O_DIRECTORY:0)}function j(e,t){try{return he(e,{bigint:!0})}catch(e){let n=qe(typeof e==`object`?e:null);throw E(`HOST_IO`,t,n===void 0?{}:{hostCode:n})}}function qe(e){if(!(e===null||!(`code`in e)))return typeof e.code==`string`?e.code:void 0}let Je;const Ye=[];function M(){if(!Je){let e=w.load(process.platform===`darwin`?`/usr/lib/libSystem.B.dylib`:`libc.so.6`);Ye.push(e);let t=process.platform===`darwin`?e.func(`int renameatx_np(int olddirfd, const char *oldpath, int newdirfd, const char *newpath, unsigned int flags)`):e.func(`int renameat2(int olddirfd, const char *oldpath, int newdirfd, const char *newpath, unsigned int flags)`),n=e.func(`int openat(int fd, const char *path, int flags, ...)`);Je={library:e,open:e.func(`int open(const char *path, int flags)`),openAt:(e,t,r,i)=>n(e,t,r,`unsigned int`,i),mkdirAt:e.func(`int mkdirat(int fd, const char *path, unsigned int mode)`),noReplaceAt:(e,n,r,i)=>t(e,n,r,i,process.platform===`darwin`?4:1),exchangeAt:(e,n,r,i)=>t(e,n,r,i,2),unlinkAt:e.func(`int unlinkat(int fd, const char *path, int flags)`),fchmod:e.func(`int fchmod(int fd, unsigned int mode)`)}}return Je}var Xe=class{openAt;rootIdentity;rootDescriptor;constructor(e){try{let{open:t,openAt:n}=M();this.openAt=n;let r=t(e,A(!0));r<0&&this.throwOpenFailure(w.errno(),`open-root`),this.rootDescriptor=r;let i=j(r,`inspect-root`);if(!i.isDirectory())throw E(`UNSAFE_ENTRY`,`open-root`);this.rootIdentity=D(i)}catch(e){throw this.rootDescriptor!==void 0&&(this.closeDescriptor(this.rootDescriptor),this.rootDescriptor=void 0),e instanceof T?e:E(`UNSUPPORTED_BACKEND`,`load-posix-backend`)}}readBytes(e,t,n){let r=this.rootDescriptor;if(r===void 0)throw E(`AUTHORITY_CLOSED`,`read`);this.assertRootIdentity(r);let i=r,a=!1,o;try{for(let t=0;t<e.length;t+=1){let r=t===e.length-1,s=this.openAt(i,e[t],A(!r),0);if(s<0){let e=w.errno();if(e===w.os.errno.ENOENT)return;this.throwOpenFailure(e,r?`open-file`:`open-directory`,t)}if(r){o=s;break}if(!j(s,`inspect-directory`).isDirectory())throw this.closeDescriptor(s),E(`UNSAFE_ENTRY`,`inspect-directory`,{segmentIndex:t});a&&this.closeDescriptor(i),i=s,a=!0,n.afterDirectoryOpened?.(t)}if(o===void 0)throw E(`HOST_IO`,`open-file`);let s=this.readFile(o,t,n);return this.assertRootIdentity(r),s}catch(e){if(e instanceof T)throw e;let t=qe(typeof e==`object`?e:null);throw E(`HOST_IO`,`read`,t===void 0?{}:{hostCode:t})}finally{this.closeOptionalDescriptor(o),this.closeOptionalDescriptor(a?i:void 0)}}writeUtf8(e,t,n){let r=this.rootDescriptor;if(r===void 0)throw E(`AUTHORITY_CLOSED`,`write`);this.assertRootIdentity(r);let i=e.slice(0,-1),a=e.at(-1);if(a===void 0)throw E(`INVALID_PATH`,`write`);let o=r,s=!1,c,l,u=!0,d=!1,f;try{let e=this.openWriteParent(r,i,n);o=e.descriptor,s=e.owned,f=this.readExistingFileIdentity(o,a);let p=this.createTemporaryFile(o,f===void 0?438:384);c=p.descriptor,l=p.name,Oe(c,t,`utf8`),f!==void 0&&this.setMode(c,Number(f.mode&BigInt(4095))),ge(c);let m=D(j(c,`inspect-temporary`));n.afterTemporaryWritten?.(l),this.assertDirectoryChain(r,i,e.identities),this.assertNamedIdentity(o,l,m,`temporary`),n.afterPreCommitValidated?.();let h=l,g=!1;try{f===void 0?this.renameWithoutReplacement(o,h,a):(this.exchange(o,h,a),d=!0),g=!0,u=!1;let t=this.readNamedIdentity(o,a,`inspect-target`,!0);if(t===void 0||!O(t,m))throw E(`FILE_CHANGED`,`commit-write`);if(d){if(f===void 0)throw E(`HOST_IO`,`commit-write`);let e=this.readNamedIdentity(o,h,`inspect-displaced`,!0);if(e===void 0||!O(e,f))throw E(`FILE_CHANGED`,`commit-write`)}this.assertDirectoryChain(r,i,e.identities),this.assertRootIdentity(r),d&&this.unlink(o,h,!1),l=void 0}catch(e){throw g&&this.rollbackCommittedWrite(o,h,a,m,f,d)&&(u=!0),e}}catch(e){if(e instanceof T)throw e;let t=qe(typeof e==`object`?e:null);throw E(`HOST_IO`,`write`,t===void 0?{}:{hostCode:t})}finally{l!==void 0&&u&&this.unlink(o,l,!0),this.closeOptionalDescriptor(c),this.closeOptionalDescriptor(s?o:void 0)}}close(){let e=this.rootDescriptor;e!==void 0&&(this.rootDescriptor=void 0,this.closeDescriptor(e))}openWriteParent(e,t,n){let r=e,i=!1,a=[];try{for(let e=0;e<t.length;e+=1){let o=this.openAt(r,t[e],A(!0),0);if(o<0&&w.errno()===w.os.errno.ENOENT){let{mkdirAt:n}=M();if(n(r,t[e],511)<0){let t=w.errno();t!==w.os.errno.EEXIST&&this.throwOpenFailure(t,`create-directory`,e)}o=this.openAt(r,t[e],A(!0),0)}o<0&&this.throwOpenFailure(w.errno(),`open-directory`,e);let s=j(o,`inspect-directory`);if(!s.isDirectory())throw this.closeDescriptor(o),E(`UNSAFE_ENTRY`,`inspect-directory`,{segmentIndex:e});i&&this.closeDescriptor(r),r=o,i=!0,a.push(D(s)),n.afterDirectoryOpened?.(e)}return{descriptor:r,owned:i,identities:a}}catch(e){throw i&&this.closeDescriptor(r),e}}assertDirectoryChain(e,t,n){this.assertRootIdentity(e);let r=e,i=!1;try{for(let e=0;e<t.length;e+=1){let a=this.openAt(r,t[e],A(!0),0);a<0&&this.throwOpenFailure(w.errno(),`reopen-directory`,e);let o=j(a,`reinspect-directory`);if(!o.isDirectory()||!Ge(n[e],D(o)))throw this.closeDescriptor(a),E(`FILE_CHANGED`,`reinspect-directory`,{segmentIndex:e});i&&this.closeDescriptor(r),r=a,i=!0}}finally{i&&this.closeDescriptor(r)}}readExistingFileIdentity(e,t){return this.readNamedIdentity(e,t,`inspect-existing`)}readNamedIdentity(e,t,n,r=!1){let i=this.openAt(e,t,A(!1),0);if(i<0){let e=w.errno();if(e===w.os.errno.ENOENT||r&&(e===w.os.errno.ELOOP||e===w.os.errno.ENOTDIR||e===w.os.errno.EISDIR))return;this.throwOpenFailure(e,n)}try{let e=j(i,n);if(!e.isFile()){if(r)return;throw E(`UNSAFE_ENTRY`,n)}return D(e)}finally{this.closeDescriptor(i)}}createTemporaryFile(e,t){let n=S.O_CLOEXEC??(process.platform===`darwin`?He:Ue),r=S.O_WRONLY|S.O_CREAT|S.O_EXCL|S.O_NOFOLLOW|n;for(let n=0;n<32;n+=1){let n=`.atomic-tmp-${m(16).toString(`hex`)}`,i=this.openAt(e,n,r,t);if(i>=0)return{descriptor:i,name:n};let a=w.errno();a!==w.os.errno.EEXIST&&this.throwOpenFailure(a,`create-temporary`)}throw E(`HOST_IO`,`create-temporary`,{hostCode:`EEXIST`})}assertNamedIdentity(e,t,n,r){let i=this.readNamedIdentity(e,t,`inspect-${r}`);if(i===void 0||!O(i,n))throw E(`FILE_CHANGED`,`inspect-${r}`)}setMode(e,t){if(M().fchmod(e,t)<0)throw E(`HOST_IO`,`set-temporary-mode`,{hostCode:k(w.errno())})}renameWithoutReplacement(e,t,n){if(M().noReplaceAt(e,t,e,n)>=0)return;let r=w.errno();throw r===w.os.errno.EEXIST?E(`FILE_CHANGED`,`commit-write`):E(`HOST_IO`,`commit-write`,{hostCode:k(r)})}exchange(e,t,n){if(M().exchangeAt(e,t,e,n)<0)throw E(`HOST_IO`,`commit-write`,{hostCode:k(w.errno())})}unlink(e,t,n){if(M().unlinkAt(e,t,0)>=0)return;let r=w.errno();if(!(n&&r===w.os.errno.ENOENT)&&!n)throw E(`HOST_IO`,`remove-temporary`,{hostCode:k(r)})}rollbackCommittedWrite(e,t,n,r,i,a){try{let o=this.readNamedIdentity(e,n,`inspect-rollback-target`,!0);if(o===void 0||!O(o,r))return!1;if(!a||i===void 0)return this.renameWithoutReplacement(e,n,t),!0;let s=this.readNamedIdentity(e,t,`inspect-rollback-displaced`,!0);return s===void 0||!O(s,i)?!1:(this.exchange(e,t,n),!0)}catch{return!1}}readFile(e,t,n){let r=j(e,`inspect-file`);if(!r.isFile())throw E(`UNSAFE_ENTRY`,`inspect-file`);if(r.size>BigInt(t))throw E(`OVER_BUDGET`,`read-file`);let i=Number(r.size),a;try{a=Buffer.alloc(i)}catch{throw E(`HOST_IO`,`allocate-read-buffer`)}let o=0;for(;o<i;){let t=be(e,a,o,Math.min(1048576,i-o),o);if(t===0)break;o+=t,n.afterReadChunk?.(o)}let s=be(e,Buffer.alloc(1),0,1,i)!==0,c=j(e,`reinspect-file`);if(s&&i>=t)throw E(`OVER_BUDGET`,`read-file`);if(o!==i||s||!Ke(We(r),We(c)))throw E(`FILE_CHANGED`,`read-file`);return a}assertRootIdentity(e){let t=j(e,`inspect-root`);if(!t.isDirectory()||!Ge(this.rootIdentity,D(t)))throw E(`ROOT_CHANGED`,`inspect-root`)}throwOpenFailure(e,t,n){let r=k(e),i=n===void 0?{hostCode:r}:{hostCode:r,segmentIndex:n};throw e===w.os.errno.ELOOP||e===w.os.errno.ENOTDIR||e===w.os.errno.EISDIR?E(`UNSAFE_ENTRY`,t,i):E(`HOST_IO`,t,i)}closeDescriptor(e){try{de(e)}catch{}}closeOptionalDescriptor(e){e!==void 0&&this.closeDescriptor(e)}};function Ze(){let e=w.pointer(`ConversationAgentStableFileHandle`,w.opaque()),t=w.struct(`ConversationAgentUnicodeString`,{Length:`uint16_t`,MaximumLength:`uint16_t`,Buffer:w.pointer(`char16_t`)});return{handleType:e,unicodeStringType:t,objectAttributesType:w.struct(`ConversationAgentObjectAttributes`,{Length:`uint32_t`,RootDirectory:e,ObjectName:w.pointer(t),Attributes:`uint32_t`,SecurityDescriptor:`void *`,SecurityQualityOfService:`void *`}),ioStatusBlockType:w.struct(`ConversationAgentIoStatusBlock`,{Status:`intptr_t`,Information:`uintptr_t`}),attributeTagInfoType:w.struct(`ConversationAgentFileAttributeTagInfo`,{FileAttributes:`uint32_t`,ReparseTag:`uint32_t`}),fileIdInfoType:w.struct(`ConversationAgentFileIdInfo`,{VolumeSerialNumber:`uint64_t`,FileId:w.array(`uint8_t`,16,`Typed`)}),standardInfoType:w.struct(`ConversationAgentFileStandardInfo`,{AllocationSize:`int64_t`,EndOfFile:`int64_t`,NumberOfLinks:`uint32_t`,DeletePending:`uint8_t`,Directory:`uint8_t`}),renameInfoType:w.struct(`ConversationAgentFileRenameInfo`,{ReplaceIfExists:`uint8_t`,RootDirectory:e,FileNameLength:`uint32_t`,FileName:w.array(`uint16_t`,256,`Typed`)}),dispositionInfoType:w.struct(`ConversationAgentFileDispositionInfo`,{DeleteFile:`uint8_t`})}}function Qe(e,t){return{createFileW:e.func(`CreateFileW`,t.handleType,[w.pointer(`char16_t`),`uint32_t`,`uint32_t`,`void *`,`uint32_t`,`uint32_t`,t.handleType]),closeHandle:e.func(`CloseHandle`,`bool`,[t.handleType]),...$e(e,t),getFileSizeEx:e.func(`GetFileSizeEx`,`bool`,[t.handleType,w.out(w.pointer(`int64_t`))]),readFile:e.func(`ReadFile`,`bool`,[t.handleType,w.out(w.pointer(`uint8_t`)),`uint32_t`,w.out(w.pointer(`uint32_t`)),`void *`]),writeFile:e.func(`WriteFile`,`bool`,[t.handleType,w.pointer(`uint8_t`),`uint32_t`,w.out(w.pointer(`uint32_t`)),`void *`]),flushFileBuffers:e.func(`FlushFileBuffers`,`bool`,[t.handleType]),setFileInformation:e.func(`SetFileInformationByHandle`,`bool`,[t.handleType,`int32_t`,`void *`,`uint32_t`]),getLastError:e.func(`GetLastError`,`uint32_t`,[])}}function $e(e,t){let n=n=>e.func(`GetFileInformationByHandleEx`,`bool`,[t.handleType,`int32_t`,w.out(w.pointer(n)),`uint32_t`]);return{getAttributeTagInfo:n(t.attributeTagInfoType),getFileIdInfo:n(t.fileIdInfoType),getStandardInfo:n(t.standardInfoType)}}function et(e,t){return{ntCreateFile:e.func(`NtCreateFile`,`int32_t`,[w.out(w.pointer(t.handleType)),`uint32_t`,w.pointer(t.objectAttributesType),w.out(w.pointer(t.ioStatusBlockType)),`void *`,`uint32_t`,`uint32_t`,`uint32_t`,`uint32_t`,`void *`,`uint32_t`]),ntClose:e.func(`NtClose`,`int32_t`,[t.handleType])}}let N;const tt=[];function nt(){if(N!==void 0)return N;let e=Ze(),t=w.load(`kernel32.dll`);tt.push(t);let n=w.load(`ntdll.dll`);return tt.push(n),N={...e,...Qe(t,e),...et(n,e)},N}const rt=BigInt(`0`);function it(e){if(e instanceof Uint8Array||Array.isArray(e))return Buffer.from(e).toString(`hex`);throw E(`UNSUPPORTED_BACKEND`,`decode-file-identity`)}function P(e){return`WIN32_${e.getLastError()}`}function at(e,t,n){let r={};if(!e.getFileIdInfo(t,18,r,w.sizeof(e.fileIdInfoType)))throw E(`UNSUPPORTED_BACKEND`,n,{hostCode:P(e)});return{volume:BigInt(r.VolumeSerialNumber??rt),fileId:it(r.FileId)}}function ot(e,t,n,r){let i=ct(e,t);if(i.size>BigInt(n))throw E(`OVER_BUDGET`,`read-file`);let a=Number(i.size),o;try{o=Buffer.alloc(a)}catch{throw E(`HOST_IO`,`allocate-read-buffer`)}let s=st(e,t,o,r),c=[0];if(!e.readFile(t,Buffer.alloc(1),1,c,null))throw E(`HOST_IO`,`probe-file`,{hostCode:P(e)});let l=ct(e,t);if(c[0]!==0&&a>=n)throw E(`OVER_BUDGET`,`read-file`);if(!lt(i,l,s,a,c[0]))throw E(`FILE_CHANGED`,`read-file`);return o}function st(e,t,n,r){let i=0;for(;i<n.length;){let a=Math.min(1048576,n.length-i),o=[0];if(!e.readFile(t,n.subarray(i,i+a),a,o,null))throw E(`HOST_IO`,`read-file`,{hostCode:P(e)});if(o[0]===0)break;i+=o[0],r.afterReadChunk?.(i)}return i}function ct(e,t){let n=at(e,t,`inspect-file`),r=[rt];if(!e.getFileSizeEx(t,r))throw E(`HOST_IO`,`inspect-file`,{hostCode:P(e)});return{...n,size:BigInt(r[0])}}function lt(e,t,n,r,i){return n===r&&i===0&&e.volume===t.volume&&e.fileId===t.fileId&&e.size===t.size}const ut=new Set([3221225487,3221225524,3221225530]),dt=new Set([2147483693,3221225658,3221225731,3221226105,3221226763]);function F(e){let t=e>>>0;return{kind:ut.has(t)?`missing`:t===3221225525?`exists`:dt.has(t)?`unsafe`:`host-io`,hostCode:`NTSTATUS_0x${t.toString(16)}`}}const ft=BigInt(`-1`);function pt(e){if(e.length===0||e.length>255)throw E(`INVALID_PATH`,`validate-segments`)}function I(e){return e===null||BigInt.asIntN(64,e)===ft}var mt=class{api;constructor(){try{this.api=nt()}catch{throw E(`UNSUPPORTED_BACKEND`,`load-windows-backend`)}}openRoot(e){let t=this.api.createFileW(e,2147483648,7,null,3,35651584,null);if(I(t))throw E(`HOST_IO`,`open-root`,{hostCode:this.lastErrorCode()});try{return this.assertSafeHandle(t,!0,`inspect-root`),t}catch(e){throw this.close(t),e}}openRelative(e,t,n,r){let{handle:i,status:a}=this.issueRelativeOpen(e,t,n,!1);if(a>=0){if(I(i))throw E(`HOST_IO`,`open-relative`);try{return this.assertSafeHandle(i,!n,n?`inspect-file`:`inspect-directory`,r),i}catch(e){throw this.close(i),e}}I(i)||this.close(i);let o=F(a);if(o.kind===`missing`)return;let s={segmentIndex:r,hostCode:o.hostCode};throw o.kind===`unsafe`?E(`UNSAFE_ENTRY`,n?`open-file`:`open-directory`,s):E(`HOST_IO`,n?`open-file`:`open-directory`,s)}openReplacementTarget(e,t,n){let{handle:r,status:i}=this.issueRelativeOpen(e,t,!0,!0);if(i>=0){if(I(r))throw E(`HOST_IO`,`open-replacement-target`);try{return this.assertSafeHandle(r,!1,`inspect-replacement-target`,n),r}catch(e){throw this.close(r),e}}I(r)||this.close(r);let a=F(i);if(a.kind===`missing`)return;let o={segmentIndex:n,hostCode:a.hostCode};throw a.kind===`unsafe`?E(`UNSAFE_ENTRY`,`open-replacement-target`,o):E(`HOST_IO`,`open-replacement-target`,o)}openOrCreateDirectory(e,t,n){let{handle:r,status:i}=this.issueRelativeCreate(e,t,!0,3);if(i<0||I(r)){I(r)||this.close(r);let e=F(i),t={segmentIndex:n,hostCode:e.hostCode};throw e.kind===`unsafe`?E(`UNSAFE_ENTRY`,`open-directory`,t):E(`HOST_IO`,`open-directory`,t)}try{return this.assertSafeHandle(r,!0,`inspect-directory`,n),r}catch(e){throw this.close(r),e}}createTemporaryFile(e,t){let{handle:n,status:r}=this.issueRelativeCreate(e,t,!1,2);if(r>=0){if(I(n))throw E(`HOST_IO`,`create-temporary`);try{return this.assertSafeHandle(n,!1,`inspect-temporary`),n}catch(e){throw this.close(n),e}}I(n)||this.close(n);let i=F(r);if(i.kind!==`exists`)throw i.kind===`unsafe`?E(`UNSAFE_ENTRY`,`create-temporary`,{hostCode:i.hostCode}):E(`HOST_IO`,`create-temporary`,{hostCode:i.hostCode})}writeUtf8(e,t){let n=Buffer.from(t,`utf8`),r=0;for(;r<n.length;){let t=n.subarray(r,Math.min(n.length,r+1048576)),i=[0];if(!this.api.writeFile(e,t,t.length,i,null))throw E(`HOST_IO`,`write-temporary`,{hostCode:this.lastErrorCode()});if(i[0]<=0||i[0]>t.length)throw E(`HOST_IO`,`write-temporary`);r+=i[0]}if(!this.api.flushFileBuffers(e))throw E(`HOST_IO`,`flush-temporary`,{hostCode:this.lastErrorCode()})}renameTo(e,t,n,r){let i=this.encodeFileName(n),a=w.alloc(this.api.renameInfoType,1);try{let o={ReplaceIfExists:+!!r,RootDirectory:t,FileNameLength:Buffer.byteLength(n,`utf16le`),FileName:i};if(w.encode(a,this.api.renameInfoType,o),!this.api.setFileInformation(e,3,a,w.sizeof(this.api.renameInfoType)))throw E(`HOST_IO`,`commit-write`,{hostCode:this.lastErrorCode()})}finally{w.free(a)}}markForDeletion(e){let t=w.alloc(this.api.dispositionInfoType,1);try{w.encode(t,this.api.dispositionInfoType,{DeleteFile:1}),this.api.setFileInformation(e,4,t,w.sizeof(this.api.dispositionInfoType))}catch{}finally{w.free(t)}}readFile(e,t,n){return ot(this.api,e,t,n)}queryIdentity(e,t){return at(this.api,e,t)}close(e){try{if(this.api.ntClose(e)>=0)return}catch{}try{this.api.closeHandle(e)}catch{}}issueRelativeOpen(e,t,n,r){pt(t);let i=w.alloc(this.api.unicodeStringType,1);try{w.encode(i,this.api.unicodeStringType,{Length:Buffer.byteLength(t,`utf16le`),MaximumLength:Buffer.byteLength(`${t}\0`,`utf16le`),Buffer:t});let a={Length:w.sizeof(this.api.objectAttributesType),RootDirectory:e,ObjectName:i,Attributes:4160,SecurityDescriptor:null,SecurityQualityOfService:null},o=[null],s={Status:0,Information:0},c=n?5:7,l=this.api.ntCreateFile(o,(n?1|(r?65536:0):1)|1048704,a,s,null,0,c,1,(n?64:1)|2097184,null,0);return{handle:o[0],status:l}}finally{w.free(i)}}issueRelativeCreate(e,t,n,r){pt(t);let i=w.alloc(this.api.unicodeStringType,1);try{w.encode(i,this.api.unicodeStringType,{Length:Buffer.byteLength(t,`utf16le`),MaximumLength:Buffer.byteLength(`${t}\0`,`utf16le`),Buffer:t});let a={Length:w.sizeof(this.api.objectAttributesType),RootDirectory:e,ObjectName:i,Attributes:4160,SecurityDescriptor:null,SecurityQualityOfService:null},o=[null],s=this.api.ntCreateFile(o,(n?1:65538)|1048704,a,{Status:0,Information:0},null,n?0:128,7,r,(n?1:64)|2097184,null,0);return{handle:o[0],status:s}}finally{w.free(i)}}encodeFileName(e){if(e.length===0||e.length>255)throw E(`INVALID_PATH`,`commit-write`);let t=new Uint16Array(256);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t}assertSafeHandle(e,t,n,r){let i={},a={};if(!this.api.getAttributeTagInfo(e,9,i,w.sizeof(this.api.attributeTagInfoType))||!this.api.getStandardInfo(e,1,a,w.sizeof(this.api.standardInfoType)))throw E(`HOST_IO`,n,{hostCode:this.lastErrorCode()});if((i.FileAttributes??0)&1024||!!a.Directory!==t)throw E(`UNSAFE_ENTRY`,n,r===void 0?{}:{segmentIndex:r})}lastErrorCode(){return P(this.api)}};function L(e,t){return e.volume===t.volume&&e.fileId===t.fileId}var ht=class{native=new mt;rootIdentity;rootHandle;constructor(e){try{let t=this.native.openRoot(e);this.rootHandle=t,this.rootIdentity=this.native.queryIdentity(t,`inspect-root`)}catch(e){throw this.rootHandle!==void 0&&(this.native.close(this.rootHandle),this.rootHandle=void 0),e instanceof T?e:E(`UNSUPPORTED_BACKEND`,`load-windows-backend`)}}readBytes(e,t,n){let r=this.rootHandle;if(r===void 0)throw E(`AUTHORITY_CLOSED`,`read`);this.assertRootIdentity(r);let i=r,a=!1,o;try{for(let t=0;t<e.length;t+=1){let r=t===e.length-1,s=this.native.openRelative(i,e[t],r,t);if(s===void 0)return;if(r){o=s;break}a&&this.native.close(i),i=s,a=!0,n.afterDirectoryOpened?.(t)}if(o===void 0)throw E(`HOST_IO`,`open-file`);let s=this.native.readFile(o,t,n);return this.assertRootIdentity(r),s}catch(e){throw e instanceof T?e:E(`HOST_IO`,`read`)}finally{o!==void 0&&this.native.close(o),a&&this.native.close(i)}}writeUtf8(e,t,n){let r=this.rootHandle;if(r===void 0)throw E(`AUTHORITY_CLOSED`,`write`);this.assertRootIdentity(r);let i=e.slice(0,-1),a=e.at(-1);if(a===void 0)throw E(`INVALID_PATH`,`write`);let o=r,s=!1,c,l,u=!1,d,f,p,h=!1;try{let g=this.openWriteParent(r,i,n);o=g.handle,s=g.owned,d=this.native.openReplacementTarget(o,a,e.length-1),d!==void 0&&(f=this.native.queryIdentity(d,`inspect-existing`));let _=this.createTemporaryFile(o);c=_.handle,l=_.name,this.native.writeUtf8(c,t);let v=this.native.queryIdentity(c,`inspect-temporary`);n.afterTemporaryWritten?.(_.name),this.assertDirectoryChain(r,i,g.identities),n.afterPreCommitValidated?.(),d!==void 0&&f!==void 0&&(p=`.atomic-backup-${m(16).toString(`hex`)}`,this.native.renameTo(d,o,p,!1),this.assertNamedIdentity(o,p,f)),this.native.renameTo(c,o,a,!1),u=!0;let y=this.native.openRelative(o,a,!0,e.length-1);if(y===void 0)throw E(`FILE_CHANGED`,`commit-write`);try{if(!L(this.native.queryIdentity(y,`inspect-target`),v))throw E(`FILE_CHANGED`,`commit-write`)}finally{this.native.close(y)}this.assertDirectoryChain(r,i,g.identities),this.assertRootIdentity(r),h=!0}catch(e){if(u&&c!==void 0&&l!==void 0)try{this.native.renameTo(c,o,l,!1),u=!1}catch{}if(d!==void 0&&p!==void 0)try{this.native.renameTo(d,o,a,!1),p=void 0}catch{}throw e instanceof T?e:E(`HOST_IO`,`write`)}finally{c!==void 0&&(u||this.native.markForDeletion(c),this.native.close(c)),d!==void 0&&(h&&p!==void 0&&this.native.markForDeletion(d),this.native.close(d)),s&&this.native.close(o)}}close(){let e=this.rootHandle;e!==void 0&&(this.rootHandle=void 0,this.native.close(e))}openWriteParent(e,t,n){let r=e,i=!1,a=[];try{for(let e=0;e<t.length;e+=1){let o=this.native.openOrCreateDirectory(r,t[e],e),s=this.native.queryIdentity(o,`inspect-directory`);i&&this.native.close(r),r=o,i=!0,a.push(s),n.afterDirectoryOpened?.(e)}return{handle:r,owned:i,identities:a}}catch(e){throw i&&this.native.close(r),e}}assertDirectoryChain(e,t,n){this.assertRootIdentity(e);let r=e,i=!1;try{for(let e=0;e<t.length;e+=1){let a=this.native.openRelative(r,t[e],!1,e);if(a===void 0)throw E(`FILE_CHANGED`,`reopen-directory`,{segmentIndex:e});if(!L(this.native.queryIdentity(a,`reinspect-directory`),n[e]))throw this.native.close(a),E(`FILE_CHANGED`,`reinspect-directory`,{segmentIndex:e});i&&this.native.close(r),r=a,i=!0}}finally{i&&this.native.close(r)}}createTemporaryFile(e){for(let t=0;t<32;t+=1){let t=`.atomic-tmp-${m(16).toString(`hex`)}`,n=this.native.createTemporaryFile(e,t);if(n!==void 0)return{handle:n,name:t}}throw E(`HOST_IO`,`create-temporary`,{hostCode:`NAME_COLLISION`})}assertNamedIdentity(e,t,n){let r=this.native.openRelative(e,t,!0,0);if(r===void 0)throw E(`FILE_CHANGED`,`inspect-named-entry`);try{if(!L(this.native.queryIdentity(r,`inspect-named-entry`),n))throw E(`FILE_CHANGED`,`inspect-named-entry`)}finally{this.native.close(r)}}assertRootIdentity(e){if(!L(this.native.queryIdentity(e,`inspect-root`),this.rootIdentity))throw E(`ROOT_CHANGED`,`inspect-root`)}};const gt=new Set([`darwin-arm64`,`darwin-x64`,`linux-arm64`,`linux-x64`,`win32-x64`]);function _t(e){let t=`${process.platform}-${process.arch}`;if(!gt.has(t))throw E(`UNSUPPORTED_BACKEND`,`select-backend`,{hostCode:t});return process.platform===`win32`?new ht(e):new Xe(e)}function vt(e){if(typeof e!=`string`||e.trim().length===0||e.includes(`\0`))throw E(`INVALID_PATH`,`validate-root`);return b(e)}function yt(e){if(!Array.isArray(e)||e.length===0)throw E(`INVALID_PATH`,`validate-segments`);for(let t=0;t<e.length;t+=1){let n=e[t];if(typeof n!=`string`||n.length===0||n===`.`||n===`..`||n.includes(`\0`)||n.includes(`/`)||n.includes(`\\`))throw E(`INVALID_PATH`,`validate-segments`,{segmentIndex:t})}}function bt(e){if(!Number.isSafeInteger(e)||e<0)throw E(`INVALID_PATH`,`validate-budget`)}const xt=new FinalizationRegistry(e=>{e.close()});var St=class{hooks;backend;finalizerToken={};constructor(e,t){this.hooks=t;let n=_t(vt(e));this.backend=n,xt.register(this,n,this.finalizerToken)}writeUtf8(e,t){let n=this.backend;if(n===void 0)throw E(`AUTHORITY_CLOSED`,`write`);if(yt(e),typeof t!=`string`)throw E(`INVALID_PATH`,`validate-content`);try{n.writeUtf8(e,t,this.hooks)}catch(e){throw e instanceof T?e:E(`HOST_IO`,`write`)}}close(){let e=this.backend;if(e!==void 0){this.backend=void 0,xt.unregister(this.finalizerToken);try{e.close()}catch(e){throw e instanceof T?e:E(`HOST_IO`,`close`)}}}[Symbol.dispose](){this.close()}};function Ct(e){return new St(e,{})}const wt=new FinalizationRegistry(e=>{e.close()});function Tt(e,t){yt(e),bt(t)}var Et=class{hooks;backend;finalizerToken={};constructor(e,t){this.hooks=t;let n=_t(vt(e));this.backend=n,wt.register(this,n,this.finalizerToken)}readBytes(e,t){let n=this.backend;if(n===void 0)throw E(`AUTHORITY_CLOSED`,`read`);Tt(e,t);try{return n.readBytes(e,t,this.hooks)}catch(e){throw e instanceof T?e:E(`HOST_IO`,`read`)}}close(){let e=this.backend;if(e!==void 0){this.backend=void 0,wt.unregister(this.finalizerToken);try{e.close()}catch(e){throw e instanceof T?e:E(`HOST_IO`,`close`)}}}[Symbol.dispose](){this.close()}};function Dt(e){return new Et(e,{})}function Ot(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 kt(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 At(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 jt=class{sandbox;generation=0;restoring=!1;connectSandbox;createSandboxFromSnapshot;constructor(e){kt(e.sandbox),this.sandbox=e.sandbox,this.connectSandbox=e.connectSandbox,this.createSandboxFromSnapshot=e.createSandboxFromSnapshot}async run(e,t){return At(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 Ot(t.snapshotId??t.id)}let t=Ot(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{Ot(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(kt(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 Mt(e){return e===void 0?`host`:`sandbox-${e.filesystem??`separate`}`}function Nt(e){return Mt(e)===`sandbox-separate`}function Pt(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 Ft=/^[A-Za-z]:[\\/]/,It=/'/g;async function Lt(e,t,n={}){if(e.applyManifest)return e.applyManifest(t,n);Pt(t);let r=Yt(n.targetRoot??`/workspace`),i=[];for(let[a,o]of Object.entries(t.entries)){let t=Rt(a),s=Xt(r,t);i.push(await zt(e,t,s,r,o,n))}return{entries:i}}function Rt(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(`\\`)||Ft.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 zt(e,t,n,r,i,a){switch(i.type){case`file`:return await Wt(e,n,r,i.content),R(t,i.type);case`dir`:return await Gt(e,n),R(t,i.type);case`localFile`:return await Bt(e,i.src,n,r,a),R(t,i.type);case`localDir`:return await Vt(e,i.src,n,a),R(t,i.type);case`gitRepo`:return await Ut(e,i,n),R(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 Qt(i)}}function R(e,t){return{path:e,type:t,status:`applied`}}async function Bt(e,t,n,r,i){await Wt(e,n,r,await oe(qt(t,i.hostRoot),`utf8`))}async function Vt(e,t,n,r){await Ht(e,qt(t,r.hostRoot),n)}async function Ht(e,t,n){await Gt(e,n);let r=await se(t,{withFileTypes:!0});for(let i of r){let r=y(t,i.name),a=Xt(n,i.name);if(i.isDirectory()){await Ht(e,r,a);continue}if(i.isFile()){let t=await oe(r,`utf8`);await e.writeFile(a,t)}}}async function Ut(e,t,n){await Kt(e,`git clone${t.shallow===!1?``:` --depth 1`}${t.ref?` --branch ${Zt(t.ref)}`:``} ${Zt(t.url)} ${Zt(n)}`)}async function Wt(e,t,n,r){let i=ee.dirname(t);i!==n&&await Gt(e,i),await e.writeFile(t,r)}async function Gt(e,t){await Kt(e,`mkdir -p ${Zt(t)}`)}async function Kt(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 qt(e,t){return v(e)?b(e):b(t??process.cwd(),e)}function Jt(e){let t=e.length;for(;t>0&&e[t-1]===`/`;)--t;return e.slice(0,t)}function Yt(e){let t=Jt(e.replace(/\\/g,`/`));if(!t.startsWith(`/`))throw Error(`workspace manifest targetRoot must be an absolute sandbox path`);return t.length===0?`/`:t}function Xt(e,t){let n=Yt(e);return n===`/`?`/${t}`:`${n}/${t}`}function Zt(e){return`'${e.replace(It,`'\\''`)}'`}function Qt(e){throw Error(`unsupported workspace manifest entry: ${JSON.stringify(e)}`)}function $t(e){return[...new Set([`.claude/worktrees`,...e?.writableWorktreeContainers??[]])]}function z(e,t){let n=e.length;for(;n>0&&e[n-1]===`/`;)--n;return`${e.slice(0,n)}/${t}`}function en(t){return[...new Set([...n,...t?.protectedDirectoryNames??[],...e])]}function tn(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 en(t.pathProtection)){let i=z(t.root,r);e.exists(i)&&n.push(`--ro-bind`,i,i)}for(let r of $t(t.pathProtection)){let i=z(t.root,r);if(e.exists(i)){n.push(`--bind`,i,i);for(let t of e.listDirectory(i)){let r=z(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 nn(e){return e.replace(/[\\^$.*+?()[\]{}|"]/g,e=>`\\${e}`)}function B(e){return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function rn(t){let n=[t.root,...t.tempDirectories,...t.allowWrite].map(e=>`(subpath ${B(e)})`).join(` `),r=en(t.pathProtection).map(n=>{let r=z(t.root,n);return e.includes(n)?`(literal ${B(r)})`:`(subpath ${B(r)})`}),i=$t(t.pathProtection).map(e=>`(subpath ${B(z(t.root,e))})`),a=[`(literal ${B(z(t.root,`.git`))})`,...$t(t.pathProtection).map(e=>`(regex #"^${nn(z(t.root,e))}/[^/]+/\\.git$")`)],o=[`(version 1)`,`(allow default)`,`(deny file-write*)`,`(allow file-write* ${n} (literal "/dev/null") (regex #"^/dev/tty") (regex #"^/dev/fd/"))`,`(deny file-write* ${r.join(` `)})`,`(allow file-write* ${i.join(` `)})`,`(deny file-write* ${a.join(` `)})`,...(t.pathProtection?.protectedPaths.length??0)>0?[`(deny file-write* ${t.pathProtection.protectedPaths.map(e=>`(subpath ${B(e)})`).join(` `)})`]:[]];if(t.denyRead.length>0){let e=t.denyRead.map(e=>e.directory?`(subpath ${B(e.path)})`:`(literal ${B(e.path)})`);o.push(`(deny file-read* ${e.join(` `)})`)}return t.network||o.push(`(deny network*)`),o.join(`
|
|
1
|
+
import{Bt as e,N as t,U as n,b as r,jt as i,p as a,rt as o}from"./node-Ct446qHg.js";import{_ as s,l as c,r as l,s as u,w as d}from"./bounded-output-BdWv9SX3-28em7iHq.js";import{l as f,s as p}from"./node-DdB-oeq6.js";import{randomBytes as m,randomUUID as h}from"node:crypto";import{basename as g,dirname as _,isAbsolute as v,join as y,posix as ee,relative as te,resolve as b,sep as ne}from"node:path";import{spawn as re,spawnSync as ie}from"node:child_process";import{open as ae,readFile as oe,readdir as se,readlink as ce,realpath as le,stat as x}from"node:fs/promises";import{chmodSync as ue,closeSync as de,constants as S,cpSync as fe,createReadStream as pe,existsSync as me,fstatSync as he,fsyncSync as ge,lstatSync as _e,mkdirSync as ve,readFileSync as ye,readSync as be,readdirSync as xe,readlinkSync as Se,realpathSync as Ce,renameSync as we,rmSync as Te,statSync as Ee,symlinkSync as De,writeFileSync as Oe}from"node:fs";import{homedir as ke,tmpdir as Ae}from"node:os";import{z as C}from"zod";import{EventEmitter as je}from"node:events";import{Worker as Me}from"node:worker_threads";import*as w from"koffi";import Ne from"fast-glob";import Pe from"p-limit";const Fe=2e3,Ie=process.platform===`win32`;function Le(e){return e.exitCode!==null||e.signalCode!==null}function Re(e,t,n){if(n&&!Ie&&typeof e.pid==`number`)try{process.kill(-e.pid,t);return}catch{}try{e.kill(t)}catch{}}function ze(e,t){if(Ie&&typeof e.pid==`number`){ie(`taskkill`,[`/pid`,String(e.pid),`/T`,`/F`],{stdio:`ignore`});return}Re(e,`SIGKILL`,t)}async function Be(e,t={}){let n=t.graceMs??2e3,r=t.signal??`SIGTERM`,i=t.processGroup??!1;if(!Le(e)){if(typeof e.pid!=`number`)throw Error(`[agent-process] killProcessTree called with an unspawned child (no pid)`);if(t.preKill){try{await t.preKill()}catch{}if(Le(e))return}return new Promise(t=>{let a,o=()=>{a&&clearTimeout(a),t()};if(e.once(`exit`,o),Le(e)){e.removeListener(`exit`,o),t();return}Re(e,r,i),a=setTimeout(()=>{Le(e)||ze(e,i)},n),a.unref?.()})}}const Ve={INVALID_PATH:`The requested root-relative file operation is invalid.`,UNSAFE_ENTRY:`The requested entry cannot be opened without following an unsafe object.`,UNSUPPORTED_BACKEND:`This host cannot provide stable root-relative file operations.`,AUTHORITY_CLOSED:`The stable rooted file authority is closed.`,ROOT_CHANGED:`The retained root identity changed during the operation.`,FILE_CHANGED:`The file identity or contents changed during the bounded read.`,OVER_BUDGET:`The file exceeds the supplied byte budget.`,HOST_IO:`The host could not complete the stable root-relative file operation.`};var T=class extends Error{code;context;constructor(e,t){super(Ve[e]),this.name=`StableFileAuthorityError`,this.code=e,this.context=Object.freeze({...t})}};function E(e,t,n={}){return new T(e,{operation:t,...n})}const He=16777216,Ue=524288;function D(e){return{device:e.dev,inode:e.ino,mode:e.mode}}function We(e){return{...D(e),size:e.size,modified:e.mtimeNs,changed:e.ctimeNs}}function Ge(e,t){return e.device===t.device&&e.inode===t.inode&&e.mode===t.mode}function O(e,t){return e.device===t.device&&e.inode===t.inode}function Ke(e,t){return Ge(e,t)&&e.size===t.size&&e.modified===t.modified&&e.changed===t.changed}function k(e){for(let[t,n]of Object.entries(w.os.errno))if(n===e)return t;return`ERRNO_${e}`}function A(e){let t=S.O_CLOEXEC??(process.platform===`darwin`?He:Ue);return S.O_RDONLY|S.O_NOFOLLOW|S.O_NONBLOCK|t|(e?S.O_DIRECTORY:0)}function j(e,t){try{return he(e,{bigint:!0})}catch(e){let n=qe(typeof e==`object`?e:null);throw E(`HOST_IO`,t,n===void 0?{}:{hostCode:n})}}function qe(e){if(!(e===null||!(`code`in e)))return typeof e.code==`string`?e.code:void 0}let Je;const Ye=[];function M(){if(!Je){let e=w.load(process.platform===`darwin`?`/usr/lib/libSystem.B.dylib`:`libc.so.6`);Ye.push(e);let t=process.platform===`darwin`?e.func(`int renameatx_np(int olddirfd, const char *oldpath, int newdirfd, const char *newpath, unsigned int flags)`):e.func(`int renameat2(int olddirfd, const char *oldpath, int newdirfd, const char *newpath, unsigned int flags)`),n=e.func(`int openat(int fd, const char *path, int flags, ...)`);Je={library:e,open:e.func(`int open(const char *path, int flags)`),openAt:(e,t,r,i)=>n(e,t,r,`unsigned int`,i),mkdirAt:e.func(`int mkdirat(int fd, const char *path, unsigned int mode)`),noReplaceAt:(e,n,r,i)=>t(e,n,r,i,process.platform===`darwin`?4:1),exchangeAt:(e,n,r,i)=>t(e,n,r,i,2),unlinkAt:e.func(`int unlinkat(int fd, const char *path, int flags)`),fchmod:e.func(`int fchmod(int fd, unsigned int mode)`)}}return Je}var Xe=class{openAt;rootIdentity;rootDescriptor;constructor(e){try{let{open:t,openAt:n}=M();this.openAt=n;let r=t(e,A(!0));r<0&&this.throwOpenFailure(w.errno(),`open-root`),this.rootDescriptor=r;let i=j(r,`inspect-root`);if(!i.isDirectory())throw E(`UNSAFE_ENTRY`,`open-root`);this.rootIdentity=D(i)}catch(e){throw this.rootDescriptor!==void 0&&(this.closeDescriptor(this.rootDescriptor),this.rootDescriptor=void 0),e instanceof T?e:E(`UNSUPPORTED_BACKEND`,`load-posix-backend`)}}assertNamedRoot(e){if(this.rootDescriptor===void 0)throw E(`AUTHORITY_CLOSED`,`inspect-root`);this.assertRootIdentity(this.rootDescriptor);let t=M().open(e,A(!0));if(t<0)throw E(`ROOT_CHANGED`,`inspect-named-root`);try{let e=j(t,`inspect-named-root`);if(!e.isDirectory()||!O(this.rootIdentity,D(e)))throw E(`ROOT_CHANGED`,`inspect-named-root`)}finally{this.closeDescriptor(t)}}readBytes(e,t,n){let r=this.rootDescriptor;if(r===void 0)throw E(`AUTHORITY_CLOSED`,`read`);this.assertRootIdentity(r);let i=r,a=!1,o;try{for(let t=0;t<e.length;t+=1){let r=t===e.length-1,s=this.openAt(i,e[t],A(!r),0);if(s<0){let e=w.errno();if(e===w.os.errno.ENOENT)return;this.throwOpenFailure(e,r?`open-file`:`open-directory`,t)}if(r){o=s;break}if(!j(s,`inspect-directory`).isDirectory())throw this.closeDescriptor(s),E(`UNSAFE_ENTRY`,`inspect-directory`,{segmentIndex:t});a&&this.closeDescriptor(i),i=s,a=!0,n.afterDirectoryOpened?.(t)}if(o===void 0)throw E(`HOST_IO`,`open-file`);let s=this.readFile(o,t,n);return this.assertRootIdentity(r),s}catch(e){if(e instanceof T)throw e;let t=qe(typeof e==`object`?e:null);throw E(`HOST_IO`,`read`,t===void 0?{}:{hostCode:t})}finally{this.closeOptionalDescriptor(o),this.closeOptionalDescriptor(a?i:void 0)}}writeUtf8(e,t,n){let r=this.rootDescriptor;if(r===void 0)throw E(`AUTHORITY_CLOSED`,`write`);this.assertRootIdentity(r);let i=e.slice(0,-1),a=e.at(-1);if(a===void 0)throw E(`INVALID_PATH`,`write`);let o=r,s=!1,c,l,u=!0,d=!1,f;try{let e=this.openWriteParent(r,i,n);o=e.descriptor,s=e.owned,f=this.readExistingFileIdentity(o,a);let p=this.createTemporaryFile(o,f===void 0?438:384);c=p.descriptor,l=p.name,Oe(c,t,`utf8`),f!==void 0&&this.setMode(c,Number(f.mode&BigInt(4095))),ge(c);let m=D(j(c,`inspect-temporary`));n.afterTemporaryWritten?.(l),this.assertDirectoryChain(r,i,e.identities),this.assertNamedIdentity(o,l,m,`temporary`),n.afterPreCommitValidated?.();let h=l,g=!1;try{f===void 0?this.renameWithoutReplacement(o,h,a):(this.exchange(o,h,a),d=!0),g=!0,u=!1,n.afterCommit?.();let t=this.readNamedIdentity(o,a,`inspect-target`,!0);if(t===void 0||!O(t,m))throw E(`FILE_CHANGED`,`commit-write`);if(d){if(f===void 0)throw E(`HOST_IO`,`commit-write`);let e=this.readNamedIdentity(o,h,`inspect-displaced`,!0);if(e===void 0||!O(e,f))throw E(`FILE_CHANGED`,`commit-write`)}this.assertDirectoryChain(r,i,e.identities),this.assertRootIdentity(r),d&&this.unlink(o,h,!1),l=void 0}catch(e){throw g&&this.rollbackCommittedWrite(o,h,a,m,f,d)&&(u=!0),e}}catch(e){if(e instanceof T)throw e;let t=qe(typeof e==`object`?e:null);throw E(`HOST_IO`,`write`,t===void 0?{}:{hostCode:t})}finally{l!==void 0&&u&&this.unlink(o,l,!0),this.closeOptionalDescriptor(c),this.closeOptionalDescriptor(s?o:void 0)}}close(){let e=this.rootDescriptor;e!==void 0&&(this.rootDescriptor=void 0,this.closeDescriptor(e))}openWriteParent(e,t,n){let r=e,i=!1,a=[];try{for(let e=0;e<t.length;e+=1){let o=this.openAt(r,t[e],A(!0),0);if(o<0&&w.errno()===w.os.errno.ENOENT){let{mkdirAt:n}=M();if(n(r,t[e],511)<0){let t=w.errno();t!==w.os.errno.EEXIST&&this.throwOpenFailure(t,`create-directory`,e)}o=this.openAt(r,t[e],A(!0),0)}o<0&&this.throwOpenFailure(w.errno(),`open-directory`,e);let s=j(o,`inspect-directory`);if(!s.isDirectory())throw this.closeDescriptor(o),E(`UNSAFE_ENTRY`,`inspect-directory`,{segmentIndex:e});i&&this.closeDescriptor(r),r=o,i=!0,a.push(D(s)),n.afterDirectoryOpened?.(e)}return{descriptor:r,owned:i,identities:a}}catch(e){throw i&&this.closeDescriptor(r),e}}assertDirectoryChain(e,t,n){this.assertRootIdentity(e);let r=e,i=!1;try{for(let e=0;e<t.length;e+=1){let a=this.openAt(r,t[e],A(!0),0);a<0&&this.throwOpenFailure(w.errno(),`reopen-directory`,e);let o=j(a,`reinspect-directory`);if(!o.isDirectory()||!Ge(n[e],D(o)))throw this.closeDescriptor(a),E(`FILE_CHANGED`,`reinspect-directory`,{segmentIndex:e});i&&this.closeDescriptor(r),r=a,i=!0}}finally{i&&this.closeDescriptor(r)}}readExistingFileIdentity(e,t){return this.readNamedIdentity(e,t,`inspect-existing`)}readNamedIdentity(e,t,n,r=!1){let i=this.openAt(e,t,A(!1),0);if(i<0){let e=w.errno();if(e===w.os.errno.ENOENT||r&&(e===w.os.errno.ELOOP||e===w.os.errno.ENOTDIR||e===w.os.errno.EISDIR))return;this.throwOpenFailure(e,n)}try{let e=j(i,n);if(!e.isFile()){if(r)return;throw E(`UNSAFE_ENTRY`,n)}return D(e)}finally{this.closeDescriptor(i)}}createTemporaryFile(e,t){let n=S.O_CLOEXEC??(process.platform===`darwin`?He:Ue),r=S.O_WRONLY|S.O_CREAT|S.O_EXCL|S.O_NOFOLLOW|n;for(let n=0;n<32;n+=1){let n=`.atomic-tmp-${m(16).toString(`hex`)}`,i=this.openAt(e,n,r,t);if(i>=0)return{descriptor:i,name:n};let a=w.errno();a!==w.os.errno.EEXIST&&this.throwOpenFailure(a,`create-temporary`)}throw E(`HOST_IO`,`create-temporary`,{hostCode:`EEXIST`})}assertNamedIdentity(e,t,n,r){let i=this.readNamedIdentity(e,t,`inspect-${r}`);if(i===void 0||!O(i,n))throw E(`FILE_CHANGED`,`inspect-${r}`)}setMode(e,t){if(M().fchmod(e,t)<0)throw E(`HOST_IO`,`set-temporary-mode`,{hostCode:k(w.errno())})}renameWithoutReplacement(e,t,n){if(M().noReplaceAt(e,t,e,n)>=0)return;let r=w.errno();throw r===w.os.errno.EEXIST?E(`FILE_CHANGED`,`commit-write`):E(`HOST_IO`,`commit-write`,{hostCode:k(r)})}exchange(e,t,n){if(M().exchangeAt(e,t,e,n)<0)throw E(`HOST_IO`,`commit-write`,{hostCode:k(w.errno())})}unlink(e,t,n){if(M().unlinkAt(e,t,0)>=0)return;let r=w.errno();if(!(n&&r===w.os.errno.ENOENT)&&!n)throw E(`HOST_IO`,`remove-temporary`,{hostCode:k(r)})}rollbackCommittedWrite(e,t,n,r,i,a){try{let o=this.readNamedIdentity(e,n,`inspect-rollback-target`,!0);if(o===void 0||!O(o,r))return!1;if(!a||i===void 0)return this.renameWithoutReplacement(e,n,t),!0;let s=this.readNamedIdentity(e,t,`inspect-rollback-displaced`,!0);return s===void 0||!O(s,i)?!1:(this.exchange(e,t,n),!0)}catch{return!1}}readFile(e,t,n){let r=j(e,`inspect-file`);if(!r.isFile())throw E(`UNSAFE_ENTRY`,`inspect-file`);if(r.size>BigInt(t))throw E(`OVER_BUDGET`,`read-file`);let i=Number(r.size),a;try{a=Buffer.alloc(i)}catch{throw E(`HOST_IO`,`allocate-read-buffer`)}let o=0;for(;o<i;){let t=be(e,a,o,Math.min(1048576,i-o),o);if(t===0)break;o+=t,n.afterReadChunk?.(o)}let s=be(e,Buffer.alloc(1),0,1,i)!==0,c=j(e,`reinspect-file`);if(s&&i>=t)throw E(`OVER_BUDGET`,`read-file`);if(o!==i||s||!Ke(We(r),We(c)))throw E(`FILE_CHANGED`,`read-file`);return a}assertRootIdentity(e){let t=j(e,`inspect-root`);if(!t.isDirectory()||!Ge(this.rootIdentity,D(t)))throw E(`ROOT_CHANGED`,`inspect-root`)}throwOpenFailure(e,t,n){let r=k(e),i=n===void 0?{hostCode:r}:{hostCode:r,segmentIndex:n};throw e===w.os.errno.ELOOP||e===w.os.errno.ENOTDIR||e===w.os.errno.EISDIR?E(`UNSAFE_ENTRY`,t,i):E(`HOST_IO`,t,i)}closeDescriptor(e){try{de(e)}catch{}}closeOptionalDescriptor(e){e!==void 0&&this.closeDescriptor(e)}};function Ze(){let e=w.pointer(`ConversationAgentStableFileHandle`,w.opaque()),t=w.struct(`ConversationAgentUnicodeString`,{Length:`uint16_t`,MaximumLength:`uint16_t`,Buffer:w.pointer(`char16_t`)});return{handleType:e,unicodeStringType:t,objectAttributesType:w.struct(`ConversationAgentObjectAttributes`,{Length:`uint32_t`,RootDirectory:e,ObjectName:w.pointer(t),Attributes:`uint32_t`,SecurityDescriptor:`void *`,SecurityQualityOfService:`void *`}),ioStatusBlockType:w.struct(`ConversationAgentIoStatusBlock`,{Status:`intptr_t`,Information:`uintptr_t`}),attributeTagInfoType:w.struct(`ConversationAgentFileAttributeTagInfo`,{FileAttributes:`uint32_t`,ReparseTag:`uint32_t`}),fileIdInfoType:w.struct(`ConversationAgentFileIdInfo`,{VolumeSerialNumber:`uint64_t`,FileId:w.array(`uint8_t`,16,`Typed`)}),standardInfoType:w.struct(`ConversationAgentFileStandardInfo`,{AllocationSize:`int64_t`,EndOfFile:`int64_t`,NumberOfLinks:`uint32_t`,DeletePending:`uint8_t`,Directory:`uint8_t`}),renameInfoType:w.struct(`ConversationAgentFileRenameInfo`,{ReplaceIfExists:`uint8_t`,RootDirectory:e,FileNameLength:`uint32_t`,FileName:w.array(`uint16_t`,256,`Typed`)}),dispositionInfoType:w.struct(`ConversationAgentFileDispositionInfo`,{DeleteFile:`uint8_t`})}}function Qe(e,t){return{createFileW:e.func(`CreateFileW`,t.handleType,[w.pointer(`char16_t`),`uint32_t`,`uint32_t`,`void *`,`uint32_t`,`uint32_t`,t.handleType]),closeHandle:e.func(`CloseHandle`,`bool`,[t.handleType]),...$e(e,t),getFileSizeEx:e.func(`GetFileSizeEx`,`bool`,[t.handleType,w.out(w.pointer(`int64_t`))]),readFile:e.func(`ReadFile`,`bool`,[t.handleType,w.out(w.pointer(`uint8_t`)),`uint32_t`,w.out(w.pointer(`uint32_t`)),`void *`]),writeFile:e.func(`WriteFile`,`bool`,[t.handleType,w.pointer(`uint8_t`),`uint32_t`,w.out(w.pointer(`uint32_t`)),`void *`]),flushFileBuffers:e.func(`FlushFileBuffers`,`bool`,[t.handleType]),setFileInformation:e.func(`SetFileInformationByHandle`,`bool`,[t.handleType,`int32_t`,`void *`,`uint32_t`]),getLastError:e.func(`GetLastError`,`uint32_t`,[])}}function $e(e,t){let n=n=>e.func(`GetFileInformationByHandleEx`,`bool`,[t.handleType,`int32_t`,w.out(w.pointer(n)),`uint32_t`]);return{getAttributeTagInfo:n(t.attributeTagInfoType),getFileIdInfo:n(t.fileIdInfoType),getStandardInfo:n(t.standardInfoType)}}function et(e,t){return{ntCreateFile:e.func(`NtCreateFile`,`int32_t`,[w.out(w.pointer(t.handleType)),`uint32_t`,w.pointer(t.objectAttributesType),w.out(w.pointer(t.ioStatusBlockType)),`void *`,`uint32_t`,`uint32_t`,`uint32_t`,`uint32_t`,`void *`,`uint32_t`]),ntClose:e.func(`NtClose`,`int32_t`,[t.handleType])}}let N;const tt=[];function nt(){if(N!==void 0)return N;let e=Ze(),t=w.load(`kernel32.dll`);tt.push(t);let n=w.load(`ntdll.dll`);return tt.push(n),N={...e,...Qe(t,e),...et(n,e)},N}const rt=BigInt(`0`);function it(e){if(e instanceof Uint8Array||Array.isArray(e))return Buffer.from(e).toString(`hex`);throw E(`UNSUPPORTED_BACKEND`,`decode-file-identity`)}function P(e){return`WIN32_${e.getLastError()}`}function at(e,t,n){let r={};if(!e.getFileIdInfo(t,18,r,w.sizeof(e.fileIdInfoType)))throw E(`UNSUPPORTED_BACKEND`,n,{hostCode:P(e)});return{volume:BigInt(r.VolumeSerialNumber??rt),fileId:it(r.FileId)}}function ot(e,t,n,r){let i=ct(e,t);if(i.size>BigInt(n))throw E(`OVER_BUDGET`,`read-file`);let a=Number(i.size),o;try{o=Buffer.alloc(a)}catch{throw E(`HOST_IO`,`allocate-read-buffer`)}let s=st(e,t,o,r),c=[0];if(!e.readFile(t,Buffer.alloc(1),1,c,null))throw E(`HOST_IO`,`probe-file`,{hostCode:P(e)});let l=ct(e,t);if(c[0]!==0&&a>=n)throw E(`OVER_BUDGET`,`read-file`);if(!lt(i,l,s,a,c[0]))throw E(`FILE_CHANGED`,`read-file`);return o}function st(e,t,n,r){let i=0;for(;i<n.length;){let a=Math.min(1048576,n.length-i),o=[0];if(!e.readFile(t,n.subarray(i,i+a),a,o,null))throw E(`HOST_IO`,`read-file`,{hostCode:P(e)});if(o[0]===0)break;i+=o[0],r.afterReadChunk?.(i)}return i}function ct(e,t){let n=at(e,t,`inspect-file`),r=[rt];if(!e.getFileSizeEx(t,r))throw E(`HOST_IO`,`inspect-file`,{hostCode:P(e)});return{...n,size:BigInt(r[0])}}function lt(e,t,n,r,i){return n===r&&i===0&&e.volume===t.volume&&e.fileId===t.fileId&&e.size===t.size}const ut=new Set([3221225487,3221225524,3221225530]),dt=new Set([2147483693,3221225658,3221225731,3221226105,3221226763]);function F(e){let t=e>>>0;return{kind:ut.has(t)?`missing`:t===3221225525?`exists`:dt.has(t)?`unsafe`:`host-io`,hostCode:`NTSTATUS_0x${t.toString(16)}`}}const ft=BigInt(`-1`);function pt(e){if(e.length===0||e.length>255)throw E(`INVALID_PATH`,`validate-segments`)}function I(e){return e===null||BigInt.asIntN(64,e)===ft}var mt=class{api;constructor(){try{this.api=nt()}catch{throw E(`UNSUPPORTED_BACKEND`,`load-windows-backend`)}}openRoot(e){let t=this.api.createFileW(e,2147483648,7,null,3,35651584,null);if(I(t))throw E(`HOST_IO`,`open-root`,{hostCode:this.lastErrorCode()});try{return this.assertSafeHandle(t,!0,`inspect-root`),t}catch(e){throw this.close(t),e}}openRelative(e,t,n,r){let{handle:i,status:a}=this.issueRelativeOpen(e,t,n,!1);if(a>=0){if(I(i))throw E(`HOST_IO`,`open-relative`);try{return this.assertSafeHandle(i,!n,n?`inspect-file`:`inspect-directory`,r),i}catch(e){throw this.close(i),e}}I(i)||this.close(i);let o=F(a);if(o.kind===`missing`)return;let s={segmentIndex:r,hostCode:o.hostCode};throw o.kind===`unsafe`?E(`UNSAFE_ENTRY`,n?`open-file`:`open-directory`,s):E(`HOST_IO`,n?`open-file`:`open-directory`,s)}openReplacementTarget(e,t,n){let{handle:r,status:i}=this.issueRelativeOpen(e,t,!0,!0);if(i>=0){if(I(r))throw E(`HOST_IO`,`open-replacement-target`);try{return this.assertSafeHandle(r,!1,`inspect-replacement-target`,n),r}catch(e){throw this.close(r),e}}I(r)||this.close(r);let a=F(i);if(a.kind===`missing`)return;let o={segmentIndex:n,hostCode:a.hostCode};throw a.kind===`unsafe`?E(`UNSAFE_ENTRY`,`open-replacement-target`,o):E(`HOST_IO`,`open-replacement-target`,o)}openOrCreateDirectory(e,t,n){let{handle:r,status:i}=this.issueRelativeCreate(e,t,!0,3);if(i<0||I(r)){I(r)||this.close(r);let e=F(i),t={segmentIndex:n,hostCode:e.hostCode};throw e.kind===`unsafe`?E(`UNSAFE_ENTRY`,`open-directory`,t):E(`HOST_IO`,`open-directory`,t)}try{return this.assertSafeHandle(r,!0,`inspect-directory`,n),r}catch(e){throw this.close(r),e}}createTemporaryFile(e,t){let{handle:n,status:r}=this.issueRelativeCreate(e,t,!1,2);if(r>=0){if(I(n))throw E(`HOST_IO`,`create-temporary`);try{return this.assertSafeHandle(n,!1,`inspect-temporary`),n}catch(e){throw this.close(n),e}}I(n)||this.close(n);let i=F(r);if(i.kind!==`exists`)throw i.kind===`unsafe`?E(`UNSAFE_ENTRY`,`create-temporary`,{hostCode:i.hostCode}):E(`HOST_IO`,`create-temporary`,{hostCode:i.hostCode})}writeUtf8(e,t){let n=Buffer.from(t,`utf8`),r=0;for(;r<n.length;){let t=n.subarray(r,Math.min(n.length,r+1048576)),i=[0];if(!this.api.writeFile(e,t,t.length,i,null))throw E(`HOST_IO`,`write-temporary`,{hostCode:this.lastErrorCode()});if(i[0]<=0||i[0]>t.length)throw E(`HOST_IO`,`write-temporary`);r+=i[0]}if(!this.api.flushFileBuffers(e))throw E(`HOST_IO`,`flush-temporary`,{hostCode:this.lastErrorCode()})}renameTo(e,t,n,r){let i=this.encodeFileName(n),a=w.alloc(this.api.renameInfoType,1);try{let o={ReplaceIfExists:+!!r,RootDirectory:t,FileNameLength:Buffer.byteLength(n,`utf16le`),FileName:i};if(w.encode(a,this.api.renameInfoType,o),!this.api.setFileInformation(e,3,a,w.sizeof(this.api.renameInfoType)))throw E(`HOST_IO`,`commit-write`,{hostCode:this.lastErrorCode()})}finally{w.free(a)}}markForDeletion(e){let t=w.alloc(this.api.dispositionInfoType,1);try{w.encode(t,this.api.dispositionInfoType,{DeleteFile:1}),this.api.setFileInformation(e,4,t,w.sizeof(this.api.dispositionInfoType))}catch{}finally{w.free(t)}}readFile(e,t,n){return ot(this.api,e,t,n)}queryIdentity(e,t){return at(this.api,e,t)}close(e){try{if(this.api.ntClose(e)>=0)return}catch{}try{this.api.closeHandle(e)}catch{}}issueRelativeOpen(e,t,n,r){pt(t);let i=w.alloc(this.api.unicodeStringType,1);try{w.encode(i,this.api.unicodeStringType,{Length:Buffer.byteLength(t,`utf16le`),MaximumLength:Buffer.byteLength(`${t}\0`,`utf16le`),Buffer:t});let a={Length:w.sizeof(this.api.objectAttributesType),RootDirectory:e,ObjectName:i,Attributes:4160,SecurityDescriptor:null,SecurityQualityOfService:null},o=[null],s={Status:0,Information:0},c=n?5:7,l=this.api.ntCreateFile(o,(n?1|(r?65536:0):1)|1048704,a,s,null,0,c,1,(n?64:1)|2097184,null,0);return{handle:o[0],status:l}}finally{w.free(i)}}issueRelativeCreate(e,t,n,r){pt(t);let i=w.alloc(this.api.unicodeStringType,1);try{w.encode(i,this.api.unicodeStringType,{Length:Buffer.byteLength(t,`utf16le`),MaximumLength:Buffer.byteLength(`${t}\0`,`utf16le`),Buffer:t});let a={Length:w.sizeof(this.api.objectAttributesType),RootDirectory:e,ObjectName:i,Attributes:4160,SecurityDescriptor:null,SecurityQualityOfService:null},o=[null],s=this.api.ntCreateFile(o,(n?1:65538)|1048704,a,{Status:0,Information:0},null,n?0:128,7,r,(n?1:64)|2097184,null,0);return{handle:o[0],status:s}}finally{w.free(i)}}encodeFileName(e){if(e.length===0||e.length>255)throw E(`INVALID_PATH`,`commit-write`);let t=new Uint16Array(256);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t}assertSafeHandle(e,t,n,r){let i={},a={};if(!this.api.getAttributeTagInfo(e,9,i,w.sizeof(this.api.attributeTagInfoType))||!this.api.getStandardInfo(e,1,a,w.sizeof(this.api.standardInfoType)))throw E(`HOST_IO`,n,{hostCode:this.lastErrorCode()});if((i.FileAttributes??0)&1024||!!a.Directory!==t)throw E(`UNSAFE_ENTRY`,n,r===void 0?{}:{segmentIndex:r})}lastErrorCode(){return P(this.api)}};function L(e,t){return e.volume===t.volume&&e.fileId===t.fileId}var ht=class{native=new mt;rootIdentity;rootHandle;constructor(e){try{let t=this.native.openRoot(e);this.rootHandle=t,this.rootIdentity=this.native.queryIdentity(t,`inspect-root`)}catch(e){throw this.rootHandle!==void 0&&(this.native.close(this.rootHandle),this.rootHandle=void 0),e instanceof T?e:E(`UNSUPPORTED_BACKEND`,`load-windows-backend`)}}readBytes(e,t,n){let r=this.rootHandle;if(r===void 0)throw E(`AUTHORITY_CLOSED`,`read`);this.assertRootIdentity(r);let i=r,a=!1,o;try{for(let t=0;t<e.length;t+=1){let r=t===e.length-1,s=this.native.openRelative(i,e[t],r,t);if(s===void 0)return;if(r){o=s;break}a&&this.native.close(i),i=s,a=!0,n.afterDirectoryOpened?.(t)}if(o===void 0)throw E(`HOST_IO`,`open-file`);let s=this.native.readFile(o,t,n);return this.assertRootIdentity(r),s}catch(e){throw e instanceof T?e:E(`HOST_IO`,`read`)}finally{o!==void 0&&this.native.close(o),a&&this.native.close(i)}}writeUtf8(e,t,n){let r=this.rootHandle;if(r===void 0)throw E(`AUTHORITY_CLOSED`,`write`);this.assertRootIdentity(r);let i=e.slice(0,-1),a=e.at(-1);if(a===void 0)throw E(`INVALID_PATH`,`write`);let o=r,s=!1,c,l,u=!1,d,f,p,h=!1;try{let g=this.openWriteParent(r,i,n);o=g.handle,s=g.owned,d=this.native.openReplacementTarget(o,a,e.length-1),d!==void 0&&(f=this.native.queryIdentity(d,`inspect-existing`));let _=this.createTemporaryFile(o);c=_.handle,l=_.name,this.native.writeUtf8(c,t);let v=this.native.queryIdentity(c,`inspect-temporary`);n.afterTemporaryWritten?.(_.name),this.assertDirectoryChain(r,i,g.identities),n.afterPreCommitValidated?.(),d!==void 0&&f!==void 0&&(p=`.atomic-backup-${m(16).toString(`hex`)}`,this.native.renameTo(d,o,p,!1),this.assertNamedIdentity(o,p,f)),this.native.renameTo(c,o,a,!1),u=!0;let y=this.native.openRelative(o,a,!0,e.length-1);if(y===void 0)throw E(`FILE_CHANGED`,`commit-write`);try{if(!L(this.native.queryIdentity(y,`inspect-target`),v))throw E(`FILE_CHANGED`,`commit-write`)}finally{this.native.close(y)}this.assertDirectoryChain(r,i,g.identities),this.assertRootIdentity(r),h=!0}catch(e){if(u&&c!==void 0&&l!==void 0)try{this.native.renameTo(c,o,l,!1),u=!1}catch{}if(d!==void 0&&p!==void 0)try{this.native.renameTo(d,o,a,!1),p=void 0}catch{}throw e instanceof T?e:E(`HOST_IO`,`write`)}finally{c!==void 0&&(u||this.native.markForDeletion(c),this.native.close(c)),d!==void 0&&(h&&p!==void 0&&this.native.markForDeletion(d),this.native.close(d)),s&&this.native.close(o)}}close(){let e=this.rootHandle;e!==void 0&&(this.rootHandle=void 0,this.native.close(e))}openWriteParent(e,t,n){let r=e,i=!1,a=[];try{for(let e=0;e<t.length;e+=1){let o=this.native.openOrCreateDirectory(r,t[e],e),s=this.native.queryIdentity(o,`inspect-directory`);i&&this.native.close(r),r=o,i=!0,a.push(s),n.afterDirectoryOpened?.(e)}return{handle:r,owned:i,identities:a}}catch(e){throw i&&this.native.close(r),e}}assertDirectoryChain(e,t,n){this.assertRootIdentity(e);let r=e,i=!1;try{for(let e=0;e<t.length;e+=1){let a=this.native.openRelative(r,t[e],!1,e);if(a===void 0)throw E(`FILE_CHANGED`,`reopen-directory`,{segmentIndex:e});if(!L(this.native.queryIdentity(a,`reinspect-directory`),n[e]))throw this.native.close(a),E(`FILE_CHANGED`,`reinspect-directory`,{segmentIndex:e});i&&this.native.close(r),r=a,i=!0}}finally{i&&this.native.close(r)}}createTemporaryFile(e){for(let t=0;t<32;t+=1){let t=`.atomic-tmp-${m(16).toString(`hex`)}`,n=this.native.createTemporaryFile(e,t);if(n!==void 0)return{handle:n,name:t}}throw E(`HOST_IO`,`create-temporary`,{hostCode:`NAME_COLLISION`})}assertNamedIdentity(e,t,n){let r=this.native.openRelative(e,t,!0,0);if(r===void 0)throw E(`FILE_CHANGED`,`inspect-named-entry`);try{if(!L(this.native.queryIdentity(r,`inspect-named-entry`),n))throw E(`FILE_CHANGED`,`inspect-named-entry`)}finally{this.native.close(r)}}assertRootIdentity(e){if(!L(this.native.queryIdentity(e,`inspect-root`),this.rootIdentity))throw E(`ROOT_CHANGED`,`inspect-root`)}};const gt=new Set([`darwin-arm64`,`darwin-x64`,`linux-arm64`,`linux-x64`,`win32-x64`]);function _t(e){let t=`${process.platform}-${process.arch}`;if(!gt.has(t))throw E(`UNSUPPORTED_BACKEND`,`select-backend`,{hostCode:t});return process.platform===`win32`?new ht(e):new Xe(e)}function vt(e){if(typeof e!=`string`||e.trim().length===0||e.includes(`\0`))throw E(`INVALID_PATH`,`validate-root`);return b(e)}function yt(e){if(!Array.isArray(e)||e.length===0)throw E(`INVALID_PATH`,`validate-segments`);for(let t=0;t<e.length;t+=1){let n=e[t];if(typeof n!=`string`||n.length===0||n===`.`||n===`..`||n.includes(`\0`)||n.includes(`/`)||n.includes(`\\`))throw E(`INVALID_PATH`,`validate-segments`,{segmentIndex:t})}}function bt(e){if(!Number.isSafeInteger(e)||e<0)throw E(`INVALID_PATH`,`validate-budget`)}const xt=new FinalizationRegistry(e=>{e.close()});var St=class{rootDirectory;hooks;backend;finalizerToken={};constructor(e,t){this.rootDirectory=e,this.hooks=t;let n=_t(vt(e));this.backend=n,xt.register(this,n,this.finalizerToken)}assertNamedRoot(){let e=this.backend;if(e===void 0)throw E(`AUTHORITY_CLOSED`,`inspect-root`);if(e.assertNamedRoot===void 0)throw E(`UNSUPPORTED_BACKEND`,`inspect-root`);e.assertNamedRoot(this.rootDirectory)}writeUtf8WhileNamed(e,t){let n=this.backend;if(n===void 0)throw E(`AUTHORITY_CLOSED`,`write`);if(yt(e),typeof t!=`string`)throw E(`INVALID_PATH`,`validate-content`);this.assertNamedRoot(),n.writeUtf8(e,t,{...this.hooks,afterPreCommitValidated:()=>{this.assertNamedRoot(),this.hooks.afterPreCommitValidated?.(),this.assertNamedRoot()},afterCommit:()=>{this.hooks.afterCommit?.(),this.assertNamedRoot()}})}writeUtf8(e,t){let n=this.backend;if(n===void 0)throw E(`AUTHORITY_CLOSED`,`write`);if(yt(e),typeof t!=`string`)throw E(`INVALID_PATH`,`validate-content`);try{n.writeUtf8(e,t,this.hooks)}catch(e){throw e instanceof T?e:E(`HOST_IO`,`write`)}}close(){let e=this.backend;if(e!==void 0){this.backend=void 0,xt.unregister(this.finalizerToken);try{e.close()}catch(e){throw e instanceof T?e:E(`HOST_IO`,`close`)}}}[Symbol.dispose](){this.close()}};function Ct(e){return new St(e,{})}const wt=new FinalizationRegistry(e=>{e.close()});function Tt(e,t){yt(e),bt(t)}var Et=class{hooks;backend;finalizerToken={};constructor(e,t){this.hooks=t;let n=_t(vt(e));this.backend=n,wt.register(this,n,this.finalizerToken)}readBytes(e,t){let n=this.backend;if(n===void 0)throw E(`AUTHORITY_CLOSED`,`read`);Tt(e,t);try{return n.readBytes(e,t,this.hooks)}catch(e){throw e instanceof T?e:E(`HOST_IO`,`read`)}}close(){let e=this.backend;if(e!==void 0){this.backend=void 0,wt.unregister(this.finalizerToken);try{e.close()}catch(e){throw e instanceof T?e:E(`HOST_IO`,`close`)}}}[Symbol.dispose](){this.close()}};function Dt(e){return new Et(e,{})}function Ot(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 kt(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 At(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 jt=class{sandbox;generation=0;restoring=!1;connectSandbox;createSandboxFromSnapshot;constructor(e){kt(e.sandbox),this.sandbox=e.sandbox,this.connectSandbox=e.connectSandbox,this.createSandboxFromSnapshot=e.createSandboxFromSnapshot}async run(e,t){return At(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 Ot(t.snapshotId??t.id)}let t=Ot(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{Ot(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(kt(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 Mt(e){return e===void 0?`host`:`sandbox-${e.filesystem??`separate`}`}function Nt(e){return Mt(e)===`sandbox-separate`}function Pt(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 Ft=/^[A-Za-z]:[\\/]/,It=/'/g;async function Lt(e,t,n={}){if(e.applyManifest)return e.applyManifest(t,n);Pt(t);let r=Yt(n.targetRoot??`/workspace`),i=[];for(let[a,o]of Object.entries(t.entries)){let t=Rt(a),s=Xt(r,t);i.push(await zt(e,t,s,r,o,n))}return{entries:i}}function Rt(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(`\\`)||Ft.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 zt(e,t,n,r,i,a){switch(i.type){case`file`:return await Wt(e,n,r,i.content),R(t,i.type);case`dir`:return await Gt(e,n),R(t,i.type);case`localFile`:return await Bt(e,i.src,n,r,a),R(t,i.type);case`localDir`:return await Vt(e,i.src,n,a),R(t,i.type);case`gitRepo`:return await Ut(e,i,n),R(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 Qt(i)}}function R(e,t){return{path:e,type:t,status:`applied`}}async function Bt(e,t,n,r,i){await Wt(e,n,r,await oe(qt(t,i.hostRoot),`utf8`))}async function Vt(e,t,n,r){await Ht(e,qt(t,r.hostRoot),n)}async function Ht(e,t,n){await Gt(e,n);let r=await se(t,{withFileTypes:!0});for(let i of r){let r=y(t,i.name),a=Xt(n,i.name);if(i.isDirectory()){await Ht(e,r,a);continue}if(i.isFile()){let t=await oe(r,`utf8`);await e.writeFile(a,t)}}}async function Ut(e,t,n){await Kt(e,`git clone${t.shallow===!1?``:` --depth 1`}${t.ref?` --branch ${Zt(t.ref)}`:``} ${Zt(t.url)} ${Zt(n)}`)}async function Wt(e,t,n,r){let i=ee.dirname(t);i!==n&&await Gt(e,i),await e.writeFile(t,r)}async function Gt(e,t){await Kt(e,`mkdir -p ${Zt(t)}`)}async function Kt(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 qt(e,t){return v(e)?b(e):b(t??process.cwd(),e)}function Jt(e){let t=e.length;for(;t>0&&e[t-1]===`/`;)--t;return e.slice(0,t)}function Yt(e){let t=Jt(e.replace(/\\/g,`/`));if(!t.startsWith(`/`))throw Error(`workspace manifest targetRoot must be an absolute sandbox path`);return t.length===0?`/`:t}function Xt(e,t){let n=Yt(e);return n===`/`?`/${t}`:`${n}/${t}`}function Zt(e){return`'${e.replace(It,`'\\''`)}'`}function Qt(e){throw Error(`unsupported workspace manifest entry: ${JSON.stringify(e)}`)}function $t(e){return[...new Set([`.claude/worktrees`,...e?.writableWorktreeContainers??[]])]}function z(e,t){let n=e.length;for(;n>0&&e[n-1]===`/`;)--n;return`${e.slice(0,n)}/${t}`}function en(t){return[...new Set([...n,...t?.protectedDirectoryNames??[],...e])]}function tn(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 en(t.pathProtection)){let i=z(t.root,r);e.exists(i)&&n.push(`--ro-bind`,i,i)}for(let r of $t(t.pathProtection)){let i=z(t.root,r);if(e.exists(i)){n.push(`--bind`,i,i);for(let t of e.listDirectory(i)){let r=z(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 nn(e){return e.replace(/[\\^$.*+?()[\]{}|"]/g,e=>`\\${e}`)}function B(e){return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function rn(t){let n=[t.root,...t.tempDirectories,...t.allowWrite].map(e=>`(subpath ${B(e)})`).join(` `),r=en(t.pathProtection).map(n=>{let r=z(t.root,n);return e.includes(n)?`(literal ${B(r)})`:`(subpath ${B(r)})`}),i=$t(t.pathProtection).map(e=>`(subpath ${B(z(t.root,e))})`),a=[`(literal ${B(z(t.root,`.git`))})`,...$t(t.pathProtection).map(e=>`(regex #"^${nn(z(t.root,e))}/[^/]+/\\.git$")`)],o=[`(version 1)`,`(allow default)`,`(deny file-write*)`,`(allow file-write* ${n} (literal "/dev/null") (regex #"^/dev/tty") (regex #"^/dev/fd/"))`,`(deny file-write* ${r.join(` `)})`,`(allow file-write* ${i.join(` `)})`,`(deny file-write* ${a.join(` `)})`,...(t.pathProtection?.protectedPaths.length??0)>0?[`(deny file-write* ${t.pathProtection.protectedPaths.map(e=>`(subpath ${B(e)})`).join(` `)})`]:[]];if(t.denyRead.length>0){let e=t.denyRead.map(e=>e.directory?`(subpath ${B(e.path)})`:`(literal ${B(e.path)})`);o.push(`(deny file-read* ${e.join(` `)})`)}return t.network||o.push(`(deny network*)`),o.join(`
|
|
2
2
|
`)}const an={x64:{audit:3221225534,socket:41,ioUringSetup:425},arm64:{audit:3221225655,socket:198,ioUringSetup:425}};function V(e,t,n,r){return[e,t,n,r]}function on(e=process.arch){let t=an[e];if(t===void 0)return;let n=e=>327680|e,r=[V(32,0,0,4),V(21,1,0,t.audit),V(6,0,0,n(1)),V(32,0,0,0),V(69,0,1,1073741824),V(6,0,0,n(1)),V(21,0,1,t.ioUringSetup),V(6,0,0,n(1)),V(21,0,3,t.socket),V(32,0,0,16),V(21,0,1,1),V(6,0,0,n(97)),V(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 sn=Object.freeze({enabled:!1,autoAllowBashIfSandboxed:!0,excludedCommands:[],allowWrite:[],denyRead:[],network:!1}),cn=`/usr/bin/sandbox-exec`;function ln(e,t){let n=ie(e,[...t],{timeout:5e3,encoding:`utf8`});if(n.error!==void 0)return{ok:!1,detail:n.error.message};let r=(n.stderr??``).trim().split(`
|
|
3
3
|
`)[0];return n.status===0?{ok:!0}:{ok:!1,...r?{detail:r}:{}}}function un(e={}){let t=e.platform??process.platform,n=e.probe??ln;if(t===`linux`){if(on(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(cn,[`-p`,`(version 1)(allow default)`,`/usr/bin/true`]);return e.ok?{backend:`seatbelt`,executable:cn,missing:[]}:{backend:`seatbelt`,missing:[`sandbox-exec cannot run${e.detail?`: ${e.detail}`:``}`]}}return{missing:[],unsupportedPlatform:t}}function dn(e){try{return Ce(e)}catch{return e}}function fn(e){try{return Ee(e).isDirectory()}catch{return!1}}function pn(e){let t=_e(e);if(!t.isSymbolicLink()&&(ue(e,t.mode|448),t.isDirectory()))for(let t of xe(e))pn(`${e}/${t}`)}function mn(e){try{return _e(e).isSymbolicLink()}catch{return!1}}function hn(e){return e.trim().split(/\s+/)[0]}var gn=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=dn(e.root),this.availability=e.availability,this.homeDirectory=e.homeDirectory??ke(),this.hiddenPaths=Object.freeze([...e.hiddenPaths??[]]),this.current={...sn,...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(t(e).length!==1)return!0;let n=hn(e);return n===void 0||!this.current.excludedCommands.includes(n)}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`,rn(n),e.command,...e.args],cwd:e.cwd};let i=n.network?void 0:on();this.protectedEntryStates().some(e=>e.path===`${this.root}/${this.projectStateDirectory}`&&e.kind===`symlink`)||ve(`${this.root}/${this.projectStateDirectory}`,{recursive:!0});let a=tn({policy:n,exists:e=>me(e)&&!mn(e),listDirectory:e=>xe(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 en(this.pathProtection).map(e=>{let t=`${this.root}/${e}`;try{return _e(t).isSymbolicLink()?{path:t,kind:`symlink`,target:Se(t)}:{path:t,kind:`present`}}catch{return{path:t,kind:`missing`}}})}resolvesOutsideWritableWorkspace(e){let t;try{t=Ce(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`&&De(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)}`;ve(t,{recursive:!0});try{we(e,n)}catch(t){if(this.inFlight>0)throw t;pn(e),t.code===`EXDEV`?(fe(e,n,{recursive:!0,verbatimSymlinks:!0}),Te(e,{recursive:!0,force:!0})):we(e,n)}return`moved ${e} to ${n}`}policy(){let e=e=>{let t=e===`~`||e.startsWith(`~/`)?`${this.homeDirectory}${e.slice(1)}`:e;return dn(v(t)?t:b(this.root,t))},t=[...new Set([Ae(),`/tmp`].filter(me).map(dn))];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:fn(n)}}),network:this.current.network}}run(e,t={}){let n=d(),r=t.workingDirectory??this.root,i=this.wrapCommand({command:n.command,args:n.commandArgs(e),cwd:r},e);return new Promise((e,n)=>{let r=i.inputDescriptors??[],a;try{a=re(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(ye(e,`utf8`))}writeFile(e,t){return Oe(e,t,`utf8`),Promise.resolve()}};const _n=C.discriminatedUnion(`success`,[C.object({success:C.literal(!0),output:C.string()}),C.object({success:C.literal(!1),output:C.string(),error:C.string().min(1)})]);function H(e,t,n,i,a={}){let c={name:e,description:t,parameters:r(n),...a.deferLoading!==void 0&&{deferLoading:a.deferLoading}},l=async(e,t)=>{let r=n.safeParse(e);if(!r.success)throw new s(`Zod validation failed: ${r.error}`);let a=await i(r.data,t);return typeof a==`string`?a:JSON.stringify(a)};return a.resultMode===`invocation-json`?o.fromResult(c,async(t,n)=>{let r=Date.now(),i=await l(t,n),a=Date.now()-r;if(typeof i!=`string`)throw new s(`Expected invocation JSON output`);let o=JSON.parse(i),c=_n.parse(o);return{success:c.success,data:i,metadata:{executionTime:a,toolName:e,parameters:t},...c.success?{}:{error:c.error}}}):new o(c,l)}const vn={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 yn(){for(let[e,t]of Object.entries(vn))i(e,t)}yn();const bn=1e3,xn=C.object({activeFiles:C.array(C.string()).optional().describe(`Repo-relative files currently in focus; the map is ranked toward what they reference.`),mentionedIdentifiers:C.array(C.string()).optional().describe(`Symbol names to bias the map toward (e.g. identifiers named in the task).`),tokenBudget:C.number().int().positive().optional().describe(`Maximum tokens for the returned map (default ${bn}).`)});function Sn(e){return e.map(e=>`${e.file}:${e.line} ${e.kind} ${e.name}`).join(`
|
|
4
4
|
`)}async function Cn(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??bn});return n.symbols.length===0?`No relevant symbols found within the token budget.`:`Most relevant symbols (~${n.totalTokens} tokens):\n${Sn(n.symbols)}`}function wn(e={}){return H(`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.`,xn,async t=>Cn(t,e))}const Tn=`Computer use is not available in this session (no driver injected).`,En=C.enum([`left`,`right`,`middle`]),Dn=C.object({x:C.number(),y:C.number()}),On=C.object({type:C.enum([`click`,`double_click`,`type`,`keypress`,`scroll`,`drag`,`wait`,`takeover`]).describe(`Which action to perform.`),x:C.number().optional().describe(`X coordinate (click/double_click/scroll).`),y:C.number().optional().describe(`Y coordinate (click/double_click/scroll).`),button:En.optional().describe(`Mouse button (click/double_click/drag).`),text:C.string().optional().describe(`Text to type (type).`),keys:C.array(C.string()).optional().describe(`Keys to press as a chord (keypress).`),deltaX:C.number().optional().describe(`Horizontal wheel delta (scroll).`),deltaY:C.number().optional().describe(`Vertical wheel delta (scroll).`),path:C.array(Dn).optional().describe(`Points to drag through (drag).`),ms:C.number().optional().describe(`Milliseconds to wait (wait).`),reason:C.string().optional().describe(`Human-readable reason surfaced to the user (takeover).`)}),kn=C.object({action:On.describe(`The single mutating action to perform.`)}),An=C.object({});var U=class extends Error{};function W(e,t,n){if(typeof e!=`number`)throw new U(`Action '${n}' requires numeric '${t}'.`);return e}function jn(e){let t=e.button;switch(e.type){case`click`:return{type:`click`,x:W(e.x,`x`,`click`),y:W(e.y,`y`,`click`),...t?{button:t}:{}};case`double_click`:return{type:`double_click`,x:W(e.x,`x`,`double_click`),y:W(e.y,`y`,`double_click`),...t?{button:t}:{}};case`type`:if(typeof e.text!=`string`)throw new U(`Action 'type' requires 'text'.`);return{type:`type`,text:e.text};case`keypress`:if(!e.keys||e.keys.length===0)throw new U(`Action 'keypress' requires non-empty 'keys'.`);return{type:`keypress`,keys:e.keys};case`scroll`:return{type:`scroll`,x:W(e.x,`x`,`scroll`),y:W(e.y,`y`,`scroll`),deltaX:W(e.deltaX,`deltaX`,`scroll`),deltaY:W(e.deltaY,`deltaY`,`scroll`)};case`drag`:if(!e.path||e.path.length<2)throw new U(`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 U(`Unknown action type: ${String(t)}`)}}}async function Mn(e){if(!e.driver)return JSON.stringify({success:!1,error:Tn});let t=await e.driver.screenshot();return JSON.stringify(t?{success:!0,screenshot:t}:{success:!0,takeover:!0})}async function Nn(e,t){if(!t.driver)return JSON.stringify({success:!1,error:Tn});let n;try{n=jn(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 Pn(e={}){return H(`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.`,An,async()=>Mn(e))}function Fn(e={}){return H(`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.",kn,async t=>Nn(t,e))}function In(e={}){return[Pn(e),Fn(e)]}const Ln=[{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 Rn(e,t){let n=t?Ln.filter(e=>t.includes(e.toolName)):Ln,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(`
|
|
@@ -63,5 +63,5 @@ readline.createInterface({ input: process.stdin }).on('line', line => {
|
|
|
63
63
|
`)}async terminate(){this.child.exitCode===null&&this.child.signalCode===null&&this.child.kill(`SIGKILL`),await this.closed}},Mr=class{pattern;signal;worker=process.versions.bun?new jr:new Me(Ar,{eval:!0,execArgv:[],resourceLimits:{maxOldGenerationSizeMb:128,maxYoungGenerationSizeMb:32}});pending=new Map;nextId=0;stopped=!1;termination;timer;abort=()=>{this.stop(Error(`Grep search cancelled`))};constructor(e,t){this.pattern=e,this.signal=t,this.worker.on(`message`,e=>{let t=this.pending.get(e.id);!t||this.stopped||(this.pending.delete(e.id),Array.isArray(e.matches)&&e.matches.every(e=>typeof e==`string`)?t.resolve(e.matches):t.reject(Error(e.error??`Invalid grep worker response`)))}),this.worker.on(`error`,()=>{this.stop(Error(`Grep search worker failed`))}),this.worker.once(`exit`,()=>{this.stop(Error(`Grep search worker exited`))}),this.timer=setTimeout(()=>{this.stop(Error(`Grep search timed out`))},2e3),t?.addEventListener(`abort`,this.abort,{once:!0}),t?.aborted&&this.abort()}search(e,t,n,r){if(this.stopped)return Promise.reject(Error(this.signal?.aborted?`Grep search cancelled`:`Grep search timed out`));let i=this.nextId++;return new Promise((a,o)=>{this.pending.set(i,{resolve:a,reject:o});try{this.worker.postMessage({id:i,content:e,filePath:t,pattern:this.pattern,contextLines:n,outputMode:r})}catch{this.stop(Error(`Grep search worker failed`))}})}async stop(e){return this.termination?this.termination:(this.stopped=!0,clearTimeout(this.timer),this.signal?.removeEventListener(`abort`,this.abort),this.termination=(async()=>{try{await this.worker.terminate()}catch{}for(let t of this.pending.values())t.reject(e??Error(`Grep search stopped`));this.pending.clear()})(),this.termination)}};const Nr=C.object({pattern:C.string().describe(`The regular expression pattern to search for in file contents`),path:C.string().optional().describe(`File or directory to search in. Defaults to the current working directory`),glob:C.string().optional().describe(`Glob pattern to filter files (e.g. "*.ts", "*.{ts,tsx}"). Only files matching this pattern will be searched`),contextLines:C.number().optional().describe(`Number of context lines to show before and after each match. Only applies when outputMode is "content". Default: 0`),outputMode:C.enum([`files_with_matches`,`content`,`count`]).optional().describe(`Output mode: "files_with_matches" shows only file paths (default), "content" shows matching lines with context, "count" shows per-file match counts`),headLimit:C.number().int().positive().optional().describe(`Maximum number of result lines (file paths, content lines, or count rows) to return. Excess results are truncated with a marker line`)}),Pr=4*1024*1024;var $=class extends c{reason;constructor(e){super(`Grep search ${e===`timeout`?`timed out`:e===`cancelled`?`cancelled`:e===`limit`?`exceeded its byte limit`:`worker failed`}`,`Grep`),this.reason=e}};async function Fr(e,t){let{pattern:n,path:r,glob:i,contextLines:a=0,outputMode:o=`files_with_matches`,headLimit:s}=e,c=t.cwd,{root:l,error:u}=tr(r,c);if(u)return u;try{new RegExp(n)}catch{let e={success:!1,output:``,error:`Invalid regex pattern: ${n}`};return JSON.stringify(e)}let d;try{d=await x(l)}catch{let e={success:!1,output:``,error:`Path not found: ${l}`};return JSON.stringify(e)}let f,p=!1;if(d.isFile())f=[l];else{let e=await Or(l,i,c);f=e.files,p=e.truncated}let m=new Mr(n,t.signal),h=new AbortController,g=()=>h.abort();t.signal?.addEventListener(`abort`,g,{once:!0}),t.signal?.aborted&&g();let _;try{if(h.signal.aborted)throw new $(`cancelled`);let e=Array(f.length),t=0,n,r=async e=>{let t;try{if((await x(e)).size>Pr)throw new $(`limit`);let n=pe(e,{highWaterMark:65536,signal:h.signal}),r=[],i=0;try{for await(let e of n){if(h.signal.aborted)throw new $(`cancelled`);let t=Buffer.isBuffer(e)?e:Buffer.from(e);if(i+=t.length,i>Pr)throw new $(`limit`);r.push(t)}}finally{n.destroy()}let a=Buffer.concat(r,i),o=Math.min(a.length,8192),s=!1;for(let e=0;e<o;e++)if(a[e]===0){s=!0;break}if(s)return[];t=a.toString(`utf8`)}catch(e){if(e instanceof $)throw e;if(h.signal.aborted)throw new $(`cancelled`);return[]}return m.search(t,e,a,o)};if(await Promise.all(Array.from({length:Math.min(8,f.length)},async()=>{for(;n===void 0&&t<f.length;){let i=t++;try{e[i]=await r(f[i])}catch(e){n===void 0&&(n=e,h.abort(),m.stop(e instanceof Error?e:Error(`Grep search failed`)))}}})),n!==void 0)throw n;_=e}catch(e){let t=e instanceof Error?e.message:``;throw e instanceof $?e:new $(t.includes(`timed out`)?`timeout`:t.includes(`cancelled`)?`cancelled`:t.includes(`byte limit`)?`limit`:`failed`)}finally{t.signal?.removeEventListener(`abort`,g),await m.stop()}let v=0;for(let e of _)for(let t of e)if(v+=Buffer.byteLength(t,`utf8`)+1,v>4*1024*1024)throw new $(`limit`);let y=_.flat();if(s!==void 0&&y.length>s){let e=y.length-s;y=[...y.slice(0,s),`(+${e} more results truncated by headLimit)`]}p&&(y=[...y,`[File enumeration stopped early; the search tree has more files than this tool scans in one call. Results may be incomplete — narrow the path or glob.]`]);let ee={success:!0,output:Xn(y.length>0?y.join(`
|
|
64
64
|
`):`(no matches)`,t)};return JSON.stringify(ee)}function Ir(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 Lr(e){return H(`Grep`,e.description??Ir(e.shellToolName??`Shell`),Nr,async t=>Fr(t,e),{resultMode:`invocation-json`})}const Rr=3e4,zr=5e6,Br=C.object({url:C.string().describe(`The URL to fetch`),headers:C.record(C.string(),C.string()).optional().describe(`Optional HTTP headers as key-value pairs`)});function Vr(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 Hr(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 Ur={"&":`&`,"<":`<`,">":`>`,""":`"`,"'":`'`," ":` `},Wr=/&(?:amp|lt|gt|quot|nbsp|#39);/g;function Gr(e){return Hr(Vr(Vr(e,`script`),`style`)).replace(Wr,e=>Ur[e]).replace(/\s+/g,` `).trim()}function Kr(e){if(!(e instanceof Error))return String(e);if(e.name===`AbortError`)return`Request timed out after ${Rr/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.`}function qr(e,t){return/text\/(plain|markdown)/i.test(e)?new TextDecoder().decode(t).split(/\r?\n/).find(e=>e.trim()!==``)?.startsWith(`# `)??!1:!1}async function Jr(e,t,n,r){let i=`${e}/llms.txt`;try{let e=await f(i,{headers:n===void 0?{}:{"User-Agent":n},signal:r,timeoutMs:2e3,maxResponseBytes:512e3},t.policy,t.deps);return!e.ok||e.status<200||e.status>=300?void 0:qr(e.headers.get(`content-type`)??``,e.body)?i:void 0}catch{return}}function Yr(e){return`\n\nThis site publishes an LLM index at ${e} (llms.txt); fetch it for a curated map of the docs.`}async function Xr(e,t,n,r,i){let{url:a,headers:o}=e;try{new URL(a)}catch{let e={success:!1,output:``,error:`Invalid URL: "${a}". Fix the URL format before retrying.`};return JSON.stringify(e)}try{let e=await f(a,{headers:{...n===void 0?{}:{"User-Agent":n},...o??{}},signal:i,timeoutMs:Rr,maxResponseBytes:zr},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 ${zr} 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 s=e.headers.get(`content-type`)??``,c=new TextDecoder().decode(e.body);if(s.includes(`html`)){let a=new URL(e.finalUrl).origin,o=r?.get(a);if(r&&o===void 0){let e=Jr(a,t,n,i).then(t=>(t===void 0&&i?.aborted&&r.get(a)===e&&r.delete(a),t));o=e,r.set(a,o)}c=Gr(c);let s=await o;s!==void 0&&(c+=Yr(s))}return JSON.stringify({success:!0,output:c})}catch(e){let t={success:!1,output:``,error:Kr(e)};return JSON.stringify(t)}}const Zr=`Fetch a URL and return its content as text. HTML pages are converted to plain text. Documentation sites may publish a curated index at /llms.txt (full text at /llms-full.txt)`,Qr=`${Zr}; when a fetched page's site has one, the result points to it.`,$r=`${Zr}.`;function ei(e={}){let t=e.egress??{},n=e.llmsTxtProbe===!1?void 0:new Map;return H(`WebFetch`,e.description??(n?Qr:$r),Br,async(r,i)=>Xr(r,t,e.userAgent,n,i?.signal),{resultMode:`invocation-json`})}const ti=ei();function ni(){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 ri=C.object({query:C.string().describe(`The search query`),limit:C.number().optional().describe(`Maximum number of results to return (default: 10)`)});async function ii(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 ai(e={}){let t=e.provider??ni();return H(`WebSearch`,e.description??`Search the web and return results with title, URL, and snippet.`,ri,async(e,n)=>ii(e,t,n?.signal),{resultMode:`invocation-json`})}const oi=ai(),si=C.object({question:C.string().min(1).describe(`The complete question to ask the user.`),header:C.string().optional().describe(`Very short topic label for the question (e.g. "Auth method").`),options:C.array(C.union([C.string().min(1).describe(`Display text of this choice.`),C.object({label:C.string().min(1).describe(`Display text of this choice.`),description:C.string().optional().describe(`What choosing this option means.`)})])).optional().describe(`Predefined choices (strings or {label, description}). Omit for pure free text.`),multiSelect:C.boolean().optional().describe(`Allow selecting multiple options (default: single select).`),allowFreeText:C.boolean().optional().describe(`Allow a typed custom answer besides the options (default: true).`)}),ci=C.object({questions:C.array(si).min(1).max(4).describe(`Questions to ask the user (1-4), rendered one at a time.`)}),li=[`Ask the user one or more structured questions and wait for their answers.`,``,`Use this when you are blocked on a decision only the user can make — ambiguous requirements,`,`mutually exclusive approaches, or choices with real trade-offs. Do not use it for decisions with`,`a conventional default or facts you can verify yourself.`,``,`Provide 1-4 questions. Each question offers predefined options and/or free text:`,` - options + default: user picks one option (or types a custom answer unless allowFreeText: false)`,` - multiSelect: true: user may pick several options`,` - no options: pure free-text entry`,``,"The result is a JSON array with one entry per question: the selected option labels in `values`","and/or the typed answer in `text`, or `cancelled: true` if the user dismissed the question.","If no interactive user is attached (headless run), the result is `{ unavailable: true }` —",`continue autonomously with your best judgment and say what you assumed.`].join(`
|
|
65
65
|
`);function ui(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 di(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(ui(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 fi(e={}){return H(`AskUserQuestion`,e.description??li,ci,async(e,t)=>{let n=e,r=t?.ask,i=r?await di(n,r):{unavailable:!0,reason:`no interactive user attached`},a={success:!0,output:JSON.stringify(i)};return JSON.stringify(a)},{resultMode:`invocation-json`})}fi();const pi=1/0;function mi(e,t){e.description!==void 0&&t.push(e.description);for(let[n,r]of Object.entries(e.properties??{}))t.push(n),mi(r,t);e.items!==void 0&&mi(e.items,t);for(let n of e.anyOf??[])mi(n,t)}function hi(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 mi(e.parameters,r),r.some(e=>e.toLowerCase().includes(t))?3:pi}function gi(e,t,n){let r=t.trim().toLowerCase();return r.length===0?[]:e.map(e=>({schema:e,rank:hi(e,r)})).filter(e=>e.rank!==pi).sort((e,t)=>e.rank-t.rank||(e.schema.name<t.schema.name?-1:1)).slice(0,n).map(e=>e.schema)}const _i=a,vi=C.object({query:C.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:C.array(C.string().min(1)).optional().describe(`Exact tool names to load, skipping the search. An unknown name is an error naming it.`),limit:C.number().int().positive().optional().describe(`Maximum tools to load from a query match (default 5).`)}),yi=[`Load tools whose definitions are withheld from your tool list, so you can call them.`,``,`Some tools are deferred: they exist and are callable, but their schemas are not sent to you until`,`you load them here. If a capability you need is not in your tool list, search for it before`,`concluding it is unavailable — and if a tool call fails as "deferred and not yet loaded", load it`,`with this tool and call it again.`,``,` - query: what you are trying to do (e.g. "read a spreadsheet", "postgres"). Matched against tool`,` names, descriptions, and parameter names and descriptions. An exact tool name works too.`,` - names: load exactly these tools, skipping the search. Unknown names are an error.`,` - limit: how many matches to load (default 5).`,``,`The result lists what is now loaded; those tools appear in your tool list from your next turn and`,`stay available. A query that matches nothing returns an empty list — that is a normal answer, not`,"a failure. `unavailableSources` names any tool source that could not be consulted."].join(`
|
|
66
|
-
`);function bi(e){let t=e?.deferredTools;if(!t)throw Error(`${_i} 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 xi(e,t){if(e.names!==void 0)return t.loadDeferredTools(e.names);if(e.query===void 0)throw Error(`${_i} needs either "query" to search for tools or "names" to load exact ones.`);let n=gi(t.listDeferredTools(),e.query,e.limit??5);return t.loadDeferredTools(n.map(e=>e.name))}function Si(e={}){return H(_i,e.description??yi,vi,async(e,t)=>{let n={loaded:xi(e,bi(t)).map(({name:e,description:t})=>({name:e,description:t})),unavailableSources:[]},r={success:!0,output:JSON.stringify(n)};return JSON.stringify(r)},{resultMode:`invocation-json`})}Si();export{
|
|
67
|
-
//# sourceMappingURL=node-
|
|
66
|
+
`);function bi(e){let t=e?.deferredTools;if(!t)throw Error(`${_i} 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 xi(e,t){if(e.names!==void 0)return t.loadDeferredTools(e.names);if(e.query===void 0)throw Error(`${_i} needs either "query" to search for tools or "names" to load exact ones.`);let n=gi(t.listDeferredTools(),e.query,e.limit??5);return t.loadDeferredTools(n.map(e=>e.name))}function Si(e={}){return H(_i,e.description??yi,vi,async(e,t)=>{let n={loaded:xi(e,bi(t)).map(({name:e,description:t})=>({name:e,description:t})),unavailableSources:[]},r={success:!0,output:JSON.stringify(n)};return JSON.stringify(r)},{resultMode:`invocation-json`})}Si();export{Be as A,un as C,Dt as D,oi as E,Ct as O,Mt as S,ti as T,Si as _,X as a,mr as b,fi as c,br as d,Tr as f,Gn as g,wn as h,gn as i,Fe as j,T as k,Kn as l,lr as m,jt as n,Z as o,Lr as p,$ as r,Lt as s,sn as t,In as u,ei as v,Nt as w,H as x,ai as y};
|
|
67
|
+
//# sourceMappingURL=node-DwQY2ITL.js.map
|